LLVM  4.0.0
MachineSSAUpdater.cpp
Go to the documentation of this file.
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 
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/Support/Debug.h"
28 using namespace llvm;
29 
30 #define DEBUG_TYPE "machine-ssaupdater"
31 
33 static AvailableValsTy &getAvailableVals(void *AV) {
34  return *static_cast<AvailableValsTy*>(AV);
35 }
36 
39  : AV(nullptr), InsertedPHIs(NewPHI) {
40  TII = MF.getSubtarget().getInstrInfo();
41  MRI = &MF.getRegInfo();
42 }
43 
45  delete static_cast<AvailableValsTy*>(AV);
46 }
47 
48 /// Initialize - Reset this object to get ready for a new set of SSA
49 /// updates. ProtoValue is the value used to name PHI nodes.
51  if (!AV)
52  AV = new AvailableValsTy();
53  else
54  getAvailableVals(AV).clear();
55 
56  VR = V;
57  VRC = MRI->getRegClass(VR);
58 }
59 
60 /// HasValueForBlock - Return true if the MachineSSAUpdater already has a value for
61 /// the specified block.
63  return getAvailableVals(AV).count(BB);
64 }
65 
66 /// AddAvailableValue - Indicate that a rewritten value is available in the
67 /// specified block with the specified value.
69  getAvailableVals(AV)[BB] = V;
70 }
71 
72 /// GetValueAtEndOfBlock - Construct SSA form, materializing a value that is
73 /// live at the end of the specified block.
75  return GetValueAtEndOfBlockInternal(BB);
76 }
77 
78 static
80  SmallVectorImpl<std::pair<MachineBasicBlock*, unsigned> > &PredValues) {
81  if (BB->empty())
82  return 0;
83 
85  if (!I->isPHI())
86  return 0;
87 
88  AvailableValsTy AVals;
89  for (unsigned i = 0, e = PredValues.size(); i != e; ++i)
90  AVals[PredValues[i].first] = PredValues[i].second;
91  while (I != BB->end() && I->isPHI()) {
92  bool Same = true;
93  for (unsigned i = 1, e = I->getNumOperands(); i != e; i += 2) {
94  unsigned SrcReg = I->getOperand(i).getReg();
95  MachineBasicBlock *SrcBB = I->getOperand(i+1).getMBB();
96  if (AVals[SrcBB] != SrcReg) {
97  Same = false;
98  break;
99  }
100  }
101  if (Same)
102  return I->getOperand(0).getReg();
103  ++I;
104  }
105  return 0;
106 }
107 
108 /// InsertNewDef - Insert an empty PHI or IMPLICIT_DEF instruction which define
109 /// a value of the given register class at the start of the specified basic
110 /// block. It returns the virtual register defined by the instruction.
111 static
114  const TargetRegisterClass *RC,
116  const TargetInstrInfo *TII) {
117  unsigned NewVR = MRI->createVirtualRegister(RC);
118  return BuildMI(*BB, I, DebugLoc(), TII->get(Opcode), NewVR);
119 }
120 
121 /// GetValueInMiddleOfBlock - Construct SSA form, materializing a value that
122 /// is live in the middle of the specified block.
123 ///
124 /// GetValueInMiddleOfBlock is the same as GetValueAtEndOfBlock except in one
125 /// important case: if there is a definition of the rewritten value after the
126 /// 'use' in BB. Consider code like this:
127 ///
128 /// X1 = ...
129 /// SomeBB:
130 /// use(X)
131 /// X2 = ...
132 /// br Cond, SomeBB, OutBB
133 ///
134 /// In this case, there are two values (X1 and X2) added to the AvailableVals
135 /// set by the client of the rewriter, and those values are both live out of
136 /// their respective blocks. However, the use of X happens in the *middle* of
137 /// a block. Because of this, we need to insert a new PHI node in SomeBB to
138 /// merge the appropriate values, and this value isn't live out of the block.
139 ///
141  // If there is no definition of the renamed variable in this block, just use
142  // GetValueAtEndOfBlock to do our work.
143  if (!HasValueForBlock(BB))
144  return GetValueAtEndOfBlockInternal(BB);
145 
146  // If there are no predecessors, just return undef.
147  if (BB->pred_empty()) {
148  // Insert an implicit_def to represent an undef value.
149  MachineInstr *NewDef = InsertNewDef(TargetOpcode::IMPLICIT_DEF,
150  BB, BB->getFirstTerminator(),
151  VRC, MRI, TII);
152  return NewDef->getOperand(0).getReg();
153  }
154 
155  // Otherwise, we have the hard case. Get the live-in values for each
156  // predecessor.
158  unsigned SingularValue = 0;
159 
160  bool isFirstPred = true;
162  E = BB->pred_end(); PI != E; ++PI) {
163  MachineBasicBlock *PredBB = *PI;
164  unsigned PredVal = GetValueAtEndOfBlockInternal(PredBB);
165  PredValues.push_back(std::make_pair(PredBB, PredVal));
166 
167  // Compute SingularValue.
168  if (isFirstPred) {
169  SingularValue = PredVal;
170  isFirstPred = false;
171  } else if (PredVal != SingularValue)
172  SingularValue = 0;
173  }
174 
175  // Otherwise, if all the merged values are the same, just use it.
176  if (SingularValue != 0)
177  return SingularValue;
178 
179  // If an identical PHI is already in BB, just reuse it.
180  unsigned DupPHI = LookForIdenticalPHI(BB, PredValues);
181  if (DupPHI)
182  return DupPHI;
183 
184  // Otherwise, we do need a PHI: insert one now.
185  MachineBasicBlock::iterator Loc = BB->empty() ? BB->end() : BB->begin();
186  MachineInstrBuilder InsertedPHI = InsertNewDef(TargetOpcode::PHI, BB,
187  Loc, VRC, MRI, TII);
188 
189  // Fill in all the predecessors of the PHI.
190  for (unsigned i = 0, e = PredValues.size(); i != e; ++i)
191  InsertedPHI.addReg(PredValues[i].second).addMBB(PredValues[i].first);
192 
193  // See if the PHI node can be merged to a single value. This can happen in
194  // loop cases when we get a PHI of itself and one other value.
195  if (unsigned ConstVal = InsertedPHI->isConstantValuePHI()) {
196  InsertedPHI->eraseFromParent();
197  return ConstVal;
198  }
199 
200  // If the client wants to know about all new instructions, tell it.
201  if (InsertedPHIs) InsertedPHIs->push_back(InsertedPHI);
202 
203  DEBUG(dbgs() << " Inserted PHI: " << *InsertedPHI << "\n");
204  return InsertedPHI->getOperand(0).getReg();
205 }
206 
207 static
209  MachineOperand *U) {
210  for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
211  if (&MI->getOperand(i) == U)
212  return MI->getOperand(i+1).getMBB();
213  }
214 
215  llvm_unreachable("MachineOperand::getParent() failure?");
216 }
217 
218 /// RewriteUse - Rewrite a use of the symbolic value. This handles PHI nodes,
219 /// which use their value in the corresponding predecessor.
222  unsigned NewVR = 0;
223  if (UseMI->isPHI()) {
224  MachineBasicBlock *SourceBB = findCorrespondingPred(UseMI, &U);
225  NewVR = GetValueAtEndOfBlockInternal(SourceBB);
226  } else {
227  NewVR = GetValueInMiddleOfBlock(UseMI->getParent());
228  }
229 
230  U.setReg(NewVR);
231 }
232 
233 /// SSAUpdaterTraits<MachineSSAUpdater> - Traits for the SSAUpdaterImpl
234 /// template, specialized for MachineSSAUpdater.
235 namespace llvm {
236 template<>
238 public:
240  typedef unsigned ValT;
242 
244  static BlkSucc_iterator BlkSucc_begin(BlkT *BB) { return BB->succ_begin(); }
245  static BlkSucc_iterator BlkSucc_end(BlkT *BB) { return BB->succ_end(); }
246 
247  /// Iterator for PHI operands.
248  class PHI_iterator {
249  private:
250  MachineInstr *PHI;
251  unsigned idx;
252 
253  public:
254  explicit PHI_iterator(MachineInstr *P) // begin iterator
255  : PHI(P), idx(1) {}
256  PHI_iterator(MachineInstr *P, bool) // end iterator
257  : PHI(P), idx(PHI->getNumOperands()) {}
258 
259  PHI_iterator &operator++() { idx += 2; return *this; }
260  bool operator==(const PHI_iterator& x) const { return idx == x.idx; }
261  bool operator!=(const PHI_iterator& x) const { return !operator==(x); }
262  unsigned getIncomingValue() { return PHI->getOperand(idx).getReg(); }
264  return PHI->getOperand(idx+1).getMBB();
265  }
266  };
267  static inline PHI_iterator PHI_begin(PhiT *PHI) { return PHI_iterator(PHI); }
268  static inline PHI_iterator PHI_end(PhiT *PHI) {
269  return PHI_iterator(PHI, true);
270  }
271 
272  /// FindPredecessorBlocks - Put the predecessors of BB into the Preds
273  /// vector.
277  E = BB->pred_end(); PI != E; ++PI)
278  Preds->push_back(*PI);
279  }
280 
281  /// GetUndefVal - Create an IMPLICIT_DEF instruction with a new register.
282  /// Add it into the specified block and return the register.
283  static unsigned GetUndefVal(MachineBasicBlock *BB,
284  MachineSSAUpdater *Updater) {
285  // Insert an implicit_def to represent an undef value.
286  MachineInstr *NewDef = InsertNewDef(TargetOpcode::IMPLICIT_DEF,
287  BB, BB->getFirstTerminator(),
288  Updater->VRC, Updater->MRI,
289  Updater->TII);
290  return NewDef->getOperand(0).getReg();
291  }
292 
293  /// CreateEmptyPHI - Create a PHI instruction that defines a new register.
294  /// Add it into the specified block and return the register.
295  static unsigned CreateEmptyPHI(MachineBasicBlock *BB, unsigned NumPreds,
296  MachineSSAUpdater *Updater) {
297  MachineBasicBlock::iterator Loc = BB->empty() ? BB->end() : BB->begin();
298  MachineInstr *PHI = InsertNewDef(TargetOpcode::PHI, BB, Loc,
299  Updater->VRC, Updater->MRI,
300  Updater->TII);
301  return PHI->getOperand(0).getReg();
302  }
303 
304  /// AddPHIOperand - Add the specified value as an operand of the PHI for
305  /// the specified predecessor block.
306  static void AddPHIOperand(MachineInstr *PHI, unsigned Val,
307  MachineBasicBlock *Pred) {
308  MachineInstrBuilder(*Pred->getParent(), PHI).addReg(Val).addMBB(Pred);
309  }
310 
311  /// InstrIsPHI - Check if an instruction is a PHI.
312  ///
314  if (I && I->isPHI())
315  return I;
316  return nullptr;
317  }
318 
319  /// ValueIsPHI - Check if the instruction that defines the specified register
320  /// is a PHI instruction.
321  static MachineInstr *ValueIsPHI(unsigned Val, MachineSSAUpdater *Updater) {
322  return InstrIsPHI(Updater->MRI->getVRegDef(Val));
323  }
324 
325  /// ValueIsNewPHI - Like ValueIsPHI but also check if the PHI has no source
326  /// operands, i.e., it was just added.
327  static MachineInstr *ValueIsNewPHI(unsigned Val, MachineSSAUpdater *Updater) {
328  MachineInstr *PHI = ValueIsPHI(Val, Updater);
329  if (PHI && PHI->getNumOperands() <= 1)
330  return PHI;
331  return nullptr;
332  }
333 
334  /// GetPHIValue - For the specified PHI instruction, return the register
335  /// that it defines.
336  static unsigned GetPHIValue(MachineInstr *PHI) {
337  return PHI->getOperand(0).getReg();
338  }
339 };
340 
341 } // End llvm namespace
342 
343 /// GetValueAtEndOfBlockInternal - Check to see if AvailableVals has an entry
344 /// for the specified BB and if so, return it. If not, construct SSA form by
345 /// first calculating the required placement of PHIs and then inserting new
346 /// PHIs where needed.
347 unsigned MachineSSAUpdater::GetValueAtEndOfBlockInternal(MachineBasicBlock *BB){
348  AvailableValsTy &AvailableVals = getAvailableVals(AV);
349  if (unsigned V = AvailableVals[BB])
350  return V;
351 
352  SSAUpdaterImpl<MachineSSAUpdater> Impl(this, &AvailableVals, InsertedPHIs);
353  return Impl.GetValue(BB);
354 }
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
size_t i
MachineBasicBlock * getMBB() const
unsigned createVirtualRegister(const TargetRegisterClass *RegClass)
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
static MachineInstrBuilder InsertNewDef(unsigned Opcode, MachineBasicBlock *BB, MachineBasicBlock::iterator I, const TargetRegisterClass *RC, MachineRegisterInfo *MRI, const TargetInstrInfo *TII)
InsertNewDef - Insert an empty PHI or IMPLICIT_DEF instruction which define a value of the given regi...
iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
void RewriteUse(MachineOperand &U)
RewriteUse - Rewrite a use of the symbolic value.
A debug info location.
Definition: DebugLoc.h:34
static void FindPredecessorBlocks(MachineBasicBlock *BB, SmallVectorImpl< MachineBasicBlock * > *Preds)
FindPredecessorBlocks - Put the predecessors of BB into the Preds vector.
MachineSSAUpdater - This class updates SSA form for a set of virtual registers defined in multiple bl...
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
unsigned GetValueAtEndOfBlock(MachineBasicBlock *BB)
GetValueAtEndOfBlock - Construct SSA form, materializing a value that is live at the end of the speci...
const HexagonInstrInfo * TII
bool isPHI() const
Definition: MachineInstr.h:786
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:32
bool HasValueForBlock(MachineBasicBlock *BB) const
HasValueForBlock - Return true if the MachineSSAUpdater already has a value for the specified block...
void eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
const TargetRegisterClass * getRegClass(unsigned Reg) const
Return the register class of the specified virtual register.
std::vector< MachineBasicBlock * >::iterator succ_iterator
unsigned getNumOperands() const
Access to explicit operands of the instruction.
Definition: MachineInstr.h:277
static MachineInstr * ValueIsNewPHI(unsigned Val, MachineSSAUpdater *Updater)
ValueIsNewPHI - Like ValueIsPHI but also check if the PHI has no source operands, i...
std::vector< MachineBasicBlock * >::iterator pred_iterator
void Initialize(unsigned V)
Initialize - Reset this object to get ready for a new set of SSA updates.
static GCRegistry::Add< CoreCLRGC > E("coreclr","CoreCLR-compatible GC")
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:131
TargetInstrInfo - Interface to description of machine instruction set.
MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
#define P(N)
unsigned const MachineRegisterInfo * MRI
MachineInstrBuilder & UseMI
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:279
static BlkSucc_iterator BlkSucc_end(BlkT *BB)
static void AddPHIOperand(MachineInstr *PHI, unsigned Val, MachineBasicBlock *Pred)
AddPHIOperand - Add the specified value as an operand of the PHI for the specified predecessor block...
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode...
Definition: MCInstrInfo.h:45
static MachineBasicBlock * findCorrespondingPred(const MachineInstr *MI, MachineOperand *U)
static unsigned CreateEmptyPHI(MachineBasicBlock *BB, unsigned NumPreds, MachineSSAUpdater *Updater)
CreateEmptyPHI - Create a PHI instruction that defines a new register.
MachineOperand class - Representation of each machine instruction operand.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:843
static MachineInstr * ValueIsPHI(unsigned Val, MachineSSAUpdater *Updater)
ValueIsPHI - Check if the instruction that defines the specified register is a PHI instruction...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
size_type count(const KeyT &Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition: DenseMap.h:122
MachineBasicBlock::succ_iterator BlkSucc_iterator
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
static unsigned LookForIdenticalPHI(MachineBasicBlock *BB, SmallVectorImpl< std::pair< MachineBasicBlock *, unsigned > > &PredValues)
Representation of each machine instruction.
Definition: MachineInstr.h:52
static unsigned GetUndefVal(MachineBasicBlock *BB, MachineSSAUpdater *Updater)
GetUndefVal - Create an IMPLICIT_DEF instruction with a new register.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
void setReg(unsigned Reg)
Change the register this operand corresponds to.
#define I(x, y, z)
Definition: MD5.cpp:54
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
Definition: SmallVector.h:135
unsigned GetValueInMiddleOfBlock(MachineBasicBlock *BB)
GetValueInMiddleOfBlock - Construct SSA form, materializing a value that is live in the middle of the...
void AddAvailableValue(MachineBasicBlock *BB, unsigned V)
AddAvailableValue - Indicate that a rewritten value is available at the end of the specified block wi...
MachineInstr * getVRegDef(unsigned Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
DenseMap< MachineBasicBlock *, unsigned > AvailableValsTy
unsigned getReg() const
getReg - Returns the register number.
unsigned isConstantValuePHI() const
If the specified instruction is a PHI that always merges together the same virtual register...
virtual const TargetInstrInfo * getInstrInfo() const
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned char TargetFlags=0) const
#define DEBUG(X)
Definition: Debug.h:100
static MachineInstr * InstrIsPHI(MachineInstr *I)
InstrIsPHI - Check if an instruction is a PHI.
IRTranslator LLVM IR MI
static unsigned GetPHIValue(MachineInstr *PHI)
GetPHIValue - For the specified PHI instruction, return the register that it defines.
bool operator==(uint64_t V1, const APInt &V2)
Definition: APInt.h:1722
static AvailableValsTy & getAvailableVals(void *AV)
static BlkSucc_iterator BlkSucc_begin(BlkT *BB)
const MachineInstrBuilder & addReg(unsigned RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
MachineSSAUpdater(MachineFunction &MF, SmallVectorImpl< MachineInstr * > *InsertedPHIs=nullptr)
MachineSSAUpdater constructor.