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 
14 #include "llvm/CodeGen/MachineSSAUpdater.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/CodeGen/MachineBasicBlock.h"
18 #include "llvm/CodeGen/MachineFunction.h"
19 #include "llvm/CodeGen/MachineInstr.h"
20 #include "llvm/CodeGen/MachineInstrBuilder.h"
21 #include "llvm/CodeGen/MachineOperand.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/CodeGen/TargetInstrInfo.h"
24 #include "llvm/CodeGen/TargetOpcodes.h"
25 #include "llvm/CodeGen/TargetSubtargetInfo.h"
26 #include "llvm/IR/DebugLoc.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/Transforms/Utils/SSAUpdaterImpl.h"
31 #include <utility>
32 
33 using namespace llvm;
34 
35 #define DEBUG_TYPE "machine-ssaupdater"
36 
37 using AvailableValsTy = DenseMap<MachineBasicBlock *, Register>;
38 
39 static AvailableValsTy &getAvailableVals(void *AV) {
40   return *static_cast<AvailableValsTy*>(AV);
41 }
42 
43 MachineSSAUpdater::MachineSSAUpdater(MachineFunction &MF,
44                                      SmallVectorImpl<MachineInstr*> *NewPHI)
45   : InsertedPHIs(NewPHI), TII(MF.getSubtarget().getInstrInfo()),
46     MRI(&MF.getRegInfo()) {}
47 
48 MachineSSAUpdater::~MachineSSAUpdater() {
49   delete static_cast<AvailableValsTy*>(AV);
50 }
51 
52 /// Initialize - Reset this object to get ready for a new set of SSA
53 /// updates.
54 void MachineSSAUpdater::Initialize(const TargetRegisterClass *RC) {
55   if (!AV)
56     AV = new AvailableValsTy();
57   else
58     getAvailableVals(AV).clear();
59 
60   VRC = RC;
61 }
62 
63 void MachineSSAUpdater::Initialize(Register V) {
64   Initialize(MRI->getRegClass(V));
65 }
66 
67 /// HasValueForBlock - Return true if the MachineSSAUpdater already has a value for
68 /// the specified block.
69 bool MachineSSAUpdater::HasValueForBlock(MachineBasicBlock *BB) const {
70   return getAvailableVals(AV).count(BB);
71 }
72 
73 /// AddAvailableValue - Indicate that a rewritten value is available in the
74 /// specified block with the specified value.
75 void MachineSSAUpdater::AddAvailableValue(MachineBasicBlock *BB, Register V) {
76   getAvailableVals(AV)[BB] = V;
77 }
78 
79 /// GetValueAtEndOfBlock - Construct SSA form, materializing a value that is
80 /// live at the end of the specified block.
81 Register MachineSSAUpdater::GetValueAtEndOfBlock(MachineBasicBlock *BB) {
82   return GetValueAtEndOfBlockInternal(BB);
83 }
84 
85 static
86 Register LookForIdenticalPHI(MachineBasicBlock *BB,
87         SmallVectorImpl<std::pair<MachineBasicBlock *, Register>> &PredValues) {
88   if (BB->empty())
89     return Register();
90 
91   MachineBasicBlock::iterator I = BB->begin();
92   if (!I->isPHI())
93     return Register();
94 
95   AvailableValsTy AVals;
96   for (unsigned i = 0, e = PredValues.size(); i != e; ++i)
97     AVals[PredValues[i].first] = PredValues[i].second;
98   while (I != BB->end() && I->isPHI()) {
99     bool Same = true;
100     for (unsigned i = 1, e = I->getNumOperands(); i != e; i += 2) {
101       Register SrcReg = I->getOperand(i).getReg();
102       MachineBasicBlock *SrcBB = I->getOperand(i+1).getMBB();
103       if (AVals[SrcBB] != SrcReg) {
104         Same = false;
105         break;
106       }
107     }
108     if (Same)
109       return I->getOperand(0).getReg();
110     ++I;
111   }
112   return Register();
113 }
114 
115 /// InsertNewDef - Insert an empty PHI or IMPLICIT_DEF instruction which define
116 /// a value of the given register class at the start of the specified basic
117 /// block. It returns the virtual register defined by the instruction.
118 static
119 MachineInstrBuilder InsertNewDef(unsigned Opcode,
120                            MachineBasicBlock *BB, MachineBasicBlock::iterator I,
121                            const TargetRegisterClass *RC,
122                            MachineRegisterInfo *MRI,
123                            const TargetInstrInfo *TII) {
124   Register NewVR = MRI->createVirtualRegister(RC);
125   return BuildMI(*BB, I, DebugLoc(), TII->get(Opcode), NewVR);
126 }
127 
128 /// GetValueInMiddleOfBlock - Construct SSA form, materializing a value that
129 /// is live in the middle of the specified block. If ExistingValueOnly is
130 /// true then this will only return an existing value or $noreg; otherwise new
131 /// instructions may be inserted to materialize a value.
132 ///
133 /// GetValueInMiddleOfBlock is the same as GetValueAtEndOfBlock except in one
134 /// important case: if there is a definition of the rewritten value after the
135 /// 'use' in BB.  Consider code like this:
136 ///
137 ///      X1 = ...
138 ///   SomeBB:
139 ///      use(X)
140 ///      X2 = ...
141 ///      br Cond, SomeBB, OutBB
142 ///
143 /// In this case, there are two values (X1 and X2) added to the AvailableVals
144 /// set by the client of the rewriter, and those values are both live out of
145 /// their respective blocks.  However, the use of X happens in the *middle* of
146 /// a block.  Because of this, we need to insert a new PHI node in SomeBB to
147 /// merge the appropriate values, and this value isn't live out of the block.
148 Register MachineSSAUpdater::GetValueInMiddleOfBlock(MachineBasicBlock *BB,
149                                                     bool ExistingValueOnly) {
150   // If there is no definition of the renamed variable in this block, just use
151   // GetValueAtEndOfBlock to do our work.
152   if (!HasValueForBlock(BB))
153     return GetValueAtEndOfBlockInternal(BB, ExistingValueOnly);
154 
155   // Ok, we have already got a value for this block. If it is out of our block
156   // or it is a phi - we can re-use it as it will be defined in the middle of
157   // block as well.
158   Register defR = getAvailableVals(AV).lookup(BB);
159   if (auto I = MRI->getVRegDef(defR))
160     if (I->isPHI() || I->getParent() != BB)
161       return defR;
162 
163   // If there are no predecessors, just return undef.
164   if (BB->pred_empty()) {
165     // If we cannot insert new instructions, just return $noreg.
166     if (ExistingValueOnly)
167       return Register();
168     // Insert an implicit_def to represent an undef value.
169     MachineInstr *NewDef = InsertNewDef(TargetOpcode::IMPLICIT_DEF,
170                                         BB, BB->getFirstTerminator(),
171                                         VRC, MRI, TII);
172     return NewDef->getOperand(0).getReg();
173   }
174 
175   // Otherwise, we have the hard case.  Get the live-in values for each
176   // predecessor.
177   SmallVector<std::pair<MachineBasicBlock*, Register>, 8> PredValues;
178   Register SingularValue;
179 
180   bool isFirstPred = true;
181   for (MachineBasicBlock *PredBB : BB->predecessors()) {
182     Register PredVal = GetValueAtEndOfBlockInternal(PredBB, ExistingValueOnly);
183     PredValues.push_back(std::make_pair(PredBB, PredVal));
184 
185     // Compute SingularValue.
186     if (isFirstPred) {
187       SingularValue = PredVal;
188       isFirstPred = false;
189     } else if (PredVal != SingularValue)
190       SingularValue = Register();
191   }
192 
193   // Otherwise, if all the merged values are the same, just use it.
194   if (SingularValue)
195     return SingularValue;
196 
197   // If an identical PHI is already in BB, just reuse it.
198   Register DupPHI = LookForIdenticalPHI(BB, PredValues);
199   if (DupPHI)
200     return DupPHI;
201 
202   // If we cannot create new instructions, return $noreg now.
203   if (ExistingValueOnly)
204     return Register();
205 
206   // Otherwise, we do need a PHI: insert one now.
207   MachineBasicBlock::iterator Loc = BB->empty() ? BB->end() : BB->begin();
208   MachineInstrBuilder InsertedPHI = InsertNewDef(TargetOpcode::PHI, BB,
209                                                  Loc, VRC, MRI, TII);
210 
211   // Fill in all the predecessors of the PHI.
212   for (unsigned i = 0, e = PredValues.size(); i != e; ++i)
213     InsertedPHI.addReg(PredValues[i].second).addMBB(PredValues[i].first);
214 
215   // See if the PHI node can be merged to a single value.  This can happen in
216   // loop cases when we get a PHI of itself and one other value.
217   if (unsigned ConstVal = InsertedPHI->isConstantValuePHI()) {
218     InsertedPHI->eraseFromParent();
219     return ConstVal;
220   }
221 
222   // If the client wants to know about all new instructions, tell it.
223   if (InsertedPHIs) InsertedPHIs->push_back(InsertedPHI);
224 
225   LLVM_DEBUG(dbgs() << "  Inserted PHI: " << *InsertedPHI << "\n");
226   return InsertedPHI.getReg(0);
227 }
228 
229 static
230 MachineBasicBlock *findCorrespondingPred(const MachineInstr *MI,
231                                          MachineOperand *U) {
232   for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
233     if (&MI->getOperand(i) == U)
234       return MI->getOperand(i+1).getMBB();
235   }
236 
237   llvm_unreachable("MachineOperand::getParent() failure?");
238 }
239 
240 /// RewriteUse - Rewrite a use of the symbolic value.  This handles PHI nodes,
241 /// which use their value in the corresponding predecessor.
242 void MachineSSAUpdater::RewriteUse(MachineOperand &U) {
243   MachineInstr *UseMI = U.getParent();
244   Register NewVR;
245   if (UseMI->isPHI()) {
246     MachineBasicBlock *SourceBB = findCorrespondingPred(UseMI, &U);
247     NewVR = GetValueAtEndOfBlockInternal(SourceBB);
248   } else {
249     NewVR = GetValueInMiddleOfBlock(UseMI->getParent());
250   }
251 
252   U.setReg(NewVR);
253 }
254 
255 namespace llvm {
256 
257 /// SSAUpdaterTraits<MachineSSAUpdater> - Traits for the SSAUpdaterImpl
258 /// template, specialized for MachineSSAUpdater.
259 template<>
260 class SSAUpdaterTraits<MachineSSAUpdater> {
261 public:
262   using BlkT = MachineBasicBlock;
263   using ValT = Register;
264   using PhiT = MachineInstr;
265   using BlkSucc_iterator = MachineBasicBlock::succ_iterator;
266 
267   static BlkSucc_iterator BlkSucc_begin(BlkT *BB) { return BB->succ_begin(); }
268   static BlkSucc_iterator BlkSucc_end(BlkT *BB) { return BB->succ_end(); }
269 
270   /// Iterator for PHI operands.
271   class PHI_iterator {
272   private:
273     MachineInstr *PHI;
274     unsigned idx;
275 
276   public:
277     explicit PHI_iterator(MachineInstr *P) // begin iterator
278       : PHI(P), idx(1) {}
279     PHI_iterator(MachineInstr *P, bool) // end iterator
280       : PHI(P), idx(PHI->getNumOperands()) {}
281 
282     PHI_iterator &operator++() { idx += 2; return *this; }
283     bool operator==(const PHI_iterator& x) const { return idx == x.idx; }
284     bool operator!=(const PHI_iterator& x) const { return !operator==(x); }
285 
286     unsigned getIncomingValue() { return PHI->getOperand(idx).getReg(); }
287 
288     MachineBasicBlock *getIncomingBlock() {
289       return PHI->getOperand(idx+1).getMBB();
290     }
291   };
292 
293   static inline PHI_iterator PHI_begin(PhiT *PHI) { return PHI_iterator(PHI); }
294 
295   static inline PHI_iterator PHI_end(PhiT *PHI) {
296     return PHI_iterator(PHI, true);
297   }
298 
299   /// FindPredecessorBlocks - Put the predecessors of BB into the Preds
300   /// vector.
301   static void FindPredecessorBlocks(MachineBasicBlock *BB,
302                                     SmallVectorImpl<MachineBasicBlock*> *Preds){
303     append_range(*Preds, BB->predecessors());
304   }
305 
306   /// GetUndefVal - Create an IMPLICIT_DEF instruction with a new register.
307   /// Add it into the specified block and return the register.
308   static Register GetUndefVal(MachineBasicBlock *BB,
309                               MachineSSAUpdater *Updater) {
310     // Insert an implicit_def to represent an undef value.
311     MachineInstr *NewDef = InsertNewDef(TargetOpcode::IMPLICIT_DEF,
312                                         BB, BB->getFirstNonPHI(),
313                                         Updater->VRC, Updater->MRI,
314                                         Updater->TII);
315     return NewDef->getOperand(0).getReg();
316   }
317 
318   /// CreateEmptyPHI - Create a PHI instruction that defines a new register.
319   /// Add it into the specified block and return the register.
320   static Register CreateEmptyPHI(MachineBasicBlock *BB, unsigned NumPreds,
321                                  MachineSSAUpdater *Updater) {
322     MachineBasicBlock::iterator Loc = BB->empty() ? BB->end() : BB->begin();
323     MachineInstr *PHI = InsertNewDef(TargetOpcode::PHI, BB, Loc,
324                                      Updater->VRC, Updater->MRI,
325                                      Updater->TII);
326     return PHI->getOperand(0).getReg();
327   }
328 
329   /// AddPHIOperand - Add the specified value as an operand of the PHI for
330   /// the specified predecessor block.
331   static void AddPHIOperand(MachineInstr *PHI, Register Val,
332                             MachineBasicBlock *Pred) {
333     MachineInstrBuilder(*Pred->getParent(), PHI).addReg(Val).addMBB(Pred);
334   }
335 
336   /// InstrIsPHI - Check if an instruction is a PHI.
337   static MachineInstr *InstrIsPHI(MachineInstr *I) {
338     if (I && I->isPHI())
339       return I;
340     return nullptr;
341   }
342 
343   /// ValueIsPHI - Check if the instruction that defines the specified register
344   /// is a PHI instruction.
345   static MachineInstr *ValueIsPHI(Register Val, MachineSSAUpdater *Updater) {
346     return InstrIsPHI(Updater->MRI->getVRegDef(Val));
347   }
348 
349   /// ValueIsNewPHI - Like ValueIsPHI but also check if the PHI has no source
350   /// operands, i.e., it was just added.
351   static MachineInstr *ValueIsNewPHI(Register Val, MachineSSAUpdater *Updater) {
352     MachineInstr *PHI = ValueIsPHI(Val, Updater);
353     if (PHI && PHI->getNumOperands() <= 1)
354       return PHI;
355     return nullptr;
356   }
357 
358   /// GetPHIValue - For the specified PHI instruction, return the register
359   /// that it defines.
360   static Register GetPHIValue(MachineInstr *PHI) {
361     return PHI->getOperand(0).getReg();
362   }
363 };
364 
365 } // end namespace llvm
366 
367 /// GetValueAtEndOfBlockInternal - Check to see if AvailableVals has an entry
368 /// for the specified BB and if so, return it.  If not, construct SSA form by
369 /// first calculating the required placement of PHIs and then inserting new
370 /// PHIs where needed.
371 Register
372 MachineSSAUpdater::GetValueAtEndOfBlockInternal(MachineBasicBlock *BB,
373                                                 bool ExistingValueOnly) {
374   AvailableValsTy &AvailableVals = getAvailableVals(AV);
375   Register ExistingVal = AvailableVals.lookup(BB);
376   if (ExistingVal || ExistingValueOnly)
377     return ExistingVal;
378 
379   SSAUpdaterImpl<MachineSSAUpdater> Impl(this, &AvailableVals, InsertedPHIs);
380   return Impl.GetValue(BB);
381 }
382