LLVM 24.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"
22#include "llvm/Pass.h"
23#include <utility>
24using namespace llvm;
25
27 std::function<bool(const MachineFunction &)> Ftor) {
28 if (Ftor && !Ftor(MF))
29 return false;
30
31 bool Changed = false;
32 for (MachineBasicBlock &MBB : MF) {
33 for (MachineBasicBlock::instr_iterator MII = MBB.instr_begin(),
34 MIE = MBB.instr_end(); MII != MIE; ) {
35 MachineInstr *MI = &*MII;
36
37 // Remove BUNDLE instruction and the InsideBundle flags from bundled
38 // instructions.
39 if (MI->isBundle()) {
40 while (++MII != MIE && MII->isBundledWithPred()) {
41 MII->unbundleFromPred();
42 for (MachineOperand &MO : MII->operands()) {
43 if (MO.isReg() && MO.isInternalRead())
44 MO.setIsInternalRead(false);
45 }
46 }
47 MI->eraseFromParent();
48
49 Changed = true;
50 continue;
51 }
52
53 ++MII;
54 }
55 }
56
57 return Changed;
58}
59
60namespace {
61
62class UnpackMachineBundlesLegacy : public MachineFunctionPass {
63public:
64 static char ID; // Pass identification
65 UnpackMachineBundlesLegacy(
66 std::function<bool(const MachineFunction &)> Ftor = nullptr)
67 : MachineFunctionPass(ID), PredicateFtor(std::move(Ftor)) {}
68
69 bool runOnMachineFunction(MachineFunction &MF) override;
70
71private:
72 std::function<bool(const MachineFunction &)> PredicateFtor;
73};
74} // end anonymous namespace
75
83
84char UnpackMachineBundlesLegacy::ID = 0;
85char &llvm::UnpackMachineBundlesID = UnpackMachineBundlesLegacy::ID;
86INITIALIZE_PASS(UnpackMachineBundlesLegacy, "unpack-mi-bundles",
87 "Unpack machine instruction bundles", false, false)
88
89bool UnpackMachineBundlesLegacy::runOnMachineFunction(MachineFunction &MF) {
90 return unpackBundles(MF, PredicateFtor);
91}
92
94 std::function<bool(const MachineFunction &)> Ftor) {
95 return new UnpackMachineBundlesLegacy(std::move(Ftor));
96}
97
98/// Return the first DebugLoc that has line number information, given a
99/// range of instructions. The search range is from FirstMI to LastMI
100/// (exclusive). Otherwise return the first DILocation or an empty location if
101/// there are none.
104 DebugLoc DL;
105 for (auto MII = FirstMI; MII != LastMI; ++MII) {
106 if (DebugLoc MIIDL = MII->getDebugLoc()) {
107 if (MIIDL.getLine() != 0)
108 return MIIDL;
109 DL = MIIDL.get();
110 }
111 }
112 return DL;
113}
114
115/// Check if target reg is contained in given lists, which are:
116/// LocalDefsV as given list for virtual regs
117/// LocalDefsP as given list for physical regs, in BitVector[RegUnit] form
119 const BitVector &LocalDefsP, Register Reg,
120 const TargetRegisterInfo *TRI) {
121 if (Reg.isPhysical()) {
122 for (MCRegUnit Unit : TRI->regunits(Reg.asMCReg()))
123 if (!LocalDefsP[static_cast<unsigned>(Unit)])
124 return false;
125
126 return true;
127 }
128 return LocalDefsV.contains(Reg);
129}
130
131/// finalizeBundle - Finalize a machine instruction bundle which includes
132/// a sequence of instructions starting from FirstMI to LastMI (exclusive).
133/// This routine adds a BUNDLE instruction to represent the bundle, it adds
134/// IsInternalRead markers to MachineOperands which are defined inside the
135/// bundle, and it copies externally visible defs and uses to the BUNDLE
136/// instruction.
140 assert(FirstMI != LastMI && "Empty bundle?");
141 MIBundleBuilder Bundle(MBB, FirstMI, LastMI);
142
143 MachineFunction &MF = *MBB.getParent();
146
148 BuildMI(MF, getDebugLoc(FirstMI, LastMI), TII->get(TargetOpcode::BUNDLE));
149 Bundle.prepend(MIB);
150
152 BitVector LocalDefsP(TRI->getNumRegUnits());
153 SmallSet<Register, 8> DeadDefSet;
155 SmallSet<Register, 8> KilledUseSet;
156 SmallSet<Register, 8> UndefUseSet;
159 for (auto MII = FirstMI; MII != LastMI; ++MII) {
160 // Debug instructions have no effects to track.
161 if (MII->isDebugInstr())
162 continue;
163
164 for (MachineOperand &MO : MII->all_uses()) {
165 Register Reg = MO.getReg();
166 if (!Reg)
167 continue;
168
169 if (containsReg(LocalDefs, LocalDefsP, Reg, TRI)) {
170 MO.setIsInternalRead();
171 if (MO.isKill()) {
172 // Internal def is now killed.
173 DeadDefSet.insert(Reg);
174 }
175 } else {
176 if (ExternUses.insert(Reg)) {
177 if (MO.isUndef())
178 UndefUseSet.insert(Reg);
179 }
180 if (MO.isKill()) {
181 // External def is now killed.
182 KilledUseSet.insert(Reg);
183 }
184 if (MO.isTied() && Reg.isVirtual()) {
185 // Record tied operand constraints that involve virtual registers so
186 // that bundles that are formed pre-register allocation reflect the
187 // relevant constraints.
188 unsigned TiedIdx = MII->findTiedOperandIdx(MO.getOperandNo());
189 MachineOperand &TiedMO = MII->getOperand(TiedIdx);
190 Register DefReg = TiedMO.getReg();
191 TiedOperands.emplace_back(DefReg, Reg);
192 }
193 }
194 }
195
196 for (MachineOperand &MO : MII->all_defs()) {
197 Register Reg = MO.getReg();
198 if (!Reg)
199 continue;
200
201 if (LocalDefs.insert(Reg)) {
202 if (!MO.isDead() && Reg.isPhysical()) {
203 for (MCRegUnit Unit : TRI->regunits(Reg.asMCReg()))
204 LocalDefsP.set(static_cast<unsigned>(Unit));
205 }
206 } else {
207 if (!MO.isDead()) {
208 // Re-defined inside the bundle, it's no longer dead.
209 DeadDefSet.erase(Reg);
210 }
211 }
212 if (MO.isDead())
213 DeadDefSet.insert(Reg);
214 }
215
216 // Set FrameSetup/FrameDestroy for the bundle. If any of the instructions
217 // got the property, then also set it on the bundle.
218 if (MII->getFlag(MachineInstr::FrameSetup))
220 if (MII->getFlag(MachineInstr::FrameDestroy))
222
223 if (MII->mayLoadOrStore())
224 MemMIs.push_back(&*MII);
225 }
226
227 for (Register Reg : LocalDefs) {
228 // If it's not live beyond end of the bundle, mark it dead.
229 bool isDead = DeadDefSet.contains(Reg);
230 MIB.addReg(Reg, getDefRegState(true) | getDeadRegState(isDead) |
231 getImplRegState(true));
232 }
233
234 for (Register Reg : ExternUses) {
235 bool isKill = KilledUseSet.contains(Reg);
236 bool isUndef = UndefUseSet.contains(Reg);
237 MIB.addReg(Reg, getKillRegState(isKill) | getUndefRegState(isUndef) |
238 getImplRegState(true));
239 }
240
241 for (auto [DefReg, UseReg] : TiedOperands) {
242 unsigned DefIdx =
243 std::distance(LocalDefs.begin(), llvm::find(LocalDefs, DefReg));
244 unsigned UseIdx =
245 std::distance(ExternUses.begin(), llvm::find(ExternUses, UseReg));
246 assert(DefIdx < LocalDefs.size());
247 assert(UseIdx < ExternUses.size());
248 MIB->tieOperands(DefIdx, LocalDefs.size() + UseIdx);
249 }
250
251 MIB->cloneMergedMemRefs(MF, MemMIs);
252}
253
254/// finalizeBundle - Same functionality as the previous finalizeBundle except
255/// the last instruction in the bundle is not provided as an input. This is
256/// used in cases where bundles are pre-determined by marking instructions
257/// with 'InsideBundle' marker. It returns the MBB instruction iterator that
258/// points to the end of the bundle.
263 MachineBasicBlock::instr_iterator LastMI = std::next(FirstMI);
264 while (LastMI != E && LastMI->isInsideBundle())
265 ++LastMI;
266 finalizeBundle(MBB, FirstMI, LastMI);
267 return LastMI;
268}
269
270/// finalizeBundles - Finalize instruction bundles in the specified
271/// MachineFunction. Return true if any bundles are finalized.
273 bool Changed = false;
274 for (MachineBasicBlock &MBB : MF) {
275 MachineBasicBlock::instr_iterator MII = MBB.instr_begin();
276 MachineBasicBlock::instr_iterator MIE = MBB.instr_end();
277 if (MII == MIE)
278 continue;
279 assert(!MII->isInsideBundle() &&
280 "First instr cannot be inside bundle before finalization!");
281
282 for (++MII; MII != MIE; ) {
283 if (!MII->isInsideBundle())
284 ++MII;
285 else {
286 MII = finalizeBundle(MBB, std::prev(MII));
287 Changed = true;
288 }
289 }
290 }
291
292 return Changed;
293}
294
297 SmallVectorImpl<std::pair<MachineInstr *, unsigned>> *Ops) {
298 VirtRegInfo RI = {false, false, false};
299 for (MIBundleOperands O(MI); O.isValid(); ++O) {
300 MachineOperand &MO = *O;
301 if (!MO.isReg() || MO.getReg() != Reg)
302 continue;
303
304 // Remember each (MI, OpNo) that refers to Reg.
305 if (Ops)
306 Ops->push_back(std::make_pair(MO.getParent(), O.getOperandNo()));
307
308 // Both defs and uses can read virtual registers.
309 if (MO.readsReg()) {
310 RI.Reads = true;
311 if (MO.isDef())
312 RI.Tied = true;
313 }
314
315 // Only defs can write.
316 if (MO.isDef())
317 RI.Writes = true;
318 else if (!RI.Tied &&
319 MO.getParent()->isRegTiedToDefOperand(O.getOperandNo()))
320 RI.Tied = true;
321 }
322 return RI;
323}
324
325std::pair<LaneBitmask, LaneBitmask>
327 const MachineRegisterInfo &MRI,
328 const TargetRegisterInfo &TRI) {
329
330 LaneBitmask UseMask, DefMask;
331
332 for (const MachineOperand &MO : const_mi_bundle_ops(MI)) {
333 if (!MO.isReg() || MO.getReg() != Reg)
334 continue;
335
336 unsigned SubReg = MO.getSubReg();
337 if (SubReg == 0 && MO.isUse() && !MO.isUndef())
338 UseMask |= MRI.getMaxLaneMaskForVReg(Reg);
339
340 LaneBitmask SubRegMask = TRI.getSubRegIndexLaneMask(SubReg);
341 if (MO.isDef()) {
342 if (!MO.isUndef())
343 UseMask |= ~SubRegMask;
344 DefMask |= SubRegMask;
345 } else if (!MO.isUndef())
346 UseMask |= SubRegMask;
347 }
348
349 return {UseMask, DefMask};
350}
351
353 const TargetRegisterInfo *TRI) {
354 bool AllDefsDead = true;
355 PhysRegInfo PRI = {false, false, false, false, false, false, false, false};
356
357 assert(Reg.isPhysical() && "analyzePhysReg not given a physical register!");
358 for (const MachineOperand &MO : const_mi_bundle_ops(MI)) {
359 if (MO.isRegMask() && MO.clobbersPhysReg(Reg)) {
360 PRI.Clobbered = true;
361 continue;
362 }
363
364 if (!MO.isReg())
365 continue;
366
367 Register MOReg = MO.getReg();
368 if (!MOReg || !MOReg.isPhysical())
369 continue;
370
371 if (!TRI->regsOverlap(MOReg, Reg))
372 continue;
373
374 bool Covered = TRI->isSuperRegisterEq(Reg, MOReg);
375 if (MO.readsReg()) {
376 PRI.Read = true;
377 if (Covered) {
378 PRI.FullyRead = true;
379 if (MO.isKill())
380 PRI.Killed = true;
381 }
382 } else if (MO.isDef()) {
383 PRI.Defined = true;
384 if (Covered)
385 PRI.FullyDefined = true;
386 if (!MO.isDead())
387 AllDefsDead = false;
388 }
389 }
390
391 if (AllDefsDead) {
392 if (PRI.FullyDefined || PRI.Clobbered)
393 PRI.DeadDef = true;
394 else if (PRI.Defined)
395 PRI.PartialDeadDef = true;
396 }
397
398 return PRI;
399}
400
404 // For testing purposes, bundle the entire contents of each basic block
405 // except for terminators.
406 for (MachineBasicBlock &MBB : MF)
407 finalizeBundle(MBB, MBB.instr_begin(), MBB.getFirstInstrTerminator());
409}
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
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 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)
Func MI getDebugLoc()))
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()
Set all bits in the bitvector.
Definition BitVector.h:366
A debug info location.
Definition DebugLoc.h:126
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:258
iterator begin()
Get an iterator to the beginning of the SetVector.
Definition SetVector.h:112
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:345
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.
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.