TailDuplicator.cpp 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007
  1. //===- TailDuplicator.cpp - Duplicate blocks into predecessors' tails -----===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This utility class duplicates basic blocks ending in unconditional branches
  10. // into the tails of their predecessors.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/CodeGen/TailDuplicator.h"
  14. #include "llvm/ADT/DenseMap.h"
  15. #include "llvm/ADT/DenseSet.h"
  16. #include "llvm/ADT/STLExtras.h"
  17. #include "llvm/ADT/SetVector.h"
  18. #include "llvm/ADT/SmallPtrSet.h"
  19. #include "llvm/ADT/SmallVector.h"
  20. #include "llvm/ADT/Statistic.h"
  21. #include "llvm/CodeGen/MachineBasicBlock.h"
  22. #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
  23. #include "llvm/CodeGen/MachineFunction.h"
  24. #include "llvm/CodeGen/MachineInstr.h"
  25. #include "llvm/CodeGen/MachineInstrBuilder.h"
  26. #include "llvm/CodeGen/MachineOperand.h"
  27. #include "llvm/CodeGen/MachineRegisterInfo.h"
  28. #include "llvm/CodeGen/MachineSSAUpdater.h"
  29. #include "llvm/CodeGen/TargetInstrInfo.h"
  30. #include "llvm/CodeGen/TargetRegisterInfo.h"
  31. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  32. #include "llvm/IR/DebugLoc.h"
  33. #include "llvm/IR/Function.h"
  34. #include "llvm/Support/CommandLine.h"
  35. #include "llvm/Support/Debug.h"
  36. #include "llvm/Support/ErrorHandling.h"
  37. #include "llvm/Support/raw_ostream.h"
  38. #include "llvm/Target/TargetMachine.h"
  39. #include <algorithm>
  40. #include <cassert>
  41. #include <iterator>
  42. #include <utility>
  43. using namespace llvm;
  44. #define DEBUG_TYPE "tailduplication"
  45. STATISTIC(NumTails, "Number of tails duplicated");
  46. STATISTIC(NumTailDups, "Number of tail duplicated blocks");
  47. STATISTIC(NumTailDupAdded,
  48. "Number of instructions added due to tail duplication");
  49. STATISTIC(NumTailDupRemoved,
  50. "Number of instructions removed due to tail duplication");
  51. STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
  52. STATISTIC(NumAddedPHIs, "Number of phis added");
  53. // Heuristic for tail duplication.
  54. static cl::opt<unsigned> TailDuplicateSize(
  55. "tail-dup-size",
  56. cl::desc("Maximum instructions to consider tail duplicating"), cl::init(2),
  57. cl::Hidden);
  58. static cl::opt<unsigned> TailDupIndirectBranchSize(
  59. "tail-dup-indirect-size",
  60. cl::desc("Maximum instructions to consider tail duplicating blocks that "
  61. "end with indirect branches."), cl::init(20),
  62. cl::Hidden);
  63. static cl::opt<bool>
  64. TailDupVerify("tail-dup-verify",
  65. cl::desc("Verify sanity of PHI instructions during taildup"),
  66. cl::init(false), cl::Hidden);
  67. static cl::opt<unsigned> TailDupLimit("tail-dup-limit", cl::init(~0U),
  68. cl::Hidden);
  69. void TailDuplicator::initMF(MachineFunction &MFin, bool PreRegAlloc,
  70. const MachineBranchProbabilityInfo *MBPIin,
  71. bool LayoutModeIn, unsigned TailDupSizeIn) {
  72. MF = &MFin;
  73. TII = MF->getSubtarget().getInstrInfo();
  74. TRI = MF->getSubtarget().getRegisterInfo();
  75. MRI = &MF->getRegInfo();
  76. MMI = &MF->getMMI();
  77. MBPI = MBPIin;
  78. TailDupSize = TailDupSizeIn;
  79. assert(MBPI != nullptr && "Machine Branch Probability Info required");
  80. LayoutMode = LayoutModeIn;
  81. this->PreRegAlloc = PreRegAlloc;
  82. }
  83. static void VerifyPHIs(MachineFunction &MF, bool CheckExtra) {
  84. for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ++I) {
  85. MachineBasicBlock *MBB = &*I;
  86. SmallSetVector<MachineBasicBlock *, 8> Preds(MBB->pred_begin(),
  87. MBB->pred_end());
  88. MachineBasicBlock::iterator MI = MBB->begin();
  89. while (MI != MBB->end()) {
  90. if (!MI->isPHI())
  91. break;
  92. for (MachineBasicBlock *PredBB : Preds) {
  93. bool Found = false;
  94. for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
  95. MachineBasicBlock *PHIBB = MI->getOperand(i + 1).getMBB();
  96. if (PHIBB == PredBB) {
  97. Found = true;
  98. break;
  99. }
  100. }
  101. if (!Found) {
  102. dbgs() << "Malformed PHI in " << printMBBReference(*MBB) << ": "
  103. << *MI;
  104. dbgs() << " missing input from predecessor "
  105. << printMBBReference(*PredBB) << '\n';
  106. llvm_unreachable(nullptr);
  107. }
  108. }
  109. for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
  110. MachineBasicBlock *PHIBB = MI->getOperand(i + 1).getMBB();
  111. if (CheckExtra && !Preds.count(PHIBB)) {
  112. dbgs() << "Warning: malformed PHI in " << printMBBReference(*MBB)
  113. << ": " << *MI;
  114. dbgs() << " extra input from predecessor "
  115. << printMBBReference(*PHIBB) << '\n';
  116. llvm_unreachable(nullptr);
  117. }
  118. if (PHIBB->getNumber() < 0) {
  119. dbgs() << "Malformed PHI in " << printMBBReference(*MBB) << ": "
  120. << *MI;
  121. dbgs() << " non-existing " << printMBBReference(*PHIBB) << '\n';
  122. llvm_unreachable(nullptr);
  123. }
  124. }
  125. ++MI;
  126. }
  127. }
  128. }
  129. /// Tail duplicate the block and cleanup.
  130. /// \p IsSimple - return value of isSimpleBB
  131. /// \p MBB - block to be duplicated
  132. /// \p ForcedLayoutPred - If non-null, treat this block as the layout
  133. /// predecessor, instead of using the ordering in MF
  134. /// \p DuplicatedPreds - if non-null, \p DuplicatedPreds will contain a list of
  135. /// all Preds that received a copy of \p MBB.
  136. /// \p RemovalCallback - if non-null, called just before MBB is deleted.
  137. bool TailDuplicator::tailDuplicateAndUpdate(
  138. bool IsSimple, MachineBasicBlock *MBB,
  139. MachineBasicBlock *ForcedLayoutPred,
  140. SmallVectorImpl<MachineBasicBlock*> *DuplicatedPreds,
  141. function_ref<void(MachineBasicBlock *)> *RemovalCallback) {
  142. // Save the successors list.
  143. SmallSetVector<MachineBasicBlock *, 8> Succs(MBB->succ_begin(),
  144. MBB->succ_end());
  145. SmallVector<MachineBasicBlock *, 8> TDBBs;
  146. SmallVector<MachineInstr *, 16> Copies;
  147. if (!tailDuplicate(IsSimple, MBB, ForcedLayoutPred, TDBBs, Copies))
  148. return false;
  149. ++NumTails;
  150. SmallVector<MachineInstr *, 8> NewPHIs;
  151. MachineSSAUpdater SSAUpdate(*MF, &NewPHIs);
  152. // TailBB's immediate successors are now successors of those predecessors
  153. // which duplicated TailBB. Add the predecessors as sources to the PHI
  154. // instructions.
  155. bool isDead = MBB->pred_empty() && !MBB->hasAddressTaken();
  156. if (PreRegAlloc)
  157. updateSuccessorsPHIs(MBB, isDead, TDBBs, Succs);
  158. // If it is dead, remove it.
  159. if (isDead) {
  160. NumTailDupRemoved += MBB->size();
  161. removeDeadBlock(MBB, RemovalCallback);
  162. ++NumDeadBlocks;
  163. }
  164. // Update SSA form.
  165. if (!SSAUpdateVRs.empty()) {
  166. for (unsigned i = 0, e = SSAUpdateVRs.size(); i != e; ++i) {
  167. unsigned VReg = SSAUpdateVRs[i];
  168. SSAUpdate.Initialize(VReg);
  169. // If the original definition is still around, add it as an available
  170. // value.
  171. MachineInstr *DefMI = MRI->getVRegDef(VReg);
  172. MachineBasicBlock *DefBB = nullptr;
  173. if (DefMI) {
  174. DefBB = DefMI->getParent();
  175. SSAUpdate.AddAvailableValue(DefBB, VReg);
  176. }
  177. // Add the new vregs as available values.
  178. DenseMap<unsigned, AvailableValsTy>::iterator LI =
  179. SSAUpdateVals.find(VReg);
  180. for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
  181. MachineBasicBlock *SrcBB = LI->second[j].first;
  182. unsigned SrcReg = LI->second[j].second;
  183. SSAUpdate.AddAvailableValue(SrcBB, SrcReg);
  184. }
  185. // Rewrite uses that are outside of the original def's block.
  186. MachineRegisterInfo::use_iterator UI = MRI->use_begin(VReg);
  187. while (UI != MRI->use_end()) {
  188. MachineOperand &UseMO = *UI;
  189. MachineInstr *UseMI = UseMO.getParent();
  190. ++UI;
  191. if (UseMI->isDebugValue()) {
  192. // SSAUpdate can replace the use with an undef. That creates
  193. // a debug instruction that is a kill.
  194. // FIXME: Should it SSAUpdate job to delete debug instructions
  195. // instead of replacing the use with undef?
  196. UseMI->eraseFromParent();
  197. continue;
  198. }
  199. if (UseMI->getParent() == DefBB && !UseMI->isPHI())
  200. continue;
  201. SSAUpdate.RewriteUse(UseMO);
  202. }
  203. }
  204. SSAUpdateVRs.clear();
  205. SSAUpdateVals.clear();
  206. }
  207. // Eliminate some of the copies inserted by tail duplication to maintain
  208. // SSA form.
  209. for (unsigned i = 0, e = Copies.size(); i != e; ++i) {
  210. MachineInstr *Copy = Copies[i];
  211. if (!Copy->isCopy())
  212. continue;
  213. Register Dst = Copy->getOperand(0).getReg();
  214. Register Src = Copy->getOperand(1).getReg();
  215. if (MRI->hasOneNonDBGUse(Src) &&
  216. MRI->constrainRegClass(Src, MRI->getRegClass(Dst))) {
  217. // Copy is the only use. Do trivial copy propagation here.
  218. MRI->replaceRegWith(Dst, Src);
  219. Copy->eraseFromParent();
  220. }
  221. }
  222. if (NewPHIs.size())
  223. NumAddedPHIs += NewPHIs.size();
  224. if (DuplicatedPreds)
  225. *DuplicatedPreds = std::move(TDBBs);
  226. return true;
  227. }
  228. /// Look for small blocks that are unconditionally branched to and do not fall
  229. /// through. Tail-duplicate their instructions into their predecessors to
  230. /// eliminate (dynamic) branches.
  231. bool TailDuplicator::tailDuplicateBlocks() {
  232. bool MadeChange = false;
  233. if (PreRegAlloc && TailDupVerify) {
  234. LLVM_DEBUG(dbgs() << "\n*** Before tail-duplicating\n");
  235. VerifyPHIs(*MF, true);
  236. }
  237. for (MachineFunction::iterator I = ++MF->begin(), E = MF->end(); I != E;) {
  238. MachineBasicBlock *MBB = &*I++;
  239. if (NumTails == TailDupLimit)
  240. break;
  241. bool IsSimple = isSimpleBB(MBB);
  242. if (!shouldTailDuplicate(IsSimple, *MBB))
  243. continue;
  244. MadeChange |= tailDuplicateAndUpdate(IsSimple, MBB, nullptr);
  245. }
  246. if (PreRegAlloc && TailDupVerify)
  247. VerifyPHIs(*MF, false);
  248. return MadeChange;
  249. }
  250. static bool isDefLiveOut(unsigned Reg, MachineBasicBlock *BB,
  251. const MachineRegisterInfo *MRI) {
  252. for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
  253. if (UseMI.isDebugValue())
  254. continue;
  255. if (UseMI.getParent() != BB)
  256. return true;
  257. }
  258. return false;
  259. }
  260. static unsigned getPHISrcRegOpIdx(MachineInstr *MI, MachineBasicBlock *SrcBB) {
  261. for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2)
  262. if (MI->getOperand(i + 1).getMBB() == SrcBB)
  263. return i;
  264. return 0;
  265. }
  266. // Remember which registers are used by phis in this block. This is
  267. // used to determine which registers are liveout while modifying the
  268. // block (which is why we need to copy the information).
  269. static void getRegsUsedByPHIs(const MachineBasicBlock &BB,
  270. DenseSet<unsigned> *UsedByPhi) {
  271. for (const auto &MI : BB) {
  272. if (!MI.isPHI())
  273. break;
  274. for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
  275. Register SrcReg = MI.getOperand(i).getReg();
  276. UsedByPhi->insert(SrcReg);
  277. }
  278. }
  279. }
  280. /// Add a definition and source virtual registers pair for SSA update.
  281. void TailDuplicator::addSSAUpdateEntry(unsigned OrigReg, unsigned NewReg,
  282. MachineBasicBlock *BB) {
  283. DenseMap<unsigned, AvailableValsTy>::iterator LI =
  284. SSAUpdateVals.find(OrigReg);
  285. if (LI != SSAUpdateVals.end())
  286. LI->second.push_back(std::make_pair(BB, NewReg));
  287. else {
  288. AvailableValsTy Vals;
  289. Vals.push_back(std::make_pair(BB, NewReg));
  290. SSAUpdateVals.insert(std::make_pair(OrigReg, Vals));
  291. SSAUpdateVRs.push_back(OrigReg);
  292. }
  293. }
  294. /// Process PHI node in TailBB by turning it into a copy in PredBB. Remember the
  295. /// source register that's contributed by PredBB and update SSA update map.
  296. void TailDuplicator::processPHI(
  297. MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB,
  298. DenseMap<unsigned, RegSubRegPair> &LocalVRMap,
  299. SmallVectorImpl<std::pair<unsigned, RegSubRegPair>> &Copies,
  300. const DenseSet<unsigned> &RegsUsedByPhi, bool Remove) {
  301. Register DefReg = MI->getOperand(0).getReg();
  302. unsigned SrcOpIdx = getPHISrcRegOpIdx(MI, PredBB);
  303. assert(SrcOpIdx && "Unable to find matching PHI source?");
  304. Register SrcReg = MI->getOperand(SrcOpIdx).getReg();
  305. unsigned SrcSubReg = MI->getOperand(SrcOpIdx).getSubReg();
  306. const TargetRegisterClass *RC = MRI->getRegClass(DefReg);
  307. LocalVRMap.insert(std::make_pair(DefReg, RegSubRegPair(SrcReg, SrcSubReg)));
  308. // Insert a copy from source to the end of the block. The def register is the
  309. // available value liveout of the block.
  310. Register NewDef = MRI->createVirtualRegister(RC);
  311. Copies.push_back(std::make_pair(NewDef, RegSubRegPair(SrcReg, SrcSubReg)));
  312. if (isDefLiveOut(DefReg, TailBB, MRI) || RegsUsedByPhi.count(DefReg))
  313. addSSAUpdateEntry(DefReg, NewDef, PredBB);
  314. if (!Remove)
  315. return;
  316. // Remove PredBB from the PHI node.
  317. MI->RemoveOperand(SrcOpIdx + 1);
  318. MI->RemoveOperand(SrcOpIdx);
  319. if (MI->getNumOperands() == 1)
  320. MI->eraseFromParent();
  321. }
  322. /// Duplicate a TailBB instruction to PredBB and update
  323. /// the source operands due to earlier PHI translation.
  324. void TailDuplicator::duplicateInstruction(
  325. MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB,
  326. DenseMap<unsigned, RegSubRegPair> &LocalVRMap,
  327. const DenseSet<unsigned> &UsedByPhi) {
  328. // Allow duplication of CFI instructions.
  329. if (MI->isCFIInstruction()) {
  330. BuildMI(*PredBB, PredBB->end(), PredBB->findDebugLoc(PredBB->begin()),
  331. TII->get(TargetOpcode::CFI_INSTRUCTION)).addCFIIndex(
  332. MI->getOperand(0).getCFIIndex());
  333. return;
  334. }
  335. MachineInstr &NewMI = TII->duplicate(*PredBB, PredBB->end(), *MI);
  336. if (PreRegAlloc) {
  337. for (unsigned i = 0, e = NewMI.getNumOperands(); i != e; ++i) {
  338. MachineOperand &MO = NewMI.getOperand(i);
  339. if (!MO.isReg())
  340. continue;
  341. Register Reg = MO.getReg();
  342. if (!Register::isVirtualRegister(Reg))
  343. continue;
  344. if (MO.isDef()) {
  345. const TargetRegisterClass *RC = MRI->getRegClass(Reg);
  346. Register NewReg = MRI->createVirtualRegister(RC);
  347. MO.setReg(NewReg);
  348. LocalVRMap.insert(std::make_pair(Reg, RegSubRegPair(NewReg, 0)));
  349. if (isDefLiveOut(Reg, TailBB, MRI) || UsedByPhi.count(Reg))
  350. addSSAUpdateEntry(Reg, NewReg, PredBB);
  351. } else {
  352. auto VI = LocalVRMap.find(Reg);
  353. if (VI != LocalVRMap.end()) {
  354. // Need to make sure that the register class of the mapped register
  355. // will satisfy the constraints of the class of the register being
  356. // replaced.
  357. auto *OrigRC = MRI->getRegClass(Reg);
  358. auto *MappedRC = MRI->getRegClass(VI->second.Reg);
  359. const TargetRegisterClass *ConstrRC;
  360. if (VI->second.SubReg != 0) {
  361. ConstrRC = TRI->getMatchingSuperRegClass(MappedRC, OrigRC,
  362. VI->second.SubReg);
  363. if (ConstrRC) {
  364. // The actual constraining (as in "find appropriate new class")
  365. // is done by getMatchingSuperRegClass, so now we only need to
  366. // change the class of the mapped register.
  367. MRI->setRegClass(VI->second.Reg, ConstrRC);
  368. }
  369. } else {
  370. // For mapped registers that do not have sub-registers, simply
  371. // restrict their class to match the original one.
  372. ConstrRC = MRI->constrainRegClass(VI->second.Reg, OrigRC);
  373. }
  374. if (ConstrRC) {
  375. // If the class constraining succeeded, we can simply replace
  376. // the old register with the mapped one.
  377. MO.setReg(VI->second.Reg);
  378. // We have Reg -> VI.Reg:VI.SubReg, so if Reg is used with a
  379. // sub-register, we need to compose the sub-register indices.
  380. MO.setSubReg(TRI->composeSubRegIndices(MO.getSubReg(),
  381. VI->second.SubReg));
  382. } else {
  383. // The direct replacement is not possible, due to failing register
  384. // class constraints. An explicit COPY is necessary. Create one
  385. // that can be reused
  386. auto *NewRC = MI->getRegClassConstraint(i, TII, TRI);
  387. if (NewRC == nullptr)
  388. NewRC = OrigRC;
  389. Register NewReg = MRI->createVirtualRegister(NewRC);
  390. BuildMI(*PredBB, NewMI, NewMI.getDebugLoc(),
  391. TII->get(TargetOpcode::COPY), NewReg)
  392. .addReg(VI->second.Reg, 0, VI->second.SubReg);
  393. LocalVRMap.erase(VI);
  394. LocalVRMap.insert(std::make_pair(Reg, RegSubRegPair(NewReg, 0)));
  395. MO.setReg(NewReg);
  396. // The composed VI.Reg:VI.SubReg is replaced with NewReg, which
  397. // is equivalent to the whole register Reg. Hence, Reg:subreg
  398. // is same as NewReg:subreg, so keep the sub-register index
  399. // unchanged.
  400. }
  401. // Clear any kill flags from this operand. The new register could
  402. // have uses after this one, so kills are not valid here.
  403. MO.setIsKill(false);
  404. }
  405. }
  406. }
  407. }
  408. }
  409. /// After FromBB is tail duplicated into its predecessor blocks, the successors
  410. /// have gained new predecessors. Update the PHI instructions in them
  411. /// accordingly.
  412. void TailDuplicator::updateSuccessorsPHIs(
  413. MachineBasicBlock *FromBB, bool isDead,
  414. SmallVectorImpl<MachineBasicBlock *> &TDBBs,
  415. SmallSetVector<MachineBasicBlock *, 8> &Succs) {
  416. for (MachineBasicBlock *SuccBB : Succs) {
  417. for (MachineInstr &MI : *SuccBB) {
  418. if (!MI.isPHI())
  419. break;
  420. MachineInstrBuilder MIB(*FromBB->getParent(), MI);
  421. unsigned Idx = 0;
  422. for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
  423. MachineOperand &MO = MI.getOperand(i + 1);
  424. if (MO.getMBB() == FromBB) {
  425. Idx = i;
  426. break;
  427. }
  428. }
  429. assert(Idx != 0);
  430. MachineOperand &MO0 = MI.getOperand(Idx);
  431. Register Reg = MO0.getReg();
  432. if (isDead) {
  433. // Folded into the previous BB.
  434. // There could be duplicate phi source entries. FIXME: Should sdisel
  435. // or earlier pass fixed this?
  436. for (unsigned i = MI.getNumOperands() - 2; i != Idx; i -= 2) {
  437. MachineOperand &MO = MI.getOperand(i + 1);
  438. if (MO.getMBB() == FromBB) {
  439. MI.RemoveOperand(i + 1);
  440. MI.RemoveOperand(i);
  441. }
  442. }
  443. } else
  444. Idx = 0;
  445. // If Idx is set, the operands at Idx and Idx+1 must be removed.
  446. // We reuse the location to avoid expensive RemoveOperand calls.
  447. DenseMap<unsigned, AvailableValsTy>::iterator LI =
  448. SSAUpdateVals.find(Reg);
  449. if (LI != SSAUpdateVals.end()) {
  450. // This register is defined in the tail block.
  451. for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
  452. MachineBasicBlock *SrcBB = LI->second[j].first;
  453. // If we didn't duplicate a bb into a particular predecessor, we
  454. // might still have added an entry to SSAUpdateVals to correcly
  455. // recompute SSA. If that case, avoid adding a dummy extra argument
  456. // this PHI.
  457. if (!SrcBB->isSuccessor(SuccBB))
  458. continue;
  459. unsigned SrcReg = LI->second[j].second;
  460. if (Idx != 0) {
  461. MI.getOperand(Idx).setReg(SrcReg);
  462. MI.getOperand(Idx + 1).setMBB(SrcBB);
  463. Idx = 0;
  464. } else {
  465. MIB.addReg(SrcReg).addMBB(SrcBB);
  466. }
  467. }
  468. } else {
  469. // Live in tail block, must also be live in predecessors.
  470. for (unsigned j = 0, ee = TDBBs.size(); j != ee; ++j) {
  471. MachineBasicBlock *SrcBB = TDBBs[j];
  472. if (Idx != 0) {
  473. MI.getOperand(Idx).setReg(Reg);
  474. MI.getOperand(Idx + 1).setMBB(SrcBB);
  475. Idx = 0;
  476. } else {
  477. MIB.addReg(Reg).addMBB(SrcBB);
  478. }
  479. }
  480. }
  481. if (Idx != 0) {
  482. MI.RemoveOperand(Idx + 1);
  483. MI.RemoveOperand(Idx);
  484. }
  485. }
  486. }
  487. }
  488. /// Determine if it is profitable to duplicate this block.
  489. bool TailDuplicator::shouldTailDuplicate(bool IsSimple,
  490. MachineBasicBlock &TailBB) {
  491. // When doing tail-duplication during layout, the block ordering is in flux,
  492. // so canFallThrough returns a result based on incorrect information and
  493. // should just be ignored.
  494. if (!LayoutMode && TailBB.canFallThrough())
  495. return false;
  496. // Don't try to tail-duplicate single-block loops.
  497. if (TailBB.isSuccessor(&TailBB))
  498. return false;
  499. // Set the limit on the cost to duplicate. When optimizing for size,
  500. // duplicate only one, because one branch instruction can be eliminated to
  501. // compensate for the duplication.
  502. unsigned MaxDuplicateCount;
  503. if (TailDupSize == 0 &&
  504. TailDuplicateSize.getNumOccurrences() == 0 &&
  505. MF->getFunction().hasOptSize())
  506. MaxDuplicateCount = 1;
  507. else if (TailDupSize == 0)
  508. MaxDuplicateCount = TailDuplicateSize;
  509. else
  510. MaxDuplicateCount = TailDupSize;
  511. // If the block to be duplicated ends in an unanalyzable fallthrough, don't
  512. // duplicate it.
  513. // A similar check is necessary in MachineBlockPlacement to make sure pairs of
  514. // blocks with unanalyzable fallthrough get layed out contiguously.
  515. MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
  516. SmallVector<MachineOperand, 4> PredCond;
  517. if (TII->analyzeBranch(TailBB, PredTBB, PredFBB, PredCond) &&
  518. TailBB.canFallThrough())
  519. return false;
  520. // If the target has hardware branch prediction that can handle indirect
  521. // branches, duplicating them can often make them predictable when there
  522. // are common paths through the code. The limit needs to be high enough
  523. // to allow undoing the effects of tail merging and other optimizations
  524. // that rearrange the predecessors of the indirect branch.
  525. bool HasIndirectbr = false;
  526. if (!TailBB.empty())
  527. HasIndirectbr = TailBB.back().isIndirectBranch();
  528. if (HasIndirectbr && PreRegAlloc)
  529. MaxDuplicateCount = TailDupIndirectBranchSize;
  530. // Check the instructions in the block to determine whether tail-duplication
  531. // is invalid or unlikely to be profitable.
  532. unsigned InstrCount = 0;
  533. for (MachineInstr &MI : TailBB) {
  534. // Non-duplicable things shouldn't be tail-duplicated.
  535. // CFI instructions are marked as non-duplicable, because Darwin compact
  536. // unwind info emission can't handle multiple prologue setups. In case of
  537. // DWARF, allow them be duplicated, so that their existence doesn't prevent
  538. // tail duplication of some basic blocks, that would be duplicated otherwise.
  539. if (MI.isNotDuplicable() &&
  540. (TailBB.getParent()->getTarget().getTargetTriple().isOSDarwin() ||
  541. !MI.isCFIInstruction()))
  542. return false;
  543. // Convergent instructions can be duplicated only if doing so doesn't add
  544. // new control dependencies, which is what we're going to do here.
  545. if (MI.isConvergent())
  546. return false;
  547. // Do not duplicate 'return' instructions if this is a pre-regalloc run.
  548. // A return may expand into a lot more instructions (e.g. reload of callee
  549. // saved registers) after PEI.
  550. if (PreRegAlloc && MI.isReturn())
  551. return false;
  552. // Avoid duplicating calls before register allocation. Calls presents a
  553. // barrier to register allocation so duplicating them may end up increasing
  554. // spills.
  555. if (PreRegAlloc && MI.isCall())
  556. return false;
  557. if (!MI.isPHI() && !MI.isMetaInstruction())
  558. InstrCount += 1;
  559. if (InstrCount > MaxDuplicateCount)
  560. return false;
  561. }
  562. // Check if any of the successors of TailBB has a PHI node in which the
  563. // value corresponding to TailBB uses a subregister.
  564. // If a phi node uses a register paired with a subregister, the actual
  565. // "value type" of the phi may differ from the type of the register without
  566. // any subregisters. Due to a bug, tail duplication may add a new operand
  567. // without a necessary subregister, producing an invalid code. This is
  568. // demonstrated by test/CodeGen/Hexagon/tail-dup-subreg-abort.ll.
  569. // Disable tail duplication for this case for now, until the problem is
  570. // fixed.
  571. for (auto SB : TailBB.successors()) {
  572. for (auto &I : *SB) {
  573. if (!I.isPHI())
  574. break;
  575. unsigned Idx = getPHISrcRegOpIdx(&I, &TailBB);
  576. assert(Idx != 0);
  577. MachineOperand &PU = I.getOperand(Idx);
  578. if (PU.getSubReg() != 0)
  579. return false;
  580. }
  581. }
  582. if (HasIndirectbr && PreRegAlloc)
  583. return true;
  584. if (IsSimple)
  585. return true;
  586. if (!PreRegAlloc)
  587. return true;
  588. return canCompletelyDuplicateBB(TailBB);
  589. }
  590. /// True if this BB has only one unconditional jump.
  591. bool TailDuplicator::isSimpleBB(MachineBasicBlock *TailBB) {
  592. if (TailBB->succ_size() != 1)
  593. return false;
  594. if (TailBB->pred_empty())
  595. return false;
  596. MachineBasicBlock::iterator I = TailBB->getFirstNonDebugInstr();
  597. if (I == TailBB->end())
  598. return true;
  599. return I->isUnconditionalBranch();
  600. }
  601. static bool bothUsedInPHI(const MachineBasicBlock &A,
  602. const SmallPtrSet<MachineBasicBlock *, 8> &SuccsB) {
  603. for (MachineBasicBlock *BB : A.successors())
  604. if (SuccsB.count(BB) && !BB->empty() && BB->begin()->isPHI())
  605. return true;
  606. return false;
  607. }
  608. bool TailDuplicator::canCompletelyDuplicateBB(MachineBasicBlock &BB) {
  609. for (MachineBasicBlock *PredBB : BB.predecessors()) {
  610. if (PredBB->succ_size() > 1)
  611. return false;
  612. MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
  613. SmallVector<MachineOperand, 4> PredCond;
  614. if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond))
  615. return false;
  616. if (!PredCond.empty())
  617. return false;
  618. }
  619. return true;
  620. }
  621. bool TailDuplicator::duplicateSimpleBB(
  622. MachineBasicBlock *TailBB, SmallVectorImpl<MachineBasicBlock *> &TDBBs,
  623. const DenseSet<unsigned> &UsedByPhi,
  624. SmallVectorImpl<MachineInstr *> &Copies) {
  625. SmallPtrSet<MachineBasicBlock *, 8> Succs(TailBB->succ_begin(),
  626. TailBB->succ_end());
  627. SmallVector<MachineBasicBlock *, 8> Preds(TailBB->pred_begin(),
  628. TailBB->pred_end());
  629. bool Changed = false;
  630. for (MachineBasicBlock *PredBB : Preds) {
  631. if (PredBB->hasEHPadSuccessor())
  632. continue;
  633. if (bothUsedInPHI(*PredBB, Succs))
  634. continue;
  635. MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
  636. SmallVector<MachineOperand, 4> PredCond;
  637. if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond))
  638. continue;
  639. Changed = true;
  640. LLVM_DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
  641. << "From simple Succ: " << *TailBB);
  642. MachineBasicBlock *NewTarget = *TailBB->succ_begin();
  643. MachineBasicBlock *NextBB = PredBB->getNextNode();
  644. // Make PredFBB explicit.
  645. if (PredCond.empty())
  646. PredFBB = PredTBB;
  647. // Make fall through explicit.
  648. if (!PredTBB)
  649. PredTBB = NextBB;
  650. if (!PredFBB)
  651. PredFBB = NextBB;
  652. // Redirect
  653. if (PredFBB == TailBB)
  654. PredFBB = NewTarget;
  655. if (PredTBB == TailBB)
  656. PredTBB = NewTarget;
  657. // Make the branch unconditional if possible
  658. if (PredTBB == PredFBB) {
  659. PredCond.clear();
  660. PredFBB = nullptr;
  661. }
  662. // Avoid adding fall through branches.
  663. if (PredFBB == NextBB)
  664. PredFBB = nullptr;
  665. if (PredTBB == NextBB && PredFBB == nullptr)
  666. PredTBB = nullptr;
  667. auto DL = PredBB->findBranchDebugLoc();
  668. TII->removeBranch(*PredBB);
  669. if (!PredBB->isSuccessor(NewTarget))
  670. PredBB->replaceSuccessor(TailBB, NewTarget);
  671. else {
  672. PredBB->removeSuccessor(TailBB, true);
  673. assert(PredBB->succ_size() <= 1);
  674. }
  675. if (PredTBB)
  676. TII->insertBranch(*PredBB, PredTBB, PredFBB, PredCond, DL);
  677. TDBBs.push_back(PredBB);
  678. }
  679. return Changed;
  680. }
  681. bool TailDuplicator::canTailDuplicate(MachineBasicBlock *TailBB,
  682. MachineBasicBlock *PredBB) {
  683. // EH edges are ignored by analyzeBranch.
  684. if (PredBB->succ_size() > 1)
  685. return false;
  686. MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
  687. SmallVector<MachineOperand, 4> PredCond;
  688. if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond))
  689. return false;
  690. if (!PredCond.empty())
  691. return false;
  692. return true;
  693. }
  694. /// If it is profitable, duplicate TailBB's contents in each
  695. /// of its predecessors.
  696. /// \p IsSimple result of isSimpleBB
  697. /// \p TailBB Block to be duplicated.
  698. /// \p ForcedLayoutPred When non-null, use this block as the layout predecessor
  699. /// instead of the previous block in MF's order.
  700. /// \p TDBBs A vector to keep track of all blocks tail-duplicated
  701. /// into.
  702. /// \p Copies A vector of copy instructions inserted. Used later to
  703. /// walk all the inserted copies and remove redundant ones.
  704. bool TailDuplicator::tailDuplicate(bool IsSimple, MachineBasicBlock *TailBB,
  705. MachineBasicBlock *ForcedLayoutPred,
  706. SmallVectorImpl<MachineBasicBlock *> &TDBBs,
  707. SmallVectorImpl<MachineInstr *> &Copies) {
  708. LLVM_DEBUG(dbgs() << "\n*** Tail-duplicating " << printMBBReference(*TailBB)
  709. << '\n');
  710. DenseSet<unsigned> UsedByPhi;
  711. getRegsUsedByPHIs(*TailBB, &UsedByPhi);
  712. if (IsSimple)
  713. return duplicateSimpleBB(TailBB, TDBBs, UsedByPhi, Copies);
  714. // Iterate through all the unique predecessors and tail-duplicate this
  715. // block into them, if possible. Copying the list ahead of time also
  716. // avoids trouble with the predecessor list reallocating.
  717. bool Changed = false;
  718. SmallSetVector<MachineBasicBlock *, 8> Preds(TailBB->pred_begin(),
  719. TailBB->pred_end());
  720. for (MachineBasicBlock *PredBB : Preds) {
  721. assert(TailBB != PredBB &&
  722. "Single-block loop should have been rejected earlier!");
  723. if (!canTailDuplicate(TailBB, PredBB))
  724. continue;
  725. // Don't duplicate into a fall-through predecessor (at least for now).
  726. bool IsLayoutSuccessor = false;
  727. if (ForcedLayoutPred)
  728. IsLayoutSuccessor = (ForcedLayoutPred == PredBB);
  729. else if (PredBB->isLayoutSuccessor(TailBB) && PredBB->canFallThrough())
  730. IsLayoutSuccessor = true;
  731. if (IsLayoutSuccessor)
  732. continue;
  733. LLVM_DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
  734. << "From Succ: " << *TailBB);
  735. TDBBs.push_back(PredBB);
  736. // Remove PredBB's unconditional branch.
  737. TII->removeBranch(*PredBB);
  738. // Clone the contents of TailBB into PredBB.
  739. DenseMap<unsigned, RegSubRegPair> LocalVRMap;
  740. SmallVector<std::pair<unsigned, RegSubRegPair>, 4> CopyInfos;
  741. for (MachineBasicBlock::iterator I = TailBB->begin(), E = TailBB->end();
  742. I != E; /* empty */) {
  743. MachineInstr *MI = &*I;
  744. ++I;
  745. if (MI->isPHI()) {
  746. // Replace the uses of the def of the PHI with the register coming
  747. // from PredBB.
  748. processPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, true);
  749. } else {
  750. // Replace def of virtual registers with new registers, and update
  751. // uses with PHI source register or the new registers.
  752. duplicateInstruction(MI, TailBB, PredBB, LocalVRMap, UsedByPhi);
  753. }
  754. }
  755. appendCopies(PredBB, CopyInfos, Copies);
  756. NumTailDupAdded += TailBB->size() - 1; // subtract one for removed branch
  757. // Update the CFG.
  758. PredBB->removeSuccessor(PredBB->succ_begin());
  759. assert(PredBB->succ_empty() &&
  760. "TailDuplicate called on block with multiple successors!");
  761. for (MachineBasicBlock *Succ : TailBB->successors())
  762. PredBB->addSuccessor(Succ, MBPI->getEdgeProbability(TailBB, Succ));
  763. Changed = true;
  764. ++NumTailDups;
  765. }
  766. // If TailBB was duplicated into all its predecessors except for the prior
  767. // block, which falls through unconditionally, move the contents of this
  768. // block into the prior block.
  769. MachineBasicBlock *PrevBB = ForcedLayoutPred;
  770. if (!PrevBB)
  771. PrevBB = &*std::prev(TailBB->getIterator());
  772. MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr;
  773. SmallVector<MachineOperand, 4> PriorCond;
  774. // This has to check PrevBB->succ_size() because EH edges are ignored by
  775. // analyzeBranch.
  776. if (PrevBB->succ_size() == 1 &&
  777. // Layout preds are not always CFG preds. Check.
  778. *PrevBB->succ_begin() == TailBB &&
  779. !TII->analyzeBranch(*PrevBB, PriorTBB, PriorFBB, PriorCond) &&
  780. PriorCond.empty() &&
  781. (!PriorTBB || PriorTBB == TailBB) &&
  782. TailBB->pred_size() == 1 &&
  783. !TailBB->hasAddressTaken()) {
  784. LLVM_DEBUG(dbgs() << "\nMerging into block: " << *PrevBB
  785. << "From MBB: " << *TailBB);
  786. // There may be a branch to the layout successor. This is unlikely but it
  787. // happens. The correct thing to do is to remove the branch before
  788. // duplicating the instructions in all cases.
  789. TII->removeBranch(*PrevBB);
  790. if (PreRegAlloc) {
  791. DenseMap<unsigned, RegSubRegPair> LocalVRMap;
  792. SmallVector<std::pair<unsigned, RegSubRegPair>, 4> CopyInfos;
  793. MachineBasicBlock::iterator I = TailBB->begin();
  794. // Process PHI instructions first.
  795. while (I != TailBB->end() && I->isPHI()) {
  796. // Replace the uses of the def of the PHI with the register coming
  797. // from PredBB.
  798. MachineInstr *MI = &*I++;
  799. processPHI(MI, TailBB, PrevBB, LocalVRMap, CopyInfos, UsedByPhi, true);
  800. }
  801. // Now copy the non-PHI instructions.
  802. while (I != TailBB->end()) {
  803. // Replace def of virtual registers with new registers, and update
  804. // uses with PHI source register or the new registers.
  805. MachineInstr *MI = &*I++;
  806. assert(!MI->isBundle() && "Not expecting bundles before regalloc!");
  807. duplicateInstruction(MI, TailBB, PrevBB, LocalVRMap, UsedByPhi);
  808. MI->eraseFromParent();
  809. }
  810. appendCopies(PrevBB, CopyInfos, Copies);
  811. } else {
  812. TII->removeBranch(*PrevBB);
  813. // No PHIs to worry about, just splice the instructions over.
  814. PrevBB->splice(PrevBB->end(), TailBB, TailBB->begin(), TailBB->end());
  815. }
  816. PrevBB->removeSuccessor(PrevBB->succ_begin());
  817. assert(PrevBB->succ_empty());
  818. PrevBB->transferSuccessors(TailBB);
  819. TDBBs.push_back(PrevBB);
  820. Changed = true;
  821. }
  822. // If this is after register allocation, there are no phis to fix.
  823. if (!PreRegAlloc)
  824. return Changed;
  825. // If we made no changes so far, we are safe.
  826. if (!Changed)
  827. return Changed;
  828. // Handle the nasty case in that we duplicated a block that is part of a loop
  829. // into some but not all of its predecessors. For example:
  830. // 1 -> 2 <-> 3 |
  831. // \ |
  832. // \---> rest |
  833. // if we duplicate 2 into 1 but not into 3, we end up with
  834. // 12 -> 3 <-> 2 -> rest |
  835. // \ / |
  836. // \----->-----/ |
  837. // If there was a "var = phi(1, 3)" in 2, it has to be ultimately replaced
  838. // with a phi in 3 (which now dominates 2).
  839. // What we do here is introduce a copy in 3 of the register defined by the
  840. // phi, just like when we are duplicating 2 into 3, but we don't copy any
  841. // real instructions or remove the 3 -> 2 edge from the phi in 2.
  842. for (MachineBasicBlock *PredBB : Preds) {
  843. if (is_contained(TDBBs, PredBB))
  844. continue;
  845. // EH edges
  846. if (PredBB->succ_size() != 1)
  847. continue;
  848. DenseMap<unsigned, RegSubRegPair> LocalVRMap;
  849. SmallVector<std::pair<unsigned, RegSubRegPair>, 4> CopyInfos;
  850. MachineBasicBlock::iterator I = TailBB->begin();
  851. // Process PHI instructions first.
  852. while (I != TailBB->end() && I->isPHI()) {
  853. // Replace the uses of the def of the PHI with the register coming
  854. // from PredBB.
  855. MachineInstr *MI = &*I++;
  856. processPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, false);
  857. }
  858. appendCopies(PredBB, CopyInfos, Copies);
  859. }
  860. return Changed;
  861. }
  862. /// At the end of the block \p MBB generate COPY instructions between registers
  863. /// described by \p CopyInfos. Append resulting instructions to \p Copies.
  864. void TailDuplicator::appendCopies(MachineBasicBlock *MBB,
  865. SmallVectorImpl<std::pair<unsigned,RegSubRegPair>> &CopyInfos,
  866. SmallVectorImpl<MachineInstr*> &Copies) {
  867. MachineBasicBlock::iterator Loc = MBB->getFirstTerminator();
  868. const MCInstrDesc &CopyD = TII->get(TargetOpcode::COPY);
  869. for (auto &CI : CopyInfos) {
  870. auto C = BuildMI(*MBB, Loc, DebugLoc(), CopyD, CI.first)
  871. .addReg(CI.second.Reg, 0, CI.second.SubReg);
  872. Copies.push_back(C);
  873. }
  874. }
  875. /// Remove the specified dead machine basic block from the function, updating
  876. /// the CFG.
  877. void TailDuplicator::removeDeadBlock(
  878. MachineBasicBlock *MBB,
  879. function_ref<void(MachineBasicBlock *)> *RemovalCallback) {
  880. assert(MBB->pred_empty() && "MBB must be dead!");
  881. LLVM_DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
  882. if (RemovalCallback)
  883. (*RemovalCallback)(MBB);
  884. // Remove all successors.
  885. while (!MBB->succ_empty())
  886. MBB->removeSuccessor(MBB->succ_end() - 1);
  887. // Remove the block.
  888. MBB->eraseFromParent();
  889. }