BranchFolding.cpp 81 KB

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