TailDuplicator.cpp 36 KB

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