BranchFolding.cpp 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682
  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. #endif
  430. return false;
  431. }
  432. }
  433. /// CountTerminators - Count the number of terminators in the given
  434. /// block and set I to the position of the first non-terminator, if there
  435. /// is one, or MBB->end() otherwise.
  436. static unsigned CountTerminators(MachineBasicBlock *MBB,
  437. MachineBasicBlock::iterator &I) {
  438. I = MBB->end();
  439. unsigned NumTerms = 0;
  440. for (;;) {
  441. if (I == MBB->begin()) {
  442. I = MBB->end();
  443. break;
  444. }
  445. --I;
  446. if (!I->isTerminator()) break;
  447. ++NumTerms;
  448. }
  449. return NumTerms;
  450. }
  451. /// ProfitableToMerge - Check if two machine basic blocks have a common tail
  452. /// and decide if it would be profitable to merge those tails. Return the
  453. /// length of the common tail and iterators to the first common instruction
  454. /// in each block.
  455. static bool ProfitableToMerge(MachineBasicBlock *MBB1,
  456. MachineBasicBlock *MBB2,
  457. unsigned minCommonTailLength,
  458. unsigned &CommonTailLen,
  459. MachineBasicBlock::iterator &I1,
  460. MachineBasicBlock::iterator &I2,
  461. MachineBasicBlock *SuccBB,
  462. MachineBasicBlock *PredBB) {
  463. CommonTailLen = ComputeCommonTailLength(MBB1, MBB2, I1, I2);
  464. if (CommonTailLen == 0)
  465. return false;
  466. DEBUG(dbgs() << "Common tail length of BB#" << MBB1->getNumber()
  467. << " and BB#" << MBB2->getNumber() << " is " << CommonTailLen
  468. << '\n');
  469. // It's almost always profitable to merge any number of non-terminator
  470. // instructions with the block that falls through into the common successor.
  471. if (MBB1 == PredBB || MBB2 == PredBB) {
  472. MachineBasicBlock::iterator I;
  473. unsigned NumTerms = CountTerminators(MBB1 == PredBB ? MBB2 : MBB1, I);
  474. if (CommonTailLen > NumTerms)
  475. return true;
  476. }
  477. // If one of the blocks can be completely merged and happens to be in
  478. // a position where the other could fall through into it, merge any number
  479. // of instructions, because it can be done without a branch.
  480. // TODO: If the blocks are not adjacent, move one of them so that they are?
  481. if (MBB1->isLayoutSuccessor(MBB2) && I2 == MBB2->begin())
  482. return true;
  483. if (MBB2->isLayoutSuccessor(MBB1) && I1 == MBB1->begin())
  484. return true;
  485. // If both blocks have an unconditional branch temporarily stripped out,
  486. // count that as an additional common instruction for the following
  487. // heuristics.
  488. unsigned EffectiveTailLen = CommonTailLen;
  489. if (SuccBB && MBB1 != PredBB && MBB2 != PredBB &&
  490. !MBB1->back().isBarrier() &&
  491. !MBB2->back().isBarrier())
  492. ++EffectiveTailLen;
  493. // Check if the common tail is long enough to be worthwhile.
  494. if (EffectiveTailLen >= minCommonTailLength)
  495. return true;
  496. // If we are optimizing for code size, 2 instructions in common is enough if
  497. // we don't have to split a block. At worst we will be introducing 1 new
  498. // branch instruction, which is likely to be smaller than the 2
  499. // instructions that would be deleted in the merge.
  500. MachineFunction *MF = MBB1->getParent();
  501. if (EffectiveTailLen >= 2 &&
  502. MF->getFunction()->hasFnAttr(Attribute::OptimizeForSize) &&
  503. (I1 == MBB1->begin() || I2 == MBB2->begin()))
  504. return true;
  505. return false;
  506. }
  507. /// ComputeSameTails - Look through all the blocks in MergePotentials that have
  508. /// hash CurHash (guaranteed to match the last element). Build the vector
  509. /// SameTails of all those that have the (same) largest number of instructions
  510. /// in common of any pair of these blocks. SameTails entries contain an
  511. /// iterator into MergePotentials (from which the MachineBasicBlock can be
  512. /// found) and a MachineBasicBlock::iterator into that MBB indicating the
  513. /// instruction where the matching code sequence begins.
  514. /// Order of elements in SameTails is the reverse of the order in which
  515. /// those blocks appear in MergePotentials (where they are not necessarily
  516. /// consecutive).
  517. unsigned BranchFolder::ComputeSameTails(unsigned CurHash,
  518. unsigned minCommonTailLength,
  519. MachineBasicBlock *SuccBB,
  520. MachineBasicBlock *PredBB) {
  521. unsigned maxCommonTailLength = 0U;
  522. SameTails.clear();
  523. MachineBasicBlock::iterator TrialBBI1, TrialBBI2;
  524. MPIterator HighestMPIter = prior(MergePotentials.end());
  525. for (MPIterator CurMPIter = prior(MergePotentials.end()),
  526. B = MergePotentials.begin();
  527. CurMPIter != B && CurMPIter->getHash() == CurHash;
  528. --CurMPIter) {
  529. for (MPIterator I = prior(CurMPIter); I->getHash() == CurHash ; --I) {
  530. unsigned CommonTailLen;
  531. if (ProfitableToMerge(CurMPIter->getBlock(), I->getBlock(),
  532. minCommonTailLength,
  533. CommonTailLen, TrialBBI1, TrialBBI2,
  534. SuccBB, PredBB)) {
  535. if (CommonTailLen > maxCommonTailLength) {
  536. SameTails.clear();
  537. maxCommonTailLength = CommonTailLen;
  538. HighestMPIter = CurMPIter;
  539. SameTails.push_back(SameTailElt(CurMPIter, TrialBBI1));
  540. }
  541. if (HighestMPIter == CurMPIter &&
  542. CommonTailLen == maxCommonTailLength)
  543. SameTails.push_back(SameTailElt(I, TrialBBI2));
  544. }
  545. if (I == B)
  546. break;
  547. }
  548. }
  549. return maxCommonTailLength;
  550. }
  551. /// RemoveBlocksWithHash - Remove all blocks with hash CurHash from
  552. /// MergePotentials, restoring branches at ends of blocks as appropriate.
  553. void BranchFolder::RemoveBlocksWithHash(unsigned CurHash,
  554. MachineBasicBlock *SuccBB,
  555. MachineBasicBlock *PredBB) {
  556. MPIterator CurMPIter, B;
  557. for (CurMPIter = prior(MergePotentials.end()), B = MergePotentials.begin();
  558. CurMPIter->getHash() == CurHash;
  559. --CurMPIter) {
  560. // Put the unconditional branch back, if we need one.
  561. MachineBasicBlock *CurMBB = CurMPIter->getBlock();
  562. if (SuccBB && CurMBB != PredBB)
  563. FixTail(CurMBB, SuccBB, TII);
  564. if (CurMPIter == B)
  565. break;
  566. }
  567. if (CurMPIter->getHash() != CurHash)
  568. CurMPIter++;
  569. MergePotentials.erase(CurMPIter, MergePotentials.end());
  570. }
  571. /// CreateCommonTailOnlyBlock - None of the blocks to be tail-merged consist
  572. /// only of the common tail. Create a block that does by splitting one.
  573. bool BranchFolder::CreateCommonTailOnlyBlock(MachineBasicBlock *&PredBB,
  574. unsigned maxCommonTailLength,
  575. unsigned &commonTailIndex) {
  576. commonTailIndex = 0;
  577. unsigned TimeEstimate = ~0U;
  578. for (unsigned i = 0, e = SameTails.size(); i != e; ++i) {
  579. // Use PredBB if possible; that doesn't require a new branch.
  580. if (SameTails[i].getBlock() == PredBB) {
  581. commonTailIndex = i;
  582. break;
  583. }
  584. // Otherwise, make a (fairly bogus) choice based on estimate of
  585. // how long it will take the various blocks to execute.
  586. unsigned t = EstimateRuntime(SameTails[i].getBlock()->begin(),
  587. SameTails[i].getTailStartPos());
  588. if (t <= TimeEstimate) {
  589. TimeEstimate = t;
  590. commonTailIndex = i;
  591. }
  592. }
  593. MachineBasicBlock::iterator BBI =
  594. SameTails[commonTailIndex].getTailStartPos();
  595. MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
  596. // If the common tail includes any debug info we will take it pretty
  597. // randomly from one of the inputs. Might be better to remove it?
  598. DEBUG(dbgs() << "\nSplitting BB#" << MBB->getNumber() << ", size "
  599. << maxCommonTailLength);
  600. MachineBasicBlock *newMBB = SplitMBBAt(*MBB, BBI);
  601. if (!newMBB) {
  602. DEBUG(dbgs() << "... failed!");
  603. return false;
  604. }
  605. SameTails[commonTailIndex].setBlock(newMBB);
  606. SameTails[commonTailIndex].setTailStartPos(newMBB->begin());
  607. // If we split PredBB, newMBB is the new predecessor.
  608. if (PredBB == MBB)
  609. PredBB = newMBB;
  610. return true;
  611. }
  612. // See if any of the blocks in MergePotentials (which all have a common single
  613. // successor, or all have no successor) can be tail-merged. If there is a
  614. // successor, any blocks in MergePotentials that are not tail-merged and
  615. // are not immediately before Succ must have an unconditional branch to
  616. // Succ added (but the predecessor/successor lists need no adjustment).
  617. // The lone predecessor of Succ that falls through into Succ,
  618. // if any, is given in PredBB.
  619. bool BranchFolder::TryTailMergeBlocks(MachineBasicBlock *SuccBB,
  620. MachineBasicBlock *PredBB) {
  621. bool MadeChange = false;
  622. // Except for the special cases below, tail-merge if there are at least
  623. // this many instructions in common.
  624. unsigned minCommonTailLength = TailMergeSize;
  625. DEBUG(dbgs() << "\nTryTailMergeBlocks: ";
  626. for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
  627. dbgs() << "BB#" << MergePotentials[i].getBlock()->getNumber()
  628. << (i == e-1 ? "" : ", ");
  629. dbgs() << "\n";
  630. if (SuccBB) {
  631. dbgs() << " with successor BB#" << SuccBB->getNumber() << '\n';
  632. if (PredBB)
  633. dbgs() << " which has fall-through from BB#"
  634. << PredBB->getNumber() << "\n";
  635. }
  636. dbgs() << "Looking for common tails of at least "
  637. << minCommonTailLength << " instruction"
  638. << (minCommonTailLength == 1 ? "" : "s") << '\n';
  639. );
  640. // Sort by hash value so that blocks with identical end sequences sort
  641. // together.
  642. std::stable_sort(MergePotentials.begin(), MergePotentials.end());
  643. // Walk through equivalence sets looking for actual exact matches.
  644. while (MergePotentials.size() > 1) {
  645. unsigned CurHash = MergePotentials.back().getHash();
  646. // Build SameTails, identifying the set of blocks with this hash code
  647. // and with the maximum number of instructions in common.
  648. unsigned maxCommonTailLength = ComputeSameTails(CurHash,
  649. minCommonTailLength,
  650. SuccBB, PredBB);
  651. // If we didn't find any pair that has at least minCommonTailLength
  652. // instructions in common, remove all blocks with this hash code and retry.
  653. if (SameTails.empty()) {
  654. RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
  655. continue;
  656. }
  657. // If one of the blocks is the entire common tail (and not the entry
  658. // block, which we can't jump to), we can treat all blocks with this same
  659. // tail at once. Use PredBB if that is one of the possibilities, as that
  660. // will not introduce any extra branches.
  661. MachineBasicBlock *EntryBB = MergePotentials.begin()->getBlock()->
  662. getParent()->begin();
  663. unsigned commonTailIndex = SameTails.size();
  664. // If there are two blocks, check to see if one can be made to fall through
  665. // into the other.
  666. if (SameTails.size() == 2 &&
  667. SameTails[0].getBlock()->isLayoutSuccessor(SameTails[1].getBlock()) &&
  668. SameTails[1].tailIsWholeBlock())
  669. commonTailIndex = 1;
  670. else if (SameTails.size() == 2 &&
  671. SameTails[1].getBlock()->isLayoutSuccessor(
  672. SameTails[0].getBlock()) &&
  673. SameTails[0].tailIsWholeBlock())
  674. commonTailIndex = 0;
  675. else {
  676. // Otherwise just pick one, favoring the fall-through predecessor if
  677. // there is one.
  678. for (unsigned i = 0, e = SameTails.size(); i != e; ++i) {
  679. MachineBasicBlock *MBB = SameTails[i].getBlock();
  680. if (MBB == EntryBB && SameTails[i].tailIsWholeBlock())
  681. continue;
  682. if (MBB == PredBB) {
  683. commonTailIndex = i;
  684. break;
  685. }
  686. if (SameTails[i].tailIsWholeBlock())
  687. commonTailIndex = i;
  688. }
  689. }
  690. if (commonTailIndex == SameTails.size() ||
  691. (SameTails[commonTailIndex].getBlock() == PredBB &&
  692. !SameTails[commonTailIndex].tailIsWholeBlock())) {
  693. // None of the blocks consist entirely of the common tail.
  694. // Split a block so that one does.
  695. if (!CreateCommonTailOnlyBlock(PredBB,
  696. maxCommonTailLength, commonTailIndex)) {
  697. RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
  698. continue;
  699. }
  700. }
  701. MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
  702. // MBB is common tail. Adjust all other BB's to jump to this one.
  703. // Traversal must be forwards so erases work.
  704. DEBUG(dbgs() << "\nUsing common tail in BB#" << MBB->getNumber()
  705. << " for ");
  706. for (unsigned int i=0, e = SameTails.size(); i != e; ++i) {
  707. if (commonTailIndex == i)
  708. continue;
  709. DEBUG(dbgs() << "BB#" << SameTails[i].getBlock()->getNumber()
  710. << (i == e-1 ? "" : ", "));
  711. // Hack the end off BB i, making it jump to BB commonTailIndex instead.
  712. ReplaceTailWithBranchTo(SameTails[i].getTailStartPos(), MBB);
  713. // BB i is no longer a predecessor of SuccBB; remove it from the worklist.
  714. MergePotentials.erase(SameTails[i].getMPIter());
  715. }
  716. DEBUG(dbgs() << "\n");
  717. // We leave commonTailIndex in the worklist in case there are other blocks
  718. // that match it with a smaller number of instructions.
  719. MadeChange = true;
  720. }
  721. return MadeChange;
  722. }
  723. bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
  724. if (!EnableTailMerge) return false;
  725. bool MadeChange = false;
  726. // First find blocks with no successors.
  727. MergePotentials.clear();
  728. for (MachineFunction::iterator I = MF.begin(), E = MF.end();
  729. I != E && MergePotentials.size() < TailMergeThreshold; ++I) {
  730. if (TriedMerging.count(I))
  731. continue;
  732. if (I->succ_empty())
  733. MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(I), I));
  734. }
  735. // If this is a large problem, avoid visiting the same basic blocks
  736. // multiple times.
  737. if (MergePotentials.size() == TailMergeThreshold)
  738. for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
  739. TriedMerging.insert(MergePotentials[i].getBlock());
  740. // See if we can do any tail merging on those.
  741. if (MergePotentials.size() >= 2)
  742. MadeChange |= TryTailMergeBlocks(NULL, NULL);
  743. // Look at blocks (IBB) with multiple predecessors (PBB).
  744. // We change each predecessor to a canonical form, by
  745. // (1) temporarily removing any unconditional branch from the predecessor
  746. // to IBB, and
  747. // (2) alter conditional branches so they branch to the other block
  748. // not IBB; this may require adding back an unconditional branch to IBB
  749. // later, where there wasn't one coming in. E.g.
  750. // Bcc IBB
  751. // fallthrough to QBB
  752. // here becomes
  753. // Bncc QBB
  754. // with a conceptual B to IBB after that, which never actually exists.
  755. // With those changes, we see whether the predecessors' tails match,
  756. // and merge them if so. We change things out of canonical form and
  757. // back to the way they were later in the process. (OptimizeBranches
  758. // would undo some of this, but we can't use it, because we'd get into
  759. // a compile-time infinite loop repeatedly doing and undoing the same
  760. // transformations.)
  761. for (MachineFunction::iterator I = llvm::next(MF.begin()), E = MF.end();
  762. I != E; ++I) {
  763. if (I->pred_size() >= 2) {
  764. SmallPtrSet<MachineBasicBlock *, 8> UniquePreds;
  765. MachineBasicBlock *IBB = I;
  766. MachineBasicBlock *PredBB = prior(I);
  767. MergePotentials.clear();
  768. for (MachineBasicBlock::pred_iterator P = I->pred_begin(),
  769. E2 = I->pred_end();
  770. P != E2 && MergePotentials.size() < TailMergeThreshold; ++P) {
  771. MachineBasicBlock *PBB = *P;
  772. if (TriedMerging.count(PBB))
  773. continue;
  774. // Skip blocks that loop to themselves, can't tail merge these.
  775. if (PBB == IBB)
  776. continue;
  777. // Visit each predecessor only once.
  778. if (!UniquePreds.insert(PBB))
  779. continue;
  780. // Skip blocks which may jump to a landing pad. Can't tail merge these.
  781. if (PBB->getLandingPadSuccessor())
  782. continue;
  783. MachineBasicBlock *TBB = 0, *FBB = 0;
  784. SmallVector<MachineOperand, 4> Cond;
  785. if (!TII->AnalyzeBranch(*PBB, TBB, FBB, Cond, true)) {
  786. // Failing case: IBB is the target of a cbr, and
  787. // we cannot reverse the branch.
  788. SmallVector<MachineOperand, 4> NewCond(Cond);
  789. if (!Cond.empty() && TBB == IBB) {
  790. if (TII->ReverseBranchCondition(NewCond))
  791. continue;
  792. // This is the QBB case described above
  793. if (!FBB)
  794. FBB = llvm::next(MachineFunction::iterator(PBB));
  795. }
  796. // Failing case: the only way IBB can be reached from PBB is via
  797. // exception handling. Happens for landing pads. Would be nice
  798. // to have a bit in the edge so we didn't have to do all this.
  799. if (IBB->isLandingPad()) {
  800. MachineFunction::iterator IP = PBB; IP++;
  801. MachineBasicBlock *PredNextBB = NULL;
  802. if (IP != MF.end())
  803. PredNextBB = IP;
  804. if (TBB == NULL) {
  805. if (IBB != PredNextBB) // fallthrough
  806. continue;
  807. } else if (FBB) {
  808. if (TBB != IBB && FBB != IBB) // cbr then ubr
  809. continue;
  810. } else if (Cond.empty()) {
  811. if (TBB != IBB) // ubr
  812. continue;
  813. } else {
  814. if (TBB != IBB && IBB != PredNextBB) // cbr
  815. continue;
  816. }
  817. }
  818. // Remove the unconditional branch at the end, if any.
  819. if (TBB && (Cond.empty() || FBB)) {
  820. DebugLoc dl; // FIXME: this is nowhere
  821. TII->RemoveBranch(*PBB);
  822. if (!Cond.empty())
  823. // reinsert conditional branch only, for now
  824. TII->InsertBranch(*PBB, (TBB == IBB) ? FBB : TBB, 0, NewCond, dl);
  825. }
  826. MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(PBB), *P));
  827. }
  828. }
  829. // If this is a large problem, avoid visiting the same basic blocks
  830. // multiple times.
  831. if (MergePotentials.size() == TailMergeThreshold)
  832. for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
  833. TriedMerging.insert(MergePotentials[i].getBlock());
  834. if (MergePotentials.size() >= 2)
  835. MadeChange |= TryTailMergeBlocks(IBB, PredBB);
  836. // Reinsert an unconditional branch if needed.
  837. // The 1 below can occur as a result of removing blocks in
  838. // TryTailMergeBlocks.
  839. PredBB = prior(I); // this may have been changed in TryTailMergeBlocks
  840. if (MergePotentials.size() == 1 &&
  841. MergePotentials.begin()->getBlock() != PredBB)
  842. FixTail(MergePotentials.begin()->getBlock(), IBB, TII);
  843. }
  844. }
  845. return MadeChange;
  846. }
  847. //===----------------------------------------------------------------------===//
  848. // Branch Optimization
  849. //===----------------------------------------------------------------------===//
  850. bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
  851. bool MadeChange = false;
  852. // Make sure blocks are numbered in order
  853. MF.RenumberBlocks();
  854. for (MachineFunction::iterator I = llvm::next(MF.begin()), E = MF.end();
  855. I != E; ) {
  856. MachineBasicBlock *MBB = I++;
  857. MadeChange |= OptimizeBlock(MBB);
  858. // If it is dead, remove it.
  859. if (MBB->pred_empty()) {
  860. RemoveDeadBlock(MBB);
  861. MadeChange = true;
  862. ++NumDeadBlocks;
  863. }
  864. }
  865. return MadeChange;
  866. }
  867. // Blocks should be considered empty if they contain only debug info;
  868. // else the debug info would affect codegen.
  869. static bool IsEmptyBlock(MachineBasicBlock *MBB) {
  870. if (MBB->empty())
  871. return true;
  872. for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
  873. MBBI!=MBBE; ++MBBI) {
  874. if (!MBBI->isDebugValue())
  875. return false;
  876. }
  877. return true;
  878. }
  879. // Blocks with only debug info and branches should be considered the same
  880. // as blocks with only branches.
  881. static bool IsBranchOnlyBlock(MachineBasicBlock *MBB) {
  882. MachineBasicBlock::iterator MBBI, MBBE;
  883. for (MBBI = MBB->begin(), MBBE = MBB->end(); MBBI!=MBBE; ++MBBI) {
  884. if (!MBBI->isDebugValue())
  885. break;
  886. }
  887. return (MBBI->isBranch());
  888. }
  889. /// IsBetterFallthrough - Return true if it would be clearly better to
  890. /// fall-through to MBB1 than to fall through into MBB2. This has to return
  891. /// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
  892. /// result in infinite loops.
  893. static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
  894. MachineBasicBlock *MBB2) {
  895. // Right now, we use a simple heuristic. If MBB2 ends with a call, and
  896. // MBB1 doesn't, we prefer to fall through into MBB1. This allows us to
  897. // optimize branches that branch to either a return block or an assert block
  898. // into a fallthrough to the return.
  899. if (IsEmptyBlock(MBB1) || IsEmptyBlock(MBB2)) return false;
  900. // If there is a clear successor ordering we make sure that one block
  901. // will fall through to the next
  902. if (MBB1->isSuccessor(MBB2)) return true;
  903. if (MBB2->isSuccessor(MBB1)) return false;
  904. // Neither block consists entirely of debug info (per IsEmptyBlock check),
  905. // so we needn't test for falling off the beginning here.
  906. MachineBasicBlock::iterator MBB1I = --MBB1->end();
  907. while (MBB1I->isDebugValue())
  908. --MBB1I;
  909. MachineBasicBlock::iterator MBB2I = --MBB2->end();
  910. while (MBB2I->isDebugValue())
  911. --MBB2I;
  912. return MBB2I->isCall() && !MBB1I->isCall();
  913. }
  914. /// OptimizeBlock - Analyze and optimize control flow related to the specified
  915. /// block. This is never called on the entry block.
  916. bool BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
  917. bool MadeChange = false;
  918. MachineFunction &MF = *MBB->getParent();
  919. DebugLoc dl; // FIXME: this is nowhere
  920. ReoptimizeBlock:
  921. MachineFunction::iterator FallThrough = MBB;
  922. ++FallThrough;
  923. // If this block is empty, make everyone use its fall-through, not the block
  924. // explicitly. Landing pads should not do this since the landing-pad table
  925. // points to this block. Blocks with their addresses taken shouldn't be
  926. // optimized away.
  927. if (IsEmptyBlock(MBB) && !MBB->isLandingPad() && !MBB->hasAddressTaken()) {
  928. // Dead block? Leave for cleanup later.
  929. if (MBB->pred_empty()) return MadeChange;
  930. if (FallThrough == MF.end()) {
  931. // TODO: Simplify preds to not branch here if possible!
  932. } else {
  933. // Rewrite all predecessors of the old block to go to the fallthrough
  934. // instead.
  935. while (!MBB->pred_empty()) {
  936. MachineBasicBlock *Pred = *(MBB->pred_end()-1);
  937. Pred->ReplaceUsesOfBlockWith(MBB, FallThrough);
  938. }
  939. // If MBB was the target of a jump table, update jump tables to go to the
  940. // fallthrough instead.
  941. if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo())
  942. MJTI->ReplaceMBBInJumpTables(MBB, FallThrough);
  943. MadeChange = true;
  944. }
  945. return MadeChange;
  946. }
  947. // Check to see if we can simplify the terminator of the block before this
  948. // one.
  949. MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
  950. MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
  951. SmallVector<MachineOperand, 4> PriorCond;
  952. bool PriorUnAnalyzable =
  953. TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, true);
  954. if (!PriorUnAnalyzable) {
  955. // If the CFG for the prior block has extra edges, remove them.
  956. MadeChange |= PrevBB.CorrectExtraCFGEdges(PriorTBB, PriorFBB,
  957. !PriorCond.empty());
  958. // If the previous branch is conditional and both conditions go to the same
  959. // destination, remove the branch, replacing it with an unconditional one or
  960. // a fall-through.
  961. if (PriorTBB && PriorTBB == PriorFBB) {
  962. TII->RemoveBranch(PrevBB);
  963. PriorCond.clear();
  964. if (PriorTBB != MBB)
  965. TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond, dl);
  966. MadeChange = true;
  967. ++NumBranchOpts;
  968. goto ReoptimizeBlock;
  969. }
  970. // If the previous block unconditionally falls through to this block and
  971. // this block has no other predecessors, move the contents of this block
  972. // into the prior block. This doesn't usually happen when SimplifyCFG
  973. // has been used, but it can happen if tail merging splits a fall-through
  974. // predecessor of a block.
  975. // This has to check PrevBB->succ_size() because EH edges are ignored by
  976. // AnalyzeBranch.
  977. if (PriorCond.empty() && !PriorTBB && MBB->pred_size() == 1 &&
  978. PrevBB.succ_size() == 1 &&
  979. !MBB->hasAddressTaken() && !MBB->isLandingPad()) {
  980. DEBUG(dbgs() << "\nMerging into block: " << PrevBB
  981. << "From MBB: " << *MBB);
  982. // Remove redundant DBG_VALUEs first.
  983. if (PrevBB.begin() != PrevBB.end()) {
  984. MachineBasicBlock::iterator PrevBBIter = PrevBB.end();
  985. --PrevBBIter;
  986. MachineBasicBlock::iterator MBBIter = MBB->begin();
  987. // Check if DBG_VALUE at the end of PrevBB is identical to the
  988. // DBG_VALUE at the beginning of MBB.
  989. while (PrevBBIter != PrevBB.begin() && MBBIter != MBB->end()
  990. && PrevBBIter->isDebugValue() && MBBIter->isDebugValue()) {
  991. if (!MBBIter->isIdenticalTo(PrevBBIter))
  992. break;
  993. MachineInstr *DuplicateDbg = MBBIter;
  994. ++MBBIter; -- PrevBBIter;
  995. DuplicateDbg->eraseFromParent();
  996. }
  997. }
  998. PrevBB.splice(PrevBB.end(), MBB, MBB->begin(), MBB->end());
  999. PrevBB.removeSuccessor(PrevBB.succ_begin());;
  1000. assert(PrevBB.succ_empty());
  1001. PrevBB.transferSuccessors(MBB);
  1002. MadeChange = true;
  1003. return MadeChange;
  1004. }
  1005. // If the previous branch *only* branches to *this* block (conditional or
  1006. // not) remove the branch.
  1007. if (PriorTBB == MBB && PriorFBB == 0) {
  1008. TII->RemoveBranch(PrevBB);
  1009. MadeChange = true;
  1010. ++NumBranchOpts;
  1011. goto ReoptimizeBlock;
  1012. }
  1013. // If the prior block branches somewhere else on the condition and here if
  1014. // the condition is false, remove the uncond second branch.
  1015. if (PriorFBB == MBB) {
  1016. TII->RemoveBranch(PrevBB);
  1017. TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond, dl);
  1018. MadeChange = true;
  1019. ++NumBranchOpts;
  1020. goto ReoptimizeBlock;
  1021. }
  1022. // If the prior block branches here on true and somewhere else on false, and
  1023. // if the branch condition is reversible, reverse the branch to create a
  1024. // fall-through.
  1025. if (PriorTBB == MBB) {
  1026. SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
  1027. if (!TII->ReverseBranchCondition(NewPriorCond)) {
  1028. TII->RemoveBranch(PrevBB);
  1029. TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond, dl);
  1030. MadeChange = true;
  1031. ++NumBranchOpts;
  1032. goto ReoptimizeBlock;
  1033. }
  1034. }
  1035. // If this block has no successors (e.g. it is a return block or ends with
  1036. // a call to a no-return function like abort or __cxa_throw) and if the pred
  1037. // falls through into this block, and if it would otherwise fall through
  1038. // into the block after this, move this block to the end of the function.
  1039. //
  1040. // We consider it more likely that execution will stay in the function (e.g.
  1041. // due to loops) than it is to exit it. This asserts in loops etc, moving
  1042. // the assert condition out of the loop body.
  1043. if (MBB->succ_empty() && !PriorCond.empty() && PriorFBB == 0 &&
  1044. MachineFunction::iterator(PriorTBB) == FallThrough &&
  1045. !MBB->canFallThrough()) {
  1046. bool DoTransform = true;
  1047. // We have to be careful that the succs of PredBB aren't both no-successor
  1048. // blocks. If neither have successors and if PredBB is the second from
  1049. // last block in the function, we'd just keep swapping the two blocks for
  1050. // last. Only do the swap if one is clearly better to fall through than
  1051. // the other.
  1052. if (FallThrough == --MF.end() &&
  1053. !IsBetterFallthrough(PriorTBB, MBB))
  1054. DoTransform = false;
  1055. if (DoTransform) {
  1056. // Reverse the branch so we will fall through on the previous true cond.
  1057. SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
  1058. if (!TII->ReverseBranchCondition(NewPriorCond)) {
  1059. DEBUG(dbgs() << "\nMoving MBB: " << *MBB
  1060. << "To make fallthrough to: " << *PriorTBB << "\n");
  1061. TII->RemoveBranch(PrevBB);
  1062. TII->InsertBranch(PrevBB, MBB, 0, NewPriorCond, dl);
  1063. // Move this block to the end of the function.
  1064. MBB->moveAfter(--MF.end());
  1065. MadeChange = true;
  1066. ++NumBranchOpts;
  1067. return MadeChange;
  1068. }
  1069. }
  1070. }
  1071. }
  1072. // Analyze the branch in the current block.
  1073. MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
  1074. SmallVector<MachineOperand, 4> CurCond;
  1075. bool CurUnAnalyzable= TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond, true);
  1076. if (!CurUnAnalyzable) {
  1077. // If the CFG for the prior block has extra edges, remove them.
  1078. MadeChange |= MBB->CorrectExtraCFGEdges(CurTBB, CurFBB, !CurCond.empty());
  1079. // If this is a two-way branch, and the FBB branches to this block, reverse
  1080. // the condition so the single-basic-block loop is faster. Instead of:
  1081. // Loop: xxx; jcc Out; jmp Loop
  1082. // we want:
  1083. // Loop: xxx; jncc Loop; jmp Out
  1084. if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
  1085. SmallVector<MachineOperand, 4> NewCond(CurCond);
  1086. if (!TII->ReverseBranchCondition(NewCond)) {
  1087. TII->RemoveBranch(*MBB);
  1088. TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond, dl);
  1089. MadeChange = true;
  1090. ++NumBranchOpts;
  1091. goto ReoptimizeBlock;
  1092. }
  1093. }
  1094. // If this branch is the only thing in its block, see if we can forward
  1095. // other blocks across it.
  1096. if (CurTBB && CurCond.empty() && CurFBB == 0 &&
  1097. IsBranchOnlyBlock(MBB) && CurTBB != MBB &&
  1098. !MBB->hasAddressTaken()) {
  1099. // This block may contain just an unconditional branch. Because there can
  1100. // be 'non-branch terminators' in the block, try removing the branch and
  1101. // then seeing if the block is empty.
  1102. TII->RemoveBranch(*MBB);
  1103. // If the only things remaining in the block are debug info, remove these
  1104. // as well, so this will behave the same as an empty block in non-debug
  1105. // mode.
  1106. if (!MBB->empty()) {
  1107. bool NonDebugInfoFound = false;
  1108. for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
  1109. I != E; ++I) {
  1110. if (!I->isDebugValue()) {
  1111. NonDebugInfoFound = true;
  1112. break;
  1113. }
  1114. }
  1115. if (!NonDebugInfoFound)
  1116. // Make the block empty, losing the debug info (we could probably
  1117. // improve this in some cases.)
  1118. MBB->erase(MBB->begin(), MBB->end());
  1119. }
  1120. // If this block is just an unconditional branch to CurTBB, we can
  1121. // usually completely eliminate the block. The only case we cannot
  1122. // completely eliminate the block is when the block before this one
  1123. // falls through into MBB and we can't understand the prior block's branch
  1124. // condition.
  1125. if (MBB->empty()) {
  1126. bool PredHasNoFallThrough = !PrevBB.canFallThrough();
  1127. if (PredHasNoFallThrough || !PriorUnAnalyzable ||
  1128. !PrevBB.isSuccessor(MBB)) {
  1129. // If the prior block falls through into us, turn it into an
  1130. // explicit branch to us to make updates simpler.
  1131. if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
  1132. PriorTBB != MBB && PriorFBB != MBB) {
  1133. if (PriorTBB == 0) {
  1134. assert(PriorCond.empty() && PriorFBB == 0 &&
  1135. "Bad branch analysis");
  1136. PriorTBB = MBB;
  1137. } else {
  1138. assert(PriorFBB == 0 && "Machine CFG out of date!");
  1139. PriorFBB = MBB;
  1140. }
  1141. TII->RemoveBranch(PrevBB);
  1142. TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, dl);
  1143. }
  1144. // Iterate through all the predecessors, revectoring each in-turn.
  1145. size_t PI = 0;
  1146. bool DidChange = false;
  1147. bool HasBranchToSelf = false;
  1148. while(PI != MBB->pred_size()) {
  1149. MachineBasicBlock *PMBB = *(MBB->pred_begin() + PI);
  1150. if (PMBB == MBB) {
  1151. // If this block has an uncond branch to itself, leave it.
  1152. ++PI;
  1153. HasBranchToSelf = true;
  1154. } else {
  1155. DidChange = true;
  1156. PMBB->ReplaceUsesOfBlockWith(MBB, CurTBB);
  1157. // If this change resulted in PMBB ending in a conditional
  1158. // branch where both conditions go to the same destination,
  1159. // change this to an unconditional branch (and fix the CFG).
  1160. MachineBasicBlock *NewCurTBB = 0, *NewCurFBB = 0;
  1161. SmallVector<MachineOperand, 4> NewCurCond;
  1162. bool NewCurUnAnalyzable = TII->AnalyzeBranch(*PMBB, NewCurTBB,
  1163. NewCurFBB, NewCurCond, true);
  1164. if (!NewCurUnAnalyzable && NewCurTBB && NewCurTBB == NewCurFBB) {
  1165. TII->RemoveBranch(*PMBB);
  1166. NewCurCond.clear();
  1167. TII->InsertBranch(*PMBB, NewCurTBB, 0, NewCurCond, dl);
  1168. MadeChange = true;
  1169. ++NumBranchOpts;
  1170. PMBB->CorrectExtraCFGEdges(NewCurTBB, 0, false);
  1171. }
  1172. }
  1173. }
  1174. // Change any jumptables to go to the new MBB.
  1175. if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo())
  1176. MJTI->ReplaceMBBInJumpTables(MBB, CurTBB);
  1177. if (DidChange) {
  1178. ++NumBranchOpts;
  1179. MadeChange = true;
  1180. if (!HasBranchToSelf) return MadeChange;
  1181. }
  1182. }
  1183. }
  1184. // Add the branch back if the block is more than just an uncond branch.
  1185. TII->InsertBranch(*MBB, CurTBB, 0, CurCond, dl);
  1186. }
  1187. }
  1188. // If the prior block doesn't fall through into this block, and if this
  1189. // block doesn't fall through into some other block, see if we can find a
  1190. // place to move this block where a fall-through will happen.
  1191. if (!PrevBB.canFallThrough()) {
  1192. // Now we know that there was no fall-through into this block, check to
  1193. // see if it has a fall-through into its successor.
  1194. bool CurFallsThru = MBB->canFallThrough();
  1195. if (!MBB->isLandingPad()) {
  1196. // Check all the predecessors of this block. If one of them has no fall
  1197. // throughs, move this block right after it.
  1198. for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
  1199. E = MBB->pred_end(); PI != E; ++PI) {
  1200. // Analyze the branch at the end of the pred.
  1201. MachineBasicBlock *PredBB = *PI;
  1202. MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
  1203. MachineBasicBlock *PredTBB = 0, *PredFBB = 0;
  1204. SmallVector<MachineOperand, 4> PredCond;
  1205. if (PredBB != MBB && !PredBB->canFallThrough() &&
  1206. !TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true)
  1207. && (!CurFallsThru || !CurTBB || !CurFBB)
  1208. && (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
  1209. // If the current block doesn't fall through, just move it.
  1210. // If the current block can fall through and does not end with a
  1211. // conditional branch, we need to append an unconditional jump to
  1212. // the (current) next block. To avoid a possible compile-time
  1213. // infinite loop, move blocks only backward in this case.
  1214. // Also, if there are already 2 branches here, we cannot add a third;
  1215. // this means we have the case
  1216. // Bcc next
  1217. // B elsewhere
  1218. // next:
  1219. if (CurFallsThru) {
  1220. MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(MBB));
  1221. CurCond.clear();
  1222. TII->InsertBranch(*MBB, NextBB, 0, CurCond, dl);
  1223. }
  1224. MBB->moveAfter(PredBB);
  1225. MadeChange = true;
  1226. goto ReoptimizeBlock;
  1227. }
  1228. }
  1229. }
  1230. if (!CurFallsThru) {
  1231. // Check all successors to see if we can move this block before it.
  1232. for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
  1233. E = MBB->succ_end(); SI != E; ++SI) {
  1234. // Analyze the branch at the end of the block before the succ.
  1235. MachineBasicBlock *SuccBB = *SI;
  1236. MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
  1237. // If this block doesn't already fall-through to that successor, and if
  1238. // the succ doesn't already have a block that can fall through into it,
  1239. // and if the successor isn't an EH destination, we can arrange for the
  1240. // fallthrough to happen.
  1241. if (SuccBB != MBB && &*SuccPrev != MBB &&
  1242. !SuccPrev->canFallThrough() && !CurUnAnalyzable &&
  1243. !SuccBB->isLandingPad()) {
  1244. MBB->moveBefore(SuccBB);
  1245. MadeChange = true;
  1246. goto ReoptimizeBlock;
  1247. }
  1248. }
  1249. // Okay, there is no really great place to put this block. If, however,
  1250. // the block before this one would be a fall-through if this block were
  1251. // removed, move this block to the end of the function.
  1252. MachineBasicBlock *PrevTBB = 0, *PrevFBB = 0;
  1253. SmallVector<MachineOperand, 4> PrevCond;
  1254. if (FallThrough != MF.end() &&
  1255. !TII->AnalyzeBranch(PrevBB, PrevTBB, PrevFBB, PrevCond, true) &&
  1256. PrevBB.isSuccessor(FallThrough)) {
  1257. MBB->moveAfter(--MF.end());
  1258. MadeChange = true;
  1259. return MadeChange;
  1260. }
  1261. }
  1262. }
  1263. return MadeChange;
  1264. }
  1265. //===----------------------------------------------------------------------===//
  1266. // Hoist Common Code
  1267. //===----------------------------------------------------------------------===//
  1268. /// HoistCommonCode - Hoist common instruction sequences at the start of basic
  1269. /// blocks to their common predecessor.
  1270. bool BranchFolder::HoistCommonCode(MachineFunction &MF) {
  1271. bool MadeChange = false;
  1272. for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ) {
  1273. MachineBasicBlock *MBB = I++;
  1274. MadeChange |= HoistCommonCodeInSuccs(MBB);
  1275. }
  1276. return MadeChange;
  1277. }
  1278. /// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
  1279. /// its 'true' successor.
  1280. static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
  1281. MachineBasicBlock *TrueBB) {
  1282. for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
  1283. E = BB->succ_end(); SI != E; ++SI) {
  1284. MachineBasicBlock *SuccBB = *SI;
  1285. if (SuccBB != TrueBB)
  1286. return SuccBB;
  1287. }
  1288. return NULL;
  1289. }
  1290. /// findHoistingInsertPosAndDeps - Find the location to move common instructions
  1291. /// in successors to. The location is ususally just before the terminator,
  1292. /// however if the terminator is a conditional branch and its previous
  1293. /// instruction is the flag setting instruction, the previous instruction is
  1294. /// the preferred location. This function also gathers uses and defs of the
  1295. /// instructions from the insertion point to the end of the block. The data is
  1296. /// used by HoistCommonCodeInSuccs to ensure safety.
  1297. static
  1298. MachineBasicBlock::iterator findHoistingInsertPosAndDeps(MachineBasicBlock *MBB,
  1299. const TargetInstrInfo *TII,
  1300. const TargetRegisterInfo *TRI,
  1301. SmallSet<unsigned,4> &Uses,
  1302. SmallSet<unsigned,4> &Defs) {
  1303. MachineBasicBlock::iterator Loc = MBB->getFirstTerminator();
  1304. if (!TII->isUnpredicatedTerminator(Loc))
  1305. return MBB->end();
  1306. for (unsigned i = 0, e = Loc->getNumOperands(); i != e; ++i) {
  1307. const MachineOperand &MO = Loc->getOperand(i);
  1308. if (!MO.isReg())
  1309. continue;
  1310. unsigned Reg = MO.getReg();
  1311. if (!Reg)
  1312. continue;
  1313. if (MO.isUse()) {
  1314. Uses.insert(Reg);
  1315. for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
  1316. Uses.insert(*AS);
  1317. } else if (!MO.isDead())
  1318. // Don't try to hoist code in the rare case the terminator defines a
  1319. // register that is later used.
  1320. return MBB->end();
  1321. }
  1322. if (Uses.empty())
  1323. return Loc;
  1324. if (Loc == MBB->begin())
  1325. return MBB->end();
  1326. // The terminator is probably a conditional branch, try not to separate the
  1327. // branch from condition setting instruction.
  1328. MachineBasicBlock::iterator PI = Loc;
  1329. --PI;
  1330. while (PI != MBB->begin() && Loc->isDebugValue())
  1331. --PI;
  1332. bool IsDef = false;
  1333. for (unsigned i = 0, e = PI->getNumOperands(); !IsDef && i != e; ++i) {
  1334. const MachineOperand &MO = PI->getOperand(i);
  1335. if (!MO.isReg() || MO.isUse())
  1336. continue;
  1337. unsigned Reg = MO.getReg();
  1338. if (!Reg)
  1339. continue;
  1340. if (Uses.count(Reg))
  1341. IsDef = true;
  1342. }
  1343. if (!IsDef)
  1344. // The condition setting instruction is not just before the conditional
  1345. // branch.
  1346. return Loc;
  1347. // Be conservative, don't insert instruction above something that may have
  1348. // side-effects. And since it's potentially bad to separate flag setting
  1349. // instruction from the conditional branch, just abort the optimization
  1350. // completely.
  1351. // Also avoid moving code above predicated instruction since it's hard to
  1352. // reason about register liveness with predicated instruction.
  1353. bool DontMoveAcrossStore = true;
  1354. if (!PI->isSafeToMove(TII, 0, DontMoveAcrossStore) ||
  1355. TII->isPredicated(PI))
  1356. return MBB->end();
  1357. // Find out what registers are live. Note this routine is ignoring other live
  1358. // registers which are only used by instructions in successor blocks.
  1359. for (unsigned i = 0, e = PI->getNumOperands(); i != e; ++i) {
  1360. const MachineOperand &MO = PI->getOperand(i);
  1361. if (!MO.isReg())
  1362. continue;
  1363. unsigned Reg = MO.getReg();
  1364. if (!Reg)
  1365. continue;
  1366. if (MO.isUse()) {
  1367. Uses.insert(Reg);
  1368. for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
  1369. Uses.insert(*AS);
  1370. } else {
  1371. if (Uses.count(Reg)) {
  1372. Uses.erase(Reg);
  1373. for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR)
  1374. Uses.erase(*SR); // Use getSubRegisters to be conservative
  1375. }
  1376. Defs.insert(Reg);
  1377. for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
  1378. Defs.insert(*AS);
  1379. }
  1380. }
  1381. return PI;
  1382. }
  1383. /// HoistCommonCodeInSuccs - If the successors of MBB has common instruction
  1384. /// sequence at the start of the function, move the instructions before MBB
  1385. /// terminator if it's legal.
  1386. bool BranchFolder::HoistCommonCodeInSuccs(MachineBasicBlock *MBB) {
  1387. MachineBasicBlock *TBB = 0, *FBB = 0;
  1388. SmallVector<MachineOperand, 4> Cond;
  1389. if (TII->AnalyzeBranch(*MBB, TBB, FBB, Cond, true) || !TBB || Cond.empty())
  1390. return false;
  1391. if (!FBB) FBB = findFalseBlock(MBB, TBB);
  1392. if (!FBB)
  1393. // Malformed bcc? True and false blocks are the same?
  1394. return false;
  1395. // Restrict the optimization to cases where MBB is the only predecessor,
  1396. // it is an obvious win.
  1397. if (TBB->pred_size() > 1 || FBB->pred_size() > 1)
  1398. return false;
  1399. // Find a suitable position to hoist the common instructions to. Also figure
  1400. // out which registers are used or defined by instructions from the insertion
  1401. // point to the end of the block.
  1402. SmallSet<unsigned, 4> Uses, Defs;
  1403. MachineBasicBlock::iterator Loc =
  1404. findHoistingInsertPosAndDeps(MBB, TII, TRI, Uses, Defs);
  1405. if (Loc == MBB->end())
  1406. return false;
  1407. bool HasDups = false;
  1408. SmallVector<unsigned, 4> LocalDefs;
  1409. SmallSet<unsigned, 4> LocalDefsSet;
  1410. MachineBasicBlock::iterator TIB = TBB->begin();
  1411. MachineBasicBlock::iterator FIB = FBB->begin();
  1412. MachineBasicBlock::iterator TIE = TBB->end();
  1413. MachineBasicBlock::iterator FIE = FBB->end();
  1414. while (TIB != TIE && FIB != FIE) {
  1415. // Skip dbg_value instructions. These do not count.
  1416. if (TIB->isDebugValue()) {
  1417. while (TIB != TIE && TIB->isDebugValue())
  1418. ++TIB;
  1419. if (TIB == TIE)
  1420. break;
  1421. }
  1422. if (FIB->isDebugValue()) {
  1423. while (FIB != FIE && FIB->isDebugValue())
  1424. ++FIB;
  1425. if (FIB == FIE)
  1426. break;
  1427. }
  1428. if (!TIB->isIdenticalTo(FIB, MachineInstr::CheckKillDead))
  1429. break;
  1430. if (TII->isPredicated(TIB))
  1431. // Hard to reason about register liveness with predicated instruction.
  1432. break;
  1433. bool IsSafe = true;
  1434. for (unsigned i = 0, e = TIB->getNumOperands(); i != e; ++i) {
  1435. MachineOperand &MO = TIB->getOperand(i);
  1436. if (!MO.isReg())
  1437. continue;
  1438. unsigned Reg = MO.getReg();
  1439. if (!Reg)
  1440. continue;
  1441. if (MO.isDef()) {
  1442. if (Uses.count(Reg)) {
  1443. // Avoid clobbering a register that's used by the instruction at
  1444. // the point of insertion.
  1445. IsSafe = false;
  1446. break;
  1447. }
  1448. if (Defs.count(Reg) && !MO.isDead()) {
  1449. // Don't hoist the instruction if the def would be clobber by the
  1450. // instruction at the point insertion. FIXME: This is overly
  1451. // conservative. It should be possible to hoist the instructions
  1452. // in BB2 in the following example:
  1453. // BB1:
  1454. // r1, eflag = op1 r2, r3
  1455. // brcc eflag
  1456. //
  1457. // BB2:
  1458. // r1 = op2, ...
  1459. // = op3, r1<kill>
  1460. IsSafe = false;
  1461. break;
  1462. }
  1463. } else if (!LocalDefsSet.count(Reg)) {
  1464. if (Defs.count(Reg)) {
  1465. // Use is defined by the instruction at the point of insertion.
  1466. IsSafe = false;
  1467. break;
  1468. }
  1469. if (MO.isKill() && Uses.count(Reg))
  1470. // Kills a register that's read by the instruction at the point of
  1471. // insertion. Remove the kill marker.
  1472. MO.setIsKill(false);
  1473. }
  1474. }
  1475. if (!IsSafe)
  1476. break;
  1477. bool DontMoveAcrossStore = true;
  1478. if (!TIB->isSafeToMove(TII, 0, DontMoveAcrossStore))
  1479. break;
  1480. // Remove kills from LocalDefsSet, these registers had short live ranges.
  1481. for (unsigned i = 0, e = TIB->getNumOperands(); i != e; ++i) {
  1482. MachineOperand &MO = TIB->getOperand(i);
  1483. if (!MO.isReg() || !MO.isUse() || !MO.isKill())
  1484. continue;
  1485. unsigned Reg = MO.getReg();
  1486. if (!Reg || !LocalDefsSet.count(Reg))
  1487. continue;
  1488. for (const unsigned *OR = TRI->getOverlaps(Reg); *OR; ++OR)
  1489. LocalDefsSet.erase(*OR);
  1490. }
  1491. // Track local defs so we can update liveins.
  1492. for (unsigned i = 0, e = TIB->getNumOperands(); i != e; ++i) {
  1493. MachineOperand &MO = TIB->getOperand(i);
  1494. if (!MO.isReg() || !MO.isDef() || MO.isDead())
  1495. continue;
  1496. unsigned Reg = MO.getReg();
  1497. if (!Reg)
  1498. continue;
  1499. LocalDefs.push_back(Reg);
  1500. for (const unsigned *OR = TRI->getOverlaps(Reg); *OR; ++OR)
  1501. LocalDefsSet.insert(*OR);
  1502. }
  1503. HasDups = true;;
  1504. ++TIB;
  1505. ++FIB;
  1506. }
  1507. if (!HasDups)
  1508. return false;
  1509. MBB->splice(Loc, TBB, TBB->begin(), TIB);
  1510. FBB->erase(FBB->begin(), FIB);
  1511. // Update livein's.
  1512. for (unsigned i = 0, e = LocalDefs.size(); i != e; ++i) {
  1513. unsigned Def = LocalDefs[i];
  1514. if (LocalDefsSet.count(Def)) {
  1515. TBB->addLiveIn(Def);
  1516. FBB->addLiveIn(Def);
  1517. }
  1518. }
  1519. ++NumHoist;
  1520. return true;
  1521. }