BranchFolding.cpp 75 KB

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