xref: /llvm-project/llvm/lib/CodeGen/GlobalISel/Localizer.cpp (revision d11ea2c8c541f3358e289466b4569b21b64abc66)
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 
12 #include "llvm/CodeGen/GlobalISel/Localizer.h"
13 #include "llvm/Analysis/TargetTransformInfo.h"
14 #include "llvm/ADT/DenseMap.h"
15 #include "llvm/ADT/SmallPtrSet.h"
16 #include "llvm/CodeGen/MachineRegisterInfo.h"
17 #include "llvm/Support/Debug.h"
18 
19 #define DEBUG_TYPE "localizer"
20 
21 using namespace llvm;
22 
23 char Localizer::ID = 0;
24 INITIALIZE_PASS_BEGIN(Localizer, DEBUG_TYPE,
25                       "Move/duplicate certain instructions close to their use",
26                       false, false)
27 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
28 INITIALIZE_PASS_END(Localizer, DEBUG_TYPE,
29                     "Move/duplicate certain instructions close to their use",
30                     false, false)
31 
32 Localizer::Localizer() : MachineFunctionPass(ID) { }
33 
34 void Localizer::init(MachineFunction &MF) {
35   MRI = &MF.getRegInfo();
36   TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(MF.getFunction());
37 }
38 
39 bool Localizer::shouldLocalize(const MachineInstr &MI) {
40   // Assuming a spill and reload of a value has a cost of 1 instruction each,
41   // this helper function computes the maximum number of uses we should consider
42   // for remat. E.g. on arm64 global addresses take 2 insts to materialize. We
43   // break even in terms of code size when the original MI has 2 users vs
44   // choosing to potentially spill. Any more than 2 users we we have a net code
45   // size increase. This doesn't take into account register pressure though.
46   auto maxUses = [](unsigned RematCost) {
47     // A cost of 1 means remats are basically free.
48     if (RematCost == 1)
49       return UINT_MAX;
50     if (RematCost == 2)
51       return 2U;
52 
53     // Remat is too expensive, only sink if there's one user.
54     if (RematCost > 2)
55       return 1U;
56     llvm_unreachable("Unexpected remat cost");
57   };
58 
59   // Helper to walk through uses and terminate if we've reached a limit. Saves
60   // us spending time traversing uses if all we want to know is if it's >= min.
61   auto isUsesAtMost = [&](unsigned Reg, unsigned MaxUses) {
62     unsigned NumUses = 0;
63     auto UI = MRI->use_instr_nodbg_begin(Reg), UE = MRI->use_instr_nodbg_end();
64     for (; UI != UE && NumUses < MaxUses; ++UI) {
65       NumUses++;
66     }
67     // If we haven't reached the end yet then there are more than MaxUses users.
68     return UI == UE;
69   };
70 
71   switch (MI.getOpcode()) {
72   default:
73     return false;
74   // Constants-like instructions should be close to their users.
75   // We don't want long live-ranges for them.
76   case TargetOpcode::G_CONSTANT:
77   case TargetOpcode::G_FCONSTANT:
78   case TargetOpcode::G_FRAME_INDEX:
79     return true;
80   case TargetOpcode::G_GLOBAL_VALUE: {
81     unsigned RematCost = TTI->getGISelRematGlobalCost();
82     unsigned Reg = MI.getOperand(0).getReg();
83     unsigned MaxUses = maxUses(RematCost);
84     if (MaxUses == UINT_MAX)
85       return true; // Remats are "free" so always localize.
86     bool B = isUsesAtMost(Reg, MaxUses);
87     return B;
88   }
89   }
90 }
91 
92 void Localizer::getAnalysisUsage(AnalysisUsage &AU) const {
93   AU.addRequired<TargetTransformInfoWrapperPass>();
94   getSelectionDAGFallbackAnalysisUsage(AU);
95   MachineFunctionPass::getAnalysisUsage(AU);
96 }
97 
98 bool Localizer::isLocalUse(MachineOperand &MOUse, const MachineInstr &Def,
99                            MachineBasicBlock *&InsertMBB) {
100   MachineInstr &MIUse = *MOUse.getParent();
101   InsertMBB = MIUse.getParent();
102   if (MIUse.isPHI())
103     InsertMBB = MIUse.getOperand(MIUse.getOperandNo(&MOUse) + 1).getMBB();
104   return InsertMBB == Def.getParent();
105 }
106 
107 bool Localizer::localizeInterBlock(
108     MachineFunction &MF, SmallPtrSetImpl<MachineInstr *> &LocalizedInstrs) {
109   bool Changed = false;
110   DenseMap<std::pair<MachineBasicBlock *, unsigned>, unsigned> MBBWithLocalDef;
111 
112   // Since the IRTranslator only emits constants into the entry block, and the
113   // rest of the GISel pipeline generally emits constants close to their users,
114   // we only localize instructions in the entry block here. This might change if
115   // we start doing CSE across blocks.
116   auto &MBB = MF.front();
117   for (MachineInstr &MI : MBB) {
118     if (!shouldLocalize(MI))
119       continue;
120     LLVM_DEBUG(dbgs() << "Should localize: " << MI);
121     assert(MI.getDesc().getNumDefs() == 1 &&
122            "More than one definition not supported yet");
123     unsigned Reg = MI.getOperand(0).getReg();
124     // Check if all the users of MI are local.
125     // We are going to invalidation the list of use operands, so we
126     // can't use range iterator.
127     for (auto MOIt = MRI->use_begin(Reg), MOItEnd = MRI->use_end();
128          MOIt != MOItEnd;) {
129       MachineOperand &MOUse = *MOIt++;
130       // Check if the use is already local.
131       MachineBasicBlock *InsertMBB;
132       LLVM_DEBUG(MachineInstr &MIUse = *MOUse.getParent();
133                  dbgs() << "Checking use: " << MIUse
134                         << " #Opd: " << MIUse.getOperandNo(&MOUse) << '\n');
135       if (isLocalUse(MOUse, MI, InsertMBB))
136         continue;
137       LLVM_DEBUG(dbgs() << "Fixing non-local use\n");
138       Changed = true;
139       auto MBBAndReg = std::make_pair(InsertMBB, Reg);
140       auto NewVRegIt = MBBWithLocalDef.find(MBBAndReg);
141       if (NewVRegIt == MBBWithLocalDef.end()) {
142         // Create the localized instruction.
143         MachineInstr *LocalizedMI = MF.CloneMachineInstr(&MI);
144         LocalizedInstrs.insert(LocalizedMI);
145         MachineInstr &UseMI = *MOUse.getParent();
146         if (MRI->hasOneUse(Reg) && !UseMI.isPHI())
147           InsertMBB->insert(InsertMBB->SkipPHIsAndLabels(UseMI), LocalizedMI);
148         else
149           InsertMBB->insert(InsertMBB->SkipPHIsAndLabels(InsertMBB->begin()),
150                             LocalizedMI);
151 
152         // Set a new register for the definition.
153         unsigned NewReg = MRI->createGenericVirtualRegister(MRI->getType(Reg));
154         MRI->setRegClassOrRegBank(NewReg, MRI->getRegClassOrRegBank(Reg));
155         LocalizedMI->getOperand(0).setReg(NewReg);
156         NewVRegIt =
157             MBBWithLocalDef.insert(std::make_pair(MBBAndReg, NewReg)).first;
158         LLVM_DEBUG(dbgs() << "Inserted: " << *LocalizedMI);
159       }
160       LLVM_DEBUG(dbgs() << "Update use with: " << printReg(NewVRegIt->second)
161                         << '\n');
162       // Update the user reg.
163       MOUse.setReg(NewVRegIt->second);
164     }
165   }
166   return Changed;
167 }
168 
169 bool Localizer::localizeIntraBlock(
170     SmallPtrSetImpl<MachineInstr *> &LocalizedInstrs) {
171   bool Changed = false;
172 
173   // For each already-localized instruction which has multiple users, then we
174   // scan the block top down from the current position until we hit one of them.
175 
176   // FIXME: Consider doing inst duplication if live ranges are very long due to
177   // many users, but this case may be better served by regalloc improvements.
178 
179   for (MachineInstr *MI : LocalizedInstrs) {
180     unsigned Reg = MI->getOperand(0).getReg();
181     MachineBasicBlock &MBB = *MI->getParent();
182     // If the instruction has a single use, we would have already moved it right
183     // before its user in localizeInterBlock().
184     if (MRI->hasOneUse(Reg))
185       continue;
186 
187     // All of the user MIs of this reg.
188     SmallPtrSet<MachineInstr *, 32> Users;
189     for (MachineInstr &UseMI : MRI->use_nodbg_instructions(Reg))
190       Users.insert(&UseMI);
191 
192     MachineBasicBlock::iterator II(MI);
193     ++II;
194     while (II != MBB.end() && !Users.count(&*II))
195       ++II;
196 
197     LLVM_DEBUG(dbgs() << "Intra-block: moving " << *MI << " before " << *&*II
198                       << "\n");
199     assert(II != MBB.end() && "Didn't find the user in the MBB");
200     MI->removeFromParent();
201     MBB.insert(II, MI);
202     Changed = true;
203   }
204   return Changed;
205 }
206 
207 bool Localizer::runOnMachineFunction(MachineFunction &MF) {
208   // If the ISel pipeline failed, do not bother running that pass.
209   if (MF.getProperties().hasProperty(
210           MachineFunctionProperties::Property::FailedISel))
211     return false;
212 
213   LLVM_DEBUG(dbgs() << "Localize instructions for: " << MF.getName() << '\n');
214 
215   init(MF);
216 
217   // Keep track of the instructions we localized. We'll do a second pass of
218   // intra-block localization to further reduce live ranges.
219   SmallPtrSet<MachineInstr *, 32> LocalizedInstrs;
220 
221   bool Changed = localizeInterBlock(MF, LocalizedInstrs);
222   return Changed |= localizeIntraBlock(LocalizedInstrs);
223 }
224