Localizer.cpp 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. //===- Localizer.cpp ---------------------- Localize some instrs -*- C++ -*-==//
  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. /// \file
  9. /// This file implements the Localizer class.
  10. //===----------------------------------------------------------------------===//
  11. #include "llvm/CodeGen/GlobalISel/Localizer.h"
  12. #include "llvm/ADT/DenseMap.h"
  13. #include "llvm/ADT/STLExtras.h"
  14. #include "llvm/Analysis/TargetTransformInfo.h"
  15. #include "llvm/CodeGen/GlobalISel/Utils.h"
  16. #include "llvm/CodeGen/MachineRegisterInfo.h"
  17. #include "llvm/CodeGen/TargetLowering.h"
  18. #include "llvm/InitializePasses.h"
  19. #include "llvm/Support/Debug.h"
  20. #define DEBUG_TYPE "localizer"
  21. using namespace llvm;
  22. char Localizer::ID = 0;
  23. INITIALIZE_PASS_BEGIN(Localizer, DEBUG_TYPE,
  24. "Move/duplicate certain instructions close to their use",
  25. false, false)
  26. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  27. INITIALIZE_PASS_END(Localizer, DEBUG_TYPE,
  28. "Move/duplicate certain instructions close to their use",
  29. false, false)
  30. Localizer::Localizer(std::function<bool(const MachineFunction &)> F)
  31. : MachineFunctionPass(ID), DoNotRunPass(F) {}
  32. Localizer::Localizer()
  33. : Localizer([](const MachineFunction &) { return false; }) {}
  34. void Localizer::init(MachineFunction &MF) {
  35. MRI = &MF.getRegInfo();
  36. TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(MF.getFunction());
  37. }
  38. void Localizer::getAnalysisUsage(AnalysisUsage &AU) const {
  39. AU.addRequired<TargetTransformInfoWrapperPass>();
  40. getSelectionDAGFallbackAnalysisUsage(AU);
  41. MachineFunctionPass::getAnalysisUsage(AU);
  42. }
  43. bool Localizer::isLocalUse(MachineOperand &MOUse, const MachineInstr &Def,
  44. MachineBasicBlock *&InsertMBB) {
  45. MachineInstr &MIUse = *MOUse.getParent();
  46. InsertMBB = MIUse.getParent();
  47. if (MIUse.isPHI())
  48. InsertMBB = MIUse.getOperand(MIUse.getOperandNo(&MOUse) + 1).getMBB();
  49. return InsertMBB == Def.getParent();
  50. }
  51. bool Localizer::isNonUniquePhiValue(MachineOperand &Op) const {
  52. MachineInstr *MI = Op.getParent();
  53. if (!MI->isPHI())
  54. return false;
  55. Register SrcReg = Op.getReg();
  56. for (unsigned Idx = 1; Idx < MI->getNumOperands(); Idx += 2) {
  57. auto &MO = MI->getOperand(Idx);
  58. if (&MO != &Op && MO.isReg() && MO.getReg() == SrcReg)
  59. return true;
  60. }
  61. return false;
  62. }
  63. bool Localizer::localizeInterBlock(MachineFunction &MF,
  64. LocalizedSetVecT &LocalizedInstrs) {
  65. bool Changed = false;
  66. DenseMap<std::pair<MachineBasicBlock *, unsigned>, unsigned> MBBWithLocalDef;
  67. // Since the IRTranslator only emits constants into the entry block, and the
  68. // rest of the GISel pipeline generally emits constants close to their users,
  69. // we only localize instructions in the entry block here. This might change if
  70. // we start doing CSE across blocks.
  71. auto &MBB = MF.front();
  72. auto &TL = *MF.getSubtarget().getTargetLowering();
  73. for (MachineInstr &MI : llvm::reverse(MBB)) {
  74. if (!TL.shouldLocalize(MI, TTI))
  75. continue;
  76. LLVM_DEBUG(dbgs() << "Should localize: " << MI);
  77. assert(MI.getDesc().getNumDefs() == 1 &&
  78. "More than one definition not supported yet");
  79. Register Reg = MI.getOperand(0).getReg();
  80. // Check if all the users of MI are local.
  81. // We are going to invalidation the list of use operands, so we
  82. // can't use range iterator.
  83. for (MachineOperand &MOUse :
  84. llvm::make_early_inc_range(MRI->use_operands(Reg))) {
  85. // Check if the use is already local.
  86. MachineBasicBlock *InsertMBB;
  87. LLVM_DEBUG(MachineInstr &MIUse = *MOUse.getParent();
  88. dbgs() << "Checking use: " << MIUse
  89. << " #Opd: " << MIUse.getOperandNo(&MOUse) << '\n');
  90. if (isLocalUse(MOUse, MI, InsertMBB)) {
  91. // Even if we're in the same block, if the block is very large we could
  92. // still have many long live ranges. Try to do intra-block localization
  93. // too.
  94. LocalizedInstrs.insert(&MI);
  95. continue;
  96. }
  97. // If the use is a phi operand that's not unique, don't try to localize.
  98. // If we do, we can cause unnecessary instruction bloat by duplicating
  99. // into each predecessor block, when the existing one is sufficient and
  100. // allows for easier optimization later.
  101. if (isNonUniquePhiValue(MOUse))
  102. continue;
  103. LLVM_DEBUG(dbgs() << "Fixing non-local use\n");
  104. Changed = true;
  105. auto MBBAndReg = std::make_pair(InsertMBB, Reg);
  106. auto NewVRegIt = MBBWithLocalDef.find(MBBAndReg);
  107. if (NewVRegIt == MBBWithLocalDef.end()) {
  108. // Create the localized instruction.
  109. MachineInstr *LocalizedMI = MF.CloneMachineInstr(&MI);
  110. LocalizedInstrs.insert(LocalizedMI);
  111. MachineInstr &UseMI = *MOUse.getParent();
  112. if (MRI->hasOneUse(Reg) && !UseMI.isPHI())
  113. InsertMBB->insert(UseMI, LocalizedMI);
  114. else
  115. InsertMBB->insert(InsertMBB->SkipPHIsAndLabels(InsertMBB->begin()),
  116. LocalizedMI);
  117. // Set a new register for the definition.
  118. Register NewReg = MRI->cloneVirtualRegister(Reg);
  119. LocalizedMI->getOperand(0).setReg(NewReg);
  120. NewVRegIt =
  121. MBBWithLocalDef.insert(std::make_pair(MBBAndReg, NewReg)).first;
  122. LLVM_DEBUG(dbgs() << "Inserted: " << *LocalizedMI);
  123. }
  124. LLVM_DEBUG(dbgs() << "Update use with: " << printReg(NewVRegIt->second)
  125. << '\n');
  126. // Update the user reg.
  127. MOUse.setReg(NewVRegIt->second);
  128. }
  129. }
  130. return Changed;
  131. }
  132. bool Localizer::localizeIntraBlock(LocalizedSetVecT &LocalizedInstrs) {
  133. bool Changed = false;
  134. // For each already-localized instruction which has multiple users, then we
  135. // scan the block top down from the current position until we hit one of them.
  136. // FIXME: Consider doing inst duplication if live ranges are very long due to
  137. // many users, but this case may be better served by regalloc improvements.
  138. for (MachineInstr *MI : LocalizedInstrs) {
  139. Register Reg = MI->getOperand(0).getReg();
  140. MachineBasicBlock &MBB = *MI->getParent();
  141. // All of the user MIs of this reg.
  142. SmallPtrSet<MachineInstr *, 32> Users;
  143. for (MachineInstr &UseMI : MRI->use_nodbg_instructions(Reg)) {
  144. if (!UseMI.isPHI())
  145. Users.insert(&UseMI);
  146. }
  147. // If all the users were PHIs then they're not going to be in our block,
  148. // don't try to move this instruction.
  149. if (Users.empty())
  150. continue;
  151. MachineBasicBlock::iterator II(MI);
  152. ++II;
  153. while (II != MBB.end() && !Users.count(&*II))
  154. ++II;
  155. assert(II != MBB.end() && "Didn't find the user in the MBB");
  156. LLVM_DEBUG(dbgs() << "Intra-block: moving " << *MI << " before " << *II
  157. << '\n');
  158. MI->removeFromParent();
  159. MBB.insert(II, MI);
  160. Changed = true;
  161. // If the instruction (constant) being localized has single user, we can
  162. // propagate debug location from user.
  163. if (Users.size() == 1) {
  164. const auto &DefDL = MI->getDebugLoc();
  165. const auto &UserDL = (*Users.begin())->getDebugLoc();
  166. if ((!DefDL || DefDL.getLine() == 0) && UserDL && UserDL.getLine() != 0) {
  167. MI->setDebugLoc(UserDL);
  168. }
  169. }
  170. }
  171. return Changed;
  172. }
  173. bool Localizer::runOnMachineFunction(MachineFunction &MF) {
  174. // If the ISel pipeline failed, do not bother running that pass.
  175. if (MF.getProperties().hasProperty(
  176. MachineFunctionProperties::Property::FailedISel))
  177. return false;
  178. // Don't run the pass if the target asked so.
  179. if (DoNotRunPass(MF))
  180. return false;
  181. LLVM_DEBUG(dbgs() << "Localize instructions for: " << MF.getName() << '\n');
  182. init(MF);
  183. // Keep track of the instructions we localized. We'll do a second pass of
  184. // intra-block localization to further reduce live ranges.
  185. LocalizedSetVecT LocalizedInstrs;
  186. bool Changed = localizeInterBlock(MF, LocalizedInstrs);
  187. Changed |= localizeIntraBlock(LocalizedInstrs);
  188. return Changed;
  189. }