LLVM 23.0.0git
MachineInstrBundle.cpp
Go to the documentation of this file.
1//===-- lib/CodeGen/MachineInstrBundle.cpp --------------------------------===//
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
10#include "llvm/ADT/SetVector.h"
11#include "llvm/ADT/SmallSet.h"
17#include "llvm/CodeGen/Passes.h"
21#include "llvm/IR/PassManager.h"
23#include "llvm/Pass.h"
24#include "llvm/PassRegistry.h"
25#include <utility>
26using namespace llvm;
27
29 std::function<bool(const MachineFunction &)> Ftor) {
30 if (Ftor && !Ftor(MF))
31 return false;
32
33 bool Changed = false;
34 for (MachineBasicBlock &MBB : MF) {
35 for (MachineBasicBlock::instr_iterator MII = MBB.instr_begin(),
36 MIE = MBB.instr_end(); MII != MIE; ) {
37 MachineInstr *MI = &*MII;
38
39 // Remove BUNDLE instruction and the InsideBundle flags from bundled
40 // instructions.
41 if (MI->isBundle()) {
42 while (++MII != MIE && MII->isBundledWithPred()) {
43 MII->unbundleFromPred();
44 for (MachineOperand &MO : MII->operands()) {
45 if (MO.isReg() && MO.isInternalRead())
46 MO.setIsInternalRead(false);
47 }
48 }
49 MI->eraseFromParent();
50
51 Changed = true;
52 continue;
53 }
54
55 ++MII;
56 }
57 }
58
59 return Changed;
60}
61
62namespace {
63
64class UnpackMachineBundlesLegacy : public MachineFunctionPass {
65public:
66 static char ID; // Pass identification
67 UnpackMachineBundlesLegacy(
68 std::function<bool(const MachineFunction &)> Ftor = nullptr)
69 : MachineFunctionPass(ID), PredicateFtor(std::move(Ftor)) {}
70
71 bool runOnMachineFunction(MachineFunction &MF) override;
72
73private:
74 std::function<bool(const MachineFunction &)> PredicateFtor;
75};
76} // end anonymous namespace
77
85
86char UnpackMachineBundlesLegacy::ID = 0;
87char &llvm::UnpackMachineBundlesID = UnpackMachineBundlesLegacy::ID;
88INITIALIZE_PASS(UnpackMachineBundlesLegacy, "unpack-mi-bundles",
89 "Unpack machine instruction bundles", false, false)
90
91bool UnpackMachineBundlesLegacy::runOnMachineFunction(MachineFunction &MF) {
92 return unpackBundles(MF, PredicateFtor);
93}
94
96 std::function<bool(const MachineFunction &)> Ftor) {
97 return new UnpackMachineBundlesLegacy(std::move(Ftor));
98}
99
100/// Return the first DebugLoc that has line number information, given a
101/// range of instructions. The search range is from FirstMI to LastMI
102/// (exclusive). Otherwise return the first DILocation or an empty location if
103/// there are none.
106 DebugLoc DL;
107 for (auto MII = FirstMI; MII != LastMI; ++MII) {
108 if (DebugLoc MIIDL = MII->getDebugLoc()) {
109 if (MIIDL.getLine() != 0)
110 return MIIDL;
111 DL = MIIDL.get();
112 }
113 }
114 return DL;
115}
116
117/// Check if target reg is contained in given lists, which are:
118/// LocalDefsV as given list for virtual regs
119/// LocalDefsP as given list for physical regs, in BitVector[RegUnit] form
121 const BitVector &LocalDefsP, Register Reg,
122 const TargetRegisterInfo *TRI) {
123 if (Reg.isPhysical()) {
124 for (MCRegUnit Unit : TRI->regunits(Reg.asMCReg()))
125 if (!LocalDefsP[static_cast<unsigned>(Unit)])
126 return false;
127
128 return true;
129 }
130 return LocalDefsV.contains(Reg);
131}
132
133/// finalizeBundle - Finalize a machine instruction bundle which includes
134/// a sequence of instructions starting from FirstMI to LastMI (exclusive).
135/// This routine adds a BUNDLE instruction to represent the bundle, it adds
136/// IsInternalRead markers to MachineOperands which are defined inside the
137/// bundle, and it copies externally visible defs and uses to the BUNDLE
138/// instruction.
142 assert(FirstMI != LastMI && "Empty bundle?");
143 MIBundleBuilder Bundle(MBB, FirstMI, LastMI);
144
145 MachineFunction &MF = *MBB.getParent();
148
150 BuildMI(MF, getDebugLoc(FirstMI, LastMI), TII->get(TargetOpcode::BUNDLE));
151 Bundle.prepend(MIB);
152
154 BitVector LocalDefsP(TRI->getNumRegUnits());
155 SmallSet<Register, 8> DeadDefSet;
157 SmallSet<Register, 8> KilledUseSet;
158 SmallSet<Register, 8> UndefUseSet;
161 for (auto MII = FirstMI; MII != LastMI; ++MII) {
162 // Debug instructions have no effects to track.
163 if (MII->isDebugInstr())
164 continue;
165
166 for (MachineOperand &MO : MII->all_uses()) {
167 Register Reg = MO.getReg();
168 if (!Reg)
169 continue;
170
171 if (containsReg(LocalDefs, LocalDefsP, Reg, TRI)) {
172 MO.setIsInternalRead();
173 if (MO.isKill()) {
174 // Internal def is now killed.
175 DeadDefSet.insert(Reg);
176 }
177 } else {
178 if (ExternUses.insert(Reg)) {
179 if (MO.isUndef())
180 UndefUseSet.insert(Reg);
181 }
182 if (MO.isKill()) {
183 // External def is now killed.
184 KilledUseSet.insert(Reg);
185 }
186 if (MO.isTied() && Reg.isVirtual()) {
187 // Record tied operand constraints that involve virtual registers so
188 // that bundles that are formed pre-register allocation reflect the
189 // relevant constraints.
190 unsigned TiedIdx = MII->findTiedOperandIdx(MO.getOperandNo());
191 MachineOperand &TiedMO = MII->getOperand(TiedIdx);
192 Register DefReg = TiedMO.getReg();
193 TiedOperands.emplace_back(DefReg, Reg);
194 }
195 }
196 }
197
198 for (MachineOperand &MO : MII->all_defs()) {
199 Register Reg = MO.getReg();
200 if (!Reg)
201 continue;
202
203 if (LocalDefs.insert(Reg)) {
204 if (!MO.isDead() && Reg.isPhysical()) {
205 for (MCRegUnit Unit : TRI->regunits(Reg.asMCReg()))
206 LocalDefsP.set(static_cast<unsigned>(Unit));
207 }
208 } else {
209 if (!MO.isDead()) {
210 // Re-defined inside the bundle, it's no longer dead.
211 DeadDefSet.erase(Reg);
212 }
213 }
214 if (MO.isDead())
215 DeadDefSet.insert(Reg);
216 }
217
218 // Set FrameSetup/FrameDestroy for the bundle. If any of the instructions
219 // got the property, then also set it on the bundle.
220 if (MII->getFlag(MachineInstr::FrameSetup))
222 if (MII->getFlag(MachineInstr::FrameDestroy))
224
225 if (MII->mayLoadOrStore())
226 MemMIs.push_back(&*MII);
227 }
228
229 for (Register Reg : LocalDefs) {
230 // If it's not live beyond end of the bundle, mark it dead.
231 bool isDead = DeadDefSet.contains(Reg);
232 MIB.addReg(Reg, getDefRegState(true) | getDeadRegState(isDead) |
233 getImplRegState(true));
234 }
235
236 for (Register Reg : ExternUses) {
237 bool isKill = KilledUseSet.contains(Reg);
238 bool isUndef = UndefUseSet.contains(Reg);
239 MIB.addReg(Reg, getKillRegState(isKill) | getUndefRegState(isUndef) |
240 getImplRegState(true));
241 }
242
243 for (auto [DefReg, UseReg] : TiedOperands) {
244 unsigned DefIdx =
245 std::distance(LocalDefs.begin(), llvm::find(LocalDefs, DefReg));
246 unsigned UseIdx =
247 std::distance(ExternUses.begin(), llvm::find(ExternUses, UseReg));
248 assert(DefIdx < LocalDefs.size());
249 assert(UseIdx < ExternUses.size());
250 MIB->tieOperands(DefIdx, LocalDefs.size() + UseIdx);
251 }
252
253 MIB->cloneMergedMemRefs(MF, MemMIs);
254}
255
256/// finalizeBundle - Same functionality as the previous finalizeBundle except
257/// the last instruction in the bundle is not provided as an input. This is
258/// used in cases where bundles are pre-determined by marking instructions
259/// with 'InsideBundle' marker. It returns the MBB instruction iterator that
260/// points to the end of the bundle.
265 MachineBasicBlock::instr_iterator LastMI = std::next(FirstMI);
266 while (LastMI != E && LastMI->isInsideBundle())
267 ++LastMI;
268 finalizeBundle(MBB, FirstMI, LastMI);
269 return LastMI;
270}
271
272/// finalizeBundles - Finalize instruction bundles in the specified
273/// MachineFunction. Return true if any bundles are finalized.
275 bool Changed = false;
276 for (MachineBasicBlock &MBB : MF) {
277 MachineBasicBlock::instr_iterator MII = MBB.instr_begin();
278 MachineBasicBlock::instr_iterator MIE = MBB.instr_end();
279 if (MII == MIE)
280 continue;
281 assert(!MII->isInsideBundle() &&
282 "First instr cannot be inside bundle before finalization!");
283
284 for (++MII; MII != MIE; ) {
285 if (!MII->isInsideBundle())
286 ++MII;
287 else {
288 MII = finalizeBundle(MBB, std::prev(MII));
289 Changed = true;
290 }
291 }
292 }
293
294 return Changed;
295}
296
299 SmallVectorImpl<std::pair<MachineInstr *, unsigned>> *Ops) {
300 VirtRegInfo RI = {false, false, false};
301 for (MIBundleOperands O(MI); O.isValid(); ++O) {
302 MachineOperand &MO = *O;
303 if (!MO.isReg() || MO.getReg() != Reg)
304 continue;
305
306 // Remember each (MI, OpNo) that refers to Reg.
307 if (Ops)
308 Ops->push_back(std::make_pair(MO.getParent(), O.getOperandNo()));
309
310 // Both defs and uses can read virtual registers.
311 if (MO.readsReg()) {
312 RI.Reads = true;
313 if (MO.isDef())
314 RI.Tied = true;
315 }
316
317 // Only defs can write.
318 if (MO.isDef())
319 RI.Writes = true;
320 else if (!RI.Tied &&
321 MO.getParent()->isRegTiedToDefOperand(O.getOperandNo()))
322 RI.Tied = true;
323 }
324 return RI;
325}
326
327std::pair<LaneBitmask, LaneBitmask>
329 const MachineRegisterInfo &MRI,
330 const TargetRegisterInfo &TRI) {
331
332 LaneBitmask UseMask, DefMask;
333
334 for (const MachineOperand &MO : const_mi_bundle_ops(MI)) {
335 if (!MO.isReg() || MO.getReg() != Reg)
336 continue;
337
338 unsigned SubReg = MO.getSubReg();
339 if (SubReg == 0 && MO.isUse() && !MO.isUndef())
340 UseMask |= MRI.getMaxLaneMaskForVReg(Reg);
341
342 LaneBitmask SubRegMask = TRI.getSubRegIndexLaneMask(SubReg);
343 if (MO.isDef()) {
344 if (!MO.isUndef())
345 UseMask |= ~SubRegMask;
346 DefMask |= SubRegMask;
347 } else if (!MO.isUndef())
348 UseMask |= SubRegMask;
349 }
350
351 return {UseMask, DefMask};
352}
353
355 const TargetRegisterInfo *TRI) {
356 bool AllDefsDead = true;
357 PhysRegInfo PRI = {false, false, false, false, false, false, false, false};
358
359 assert(Reg.isPhysical() && "analyzePhysReg not given a physical register!");
360 for (const MachineOperand &MO : const_mi_bundle_ops(MI)) {
361 if (MO.isRegMask() && MO.clobbersPhysReg(Reg)) {
362 PRI.Clobbered = true;
363 continue;
364 }
365
366 if (!MO.isReg())
367 continue;
368
369 Register MOReg = MO.getReg();
370 if (!MOReg || !MOReg.isPhysical())
371 continue;
372
373 if (!TRI->regsOverlap(MOReg, Reg))
374 continue;
375
376 bool Covered = TRI->isSuperRegisterEq(Reg, MOReg);
377 if (MO.readsReg()) {
378 PRI.Read = true;
379 if (Covered) {
380 PRI.FullyRead = true;
381 if (MO.isKill())
382 PRI.Killed = true;
383 }
384 } else if (MO.isDef()) {
385 PRI.Defined = true;
386 if (Covered)
387 PRI.FullyDefined = true;
388 if (!MO.isDead())
389 AllDefsDead = false;
390 }
391 }
392
393 if (AllDefsDead) {
394 if (PRI.FullyDefined || PRI.Clobbered)
395 PRI.DeadDef = true;
396 else if (PRI.Defined)
397 PRI.PartialDeadDef = true;
398 }
399
400 return PRI;
401}
402
406 // For testing purposes, bundle the entire contents of each basic block
407 // except for terminators.
408 for (MachineBasicBlock &MBB : MF)
409 finalizeBundle(MBB, MBB.instr_begin(), MBB.getFirstInstrTerminator());
411}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static Register UseReg(const MachineOperand &MO)
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
This header defines various interfaces for pass management in LLVM.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static bool unpackBundles(MachineFunction &MF, std::function< bool(const MachineFunction &)> Ftor)
static bool containsReg(SmallSetVector< Register, 32 > LocalDefsV, const BitVector &LocalDefsP, Register Reg, const TargetRegisterInfo *TRI)
Check if target reg is contained in given lists, which are: LocalDefsV as given list for virtual regs...
static DebugLoc getDebugLoc(MachineBasicBlock::instr_iterator FirstMI, MachineBasicBlock::instr_iterator LastMI)
Return the first DebugLoc that has line number information, given a range of instructions.
static bool isUndef(const MachineInstr &MI)
Register Reg
Register const TargetRegisterInfo * TRI
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
bool isDead(const MachineInstr &MI, const MachineRegisterInfo &MRI)
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallSet class.
This file defines the SmallVector class.
BitVector & set()
Definition BitVector.h:370
A debug info location.
Definition DebugLoc.h:123
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
Helper class for constructing bundles of MachineInstrs.
MIBundleBuilder & prepend(MachineInstr *MI)
Insert MI into MBB by prepending it to the instructions in the bundle.
MIBundleOperands - Iterate over all operands in a bundle of machine instructions.
Instructions::iterator instr_iterator
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & setMIFlag(MachineInstr::MIFlag Flag) const
Representation of each machine instruction.
bool isRegTiedToDefOperand(unsigned UseOpIdx, unsigned *DefOpIdx=nullptr) const
Return true if the use operand of the specified index is tied to a def operand.
LLVM_ABI void cloneMergedMemRefs(MachineFunction &MF, ArrayRef< const MachineInstr * > MIs)
Clone the merge of multiple MachineInstrs' memory reference descriptors list and replace ours with it...
LLVM_ABI void tieOperands(unsigned DefIdx, unsigned UseIdx)
Add a tie between the register operands at DefIdx and UseIdx.
MachineOperand class - Representation of each machine instruction operand.
bool readsReg() const
readsReg - Returns true if this operand reads the previous value of its register.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI LaneBitmask getMaxLaneMaskForVReg(Register Reg) const
Returns a mask covering all bits that can appear in lane masks of subregisters of the virtual registe...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
bool contains(const_arg_type key) const
Check if the SetVector contains the given key.
Definition SetVector.h:252
iterator begin()
Get an iterator to the beginning of the SetVector.
Definition SetVector.h:106
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:151
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:339
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
bool erase(const T &V)
Definition SmallSet.h:200
bool contains(const T &V) const
Check if the SmallSet contains the given element.
Definition SmallSet.h:229
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
PreservedAnalyses LLVM_ABI run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
Changed
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
LLVM_ABI void finalizeBundle(MachineBasicBlock &MBB, MachineBasicBlock::instr_iterator FirstMI, MachineBasicBlock::instr_iterator LastMI)
finalizeBundle - Finalize a machine instruction bundle which includes a sequence of instructions star...
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1765
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
constexpr RegState getImplRegState(bool B)
constexpr RegState getKillRegState(bool B)
LLVM_ABI bool finalizeBundles(MachineFunction &MF)
finalizeBundles - Finalize instruction bundles in the specified MachineFunction.
LLVM_ABI PhysRegInfo AnalyzePhysRegInBundle(const MachineInstr &MI, Register Reg, const TargetRegisterInfo *TRI)
AnalyzePhysRegInBundle - Analyze how the current instruction or bundle uses a physical register.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
constexpr RegState getDeadRegState(bool B)
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
LLVM_ABI FunctionPass * createUnpackMachineBundlesLegacy(std::function< bool(const MachineFunction &)> Ftor)
constexpr RegState getDefRegState(bool B)
iterator_range< ConstMIBundleOperands > const_mi_bundle_ops(const MachineInstr &MI)
LLVM_ABI VirtRegInfo AnalyzeVirtRegInBundle(MachineInstr &MI, Register Reg, SmallVectorImpl< std::pair< MachineInstr *, unsigned > > *Ops=nullptr)
AnalyzeVirtRegInBundle - Analyze how the current instruction or bundle uses a virtual register.
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1917
constexpr RegState getUndefRegState(bool B)
LLVM_ABI char & UnpackMachineBundlesID
UnpackMachineBundles - This pass unpack machine instruction bundles.
LLVM_ABI std::pair< LaneBitmask, LaneBitmask > AnalyzeVirtRegLanesInBundle(const MachineInstr &MI, Register Reg, const MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI)
Return a pair of lane masks (reads, writes) indicating which lanes this instruction uses with Reg.
Information about how a physical register Reg is used by a set of operands.
bool Read
Reg or one of its aliases is read.
bool Defined
Reg or one of its aliases is defined.
bool Killed
There is a use operand of reg or a super-register with kill flag set.
bool PartialDeadDef
Reg is Defined and all defs of reg or an overlapping register are dead.
bool Clobbered
There is a regmask operand indicating Reg is clobbered.
bool FullyRead
Reg or a super-register is read. The full register is read.
bool FullyDefined
Reg or a super-register is defined.
VirtRegInfo - Information about a virtual register used by a set of operands.
bool Reads
Reads - One of the operands read the virtual register.
bool Tied
Tied - Uses and defs must use the same register.
bool Writes
Writes - One of the operands writes the virtual register.