MachineSSAUpdater.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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/Support/Debug.h"
  23. #include "llvm/Support/ErrorHandling.h"
  24. #include "llvm/Support/raw_ostream.h"
  25. using namespace llvm;
  26. typedef DenseMap<MachineBasicBlock*, unsigned> AvailableValsTy;
  27. typedef std::vector<std::pair<MachineBasicBlock*, unsigned> >
  28. IncomingPredInfoTy;
  29. static AvailableValsTy &getAvailableVals(void *AV) {
  30. return *static_cast<AvailableValsTy*>(AV);
  31. }
  32. static IncomingPredInfoTy &getIncomingPredInfo(void *IPI) {
  33. return *static_cast<IncomingPredInfoTy*>(IPI);
  34. }
  35. MachineSSAUpdater::MachineSSAUpdater(MachineFunction &MF,
  36. SmallVectorImpl<MachineInstr*> *NewPHI)
  37. : AV(0), IPI(0), InsertedPHIs(NewPHI) {
  38. TII = MF.getTarget().getInstrInfo();
  39. MRI = &MF.getRegInfo();
  40. }
  41. MachineSSAUpdater::~MachineSSAUpdater() {
  42. delete &getAvailableVals(AV);
  43. delete &getIncomingPredInfo(IPI);
  44. }
  45. /// Initialize - Reset this object to get ready for a new set of SSA
  46. /// updates. ProtoValue is the value used to name PHI nodes.
  47. void MachineSSAUpdater::Initialize(unsigned V) {
  48. if (AV == 0)
  49. AV = new AvailableValsTy();
  50. else
  51. getAvailableVals(AV).clear();
  52. if (IPI == 0)
  53. IPI = new IncomingPredInfoTy();
  54. else
  55. getIncomingPredInfo(IPI).clear();
  56. VR = V;
  57. VRC = MRI->getRegClass(VR);
  58. }
  59. /// HasValueForBlock - Return true if the MachineSSAUpdater already has a value for
  60. /// the specified block.
  61. bool MachineSSAUpdater::HasValueForBlock(MachineBasicBlock *BB) const {
  62. return getAvailableVals(AV).count(BB);
  63. }
  64. /// AddAvailableValue - Indicate that a rewritten value is available in the
  65. /// specified block with the specified value.
  66. void MachineSSAUpdater::AddAvailableValue(MachineBasicBlock *BB, unsigned V) {
  67. getAvailableVals(AV)[BB] = V;
  68. }
  69. /// GetValueAtEndOfBlock - Construct SSA form, materializing a value that is
  70. /// live at the end of the specified block.
  71. unsigned MachineSSAUpdater::GetValueAtEndOfBlock(MachineBasicBlock *BB) {
  72. return GetValueAtEndOfBlockInternal(BB);
  73. }
  74. static
  75. unsigned LookForIdenticalPHI(MachineBasicBlock *BB,
  76. SmallVector<std::pair<MachineBasicBlock*, unsigned>, 8> &PredValues) {
  77. if (BB->empty())
  78. return 0;
  79. MachineBasicBlock::iterator I = BB->front();
  80. if (!I->isPHI())
  81. return 0;
  82. AvailableValsTy AVals;
  83. for (unsigned i = 0, e = PredValues.size(); i != e; ++i)
  84. AVals[PredValues[i].first] = PredValues[i].second;
  85. while (I != BB->end() && I->isPHI()) {
  86. bool Same = true;
  87. for (unsigned i = 1, e = I->getNumOperands(); i != e; i += 2) {
  88. unsigned SrcReg = I->getOperand(i).getReg();
  89. MachineBasicBlock *SrcBB = I->getOperand(i+1).getMBB();
  90. if (AVals[SrcBB] != SrcReg) {
  91. Same = false;
  92. break;
  93. }
  94. }
  95. if (Same)
  96. return I->getOperand(0).getReg();
  97. ++I;
  98. }
  99. return 0;
  100. }
  101. /// InsertNewDef - Insert an empty PHI or IMPLICIT_DEF instruction which define
  102. /// a value of the given register class at the start of the specified basic
  103. /// block. It returns the virtual register defined by the instruction.
  104. static
  105. MachineInstr *InsertNewDef(unsigned Opcode,
  106. MachineBasicBlock *BB, MachineBasicBlock::iterator I,
  107. const TargetRegisterClass *RC,
  108. MachineRegisterInfo *MRI, const TargetInstrInfo *TII) {
  109. unsigned NewVR = MRI->createVirtualRegister(RC);
  110. return BuildMI(*BB, I, DebugLoc::getUnknownLoc(), TII->get(Opcode), NewVR);
  111. }
  112. /// GetValueInMiddleOfBlock - Construct SSA form, materializing a value that
  113. /// is live in the middle of the specified block.
  114. ///
  115. /// GetValueInMiddleOfBlock is the same as GetValueAtEndOfBlock except in one
  116. /// important case: if there is a definition of the rewritten value after the
  117. /// 'use' in BB. Consider code like this:
  118. ///
  119. /// X1 = ...
  120. /// SomeBB:
  121. /// use(X)
  122. /// X2 = ...
  123. /// br Cond, SomeBB, OutBB
  124. ///
  125. /// In this case, there are two values (X1 and X2) added to the AvailableVals
  126. /// set by the client of the rewriter, and those values are both live out of
  127. /// their respective blocks. However, the use of X happens in the *middle* of
  128. /// a block. Because of this, we need to insert a new PHI node in SomeBB to
  129. /// merge the appropriate values, and this value isn't live out of the block.
  130. ///
  131. unsigned MachineSSAUpdater::GetValueInMiddleOfBlock(MachineBasicBlock *BB) {
  132. // If there is no definition of the renamed variable in this block, just use
  133. // GetValueAtEndOfBlock to do our work.
  134. if (!getAvailableVals(AV).count(BB))
  135. return GetValueAtEndOfBlockInternal(BB);
  136. // If there are no predecessors, just return undef.
  137. if (BB->pred_empty()) {
  138. // Insert an implicit_def to represent an undef value.
  139. MachineInstr *NewDef = InsertNewDef(TargetOpcode::IMPLICIT_DEF,
  140. BB, BB->getFirstTerminator(),
  141. VRC, MRI, TII);
  142. return NewDef->getOperand(0).getReg();
  143. }
  144. // Otherwise, we have the hard case. Get the live-in values for each
  145. // predecessor.
  146. SmallVector<std::pair<MachineBasicBlock*, unsigned>, 8> PredValues;
  147. unsigned SingularValue = 0;
  148. bool isFirstPred = true;
  149. for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
  150. E = BB->pred_end(); PI != E; ++PI) {
  151. MachineBasicBlock *PredBB = *PI;
  152. unsigned PredVal = GetValueAtEndOfBlockInternal(PredBB);
  153. PredValues.push_back(std::make_pair(PredBB, PredVal));
  154. // Compute SingularValue.
  155. if (isFirstPred) {
  156. SingularValue = PredVal;
  157. isFirstPred = false;
  158. } else if (PredVal != SingularValue)
  159. SingularValue = 0;
  160. }
  161. // Otherwise, if all the merged values are the same, just use it.
  162. if (SingularValue != 0)
  163. return SingularValue;
  164. // If an identical PHI is already in BB, just reuse it.
  165. unsigned DupPHI = LookForIdenticalPHI(BB, PredValues);
  166. if (DupPHI)
  167. return DupPHI;
  168. // Otherwise, we do need a PHI: insert one now.
  169. MachineBasicBlock::iterator Loc = BB->empty() ? BB->end() : BB->front();
  170. MachineInstr *InsertedPHI = InsertNewDef(TargetOpcode::PHI, BB,
  171. Loc, VRC, MRI, TII);
  172. // Fill in all the predecessors of the PHI.
  173. MachineInstrBuilder MIB(InsertedPHI);
  174. for (unsigned i = 0, e = PredValues.size(); i != e; ++i)
  175. MIB.addReg(PredValues[i].second).addMBB(PredValues[i].first);
  176. // See if the PHI node can be merged to a single value. This can happen in
  177. // loop cases when we get a PHI of itself and one other value.
  178. if (unsigned ConstVal = InsertedPHI->isConstantValuePHI()) {
  179. InsertedPHI->eraseFromParent();
  180. return ConstVal;
  181. }
  182. // If the client wants to know about all new instructions, tell it.
  183. if (InsertedPHIs) InsertedPHIs->push_back(InsertedPHI);
  184. DEBUG(dbgs() << " Inserted PHI: " << *InsertedPHI << "\n");
  185. return InsertedPHI->getOperand(0).getReg();
  186. }
  187. static
  188. MachineBasicBlock *findCorrespondingPred(const MachineInstr *MI,
  189. MachineOperand *U) {
  190. for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
  191. if (&MI->getOperand(i) == U)
  192. return MI->getOperand(i+1).getMBB();
  193. }
  194. llvm_unreachable("MachineOperand::getParent() failure?");
  195. return 0;
  196. }
  197. /// RewriteUse - Rewrite a use of the symbolic value. This handles PHI nodes,
  198. /// which use their value in the corresponding predecessor.
  199. void MachineSSAUpdater::RewriteUse(MachineOperand &U) {
  200. MachineInstr *UseMI = U.getParent();
  201. unsigned NewVR = 0;
  202. if (UseMI->isPHI()) {
  203. MachineBasicBlock *SourceBB = findCorrespondingPred(UseMI, &U);
  204. NewVR = GetValueAtEndOfBlockInternal(SourceBB);
  205. } else {
  206. NewVR = GetValueInMiddleOfBlock(UseMI->getParent());
  207. }
  208. U.setReg(NewVR);
  209. }
  210. void MachineSSAUpdater::ReplaceRegWith(unsigned OldReg, unsigned NewReg) {
  211. MRI->replaceRegWith(OldReg, NewReg);
  212. AvailableValsTy &AvailableVals = getAvailableVals(AV);
  213. for (DenseMap<MachineBasicBlock*, unsigned>::iterator
  214. I = AvailableVals.begin(), E = AvailableVals.end(); I != E; ++I)
  215. if (I->second == OldReg)
  216. I->second = NewReg;
  217. }
  218. /// GetValueAtEndOfBlockInternal - Check to see if AvailableVals has an entry
  219. /// for the specified BB and if so, return it. If not, construct SSA form by
  220. /// walking predecessors inserting PHI nodes as needed until we get to a block
  221. /// where the value is available.
  222. ///
  223. unsigned MachineSSAUpdater::GetValueAtEndOfBlockInternal(MachineBasicBlock *BB){
  224. AvailableValsTy &AvailableVals = getAvailableVals(AV);
  225. // Query AvailableVals by doing an insertion of null.
  226. std::pair<AvailableValsTy::iterator, bool> InsertRes =
  227. AvailableVals.insert(std::make_pair(BB, 0));
  228. // Handle the case when the insertion fails because we have already seen BB.
  229. if (!InsertRes.second) {
  230. // If the insertion failed, there are two cases. The first case is that the
  231. // value is already available for the specified block. If we get this, just
  232. // return the value.
  233. if (InsertRes.first->second != 0)
  234. return InsertRes.first->second;
  235. // Otherwise, if the value we find is null, then this is the value is not
  236. // known but it is being computed elsewhere in our recursion. This means
  237. // that we have a cycle. Handle this by inserting a PHI node and returning
  238. // it. When we get back to the first instance of the recursion we will fill
  239. // in the PHI node.
  240. MachineBasicBlock::iterator Loc = BB->empty() ? BB->end() : BB->front();
  241. MachineInstr *NewPHI = InsertNewDef(TargetOpcode::PHI, BB, Loc,
  242. VRC, MRI,TII);
  243. unsigned NewVR = NewPHI->getOperand(0).getReg();
  244. InsertRes.first->second = NewVR;
  245. return NewVR;
  246. }
  247. // If there are no predecessors, then we must have found an unreachable block
  248. // just return 'undef'. Since there are no predecessors, InsertRes must not
  249. // be invalidated.
  250. if (BB->pred_empty()) {
  251. // Insert an implicit_def to represent an undef value.
  252. MachineInstr *NewDef = InsertNewDef(TargetOpcode::IMPLICIT_DEF,
  253. BB, BB->getFirstTerminator(),
  254. VRC, MRI, TII);
  255. return InsertRes.first->second = NewDef->getOperand(0).getReg();
  256. }
  257. // Okay, the value isn't in the map and we just inserted a null in the entry
  258. // to indicate that we're processing the block. Since we have no idea what
  259. // value is in this block, we have to recurse through our predecessors.
  260. //
  261. // While we're walking our predecessors, we keep track of them in a vector,
  262. // then insert a PHI node in the end if we actually need one. We could use a
  263. // smallvector here, but that would take a lot of stack space for every level
  264. // of the recursion, just use IncomingPredInfo as an explicit stack.
  265. IncomingPredInfoTy &IncomingPredInfo = getIncomingPredInfo(IPI);
  266. unsigned FirstPredInfoEntry = IncomingPredInfo.size();
  267. // As we're walking the predecessors, keep track of whether they are all
  268. // producing the same value. If so, this value will capture it, if not, it
  269. // will get reset to null. We distinguish the no-predecessor case explicitly
  270. // below.
  271. unsigned SingularValue = 0;
  272. bool isFirstPred = true;
  273. for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
  274. E = BB->pred_end(); PI != E; ++PI) {
  275. MachineBasicBlock *PredBB = *PI;
  276. unsigned PredVal = GetValueAtEndOfBlockInternal(PredBB);
  277. IncomingPredInfo.push_back(std::make_pair(PredBB, PredVal));
  278. // Compute SingularValue.
  279. if (isFirstPred) {
  280. SingularValue = PredVal;
  281. isFirstPred = false;
  282. } else if (PredVal != SingularValue)
  283. SingularValue = 0;
  284. }
  285. /// Look up BB's entry in AvailableVals. 'InsertRes' may be invalidated. If
  286. /// this block is involved in a loop, a no-entry PHI node will have been
  287. /// inserted as InsertedVal. Otherwise, we'll still have the null we inserted
  288. /// above.
  289. unsigned &InsertedVal = AvailableVals[BB];
  290. // If all the predecessor values are the same then we don't need to insert a
  291. // PHI. This is the simple and common case.
  292. if (SingularValue) {
  293. // If a PHI node got inserted, replace it with the singlar value and delete
  294. // it.
  295. if (InsertedVal) {
  296. MachineInstr *OldVal = MRI->getVRegDef(InsertedVal);
  297. // Be careful about dead loops. These RAUW's also update InsertedVal.
  298. assert(InsertedVal != SingularValue && "Dead loop?");
  299. ReplaceRegWith(InsertedVal, SingularValue);
  300. OldVal->eraseFromParent();
  301. }
  302. InsertedVal = SingularValue;
  303. // Drop the entries we added in IncomingPredInfo to restore the stack.
  304. IncomingPredInfo.erase(IncomingPredInfo.begin()+FirstPredInfoEntry,
  305. IncomingPredInfo.end());
  306. return InsertedVal;
  307. }
  308. // Otherwise, we do need a PHI: insert one now if we don't already have one.
  309. MachineInstr *InsertedPHI;
  310. if (InsertedVal == 0) {
  311. MachineBasicBlock::iterator Loc = BB->empty() ? BB->end() : BB->front();
  312. InsertedPHI = InsertNewDef(TargetOpcode::PHI, BB, Loc,
  313. VRC, MRI, TII);
  314. InsertedVal = InsertedPHI->getOperand(0).getReg();
  315. } else {
  316. InsertedPHI = MRI->getVRegDef(InsertedVal);
  317. }
  318. // Fill in all the predecessors of the PHI.
  319. MachineInstrBuilder MIB(InsertedPHI);
  320. for (IncomingPredInfoTy::iterator I =
  321. IncomingPredInfo.begin()+FirstPredInfoEntry,
  322. E = IncomingPredInfo.end(); I != E; ++I)
  323. MIB.addReg(I->second).addMBB(I->first);
  324. // Drop the entries we added in IncomingPredInfo to restore the stack.
  325. IncomingPredInfo.erase(IncomingPredInfo.begin()+FirstPredInfoEntry,
  326. IncomingPredInfo.end());
  327. // See if the PHI node can be merged to a single value. This can happen in
  328. // loop cases when we get a PHI of itself and one other value.
  329. if (unsigned ConstVal = InsertedPHI->isConstantValuePHI()) {
  330. MRI->replaceRegWith(InsertedVal, ConstVal);
  331. InsertedPHI->eraseFromParent();
  332. InsertedVal = ConstVal;
  333. } else {
  334. DEBUG(dbgs() << " Inserted PHI: " << *InsertedPHI << "\n");
  335. // If the client wants to know about all new instructions, tell it.
  336. if (InsertedPHIs) InsertedPHIs->push_back(InsertedPHI);
  337. }
  338. return InsertedVal;
  339. }