Follow up to 90488. Turn a check into an assertion.
[oota-llvm.git] / lib / CodeGen / MachineSSAUpdater.cpp
1 //===- MachineSSAUpdater.cpp - Unstructured SSA Update Tool ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the MachineSSAUpdater class. It's based on SSAUpdater
11 // class in lib/Transforms/Utils.
12 //
13 //===----------------------------------------------------------------------===//
14
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"
26 using namespace llvm;
27
28 typedef DenseMap<MachineBasicBlock*, unsigned> AvailableValsTy;
29 typedef std::vector<std::pair<MachineBasicBlock*, unsigned> >
30                 IncomingPredInfoTy;
31
32 static AvailableValsTy &getAvailableVals(void *AV) {
33   return *static_cast<AvailableValsTy*>(AV);
34 }
35
36 static IncomingPredInfoTy &getIncomingPredInfo(void *IPI) {
37   return *static_cast<IncomingPredInfoTy*>(IPI);
38 }
39
40
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();
46 }
47
48 MachineSSAUpdater::~MachineSSAUpdater() {
49   delete &getAvailableVals(AV);
50   delete &getIncomingPredInfo(IPI);
51 }
52
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) {
56   if (AV == 0)
57     AV = new AvailableValsTy();
58   else
59     getAvailableVals(AV).clear();
60
61   if (IPI == 0)
62     IPI = new IncomingPredInfoTy();
63   else
64     getIncomingPredInfo(IPI).clear();
65
66   VR = V;
67   VRC = MRI->getRegClass(VR);
68 }
69
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);
74 }
75
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;
80 }
81
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);
86 }
87
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.
91 static
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, DebugLoc::getUnknownLoc(), TII->get(Opcode), NewVR);
98 }
99                           
100
101 /// GetValueInMiddleOfBlock - Construct SSA form, materializing a value that
102 /// is live in the middle of the specified block.
103 ///
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:
107 ///
108 ///      X1 = ...
109 ///   SomeBB:
110 ///      use(X)
111 ///      X2 = ...
112 ///      br Cond, SomeBB, OutBB
113 ///
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.
119 ///
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);
125
126   // If there are no predecessors, just return undef.
127   if (BB->pred_empty()) {
128     // Insert an implicit_def to represent an undef value.
129     MachineInstr *NewDef = InsertNewDef(TargetInstrInfo::IMPLICIT_DEF,
130                                         BB, BB->getFirstTerminator(),
131                                         VRC, MRI, TII);
132     return NewDef->getOperand(0).getReg();
133   }
134
135   // Otherwise, we have the hard case.  Get the live-in values for each
136   // predecessor.
137   SmallVector<std::pair<MachineBasicBlock*, unsigned>, 8> PredValues;
138   unsigned SingularValue = 0;
139
140   bool isFirstPred = true;
141   for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
142          E = BB->pred_end(); PI != E; ++PI) {
143     MachineBasicBlock *PredBB = *PI;
144     unsigned PredVal = GetValueAtEndOfBlockInternal(PredBB);
145     PredValues.push_back(std::make_pair(PredBB, PredVal));
146
147     // Compute SingularValue.
148     if (isFirstPred) {
149       SingularValue = PredVal;
150       isFirstPred = false;
151     } else if (PredVal != SingularValue)
152       SingularValue = 0;
153   }
154
155   // Otherwise, if all the merged values are the same, just use it.
156   if (SingularValue != 0)
157     return SingularValue;
158
159   // Otherwise, we do need a PHI: insert one now.
160   MachineBasicBlock::iterator Loc = BB->empty() ? BB->end() : BB->front();
161   MachineInstr *InsertedPHI = InsertNewDef(TargetInstrInfo::PHI, BB,
162                                            Loc, VRC, MRI, TII);
163
164   // Fill in all the predecessors of the PHI.
165   MachineInstrBuilder MIB(InsertedPHI);
166   for (unsigned i = 0, e = PredValues.size(); i != e; ++i)
167     MIB.addReg(PredValues[i].second).addMBB(PredValues[i].first);
168
169   // See if the PHI node can be merged to a single value.  This can happen in
170   // loop cases when we get a PHI of itself and one other value.
171   if (unsigned ConstVal = InsertedPHI->isConstantValuePHI()) {
172     InsertedPHI->eraseFromParent();
173     return ConstVal;
174   }
175
176   // If the client wants to know about all new instructions, tell it.
177   if (InsertedPHIs) InsertedPHIs->push_back(InsertedPHI);
178
179   DEBUG(errs() << "  Inserted PHI: " << *InsertedPHI << "\n");
180   return InsertedPHI->getOperand(0).getReg();
181 }
182
183 static
184 MachineBasicBlock *findCorrespondingPred(const MachineInstr *MI,
185                                          MachineOperand *U) {
186   for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
187     if (&MI->getOperand(i) == U)
188       return MI->getOperand(i+1).getMBB();
189   }
190
191   llvm_unreachable("MachineOperand::getParent() failure?");
192   return 0;
193 }
194
195 /// RewriteUse - Rewrite a use of the symbolic value.  This handles PHI nodes,
196 /// which use their value in the corresponding predecessor.
197 void MachineSSAUpdater::RewriteUse(MachineOperand &U) {
198   MachineInstr *UseMI = U.getParent();
199   unsigned NewVR = 0;
200   if (UseMI->getOpcode() == TargetInstrInfo::PHI) {
201     MachineBasicBlock *SourceBB = findCorrespondingPred(UseMI, &U);
202     NewVR = GetValueAtEndOfBlock(SourceBB);
203   } else {
204     NewVR = GetValueInMiddleOfBlock(UseMI->getParent());
205   }
206
207   U.setReg(NewVR);
208 }
209
210 void MachineSSAUpdater::ReplaceRegWith(unsigned OldReg, unsigned NewReg) {
211   MRI->replaceRegWith(OldReg, NewReg);
212
213   AvailableValsTy &AvailableVals = getAvailableVals(AV);
214   for (DenseMap<MachineBasicBlock*, unsigned>::iterator
215          I = AvailableVals.begin(), E = AvailableVals.end(); I != E; ++I)
216     if (I->second == OldReg)
217       I->second = NewReg;
218 }
219
220 /// GetValueAtEndOfBlockInternal - Check to see if AvailableVals has an entry
221 /// for the specified BB and if so, return it.  If not, construct SSA form by
222 /// walking predecessors inserting PHI nodes as needed until we get to a block
223 /// where the value is available.
224 ///
225 unsigned MachineSSAUpdater::GetValueAtEndOfBlockInternal(MachineBasicBlock *BB){
226   AvailableValsTy &AvailableVals = getAvailableVals(AV);
227
228   // Query AvailableVals by doing an insertion of null.
229   std::pair<AvailableValsTy::iterator, bool> InsertRes =
230     AvailableVals.insert(std::make_pair(BB, 0));
231
232   // Handle the case when the insertion fails because we have already seen BB.
233   if (!InsertRes.second) {
234     // If the insertion failed, there are two cases.  The first case is that the
235     // value is already available for the specified block.  If we get this, just
236     // return the value.
237     if (InsertRes.first->second != 0)
238       return InsertRes.first->second;
239
240     // Otherwise, if the value we find is null, then this is the value is not
241     // known but it is being computed elsewhere in our recursion.  This means
242     // that we have a cycle.  Handle this by inserting a PHI node and returning
243     // it.  When we get back to the first instance of the recursion we will fill
244     // in the PHI node.
245     MachineBasicBlock::iterator Loc = BB->empty() ? BB->end() : BB->front();
246     MachineInstr *NewPHI = InsertNewDef(TargetInstrInfo::PHI, BB, Loc,
247                                         VRC, MRI,TII);
248     unsigned NewVR = NewPHI->getOperand(0).getReg();
249     InsertRes.first->second = NewVR;
250     return NewVR;
251   }
252
253   // If there are no predecessors, then we must have found an unreachable block
254   // just return 'undef'.  Since there are no predecessors, InsertRes must not
255   // be invalidated.
256   if (BB->pred_empty()) {
257     // Insert an implicit_def to represent an undef value.
258     MachineInstr *NewDef = InsertNewDef(TargetInstrInfo::IMPLICIT_DEF,
259                                         BB, BB->getFirstTerminator(),
260                                         VRC, MRI, TII);
261     return InsertRes.first->second = NewDef->getOperand(0).getReg();
262   }
263
264   // Okay, the value isn't in the map and we just inserted a null in the entry
265   // to indicate that we're processing the block.  Since we have no idea what
266   // value is in this block, we have to recurse through our predecessors.
267   //
268   // While we're walking our predecessors, we keep track of them in a vector,
269   // then insert a PHI node in the end if we actually need one.  We could use a
270   // smallvector here, but that would take a lot of stack space for every level
271   // of the recursion, just use IncomingPredInfo as an explicit stack.
272   IncomingPredInfoTy &IncomingPredInfo = getIncomingPredInfo(IPI);
273   unsigned FirstPredInfoEntry = IncomingPredInfo.size();
274
275   // As we're walking the predecessors, keep track of whether they are all
276   // producing the same value.  If so, this value will capture it, if not, it
277   // will get reset to null.  We distinguish the no-predecessor case explicitly
278   // below.
279   unsigned SingularValue = 0;
280   bool isFirstPred = true;
281   for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
282          E = BB->pred_end(); PI != E; ++PI) {
283     MachineBasicBlock *PredBB = *PI;
284     unsigned PredVal = GetValueAtEndOfBlockInternal(PredBB);
285     IncomingPredInfo.push_back(std::make_pair(PredBB, PredVal));
286
287     // Compute SingularValue.
288     if (isFirstPred) {
289       SingularValue = PredVal;
290       isFirstPred = false;
291     } else if (PredVal != SingularValue)
292       SingularValue = 0;
293   }
294
295   /// Look up BB's entry in AvailableVals.  'InsertRes' may be invalidated.  If
296   /// this block is involved in a loop, a no-entry PHI node will have been
297   /// inserted as InsertedVal.  Otherwise, we'll still have the null we inserted
298   /// above.
299   unsigned &InsertedVal = AvailableVals[BB];
300
301   // If all the predecessor values are the same then we don't need to insert a
302   // PHI.  This is the simple and common case.
303   if (SingularValue) {
304     // If a PHI node got inserted, replace it with the singlar value and delete
305     // it.
306     if (InsertedVal) {
307       MachineInstr *OldVal = MRI->getVRegDef(InsertedVal);
308       // Be careful about dead loops.  These RAUW's also update InsertedVal.
309       assert(InsertedVal != SingularValue && "Dead loop?");
310       ReplaceRegWith(InsertedVal, SingularValue);
311       OldVal->eraseFromParent();
312     }
313
314     InsertedVal = SingularValue;
315
316     // Drop the entries we added in IncomingPredInfo to restore the stack.
317     IncomingPredInfo.erase(IncomingPredInfo.begin()+FirstPredInfoEntry,
318                            IncomingPredInfo.end());
319     return InsertedVal;
320   }
321
322
323   // Otherwise, we do need a PHI: insert one now if we don't already have one.
324   MachineInstr *InsertedPHI;
325   if (InsertedVal == 0) {
326     MachineBasicBlock::iterator Loc = BB->empty() ? BB->end() : BB->front();
327     InsertedPHI = InsertNewDef(TargetInstrInfo::PHI, BB, Loc,
328                                VRC, MRI, TII);
329     InsertedVal = InsertedPHI->getOperand(0).getReg();
330   } else {
331     InsertedPHI = MRI->getVRegDef(InsertedVal);
332   }
333
334   // Fill in all the predecessors of the PHI.
335   MachineInstrBuilder MIB(InsertedPHI);
336   for (IncomingPredInfoTy::iterator I =
337          IncomingPredInfo.begin()+FirstPredInfoEntry,
338          E = IncomingPredInfo.end(); I != E; ++I)
339     MIB.addReg(I->second).addMBB(I->first);
340
341   // Drop the entries we added in IncomingPredInfo to restore the stack.
342   IncomingPredInfo.erase(IncomingPredInfo.begin()+FirstPredInfoEntry,
343                          IncomingPredInfo.end());
344
345   // See if the PHI node can be merged to a single value.  This can happen in
346   // loop cases when we get a PHI of itself and one other value.
347   if (unsigned ConstVal = InsertedPHI->isConstantValuePHI()) {
348     MRI->replaceRegWith(InsertedVal, ConstVal);
349     InsertedPHI->eraseFromParent();
350     InsertedVal = ConstVal;
351   } else {
352     DEBUG(errs() << "  Inserted PHI: " << *InsertedPHI << "\n");
353
354     // If the client wants to know about all new instructions, tell it.
355     if (InsertedPHIs) InsertedPHIs->push_back(InsertedPHI);
356   }
357
358   return InsertedVal;
359 }