BranchFolding.cpp 65 KB

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