xref: /llvm-project/llvm/lib/CodeGen/GlobalISel/Localizer.cpp (revision 05da2fe52162c80dfa18aedf70cf73cb11201811)
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/ADT/DenseMap.h"
14 #include "llvm/Analysis/TargetTransformInfo.h"
15 #include "llvm/CodeGen/MachineRegisterInfo.h"
16 #include "llvm/InitializePasses.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   case TargetOpcode::G_INTTOPTR:
80     return true;
81   case TargetOpcode::G_GLOBAL_VALUE: {
82     unsigned RematCost = TTI->getGISelRematGlobalCost();
83     Register Reg = MI.getOperand(0).getReg();
84     unsigned MaxUses = maxUses(RematCost);
85     if (MaxUses == UINT_MAX)
86       return true; // Remats are "free" so always localize.
87     bool B = isUsesAtMost(Reg, MaxUses);
88     return B;
89   }
90   }
91 }
92 
93 void Localizer::getAnalysisUsage(AnalysisUsage &AU) const {
94   AU.addRequired<TargetTransformInfoWrapperPass>();
95   getSelectionDAGFallbackAnalysisUsage(AU);
96   MachineFunctionPass::getAnalysisUsage(AU);
97 }
98 
99 bool Localizer::isLocalUse(MachineOperand &MOUse, const MachineInstr &Def,
100                            MachineBasicBlock *&InsertMBB) {
101   MachineInstr &MIUse = *MOUse.getParent();
102   InsertMBB = MIUse.getParent();
103   if (MIUse.isPHI())
104     InsertMBB = MIUse.getOperand(MIUse.getOperandNo(&MOUse) + 1).getMBB();
105   return InsertMBB == Def.getParent();
106 }
107 
108 bool Localizer::localizeInterBlock(MachineFunction &MF,
109                                    LocalizedSetVecT &LocalizedInstrs) {
110   bool Changed = false;
111   DenseMap<std::pair<MachineBasicBlock *, unsigned>, unsigned> MBBWithLocalDef;
112 
113   // Since the IRTranslator only emits constants into the entry block, and the
114   // rest of the GISel pipeline generally emits constants close to their users,
115   // we only localize instructions in the entry block here. This might change if
116   // we start doing CSE across blocks.
117   auto &MBB = MF.front();
118   for (auto RI = MBB.rbegin(), RE = MBB.rend(); RI != RE; ++RI) {
119     MachineInstr &MI = *RI;
120     if (!shouldLocalize(MI))
121       continue;
122     LLVM_DEBUG(dbgs() << "Should localize: " << MI);
123     assert(MI.getDesc().getNumDefs() == 1 &&
124            "More than one definition not supported yet");
125     Register Reg = MI.getOperand(0).getReg();
126     // Check if all the users of MI are local.
127     // We are going to invalidation the list of use operands, so we
128     // can't use range iterator.
129     for (auto MOIt = MRI->use_begin(Reg), MOItEnd = MRI->use_end();
130          MOIt != MOItEnd;) {
131       MachineOperand &MOUse = *MOIt++;
132       // Check if the use is already local.
133       MachineBasicBlock *InsertMBB;
134       LLVM_DEBUG(MachineInstr &MIUse = *MOUse.getParent();
135                  dbgs() << "Checking use: " << MIUse
136                         << " #Opd: " << MIUse.getOperandNo(&MOUse) << '\n');
137       if (isLocalUse(MOUse, MI, InsertMBB))
138         continue;
139       LLVM_DEBUG(dbgs() << "Fixing non-local use\n");
140       Changed = true;
141       auto MBBAndReg = std::make_pair(InsertMBB, Reg);
142       auto NewVRegIt = MBBWithLocalDef.find(MBBAndReg);
143       if (NewVRegIt == MBBWithLocalDef.end()) {
144         // Create the localized instruction.
145         MachineInstr *LocalizedMI = MF.CloneMachineInstr(&MI);
146         LocalizedInstrs.insert(LocalizedMI);
147         MachineInstr &UseMI = *MOUse.getParent();
148         if (MRI->hasOneUse(Reg) && !UseMI.isPHI())
149           InsertMBB->insert(InsertMBB->SkipPHIsAndLabels(UseMI), LocalizedMI);
150         else
151           InsertMBB->insert(InsertMBB->SkipPHIsAndLabels(InsertMBB->begin()),
152                             LocalizedMI);
153 
154         // Set a new register for the definition.
155         Register NewReg = MRI->createGenericVirtualRegister(MRI->getType(Reg));
156         MRI->setRegClassOrRegBank(NewReg, MRI->getRegClassOrRegBank(Reg));
157         LocalizedMI->getOperand(0).setReg(NewReg);
158         NewVRegIt =
159             MBBWithLocalDef.insert(std::make_pair(MBBAndReg, NewReg)).first;
160         LLVM_DEBUG(dbgs() << "Inserted: " << *LocalizedMI);
161       }
162       LLVM_DEBUG(dbgs() << "Update use with: " << printReg(NewVRegIt->second)
163                         << '\n');
164       // Update the user reg.
165       MOUse.setReg(NewVRegIt->second);
166     }
167   }
168   return Changed;
169 }
170 
171 bool Localizer::localizeIntraBlock(LocalizedSetVecT &LocalizedInstrs) {
172   bool Changed = false;
173 
174   // For each already-localized instruction which has multiple users, then we
175   // scan the block top down from the current position until we hit one of them.
176 
177   // FIXME: Consider doing inst duplication if live ranges are very long due to
178   // many users, but this case may be better served by regalloc improvements.
179 
180   for (MachineInstr *MI : LocalizedInstrs) {
181     Register Reg = MI->getOperand(0).getReg();
182     MachineBasicBlock &MBB = *MI->getParent();
183     // All of the user MIs of this reg.
184     SmallPtrSet<MachineInstr *, 32> Users;
185     for (MachineInstr &UseMI : MRI->use_nodbg_instructions(Reg)) {
186       if (!UseMI.isPHI())
187         Users.insert(&UseMI);
188     }
189     // If all the users were PHIs then they're not going to be in our block,
190     // don't try to move this instruction.
191     if (Users.empty())
192       continue;
193 
194     MachineBasicBlock::iterator II(MI);
195     ++II;
196     while (II != MBB.end() && !Users.count(&*II))
197       ++II;
198 
199     LLVM_DEBUG(dbgs() << "Intra-block: moving " << *MI << " before " << *&*II
200                       << "\n");
201     assert(II != MBB.end() && "Didn't find the user in the MBB");
202     MI->removeFromParent();
203     MBB.insert(II, MI);
204     Changed = true;
205   }
206   return Changed;
207 }
208 
209 bool Localizer::runOnMachineFunction(MachineFunction &MF) {
210   // If the ISel pipeline failed, do not bother running that pass.
211   if (MF.getProperties().hasProperty(
212           MachineFunctionProperties::Property::FailedISel))
213     return false;
214 
215   LLVM_DEBUG(dbgs() << "Localize instructions for: " << MF.getName() << '\n');
216 
217   init(MF);
218 
219   // Keep track of the instructions we localized. We'll do a second pass of
220   // intra-block localization to further reduce live ranges.
221   LocalizedSetVecT LocalizedInstrs;
222 
223   bool Changed = localizeInterBlock(MF, LocalizedInstrs);
224   Changed |= localizeIntraBlock(LocalizedInstrs);
225   return Changed;
226 }
227