1 //===- MachineSSAUpdater.cpp - Unstructured SSA Update Tool ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the MachineSSAUpdater class. It's based on SSAUpdater
11 // class in lib/Transforms/Utils.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/CodeGen/MachineSSAUpdater.h"
16 #include "llvm/CodeGen/MachineInstr.h"
17 #include "llvm/CodeGen/MachineInstrBuilder.h"
18 #include "llvm/CodeGen/MachineRegisterInfo.h"
19 #include "llvm/Target/TargetInstrInfo.h"
20 #include "llvm/Target/TargetMachine.h"
21 #include "llvm/Target/TargetRegisterInfo.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/raw_ostream.h"
28 typedef DenseMap<MachineBasicBlock*, unsigned> AvailableValsTy;
29 typedef std::vector<std::pair<MachineBasicBlock*, unsigned> >
32 static AvailableValsTy &getAvailableVals(void *AV) {
33 return *static_cast<AvailableValsTy*>(AV);
36 static IncomingPredInfoTy &getIncomingPredInfo(void *IPI) {
37 return *static_cast<IncomingPredInfoTy*>(IPI);
41 MachineSSAUpdater::MachineSSAUpdater(MachineFunction &MF,
42 SmallVectorImpl<MachineInstr*> *NewPHI)
43 : AV(0), IPI(0), InsertedPHIs(NewPHI) {
44 TII = MF.getTarget().getInstrInfo();
45 MRI = &MF.getRegInfo();
48 MachineSSAUpdater::~MachineSSAUpdater() {
49 delete &getAvailableVals(AV);
50 delete &getIncomingPredInfo(IPI);
53 /// Initialize - Reset this object to get ready for a new set of SSA
54 /// updates. ProtoValue is the value used to name PHI nodes.
55 void MachineSSAUpdater::Initialize(unsigned V) {
57 AV = new AvailableValsTy();
59 getAvailableVals(AV).clear();
62 IPI = new IncomingPredInfoTy();
64 getIncomingPredInfo(IPI).clear();
67 VRC = MRI->getRegClass(VR);
70 /// HasValueForBlock - Return true if the MachineSSAUpdater already has a value for
71 /// the specified block.
72 bool MachineSSAUpdater::HasValueForBlock(MachineBasicBlock *BB) const {
73 return getAvailableVals(AV).count(BB);
76 /// AddAvailableValue - Indicate that a rewritten value is available in the
77 /// specified block with the specified value.
78 void MachineSSAUpdater::AddAvailableValue(MachineBasicBlock *BB, unsigned V) {
79 getAvailableVals(AV)[BB] = V;
82 /// GetValueAtEndOfBlock - Construct SSA form, materializing a value that is
83 /// live at the end of the specified block.
84 unsigned MachineSSAUpdater::GetValueAtEndOfBlock(MachineBasicBlock *BB) {
85 return GetValueAtEndOfBlockInternal(BB);
88 /// InsertNewDef - Insert an empty PHI or IMPLICIT_DEF instruction which define
89 /// a value of the given register class at the start of the specified basic
90 /// block. It returns the virtual register defined by the instruction.
92 MachineInstr *InsertNewDef(unsigned Opcode,
93 MachineBasicBlock *BB, MachineBasicBlock::iterator I,
94 const TargetRegisterClass *RC,
95 MachineRegisterInfo *MRI, const TargetInstrInfo *TII) {
96 unsigned NewVR = MRI->createVirtualRegister(RC);
97 return BuildMI(*BB, I, I->getDebugLoc(), TII->get(Opcode), NewVR);
101 /// GetValueInMiddleOfBlock - Construct SSA form, materializing a value that
102 /// is live in the middle of the specified block.
104 /// GetValueInMiddleOfBlock is the same as GetValueAtEndOfBlock except in one
105 /// important case: if there is a definition of the rewritten value after the
106 /// 'use' in BB. Consider code like this:
112 /// br Cond, SomeBB, OutBB
114 /// In this case, there are two values (X1 and X2) added to the AvailableVals
115 /// set by the client of the rewriter, and those values are both live out of
116 /// their respective blocks. However, the use of X happens in the *middle* of
117 /// a block. Because of this, we need to insert a new PHI node in SomeBB to
118 /// merge the appropriate values, and this value isn't live out of the block.
120 unsigned MachineSSAUpdater::GetValueInMiddleOfBlock(MachineBasicBlock *BB) {
121 // If there is no definition of the renamed variable in this block, just use
122 // GetValueAtEndOfBlock to do our work.
123 if (!getAvailableVals(AV).count(BB))
124 return GetValueAtEndOfBlock(BB);
126 // If there are no predecessors, just return undef.
127 if (BB->pred_empty())
128 return ~0U; // Sentinel value representing undef.
130 // Otherwise, we have the hard case. Get the live-in values for each
132 SmallVector<std::pair<MachineBasicBlock*, unsigned>, 8> PredValues;
133 unsigned SingularValue = 0;
135 bool isFirstPred = true;
136 for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
137 E = BB->pred_end(); PI != E; ++PI) {
138 MachineBasicBlock *PredBB = *PI;
139 unsigned PredVal = GetValueAtEndOfBlockInternal(PredBB);
140 PredValues.push_back(std::make_pair(PredBB, PredVal));
142 // Compute SingularValue.
144 SingularValue = PredVal;
146 } else if (PredVal != SingularValue)
150 // Otherwise, if all the merged values are the same, just use it.
151 if (SingularValue != 0)
152 return SingularValue;
154 // Otherwise, we do need a PHI: insert one now.
155 MachineInstr *InsertedPHI = InsertNewDef(TargetInstrInfo::PHI, BB,
156 BB->front(), VRC, MRI, TII);
158 // Fill in all the predecessors of the PHI.
159 MachineInstrBuilder MIB(InsertedPHI);
160 for (unsigned i = 0, e = PredValues.size(); i != e; ++i)
161 MIB.addReg(PredValues[i].second).addMBB(PredValues[i].first);
163 // See if the PHI node can be merged to a single value. This can happen in
164 // loop cases when we get a PHI of itself and one other value.
165 if (unsigned ConstVal = InsertedPHI->isConstantValuePHI()) {
166 InsertedPHI->eraseFromParent();
170 // If the client wants to know about all new instructions, tell it.
171 if (InsertedPHIs) InsertedPHIs->push_back(InsertedPHI);
173 DEBUG(errs() << " Inserted PHI: " << *InsertedPHI << "\n");
174 return InsertedPHI->getOperand(0).getReg();
178 MachineBasicBlock *findCorrespondingPred(const MachineInstr *MI,
180 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
181 if (&MI->getOperand(i) == U)
182 return MI->getOperand(i+1).getMBB();
185 llvm_unreachable("MachineOperand::getParent() failure?");
189 /// RewriteUse - Rewrite a use of the symbolic value. This handles PHI nodes,
190 /// which use their value in the corresponding predecessor.
191 void MachineSSAUpdater::RewriteUse(MachineOperand &U) {
192 MachineInstr *UseMI = U.getParent();
194 if (UseMI->getOpcode() == TargetInstrInfo::PHI) {
195 MachineBasicBlock *SourceBB = findCorrespondingPred(UseMI, &U);
196 NewVR = GetValueAtEndOfBlock(SourceBB);
198 NewVR = GetValueInMiddleOfBlock(UseMI->getParent());
202 // Insert an implicit_def to represent an undef value.
203 MachineInstr *NewDef = InsertNewDef(TargetInstrInfo::IMPLICIT_DEF,
204 UseMI->getParent(), UseMI, VRC,MRI,TII);
205 NewVR = NewDef->getOperand(0).getReg();
211 /// GetValueAtEndOfBlockInternal - Check to see if AvailableVals has an entry
212 /// for the specified BB and if so, return it. If not, construct SSA form by
213 /// walking predecessors inserting PHI nodes as needed until we get to a block
214 /// where the value is available.
216 unsigned MachineSSAUpdater::GetValueAtEndOfBlockInternal(MachineBasicBlock *BB){
217 AvailableValsTy &AvailableVals = getAvailableVals(AV);
219 // Query AvailableVals by doing an insertion of null.
220 std::pair<AvailableValsTy::iterator, bool> InsertRes =
221 AvailableVals.insert(std::make_pair(BB, 0));
223 // Handle the case when the insertion fails because we have already seen BB.
224 if (!InsertRes.second) {
225 // If the insertion failed, there are two cases. The first case is that the
226 // value is already available for the specified block. If we get this, just
228 if (InsertRes.first->second != 0)
229 return InsertRes.first->second;
231 // Otherwise, if the value we find is null, then this is the value is not
232 // known but it is being computed elsewhere in our recursion. This means
233 // that we have a cycle. Handle this by inserting a PHI node and returning
234 // it. When we get back to the first instance of the recursion we will fill
236 MachineInstr *NewPHI = InsertNewDef(TargetInstrInfo::PHI, BB, BB->front(),
238 unsigned NewVR = NewPHI->getOperand(0).getReg();
239 InsertRes.first->second = NewVR;
243 // If there are no predecessors, then we must have found an unreachable block
244 // just return 'undef'. Since there are no predecessors, InsertRes must not
246 if (BB->pred_empty())
247 return InsertRes.first->second = ~0U; // Sentinel value representing undef.
249 // Okay, the value isn't in the map and we just inserted a null in the entry
250 // to indicate that we're processing the block. Since we have no idea what
251 // value is in this block, we have to recurse through our predecessors.
253 // While we're walking our predecessors, we keep track of them in a vector,
254 // then insert a PHI node in the end if we actually need one. We could use a
255 // smallvector here, but that would take a lot of stack space for every level
256 // of the recursion, just use IncomingPredInfo as an explicit stack.
257 IncomingPredInfoTy &IncomingPredInfo = getIncomingPredInfo(IPI);
258 unsigned FirstPredInfoEntry = IncomingPredInfo.size();
260 // As we're walking the predecessors, keep track of whether they are all
261 // producing the same value. If so, this value will capture it, if not, it
262 // will get reset to null. We distinguish the no-predecessor case explicitly
264 unsigned SingularValue = 0;
265 bool isFirstPred = true;
266 for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
267 E = BB->pred_end(); PI != E; ++PI) {
268 MachineBasicBlock *PredBB = *PI;
269 unsigned PredVal = GetValueAtEndOfBlockInternal(PredBB);
270 IncomingPredInfo.push_back(std::make_pair(PredBB, PredVal));
272 // Compute SingularValue.
274 SingularValue = PredVal;
276 } else if (PredVal != SingularValue)
280 /// Look up BB's entry in AvailableVals. 'InsertRes' may be invalidated. If
281 /// this block is involved in a loop, a no-entry PHI node will have been
282 /// inserted as InsertedVal. Otherwise, we'll still have the null we inserted
284 unsigned InsertedVal = AvailableVals[BB];
286 // If all the predecessor values are the same then we don't need to insert a
287 // PHI. This is the simple and common case.
289 // If a PHI node got inserted, replace it with the singlar value and delete
292 MachineInstr *OldVal = MRI->getVRegDef(InsertedVal);
293 // Be careful about dead loops. These RAUW's also update InsertedVal.
294 assert(InsertedVal != SingularValue && "Dead loop?");
295 MRI->replaceRegWith(InsertedVal, SingularValue);
296 OldVal->eraseFromParent();
298 InsertedVal = SingularValue;
301 // Drop the entries we added in IncomingPredInfo to restore the stack.
302 IncomingPredInfo.erase(IncomingPredInfo.begin()+FirstPredInfoEntry,
303 IncomingPredInfo.end());
308 // Otherwise, we do need a PHI: insert one now if we don't already have one.
309 MachineInstr *InsertedPHI;
310 if (InsertedVal == 0) {
311 InsertedPHI = InsertNewDef(TargetInstrInfo::PHI, BB, BB->front(),
313 InsertedVal = InsertedPHI->getOperand(0).getReg();
315 InsertedPHI = MRI->getVRegDef(InsertedVal);
318 // Fill in all the predecessors of the PHI.
320 MachineInstrBuilder MIB(InsertedPHI);
321 for (IncomingPredInfoTy::iterator I =
322 IncomingPredInfo.begin()+FirstPredInfoEntry,
323 E = IncomingPredInfo.end(); I != E; ++I) {
324 if (I->second == ~0U)
327 MIB.addReg(I->second).addMBB(I->first);
330 // Drop the entries we added in IncomingPredInfo to restore the stack.
331 IncomingPredInfo.erase(IncomingPredInfo.begin()+FirstPredInfoEntry,
332 IncomingPredInfo.end());
334 // See if the PHI node can be merged to a single value. This can happen in
335 // loop cases when we get a PHI of itself and one other value.
337 InsertedPHI->eraseFromParent();
339 } else if (unsigned ConstVal = InsertedPHI->isConstantValuePHI()) {
340 MRI->replaceRegWith(InsertedVal, ConstVal);
341 InsertedPHI->eraseFromParent();
342 InsertedVal = ConstVal;
344 DEBUG(errs() << " Inserted PHI: " << *InsertedPHI << "\n");
346 // If the client wants to know about all new instructions, tell it.
347 if (InsertedPHIs) InsertedPHIs->push_back(InsertedPHI);