LLVM 20.0.0git
MachineSSAUpdater.cpp
Go to the documentation of this file.
1//===- MachineSSAUpdater.cpp - Unstructured SSA Update Tool ---------------===//
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 the MachineSSAUpdater class. It's based on SSAUpdater
10// class in lib/Transforms/Utils.
11//
12//===----------------------------------------------------------------------===//
13
15#include "llvm/ADT/DenseMap.h"
26#include "llvm/IR/DebugLoc.h"
27#include "llvm/Support/Debug.h"
31#include <utility>
32
33using namespace llvm;
34
35#define DEBUG_TYPE "machine-ssaupdater"
36
38
40 return *static_cast<AvailableValsTy*>(AV);
41}
42
45 : InsertedPHIs(NewPHI), TII(MF.getSubtarget().getInstrInfo()),
46 MRI(&MF.getRegInfo()) {}
47
49 delete static_cast<AvailableValsTy*>(AV);
50}
51
52/// Initialize - Reset this object to get ready for a new set of SSA
53/// updates.
55 if (!AV)
56 AV = new AvailableValsTy();
57 else
59
60 RegAttrs = MRI->getVRegAttrs(V);
61}
62
63/// HasValueForBlock - Return true if the MachineSSAUpdater already has a value for
64/// the specified block.
66 return getAvailableVals(AV).count(BB);
67}
68
69/// AddAvailableValue - Indicate that a rewritten value is available in the
70/// specified block with the specified value.
72 getAvailableVals(AV)[BB] = V;
73}
74
75/// GetValueAtEndOfBlock - Construct SSA form, materializing a value that is
76/// live at the end of the specified block.
78 return GetValueAtEndOfBlockInternal(BB);
79}
80
81static
83 SmallVectorImpl<std::pair<MachineBasicBlock *, Register>> &PredValues) {
84 if (BB->empty())
85 return Register();
86
88 if (!I->isPHI())
89 return Register();
90
91 AvailableValsTy AVals;
92 for (const auto &[SrcBB, SrcReg] : PredValues)
93 AVals[SrcBB] = SrcReg;
94 while (I != BB->end() && I->isPHI()) {
95 bool Same = true;
96 for (unsigned i = 1, e = I->getNumOperands(); i != e; i += 2) {
97 Register SrcReg = I->getOperand(i).getReg();
98 MachineBasicBlock *SrcBB = I->getOperand(i+1).getMBB();
99 if (AVals[SrcBB] != SrcReg) {
100 Same = false;
101 break;
102 }
103 }
104 if (Same)
105 return I->getOperand(0).getReg();
106 ++I;
107 }
108 return Register();
109}
110
111/// InsertNewDef - Insert an empty PHI or IMPLICIT_DEF instruction which define
112/// a value of the given register class at the start of the specified basic
113/// block. It returns the virtual register defined by the instruction.
118 const TargetInstrInfo *TII) {
119 Register NewVR = MRI->createVirtualRegister(RegAttrs);
120 return BuildMI(*BB, I, DebugLoc(), TII->get(Opcode), NewVR);
121}
122
123/// GetValueInMiddleOfBlock - Construct SSA form, materializing a value that
124/// is live in the middle of the specified block. If ExistingValueOnly is
125/// true then this will only return an existing value or $noreg; otherwise new
126/// instructions may be inserted to materialize a value.
127///
128/// GetValueInMiddleOfBlock is the same as GetValueAtEndOfBlock except in one
129/// important case: if there is a definition of the rewritten value after the
130/// 'use' in BB. Consider code like this:
131///
132/// X1 = ...
133/// SomeBB:
134/// use(X)
135/// X2 = ...
136/// br Cond, SomeBB, OutBB
137///
138/// In this case, there are two values (X1 and X2) added to the AvailableVals
139/// set by the client of the rewriter, and those values are both live out of
140/// their respective blocks. However, the use of X happens in the *middle* of
141/// a block. Because of this, we need to insert a new PHI node in SomeBB to
142/// merge the appropriate values, and this value isn't live out of the block.
144 bool ExistingValueOnly) {
145 // If there is no definition of the renamed variable in this block, just use
146 // GetValueAtEndOfBlock to do our work.
147 if (!HasValueForBlock(BB))
148 return GetValueAtEndOfBlockInternal(BB, ExistingValueOnly);
149
150 // If there are no predecessors, just return undef.
151 if (BB->pred_empty()) {
152 // If we cannot insert new instructions, just return $noreg.
153 if (ExistingValueOnly)
154 return Register();
155 // Insert an implicit_def to represent an undef value.
156 MachineInstr *NewDef =
157 InsertNewDef(TargetOpcode::IMPLICIT_DEF, BB, BB->getFirstTerminator(),
158 RegAttrs, MRI, TII);
159 return NewDef->getOperand(0).getReg();
160 }
161
162 // Otherwise, we have the hard case. Get the live-in values for each
163 // predecessor.
165 Register SingularValue;
166
167 bool isFirstPred = true;
168 for (MachineBasicBlock *PredBB : BB->predecessors()) {
169 Register PredVal = GetValueAtEndOfBlockInternal(PredBB, ExistingValueOnly);
170 PredValues.push_back(std::make_pair(PredBB, PredVal));
171
172 // Compute SingularValue.
173 if (isFirstPred) {
174 SingularValue = PredVal;
175 isFirstPred = false;
176 } else if (PredVal != SingularValue)
177 SingularValue = Register();
178 }
179
180 // Otherwise, if all the merged values are the same, just use it.
181 if (SingularValue)
182 return SingularValue;
183
184 // If an identical PHI is already in BB, just reuse it.
185 Register DupPHI = LookForIdenticalPHI(BB, PredValues);
186 if (DupPHI)
187 return DupPHI;
188
189 // If we cannot create new instructions, return $noreg now.
190 if (ExistingValueOnly)
191 return Register();
192
193 // Otherwise, we do need a PHI: insert one now.
194 MachineBasicBlock::iterator Loc = BB->empty() ? BB->end() : BB->begin();
195 MachineInstrBuilder InsertedPHI =
196 InsertNewDef(TargetOpcode::PHI, BB, Loc, RegAttrs, MRI, TII);
197
198 // Fill in all the predecessors of the PHI.
199 for (const auto &[SrcBB, SrcReg] : PredValues)
200 InsertedPHI.addReg(SrcReg).addMBB(SrcBB);
201
202 // See if the PHI node can be merged to a single value. This can happen in
203 // loop cases when we get a PHI of itself and one other value.
204 if (Register ConstVal = InsertedPHI->isConstantValuePHI()) {
205 InsertedPHI->eraseFromParent();
206 return ConstVal;
207 }
208
209 // If the client wants to know about all new instructions, tell it.
210 if (InsertedPHIs) InsertedPHIs->push_back(InsertedPHI);
211
212 LLVM_DEBUG(dbgs() << " Inserted PHI: " << *InsertedPHI);
213 return InsertedPHI.getReg(0);
214}
215
216static
218 MachineOperand *U) {
219 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
220 if (&MI->getOperand(i) == U)
221 return MI->getOperand(i+1).getMBB();
222 }
223
224 llvm_unreachable("MachineOperand::getParent() failure?");
225}
226
227/// RewriteUse - Rewrite a use of the symbolic value. This handles PHI nodes,
228/// which use their value in the corresponding predecessor.
230 MachineInstr *UseMI = U.getParent();
231 Register NewVR;
232 if (UseMI->isPHI()) {
234 NewVR = GetValueAtEndOfBlockInternal(SourceBB);
235 } else {
237 }
238
239 // Insert a COPY if needed to satisfy register class constraints for the using
240 // MO. Or, if possible, just constrain the class for NewVR to avoid the need
241 // for a COPY.
242 if (NewVR) {
243 const TargetRegisterClass *UseRC =
244 dyn_cast_or_null<const TargetRegisterClass *>(RegAttrs.RCOrRB);
245 if (UseRC && !MRI->constrainRegClass(NewVR, UseRC)) {
247 MachineInstr *InsertedCopy =
248 InsertNewDef(TargetOpcode::COPY, UseBB, UseBB->getFirstNonPHI(),
249 RegAttrs, MRI, TII)
250 .addReg(NewVR);
251 NewVR = InsertedCopy->getOperand(0).getReg();
252 LLVM_DEBUG(dbgs() << " Inserted COPY: " << *InsertedCopy);
253 }
254 }
255 U.setReg(NewVR);
256}
257
258namespace llvm {
259
260/// SSAUpdaterTraits<MachineSSAUpdater> - Traits for the SSAUpdaterImpl
261/// template, specialized for MachineSSAUpdater.
262template<>
264public:
266 using ValT = Register;
269
270 static BlkSucc_iterator BlkSucc_begin(BlkT *BB) { return BB->succ_begin(); }
271 static BlkSucc_iterator BlkSucc_end(BlkT *BB) { return BB->succ_end(); }
272
273 /// Iterator for PHI operands.
274 class PHI_iterator {
275 private:
277 unsigned idx;
278
279 public:
280 explicit PHI_iterator(MachineInstr *P) // begin iterator
281 : PHI(P), idx(1) {}
282 PHI_iterator(MachineInstr *P, bool) // end iterator
283 : PHI(P), idx(PHI->getNumOperands()) {}
284
285 PHI_iterator &operator++() { idx += 2; return *this; }
286 bool operator==(const PHI_iterator& x) const { return idx == x.idx; }
287 bool operator!=(const PHI_iterator& x) const { return !operator==(x); }
288
289 Register getIncomingValue() { return PHI->getOperand(idx).getReg(); }
290
292 return PHI->getOperand(idx+1).getMBB();
293 }
294 };
295
296 static inline PHI_iterator PHI_begin(PhiT *PHI) { return PHI_iterator(PHI); }
297
298 static inline PHI_iterator PHI_end(PhiT *PHI) {
299 return PHI_iterator(PHI, true);
300 }
301
302 /// FindPredecessorBlocks - Put the predecessors of BB into the Preds
303 /// vector.
306 append_range(*Preds, BB->predecessors());
307 }
308
309 /// GetPoisonVal - Create an IMPLICIT_DEF instruction with a new register.
310 /// Add it into the specified block and return the register.
312 MachineSSAUpdater *Updater) {
313 // Insert an implicit_def to represent a poison value.
314 MachineInstr *NewDef =
315 InsertNewDef(TargetOpcode::IMPLICIT_DEF, BB, BB->getFirstNonPHI(),
316 Updater->RegAttrs, Updater->MRI, Updater->TII);
317 return NewDef->getOperand(0).getReg();
318 }
319
320 /// CreateEmptyPHI - Create a PHI instruction that defines a new register.
321 /// Add it into the specified block and return the register.
322 static Register CreateEmptyPHI(MachineBasicBlock *BB, unsigned NumPreds,
323 MachineSSAUpdater *Updater) {
324 MachineBasicBlock::iterator Loc = BB->empty() ? BB->end() : BB->begin();
326 InsertNewDef(TargetOpcode::PHI, BB, Loc, Updater->RegAttrs,
327 Updater->MRI, Updater->TII);
328 return PHI->getOperand(0).getReg();
329 }
330
331 /// AddPHIOperand - Add the specified value as an operand of the PHI for
332 /// the specified predecessor block.
334 MachineBasicBlock *Pred) {
335 MachineInstrBuilder(*Pred->getParent(), PHI).addReg(Val).addMBB(Pred);
336 }
337
338 /// InstrIsPHI - Check if an instruction is a PHI.
340 if (I && I->isPHI())
341 return I;
342 return nullptr;
343 }
344
345 /// ValueIsPHI - Check if the instruction that defines the specified register
346 /// is a PHI instruction.
348 return InstrIsPHI(Updater->MRI->getVRegDef(Val));
349 }
350
351 /// ValueIsNewPHI - Like ValueIsPHI but also check if the PHI has no source
352 /// operands, i.e., it was just added.
354 MachineInstr *PHI = ValueIsPHI(Val, Updater);
355 if (PHI && PHI->getNumOperands() <= 1)
356 return PHI;
357 return nullptr;
358 }
359
360 /// GetPHIValue - For the specified PHI instruction, return the register
361 /// that it defines.
363 return PHI->getOperand(0).getReg();
364 }
365};
366
367} // end namespace llvm
368
369/// GetValueAtEndOfBlockInternal - Check to see if AvailableVals has an entry
370/// for the specified BB and if so, return it. If not, construct SSA form by
371/// first calculating the required placement of PHIs and then inserting new
372/// PHIs where needed.
374MachineSSAUpdater::GetValueAtEndOfBlockInternal(MachineBasicBlock *BB,
375 bool ExistingValueOnly) {
376 AvailableValsTy &AvailableVals = getAvailableVals(AV);
377 Register ExistingVal = AvailableVals.lookup(BB);
378 if (ExistingVal || ExistingValueOnly)
379 return ExistingVal;
380
381 SSAUpdaterImpl<MachineSSAUpdater> Impl(this, &AvailableVals, InsertedPHIs);
382 return Impl.GetValue(BB);
383}
unsigned const MachineRegisterInfo * MRI
MachineInstrBuilder & UseMI
Rewrite undef for PHI
#define LLVM_DEBUG(...)
Definition: Debug.h:106
This file defines the DenseMap class.
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition: MD5.cpp:58
static MachineInstrBuilder InsertNewDef(unsigned Opcode, MachineBasicBlock *BB, MachineBasicBlock::iterator I, MachineRegisterInfo::VRegAttrs RegAttrs, MachineRegisterInfo *MRI, const TargetInstrInfo *TII)
InsertNewDef - Insert an empty PHI or IMPLICIT_DEF instruction which define a value of the given regi...
static MachineBasicBlock * findCorrespondingPred(const MachineInstr *MI, MachineOperand *U)
static Register LookForIdenticalPHI(MachineBasicBlock *BB, SmallVectorImpl< std::pair< MachineBasicBlock *, Register > > &PredValues)
static AvailableValsTy & getAvailableVals(void *AV)
DenseMap< MachineBasicBlock *, Register > AvailableValsTy
#define P(N)
This file defines the SmallVector class.
A debug info location.
Definition: DebugLoc.h:33
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: DenseMap.h:194
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition: DenseMap.h:152
iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
SmallVectorImpl< MachineBasicBlock * >::iterator succ_iterator
iterator getFirstNonPHI()
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
iterator_range< pred_iterator > predecessors()
Register getReg(unsigned Idx) const
Get the register for the operand index.
const MachineInstrBuilder & addReg(Register RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
Representation of each machine instruction.
Definition: MachineInstr.h:69
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:347
Register isConstantValuePHI() const
If the specified instruction is a PHI that always merges together the same virtual register,...
void eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
bool isPHI() const
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:585
MachineOperand class - Representation of each machine instruction operand.
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
VRegAttrs getVRegAttrs(Register Reg) const
Returns register class or bank and low level type of Reg.
MachineInstr * getVRegDef(Register Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
const TargetRegisterClass * constrainRegClass(Register Reg, const TargetRegisterClass *RC, unsigned MinNumRegs=0)
constrainRegClass - Constrain the register class of the specified virtual register to be a common sub...
MachineSSAUpdater - This class updates SSA form for a set of virtual registers defined in multiple bl...
void Initialize(Register V)
Initialize - Reset this object to get ready for a new set of SSA updates.
Register GetValueInMiddleOfBlock(MachineBasicBlock *BB, bool ExistingValueOnly=false)
GetValueInMiddleOfBlock - Construct SSA form, materializing a value that is live in the middle of the...
void RewriteUse(MachineOperand &U)
RewriteUse - Rewrite a use of the symbolic value.
Register GetValueAtEndOfBlock(MachineBasicBlock *BB)
GetValueAtEndOfBlock - Construct SSA form, materializing a value that is live at the end of the speci...
void AddAvailableValue(MachineBasicBlock *BB, Register V)
AddAvailableValue - Indicate that a rewritten value is available at the end of the specified block wi...
bool HasValueForBlock(MachineBasicBlock *BB) const
HasValueForBlock - Return true if the MachineSSAUpdater already has a value for the specified block.
MachineSSAUpdater(MachineFunction &MF, SmallVectorImpl< MachineInstr * > *NewPHI=nullptr)
MachineSSAUpdater constructor.
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
static MachineInstr * ValueIsNewPHI(Register Val, MachineSSAUpdater *Updater)
ValueIsNewPHI - Like ValueIsPHI but also check if the PHI has no source operands, i....
static Register CreateEmptyPHI(MachineBasicBlock *BB, unsigned NumPreds, MachineSSAUpdater *Updater)
CreateEmptyPHI - Create a PHI instruction that defines a new register.
static Register GetPHIValue(MachineInstr *PHI)
GetPHIValue - For the specified PHI instruction, return the register that it defines.
static void FindPredecessorBlocks(MachineBasicBlock *BB, SmallVectorImpl< MachineBasicBlock * > *Preds)
FindPredecessorBlocks - Put the predecessors of BB into the Preds vector.
MachineBasicBlock::succ_iterator BlkSucc_iterator
static MachineInstr * ValueIsPHI(Register Val, MachineSSAUpdater *Updater)
ValueIsPHI - Check if the instruction that defines the specified register is a PHI instruction.
static Register GetPoisonVal(MachineBasicBlock *BB, MachineSSAUpdater *Updater)
GetPoisonVal - Create an IMPLICIT_DEF instruction with a new register.
static MachineInstr * InstrIsPHI(MachineInstr *I)
InstrIsPHI - Check if an instruction is a PHI.
static BlkSucc_iterator BlkSucc_begin(BlkT *BB)
static BlkSucc_iterator BlkSucc_end(BlkT *BB)
static void AddPHIOperand(MachineInstr *PHI, Register Val, MachineBasicBlock *Pred)
AddPHIOperand - Add the specified value as an operand of the PHI for the specified predecessor block.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:573
void push_back(const T &Elt)
Definition: SmallVector.h:413
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
TargetInstrInfo - Interface to description of machine instruction set.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition: STLExtras.h:2115
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
All attributes(register class or bank and low-level type) a virtual register can have.