/3rd_party/llvm/include/llvm/Transforms/Utils/SSAUpdaterImpl.h

https://code.google.com/p/softart/ · C++ Header · 456 lines · 293 code · 60 blank · 103 comment · 88 complexity · 6e9d47e6e4baae0a162572ca9b2c5cdb MD5 · raw file

  1. //===-- SSAUpdaterImpl.h - SSA Updater Implementation -----------*- C++ -*-===//
  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 provides a template that implements the core algorithm for the
  11. // SSAUpdater and MachineSSAUpdater.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #ifndef LLVM_TRANSFORMS_UTILS_SSAUPDATERIMPL_H
  15. #define LLVM_TRANSFORMS_UTILS_SSAUPDATERIMPL_H
  16. #include "llvm/ADT/DenseMap.h"
  17. #include "llvm/ADT/SmallVector.h"
  18. #include "llvm/Support/Allocator.h"
  19. #include "llvm/Support/Debug.h"
  20. #include "llvm/Support/ValueHandle.h"
  21. namespace llvm {
  22. class CastInst;
  23. class PHINode;
  24. template<typename T> class SSAUpdaterTraits;
  25. template<typename UpdaterT>
  26. class SSAUpdaterImpl {
  27. private:
  28. UpdaterT *Updater;
  29. typedef SSAUpdaterTraits<UpdaterT> Traits;
  30. typedef typename Traits::BlkT BlkT;
  31. typedef typename Traits::ValT ValT;
  32. typedef typename Traits::PhiT PhiT;
  33. /// BBInfo - Per-basic block information used internally by SSAUpdaterImpl.
  34. /// The predecessors of each block are cached here since pred_iterator is
  35. /// slow and we need to iterate over the blocks at least a few times.
  36. class BBInfo {
  37. public:
  38. BlkT *BB; // Back-pointer to the corresponding block.
  39. ValT AvailableVal; // Value to use in this block.
  40. BBInfo *DefBB; // Block that defines the available value.
  41. int BlkNum; // Postorder number.
  42. BBInfo *IDom; // Immediate dominator.
  43. unsigned NumPreds; // Number of predecessor blocks.
  44. BBInfo **Preds; // Array[NumPreds] of predecessor blocks.
  45. PhiT *PHITag; // Marker for existing PHIs that match.
  46. BBInfo(BlkT *ThisBB, ValT V)
  47. : BB(ThisBB), AvailableVal(V), DefBB(V ? this : 0), BlkNum(0), IDom(0),
  48. NumPreds(0), Preds(0), PHITag(0) { }
  49. };
  50. typedef DenseMap<BlkT*, ValT> AvailableValsTy;
  51. AvailableValsTy *AvailableVals;
  52. SmallVectorImpl<PhiT*> *InsertedPHIs;
  53. typedef SmallVectorImpl<BBInfo*> BlockListTy;
  54. typedef DenseMap<BlkT*, BBInfo*> BBMapTy;
  55. BBMapTy BBMap;
  56. BumpPtrAllocator Allocator;
  57. public:
  58. explicit SSAUpdaterImpl(UpdaterT *U, AvailableValsTy *A,
  59. SmallVectorImpl<PhiT*> *Ins) :
  60. Updater(U), AvailableVals(A), InsertedPHIs(Ins) { }
  61. /// GetValue - Check to see if AvailableVals has an entry for the specified
  62. /// BB and if so, return it. If not, construct SSA form by first
  63. /// calculating the required placement of PHIs and then inserting new PHIs
  64. /// where needed.
  65. ValT GetValue(BlkT *BB) {
  66. SmallVector<BBInfo*, 100> BlockList;
  67. BBInfo *PseudoEntry = BuildBlockList(BB, &BlockList);
  68. // Special case: bail out if BB is unreachable.
  69. if (BlockList.size() == 0) {
  70. ValT V = Traits::GetUndefVal(BB, Updater);
  71. (*AvailableVals)[BB] = V;
  72. return V;
  73. }
  74. FindDominators(&BlockList, PseudoEntry);
  75. FindPHIPlacement(&BlockList);
  76. FindAvailableVals(&BlockList);
  77. return BBMap[BB]->DefBB->AvailableVal;
  78. }
  79. /// BuildBlockList - Starting from the specified basic block, traverse back
  80. /// through its predecessors until reaching blocks with known values.
  81. /// Create BBInfo structures for the blocks and append them to the block
  82. /// list.
  83. BBInfo *BuildBlockList(BlkT *BB, BlockListTy *BlockList) {
  84. SmallVector<BBInfo*, 10> RootList;
  85. SmallVector<BBInfo*, 64> WorkList;
  86. BBInfo *Info = new (Allocator) BBInfo(BB, 0);
  87. BBMap[BB] = Info;
  88. WorkList.push_back(Info);
  89. // Search backward from BB, creating BBInfos along the way and stopping
  90. // when reaching blocks that define the value. Record those defining
  91. // blocks on the RootList.
  92. SmallVector<BlkT*, 10> Preds;
  93. while (!WorkList.empty()) {
  94. Info = WorkList.pop_back_val();
  95. Preds.clear();
  96. Traits::FindPredecessorBlocks(Info->BB, &Preds);
  97. Info->NumPreds = Preds.size();
  98. if (Info->NumPreds == 0)
  99. Info->Preds = 0;
  100. else
  101. Info->Preds = static_cast<BBInfo**>
  102. (Allocator.Allocate(Info->NumPreds * sizeof(BBInfo*),
  103. AlignOf<BBInfo*>::Alignment));
  104. for (unsigned p = 0; p != Info->NumPreds; ++p) {
  105. BlkT *Pred = Preds[p];
  106. // Check if BBMap already has a BBInfo for the predecessor block.
  107. typename BBMapTy::value_type &BBMapBucket =
  108. BBMap.FindAndConstruct(Pred);
  109. if (BBMapBucket.second) {
  110. Info->Preds[p] = BBMapBucket.second;
  111. continue;
  112. }
  113. // Create a new BBInfo for the predecessor.
  114. ValT PredVal = AvailableVals->lookup(Pred);
  115. BBInfo *PredInfo = new (Allocator) BBInfo(Pred, PredVal);
  116. BBMapBucket.second = PredInfo;
  117. Info->Preds[p] = PredInfo;
  118. if (PredInfo->AvailableVal) {
  119. RootList.push_back(PredInfo);
  120. continue;
  121. }
  122. WorkList.push_back(PredInfo);
  123. }
  124. }
  125. // Now that we know what blocks are backwards-reachable from the starting
  126. // block, do a forward depth-first traversal to assign postorder numbers
  127. // to those blocks.
  128. BBInfo *PseudoEntry = new (Allocator) BBInfo(0, 0);
  129. unsigned BlkNum = 1;
  130. // Initialize the worklist with the roots from the backward traversal.
  131. while (!RootList.empty()) {
  132. Info = RootList.pop_back_val();
  133. Info->IDom = PseudoEntry;
  134. Info->BlkNum = -1;
  135. WorkList.push_back(Info);
  136. }
  137. while (!WorkList.empty()) {
  138. Info = WorkList.back();
  139. if (Info->BlkNum == -2) {
  140. // All the successors have been handled; assign the postorder number.
  141. Info->BlkNum = BlkNum++;
  142. // If not a root, put it on the BlockList.
  143. if (!Info->AvailableVal)
  144. BlockList->push_back(Info);
  145. WorkList.pop_back();
  146. continue;
  147. }
  148. // Leave this entry on the worklist, but set its BlkNum to mark that its
  149. // successors have been put on the worklist. When it returns to the top
  150. // the list, after handling its successors, it will be assigned a
  151. // number.
  152. Info->BlkNum = -2;
  153. // Add unvisited successors to the work list.
  154. for (typename Traits::BlkSucc_iterator SI =
  155. Traits::BlkSucc_begin(Info->BB),
  156. E = Traits::BlkSucc_end(Info->BB); SI != E; ++SI) {
  157. BBInfo *SuccInfo = BBMap[*SI];
  158. if (!SuccInfo || SuccInfo->BlkNum)
  159. continue;
  160. SuccInfo->BlkNum = -1;
  161. WorkList.push_back(SuccInfo);
  162. }
  163. }
  164. PseudoEntry->BlkNum = BlkNum;
  165. return PseudoEntry;
  166. }
  167. /// IntersectDominators - This is the dataflow lattice "meet" operation for
  168. /// finding dominators. Given two basic blocks, it walks up the dominator
  169. /// tree until it finds a common dominator of both. It uses the postorder
  170. /// number of the blocks to determine how to do that.
  171. BBInfo *IntersectDominators(BBInfo *Blk1, BBInfo *Blk2) {
  172. while (Blk1 != Blk2) {
  173. while (Blk1->BlkNum < Blk2->BlkNum) {
  174. Blk1 = Blk1->IDom;
  175. if (!Blk1)
  176. return Blk2;
  177. }
  178. while (Blk2->BlkNum < Blk1->BlkNum) {
  179. Blk2 = Blk2->IDom;
  180. if (!Blk2)
  181. return Blk1;
  182. }
  183. }
  184. return Blk1;
  185. }
  186. /// FindDominators - Calculate the dominator tree for the subset of the CFG
  187. /// corresponding to the basic blocks on the BlockList. This uses the
  188. /// algorithm from: "A Simple, Fast Dominance Algorithm" by Cooper, Harvey
  189. /// and Kennedy, published in Software--Practice and Experience, 2001,
  190. /// 4:1-10. Because the CFG subset does not include any edges leading into
  191. /// blocks that define the value, the results are not the usual dominator
  192. /// tree. The CFG subset has a single pseudo-entry node with edges to a set
  193. /// of root nodes for blocks that define the value. The dominators for this
  194. /// subset CFG are not the standard dominators but they are adequate for
  195. /// placing PHIs within the subset CFG.
  196. void FindDominators(BlockListTy *BlockList, BBInfo *PseudoEntry) {
  197. bool Changed;
  198. do {
  199. Changed = false;
  200. // Iterate over the list in reverse order, i.e., forward on CFG edges.
  201. for (typename BlockListTy::reverse_iterator I = BlockList->rbegin(),
  202. E = BlockList->rend(); I != E; ++I) {
  203. BBInfo *Info = *I;
  204. BBInfo *NewIDom = 0;
  205. // Iterate through the block's predecessors.
  206. for (unsigned p = 0; p != Info->NumPreds; ++p) {
  207. BBInfo *Pred = Info->Preds[p];
  208. // Treat an unreachable predecessor as a definition with 'undef'.
  209. if (Pred->BlkNum == 0) {
  210. Pred->AvailableVal = Traits::GetUndefVal(Pred->BB, Updater);
  211. (*AvailableVals)[Pred->BB] = Pred->AvailableVal;
  212. Pred->DefBB = Pred;
  213. Pred->BlkNum = PseudoEntry->BlkNum;
  214. PseudoEntry->BlkNum++;
  215. }
  216. if (!NewIDom)
  217. NewIDom = Pred;
  218. else
  219. NewIDom = IntersectDominators(NewIDom, Pred);
  220. }
  221. // Check if the IDom value has changed.
  222. if (NewIDom && NewIDom != Info->IDom) {
  223. Info->IDom = NewIDom;
  224. Changed = true;
  225. }
  226. }
  227. } while (Changed);
  228. }
  229. /// IsDefInDomFrontier - Search up the dominator tree from Pred to IDom for
  230. /// any blocks containing definitions of the value. If one is found, then
  231. /// the successor of Pred is in the dominance frontier for the definition,
  232. /// and this function returns true.
  233. bool IsDefInDomFrontier(const BBInfo *Pred, const BBInfo *IDom) {
  234. for (; Pred != IDom; Pred = Pred->IDom) {
  235. if (Pred->DefBB == Pred)
  236. return true;
  237. }
  238. return false;
  239. }
  240. /// FindPHIPlacement - PHIs are needed in the iterated dominance frontiers
  241. /// of the known definitions. Iteratively add PHIs in the dom frontiers
  242. /// until nothing changes. Along the way, keep track of the nearest
  243. /// dominating definitions for non-PHI blocks.
  244. void FindPHIPlacement(BlockListTy *BlockList) {
  245. bool Changed;
  246. do {
  247. Changed = false;
  248. // Iterate over the list in reverse order, i.e., forward on CFG edges.
  249. for (typename BlockListTy::reverse_iterator I = BlockList->rbegin(),
  250. E = BlockList->rend(); I != E; ++I) {
  251. BBInfo *Info = *I;
  252. // If this block already needs a PHI, there is nothing to do here.
  253. if (Info->DefBB == Info)
  254. continue;
  255. // Default to use the same def as the immediate dominator.
  256. BBInfo *NewDefBB = Info->IDom->DefBB;
  257. for (unsigned p = 0; p != Info->NumPreds; ++p) {
  258. if (IsDefInDomFrontier(Info->Preds[p], Info->IDom)) {
  259. // Need a PHI here.
  260. NewDefBB = Info;
  261. break;
  262. }
  263. }
  264. // Check if anything changed.
  265. if (NewDefBB != Info->DefBB) {
  266. Info->DefBB = NewDefBB;
  267. Changed = true;
  268. }
  269. }
  270. } while (Changed);
  271. }
  272. /// FindAvailableVal - If this block requires a PHI, first check if an
  273. /// existing PHI matches the PHI placement and reaching definitions computed
  274. /// earlier, and if not, create a new PHI. Visit all the block's
  275. /// predecessors to calculate the available value for each one and fill in
  276. /// the incoming values for a new PHI.
  277. void FindAvailableVals(BlockListTy *BlockList) {
  278. // Go through the worklist in forward order (i.e., backward through the CFG)
  279. // and check if existing PHIs can be used. If not, create empty PHIs where
  280. // they are needed.
  281. for (typename BlockListTy::iterator I = BlockList->begin(),
  282. E = BlockList->end(); I != E; ++I) {
  283. BBInfo *Info = *I;
  284. // Check if there needs to be a PHI in BB.
  285. if (Info->DefBB != Info)
  286. continue;
  287. // Look for an existing PHI.
  288. FindExistingPHI(Info->BB, BlockList);
  289. if (Info->AvailableVal)
  290. continue;
  291. ValT PHI = Traits::CreateEmptyPHI(Info->BB, Info->NumPreds, Updater);
  292. Info->AvailableVal = PHI;
  293. (*AvailableVals)[Info->BB] = PHI;
  294. }
  295. // Now go back through the worklist in reverse order to fill in the
  296. // arguments for any new PHIs added in the forward traversal.
  297. for (typename BlockListTy::reverse_iterator I = BlockList->rbegin(),
  298. E = BlockList->rend(); I != E; ++I) {
  299. BBInfo *Info = *I;
  300. if (Info->DefBB != Info) {
  301. // Record the available value at join nodes to speed up subsequent
  302. // uses of this SSAUpdater for the same value.
  303. if (Info->NumPreds > 1)
  304. (*AvailableVals)[Info->BB] = Info->DefBB->AvailableVal;
  305. continue;
  306. }
  307. // Check if this block contains a newly added PHI.
  308. PhiT *PHI = Traits::ValueIsNewPHI(Info->AvailableVal, Updater);
  309. if (!PHI)
  310. continue;
  311. // Iterate through the block's predecessors.
  312. for (unsigned p = 0; p != Info->NumPreds; ++p) {
  313. BBInfo *PredInfo = Info->Preds[p];
  314. BlkT *Pred = PredInfo->BB;
  315. // Skip to the nearest preceding definition.
  316. if (PredInfo->DefBB != PredInfo)
  317. PredInfo = PredInfo->DefBB;
  318. Traits::AddPHIOperand(PHI, PredInfo->AvailableVal, Pred);
  319. }
  320. DEBUG(dbgs() << " Inserted PHI: " << *PHI << "\n");
  321. // If the client wants to know about all new instructions, tell it.
  322. if (InsertedPHIs) InsertedPHIs->push_back(PHI);
  323. }
  324. }
  325. /// FindExistingPHI - Look through the PHI nodes in a block to see if any of
  326. /// them match what is needed.
  327. void FindExistingPHI(BlkT *BB, BlockListTy *BlockList) {
  328. for (typename BlkT::iterator BBI = BB->begin(), BBE = BB->end();
  329. BBI != BBE; ++BBI) {
  330. PhiT *SomePHI = Traits::InstrIsPHI(BBI);
  331. if (!SomePHI)
  332. break;
  333. if (CheckIfPHIMatches(SomePHI)) {
  334. RecordMatchingPHIs(BlockList);
  335. break;
  336. }
  337. // Match failed: clear all the PHITag values.
  338. for (typename BlockListTy::iterator I = BlockList->begin(),
  339. E = BlockList->end(); I != E; ++I)
  340. (*I)->PHITag = 0;
  341. }
  342. }
  343. /// CheckIfPHIMatches - Check if a PHI node matches the placement and values
  344. /// in the BBMap.
  345. bool CheckIfPHIMatches(PhiT *PHI) {
  346. SmallVector<PhiT*, 20> WorkList;
  347. WorkList.push_back(PHI);
  348. // Mark that the block containing this PHI has been visited.
  349. BBMap[PHI->getParent()]->PHITag = PHI;
  350. while (!WorkList.empty()) {
  351. PHI = WorkList.pop_back_val();
  352. // Iterate through the PHI's incoming values.
  353. for (typename Traits::PHI_iterator I = Traits::PHI_begin(PHI),
  354. E = Traits::PHI_end(PHI); I != E; ++I) {
  355. ValT IncomingVal = I.getIncomingValue();
  356. BBInfo *PredInfo = BBMap[I.getIncomingBlock()];
  357. // Skip to the nearest preceding definition.
  358. if (PredInfo->DefBB != PredInfo)
  359. PredInfo = PredInfo->DefBB;
  360. // Check if it matches the expected value.
  361. if (PredInfo->AvailableVal) {
  362. if (IncomingVal == PredInfo->AvailableVal)
  363. continue;
  364. return false;
  365. }
  366. // Check if the value is a PHI in the correct block.
  367. PhiT *IncomingPHIVal = Traits::ValueIsPHI(IncomingVal, Updater);
  368. if (!IncomingPHIVal || IncomingPHIVal->getParent() != PredInfo->BB)
  369. return false;
  370. // If this block has already been visited, check if this PHI matches.
  371. if (PredInfo->PHITag) {
  372. if (IncomingPHIVal == PredInfo->PHITag)
  373. continue;
  374. return false;
  375. }
  376. PredInfo->PHITag = IncomingPHIVal;
  377. WorkList.push_back(IncomingPHIVal);
  378. }
  379. }
  380. return true;
  381. }
  382. /// RecordMatchingPHIs - For each PHI node that matches, record it in both
  383. /// the BBMap and the AvailableVals mapping.
  384. void RecordMatchingPHIs(BlockListTy *BlockList) {
  385. for (typename BlockListTy::iterator I = BlockList->begin(),
  386. E = BlockList->end(); I != E; ++I)
  387. if (PhiT *PHI = (*I)->PHITag) {
  388. BlkT *BB = PHI->getParent();
  389. ValT PHIVal = Traits::GetPHIValue(PHI);
  390. (*AvailableVals)[BB] = PHIVal;
  391. BBMap[BB]->AvailableVal = PHIVal;
  392. }
  393. }
  394. };
  395. } // End llvm namespace
  396. #endif