LLVM 24.0.0git
InitUndef.cpp
Go to the documentation of this file.
1//===- InitUndef.cpp - Initialize undef value to pseudo ----===//
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//
9// This file implements a function pass that initializes undef value to
10// temporary pseudo instruction to prevent register allocation resulting in a
11// constraint violated result for the particular instruction. It also rewrites
12// the NoReg tied operand back to an IMPLICIT_DEF.
13//
14// Certain instructions have register overlapping constraints, and
15// will cause illegal instruction trap if violated, we use early clobber to
16// model this constraint, but it can't prevent register allocator allocating
17// same or overlapped if the input register is undef value, so convert
18// IMPLICIT_DEF to temporary pseudo instruction and remove it later could
19// prevent that happen, it's not best way to resolve this, and it might
20// change the order of program or increase the register pressure, so ideally we
21// should model the constraint right, but before we model the constraint right,
22// it's the only way to prevent that happen.
23//
24// When we enable the subregister liveness option, it will also trigger the same
25// issue due to the partial of register is undef. If we pseudoinit the whole
26// register, then it will generate redundant COPY instruction. Currently, it
27// will generate INSERT_SUBREG to make sure the whole register is occupied
28// when program encounter operation that has early-clobber constraint.
29//
30//
31// See also: https://github.com/llvm/llvm-project/issues/50157
32//
33// Additionally, this pass rewrites tied operands of instructions
34// from NoReg to IMPLICIT_DEF. (Not that this is a non-overlapping set of
35// operands to the above.) We use NoReg to side step a MachineCSE
36// optimization quality problem but need to convert back before
37// TwoAddressInstruction. See pr64282 for context.
38//
39//===----------------------------------------------------------------------===//
40
42#include "llvm/ADT/SmallSet.h"
53#include "llvm/MC/MCRegister.h"
54#include "llvm/Pass.h"
55#include "llvm/Support/Debug.h"
56
57using namespace llvm;
58
59#define DEBUG_TYPE "init-undef"
60#define INIT_UNDEF_NAME "Init Undef Pass"
61
62namespace {
63
64class InitUndefLegacy : public MachineFunctionPass {
65public:
66 static char ID;
67
68 InitUndefLegacy() : MachineFunctionPass(ID) {}
69
70 bool runOnMachineFunction(MachineFunction &MF) override;
71
72 void getAnalysisUsage(AnalysisUsage &AU) const override {
73 AU.setPreservesCFG();
75 }
76
77 StringRef getPassName() const override { return INIT_UNDEF_NAME; }
78};
79
80class InitUndef {
81 const TargetInstrInfo *TII;
83 const TargetSubtargetInfo *ST;
85
86 // Newly added vregs, assumed to be fully rewritten
89
90public:
91 bool run(MachineFunction &MF);
92
93private:
95 const DeadLaneDetector *DLD);
96 bool handleSubReg(MachineFunction &MF, MachineInstr &MI,
97 const DeadLaneDetector &DLD);
98 bool fixupIllOperand(MachineInstr *MI, MachineOperand &MO);
99 bool handleReg(MachineInstr *MI);
100};
101
102} // end anonymous namespace
103
104char InitUndefLegacy::ID = 0;
105INITIALIZE_PASS(InitUndefLegacy, DEBUG_TYPE, INIT_UNDEF_NAME, false, false)
106char &llvm::InitUndefID = InitUndefLegacy::ID;
107
109 return llvm::any_of(MI.all_defs(), [](const MachineOperand &DefMO) {
110 return DefMO.isReg() && DefMO.isEarlyClobber();
111 });
112}
113
115 for (auto &DefMI : MRI->def_instructions(Reg)) {
116 if (DefMI.getOpcode() == TargetOpcode::IMPLICIT_DEF)
117 return true;
118 }
119 return false;
120}
121
122bool InitUndef::handleReg(MachineInstr *MI) {
123 bool Changed = false;
124 for (auto &UseMO : MI->uses()) {
125 if (!UseMO.isReg())
126 continue;
127 if (UseMO.isTied())
128 continue;
129 if (!UseMO.getReg().isVirtual())
130 continue;
131
132 if (UseMO.isUndef() || findImplictDefMIFromReg(UseMO.getReg(), MRI))
133 Changed |= fixupIllOperand(MI, UseMO);
134 }
135 return Changed;
136}
137
138bool InitUndef::handleSubReg(MachineFunction &MF, MachineInstr &MI,
139 const DeadLaneDetector &DLD) {
140 bool Changed = false;
141
142 for (MachineOperand &UseMO : MI.uses()) {
143 if (!UseMO.isReg())
144 continue;
145 if (!UseMO.getReg().isVirtual())
146 continue;
147 if (UseMO.isTied())
148 continue;
149
150 Register Reg = UseMO.getReg();
151 if (NewRegs.count(Reg))
152 continue;
153 DeadLaneDetector::VRegInfo Info = DLD.getVRegInfo(Reg.virtRegIndex());
154
155 if (Info.UsedLanes == Info.DefinedLanes)
156 continue;
157
158 const TargetRegisterClass *TargetRegClass = MRI->getRegClass(Reg);
159
160 LaneBitmask NeedDef = Info.UsedLanes & ~Info.DefinedLanes;
161
162 LLVM_DEBUG({
163 dbgs() << "Instruction has undef subregister.\n";
164 dbgs() << printReg(Reg, nullptr)
165 << " Used: " << PrintLaneMask(Info.UsedLanes)
166 << " Def: " << PrintLaneMask(Info.DefinedLanes)
167 << " Need Def: " << PrintLaneMask(NeedDef) << "\n";
168 });
169
170 SmallVector<unsigned> SubRegIndexNeedInsert;
171 TRI->getCoveringSubRegIndexes(TargetRegClass, NeedDef,
172 SubRegIndexNeedInsert);
173
174 // It's not possible to create the INIT_UNDEF when there is no register
175 // class associated for the subreg. This may happen for artificial subregs
176 // that are not directly addressable.
177 if (any_of(SubRegIndexNeedInsert, [&](unsigned Ind) -> bool {
178 return !TRI->getSubRegisterClass(TargetRegClass, Ind);
179 }))
180 continue;
181
182 Register LatestReg = Reg;
183 for (auto ind : SubRegIndexNeedInsert) {
184 Changed = true;
185 const TargetRegisterClass *SubRegClass =
186 TRI->getSubRegisterClass(TargetRegClass, ind);
187 Register TmpInitSubReg = MRI->createVirtualRegister(SubRegClass);
188 LLVM_DEBUG(dbgs() << "Register Class ID" << SubRegClass->getID() << "\n");
189 BuildMI(*MI.getParent(), &MI, MI.getDebugLoc(),
190 TII->get(TargetOpcode::INIT_UNDEF), TmpInitSubReg);
191 Register NewReg = MRI->createVirtualRegister(TargetRegClass);
192 BuildMI(*MI.getParent(), &MI, MI.getDebugLoc(),
193 TII->get(TargetOpcode::INSERT_SUBREG), NewReg)
194 .addReg(LatestReg)
195 .addReg(TmpInitSubReg)
196 .addImm(ind);
197 LatestReg = NewReg;
198 }
199
200 UseMO.setReg(LatestReg);
201 }
202
203 return Changed;
204}
205
206bool InitUndef::fixupIllOperand(MachineInstr *MI, MachineOperand &MO) {
207
209 dbgs() << "Emitting PseudoInitUndef Instruction for implicit register "
210 << printReg(MO.getReg()) << '\n');
211
212 const TargetRegisterClass *TargetRegClass = MRI->getRegClass(MO.getReg());
213 LLVM_DEBUG(dbgs() << "Register Class ID" << TargetRegClass->getID() << "\n");
214 Register NewReg = MRI->createVirtualRegister(TargetRegClass);
215 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
216 TII->get(TargetOpcode::INIT_UNDEF), NewReg);
217 MO.setReg(NewReg);
218 if (MO.isUndef())
219 MO.setIsUndef(false);
220 return true;
221}
222
223bool InitUndef::processBasicBlock(MachineFunction &MF, MachineBasicBlock &MBB,
224 const DeadLaneDetector *DLD) {
225 bool Changed = false;
226 for (MachineBasicBlock::iterator I = MBB.begin(); I != MBB.end(); ++I) {
227 MachineInstr &MI = *I;
228
229 // If we used NoReg to represent the passthru, switch this back to being
230 // an IMPLICIT_DEF before TwoAddressInstructions.
231 unsigned UseOpIdx;
232 if (MI.getNumDefs() != 0 && MI.isRegTiedToUseOperand(0, &UseOpIdx)) {
233 MachineOperand &UseMO = MI.getOperand(UseOpIdx);
234 if (UseMO.getReg() == MCRegister::NoRegister) {
235 const TargetRegisterClass *RC =
236 TII->getRegClass(MI.getDesc(), UseOpIdx);
237 Register NewDest = MRI->createVirtualRegister(RC);
238 // We don't have a way to update dead lanes, so keep track of the
239 // new register so that we avoid querying it later.
240 NewRegs.insert(NewDest);
241 BuildMI(MBB, I, I->getDebugLoc(), TII->get(TargetOpcode::IMPLICIT_DEF),
242 NewDest);
243 UseMO.setReg(NewDest);
244 Changed = true;
245 }
246 }
247
248 if (isEarlyClobberMI(MI)) {
249 if (MRI->subRegLivenessEnabled())
250 Changed |= handleSubReg(MF, MI, *DLD);
251 Changed |= handleReg(&MI);
252 }
253 }
254 return Changed;
255}
256
257bool InitUndefLegacy::runOnMachineFunction(MachineFunction &MF) {
258 return InitUndef().run(MF);
259}
260
263 if (!InitUndef().run(MF))
264 return PreservedAnalyses::all();
266 PA.preserveSet<CFGAnalyses>();
267 return PA;
268}
269
270bool InitUndef::run(MachineFunction &MF) {
271 ST = &MF.getSubtarget();
272
273 // The pass is only needed if early-clobber defs and undef ops cannot be
274 // allocated to the same register.
276 return false;
277
278 MRI = &MF.getRegInfo();
279 TII = ST->getInstrInfo();
280 TRI = MRI->getTargetRegisterInfo();
281
282 bool Changed = false;
283 std::unique_ptr<DeadLaneDetector> DLD;
284 if (MRI->subRegLivenessEnabled()) {
285 DLD = std::make_unique<DeadLaneDetector>(MRI, TRI);
286 DLD->computeSubRegisterLaneBitInfo();
287 }
288
289 for (MachineBasicBlock &BB : MF)
290 Changed |= processBasicBlock(MF, BB, DLD.get());
291
292 for (auto *DeadMI : DeadInsts)
293 DeadMI->eraseFromParent();
294 DeadInsts.clear();
295 NewRegs.clear();
296
297 return Changed;
298}
MachineInstrBuilder MachineInstrBuilder & DefMI
MachineBasicBlock & MBB
Analysis that tracks defined/used subregister lanes across COPY instructions and instructions that ge...
#define DEBUG_TYPE
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
static bool isEarlyClobberMI(MachineInstr &MI)
#define INIT_UNDEF_NAME
Definition InitUndef.cpp:60
static bool findImplictDefMIFromReg(Register Reg, MachineRegisterInfo *MRI)
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
This file defines the SmallSet class.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static bool processBasicBlock(MachineBasicBlock &MBB, BlockStateMap &BlockStates, DirtySuccessorsWorkList &DirtySuccessors, bool IsX86INTR, const TargetInstrInfo *TII)
Loop over all of the instructions in the basic block, inserting vzeroupper instructions before functi...
Represent the analysis usage information of a pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:275
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
const VRegInfo & getVRegInfo(unsigned RegIdx) const
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
unsigned getID() const
getID() - Return the register class ID number.
static constexpr unsigned NoRegister
Definition MCRegister.h:60
MachineInstrBundleIterator< MachineInstr > iterator
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
Representation of each machine instruction.
MachineOperand class - Representation of each machine instruction operand.
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
void setIsUndef(bool Val=true)
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
iterator_range< def_instr_iterator > def_instructions(Register Reg) const
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
const TargetRegisterInfo * getTargetRegisterInfo() const
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
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
unsigned virtRegIndex() const
Convert a virtual register number to a 0-based index.
Definition Register.h:87
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
TargetSubtargetInfo - Generic base class for all target subtargets.
virtual bool requiresDisjointEarlyClobberAndUndef() const
Whether the target has instructions where an early-clobber result operand cannot overlap with an unde...
virtual const TargetInstrInfo * getInstrInfo() const
Changed
This is an optimization pass for GlobalISel generic memory operations.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
LLVM_ABI char & InitUndefID
Printable PrintLaneMask(LaneBitmask LaneMask)
Create Printable object to print LaneBitmasks on a raw_ostream.
Definition LaneBitmask.h:92
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58