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