MachineSSAUpdater.cpp 13 KB

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