LLVM API Documentation

MachineSSAUpdater.cpp
Go to the documentation of this file.
00001 //===- MachineSSAUpdater.cpp - Unstructured SSA Update Tool ---------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the MachineSSAUpdater class. It's based on SSAUpdater
00011 // class in lib/Transforms/Utils.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/CodeGen/MachineSSAUpdater.h"
00016 #include "llvm/ADT/DenseMap.h"
00017 #include "llvm/ADT/SmallVector.h"
00018 #include "llvm/CodeGen/MachineInstr.h"
00019 #include "llvm/CodeGen/MachineInstrBuilder.h"
00020 #include "llvm/CodeGen/MachineRegisterInfo.h"
00021 #include "llvm/Support/AlignOf.h"
00022 #include "llvm/Support/Allocator.h"
00023 #include "llvm/Support/Debug.h"
00024 #include "llvm/Support/ErrorHandling.h"
00025 #include "llvm/Support/raw_ostream.h"
00026 #include "llvm/Target/TargetInstrInfo.h"
00027 #include "llvm/Target/TargetMachine.h"
00028 #include "llvm/Target/TargetRegisterInfo.h"
00029 #include "llvm/Target/TargetSubtargetInfo.h"
00030 #include "llvm/Transforms/Utils/SSAUpdaterImpl.h"
00031 using namespace llvm;
00032 
00033 #define DEBUG_TYPE "machine-ssaupdater"
00034 
00035 typedef DenseMap<MachineBasicBlock*, unsigned> AvailableValsTy;
00036 static AvailableValsTy &getAvailableVals(void *AV) {
00037   return *static_cast<AvailableValsTy*>(AV);
00038 }
00039 
00040 MachineSSAUpdater::MachineSSAUpdater(MachineFunction &MF,
00041                                      SmallVectorImpl<MachineInstr*> *NewPHI)
00042   : AV(nullptr), InsertedPHIs(NewPHI) {
00043   TII = MF.getSubtarget().getInstrInfo();
00044   MRI = &MF.getRegInfo();
00045 }
00046 
00047 MachineSSAUpdater::~MachineSSAUpdater() {
00048   delete static_cast<AvailableValsTy*>(AV);
00049 }
00050 
00051 /// Initialize - Reset this object to get ready for a new set of SSA
00052 /// updates.  ProtoValue is the value used to name PHI nodes.
00053 void MachineSSAUpdater::Initialize(unsigned V) {
00054   if (!AV)
00055     AV = new AvailableValsTy();
00056   else
00057     getAvailableVals(AV).clear();
00058 
00059   VR = V;
00060   VRC = MRI->getRegClass(VR);
00061 }
00062 
00063 /// HasValueForBlock - Return true if the MachineSSAUpdater already has a value for
00064 /// the specified block.
00065 bool MachineSSAUpdater::HasValueForBlock(MachineBasicBlock *BB) const {
00066   return getAvailableVals(AV).count(BB);
00067 }
00068 
00069 /// AddAvailableValue - Indicate that a rewritten value is available in the
00070 /// specified block with the specified value.
00071 void MachineSSAUpdater::AddAvailableValue(MachineBasicBlock *BB, unsigned V) {
00072   getAvailableVals(AV)[BB] = V;
00073 }
00074 
00075 /// GetValueAtEndOfBlock - Construct SSA form, materializing a value that is
00076 /// live at the end of the specified block.
00077 unsigned MachineSSAUpdater::GetValueAtEndOfBlock(MachineBasicBlock *BB) {
00078   return GetValueAtEndOfBlockInternal(BB);
00079 }
00080 
00081 static
00082 unsigned LookForIdenticalPHI(MachineBasicBlock *BB,
00083         SmallVectorImpl<std::pair<MachineBasicBlock*, unsigned> > &PredValues) {
00084   if (BB->empty())
00085     return 0;
00086 
00087   MachineBasicBlock::iterator I = BB->begin();
00088   if (!I->isPHI())
00089     return 0;
00090 
00091   AvailableValsTy AVals;
00092   for (unsigned i = 0, e = PredValues.size(); i != e; ++i)
00093     AVals[PredValues[i].first] = PredValues[i].second;
00094   while (I != BB->end() && I->isPHI()) {
00095     bool Same = true;
00096     for (unsigned i = 1, e = I->getNumOperands(); i != e; i += 2) {
00097       unsigned SrcReg = I->getOperand(i).getReg();
00098       MachineBasicBlock *SrcBB = I->getOperand(i+1).getMBB();
00099       if (AVals[SrcBB] != SrcReg) {
00100         Same = false;
00101         break;
00102       }
00103     }
00104     if (Same)
00105       return I->getOperand(0).getReg();
00106     ++I;
00107   }
00108   return 0;
00109 }
00110 
00111 /// InsertNewDef - Insert an empty PHI or IMPLICIT_DEF instruction which define
00112 /// a value of the given register class at the start of the specified basic
00113 /// block. It returns the virtual register defined by the instruction.
00114 static
00115 MachineInstrBuilder InsertNewDef(unsigned Opcode,
00116                            MachineBasicBlock *BB, MachineBasicBlock::iterator I,
00117                            const TargetRegisterClass *RC,
00118                            MachineRegisterInfo *MRI,
00119                            const TargetInstrInfo *TII) {
00120   unsigned NewVR = MRI->createVirtualRegister(RC);
00121   return BuildMI(*BB, I, DebugLoc(), TII->get(Opcode), NewVR);
00122 }
00123 
00124 /// GetValueInMiddleOfBlock - Construct SSA form, materializing a value that
00125 /// is live in the middle of the specified block.
00126 ///
00127 /// GetValueInMiddleOfBlock is the same as GetValueAtEndOfBlock except in one
00128 /// important case: if there is a definition of the rewritten value after the
00129 /// 'use' in BB.  Consider code like this:
00130 ///
00131 ///      X1 = ...
00132 ///   SomeBB:
00133 ///      use(X)
00134 ///      X2 = ...
00135 ///      br Cond, SomeBB, OutBB
00136 ///
00137 /// In this case, there are two values (X1 and X2) added to the AvailableVals
00138 /// set by the client of the rewriter, and those values are both live out of
00139 /// their respective blocks.  However, the use of X happens in the *middle* of
00140 /// a block.  Because of this, we need to insert a new PHI node in SomeBB to
00141 /// merge the appropriate values, and this value isn't live out of the block.
00142 ///
00143 unsigned MachineSSAUpdater::GetValueInMiddleOfBlock(MachineBasicBlock *BB) {
00144   // If there is no definition of the renamed variable in this block, just use
00145   // GetValueAtEndOfBlock to do our work.
00146   if (!HasValueForBlock(BB))
00147     return GetValueAtEndOfBlockInternal(BB);
00148 
00149   // If there are no predecessors, just return undef.
00150   if (BB->pred_empty()) {
00151     // Insert an implicit_def to represent an undef value.
00152     MachineInstr *NewDef = InsertNewDef(TargetOpcode::IMPLICIT_DEF,
00153                                         BB, BB->getFirstTerminator(),
00154                                         VRC, MRI, TII);
00155     return NewDef->getOperand(0).getReg();
00156   }
00157 
00158   // Otherwise, we have the hard case.  Get the live-in values for each
00159   // predecessor.
00160   SmallVector<std::pair<MachineBasicBlock*, unsigned>, 8> PredValues;
00161   unsigned SingularValue = 0;
00162 
00163   bool isFirstPred = true;
00164   for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
00165          E = BB->pred_end(); PI != E; ++PI) {
00166     MachineBasicBlock *PredBB = *PI;
00167     unsigned PredVal = GetValueAtEndOfBlockInternal(PredBB);
00168     PredValues.push_back(std::make_pair(PredBB, PredVal));
00169 
00170     // Compute SingularValue.
00171     if (isFirstPred) {
00172       SingularValue = PredVal;
00173       isFirstPred = false;
00174     } else if (PredVal != SingularValue)
00175       SingularValue = 0;
00176   }
00177 
00178   // Otherwise, if all the merged values are the same, just use it.
00179   if (SingularValue != 0)
00180     return SingularValue;
00181 
00182   // If an identical PHI is already in BB, just reuse it.
00183   unsigned DupPHI = LookForIdenticalPHI(BB, PredValues);
00184   if (DupPHI)
00185     return DupPHI;
00186 
00187   // Otherwise, we do need a PHI: insert one now.
00188   MachineBasicBlock::iterator Loc = BB->empty() ? BB->end() : BB->begin();
00189   MachineInstrBuilder InsertedPHI = InsertNewDef(TargetOpcode::PHI, BB,
00190                                                  Loc, VRC, MRI, TII);
00191 
00192   // Fill in all the predecessors of the PHI.
00193   for (unsigned i = 0, e = PredValues.size(); i != e; ++i)
00194     InsertedPHI.addReg(PredValues[i].second).addMBB(PredValues[i].first);
00195 
00196   // See if the PHI node can be merged to a single value.  This can happen in
00197   // loop cases when we get a PHI of itself and one other value.
00198   if (unsigned ConstVal = InsertedPHI->isConstantValuePHI()) {
00199     InsertedPHI->eraseFromParent();
00200     return ConstVal;
00201   }
00202 
00203   // If the client wants to know about all new instructions, tell it.
00204   if (InsertedPHIs) InsertedPHIs->push_back(InsertedPHI);
00205 
00206   DEBUG(dbgs() << "  Inserted PHI: " << *InsertedPHI << "\n");
00207   return InsertedPHI->getOperand(0).getReg();
00208 }
00209 
00210 static
00211 MachineBasicBlock *findCorrespondingPred(const MachineInstr *MI,
00212                                          MachineOperand *U) {
00213   for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
00214     if (&MI->getOperand(i) == U)
00215       return MI->getOperand(i+1).getMBB();
00216   }
00217 
00218   llvm_unreachable("MachineOperand::getParent() failure?");
00219 }
00220 
00221 /// RewriteUse - Rewrite a use of the symbolic value.  This handles PHI nodes,
00222 /// which use their value in the corresponding predecessor.
00223 void MachineSSAUpdater::RewriteUse(MachineOperand &U) {
00224   MachineInstr *UseMI = U.getParent();
00225   unsigned NewVR = 0;
00226   if (UseMI->isPHI()) {
00227     MachineBasicBlock *SourceBB = findCorrespondingPred(UseMI, &U);
00228     NewVR = GetValueAtEndOfBlockInternal(SourceBB);
00229   } else {
00230     NewVR = GetValueInMiddleOfBlock(UseMI->getParent());
00231   }
00232 
00233   U.setReg(NewVR);
00234 }
00235 
00236 /// SSAUpdaterTraits<MachineSSAUpdater> - Traits for the SSAUpdaterImpl
00237 /// template, specialized for MachineSSAUpdater.
00238 namespace llvm {
00239 template<>
00240 class SSAUpdaterTraits<MachineSSAUpdater> {
00241 public:
00242   typedef MachineBasicBlock BlkT;
00243   typedef unsigned ValT;
00244   typedef MachineInstr PhiT;
00245 
00246   typedef MachineBasicBlock::succ_iterator BlkSucc_iterator;
00247   static BlkSucc_iterator BlkSucc_begin(BlkT *BB) { return BB->succ_begin(); }
00248   static BlkSucc_iterator BlkSucc_end(BlkT *BB) { return BB->succ_end(); }
00249 
00250   /// Iterator for PHI operands.
00251   class PHI_iterator {
00252   private:
00253     MachineInstr *PHI;
00254     unsigned idx;
00255  
00256   public:
00257     explicit PHI_iterator(MachineInstr *P) // begin iterator
00258       : PHI(P), idx(1) {}
00259     PHI_iterator(MachineInstr *P, bool) // end iterator
00260       : PHI(P), idx(PHI->getNumOperands()) {}
00261 
00262     PHI_iterator &operator++() { idx += 2; return *this; } 
00263     bool operator==(const PHI_iterator& x) const { return idx == x.idx; }
00264     bool operator!=(const PHI_iterator& x) const { return !operator==(x); }
00265     unsigned getIncomingValue() { return PHI->getOperand(idx).getReg(); }
00266     MachineBasicBlock *getIncomingBlock() {
00267       return PHI->getOperand(idx+1).getMBB();
00268     }
00269   };
00270   static inline PHI_iterator PHI_begin(PhiT *PHI) { return PHI_iterator(PHI); }
00271   static inline PHI_iterator PHI_end(PhiT *PHI) {
00272     return PHI_iterator(PHI, true);
00273   }
00274 
00275   /// FindPredecessorBlocks - Put the predecessors of BB into the Preds
00276   /// vector.
00277   static void FindPredecessorBlocks(MachineBasicBlock *BB,
00278                                     SmallVectorImpl<MachineBasicBlock*> *Preds){
00279     for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
00280            E = BB->pred_end(); PI != E; ++PI)
00281       Preds->push_back(*PI);
00282   }
00283 
00284   /// GetUndefVal - Create an IMPLICIT_DEF instruction with a new register.
00285   /// Add it into the specified block and return the register.
00286   static unsigned GetUndefVal(MachineBasicBlock *BB,
00287                               MachineSSAUpdater *Updater) {
00288     // Insert an implicit_def to represent an undef value.
00289     MachineInstr *NewDef = InsertNewDef(TargetOpcode::IMPLICIT_DEF,
00290                                         BB, BB->getFirstTerminator(),
00291                                         Updater->VRC, Updater->MRI,
00292                                         Updater->TII);
00293     return NewDef->getOperand(0).getReg();
00294   }
00295 
00296   /// CreateEmptyPHI - Create a PHI instruction that defines a new register.
00297   /// Add it into the specified block and return the register.
00298   static unsigned CreateEmptyPHI(MachineBasicBlock *BB, unsigned NumPreds,
00299                                  MachineSSAUpdater *Updater) {
00300     MachineBasicBlock::iterator Loc = BB->empty() ? BB->end() : BB->begin();
00301     MachineInstr *PHI = InsertNewDef(TargetOpcode::PHI, BB, Loc,
00302                                      Updater->VRC, Updater->MRI,
00303                                      Updater->TII);
00304     return PHI->getOperand(0).getReg();
00305   }
00306 
00307   /// AddPHIOperand - Add the specified value as an operand of the PHI for
00308   /// the specified predecessor block.
00309   static void AddPHIOperand(MachineInstr *PHI, unsigned Val,
00310                             MachineBasicBlock *Pred) {
00311     MachineInstrBuilder(*Pred->getParent(), PHI).addReg(Val).addMBB(Pred);
00312   }
00313 
00314   /// InstrIsPHI - Check if an instruction is a PHI.
00315   ///
00316   static MachineInstr *InstrIsPHI(MachineInstr *I) {
00317     if (I && I->isPHI())
00318       return I;
00319     return nullptr;
00320   }
00321 
00322   /// ValueIsPHI - Check if the instruction that defines the specified register
00323   /// is a PHI instruction.
00324   static MachineInstr *ValueIsPHI(unsigned Val, MachineSSAUpdater *Updater) {
00325     return InstrIsPHI(Updater->MRI->getVRegDef(Val));
00326   }
00327 
00328   /// ValueIsNewPHI - Like ValueIsPHI but also check if the PHI has no source
00329   /// operands, i.e., it was just added.
00330   static MachineInstr *ValueIsNewPHI(unsigned Val, MachineSSAUpdater *Updater) {
00331     MachineInstr *PHI = ValueIsPHI(Val, Updater);
00332     if (PHI && PHI->getNumOperands() <= 1)
00333       return PHI;
00334     return nullptr;
00335   }
00336 
00337   /// GetPHIValue - For the specified PHI instruction, return the register
00338   /// that it defines.
00339   static unsigned GetPHIValue(MachineInstr *PHI) {
00340     return PHI->getOperand(0).getReg();
00341   }
00342 };
00343 
00344 } // End llvm namespace
00345 
00346 /// GetValueAtEndOfBlockInternal - Check to see if AvailableVals has an entry
00347 /// for the specified BB and if so, return it.  If not, construct SSA form by
00348 /// first calculating the required placement of PHIs and then inserting new
00349 /// PHIs where needed.
00350 unsigned MachineSSAUpdater::GetValueAtEndOfBlockInternal(MachineBasicBlock *BB){
00351   AvailableValsTy &AvailableVals = getAvailableVals(AV);
00352   if (unsigned V = AvailableVals[BB])
00353     return V;
00354 
00355   SSAUpdaterImpl<MachineSSAUpdater> Impl(this, &AvailableVals, InsertedPHIs);
00356   return Impl.GetValue(BB);
00357 }