BasicBlock.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. #include <cassert>
  2. #include <string>
  3. #include <boost/range/rbegin.hpp>
  4. #include <boost/range/rend.hpp>
  5. #include <boost/range/adaptors.hpp>
  6. #include "BasicBlock.h"
  7. #include "Procedure.h"
  8. #include "dcc.h"
  9. using namespace std;
  10. using namespace boost;
  11. BB *BB::Create(void */*ctx*/, const string &/*s*/, Function *parent, BB */*insertBefore*/)
  12. {
  13. BB *pnewBB = new BB;
  14. pnewBB->Parent = parent;
  15. return pnewBB;
  16. }
  17. /**
  18. * @arg start - basic block starts here, might be parent->Icode.end()
  19. * @arg fin - last of basic block's instructions
  20. */
  21. BB *BB::Create(const rCODE &r,eBBKind _nodeType, Function *parent)
  22. {
  23. BB* pnewBB;
  24. pnewBB = new BB;
  25. pnewBB->nodeType = _nodeType; /* Initialise */
  26. pnewBB->immedDom = NO_DOM;
  27. pnewBB->loopHead = pnewBB->caseHead = pnewBB->caseTail =
  28. pnewBB->latchNode= pnewBB->loopFollow = NO_NODE;
  29. pnewBB->instructions = r;
  30. /* Mark the basic block to which the icodes belong to, but only for
  31. * real code basic blocks (ie. not interval bbs) */
  32. if(parent)
  33. {
  34. int addr = pnewBB->begin()->loc_ip;
  35. //setInBB should automatically handle if our range is empty
  36. parent->Icode.SetInBB(pnewBB->instructions, pnewBB);
  37. assert(parent->m_ip_to_bb.find(addr)==parent->m_ip_to_bb.end());
  38. parent->m_ip_to_bb[addr] = pnewBB;
  39. parent->m_actual_cfg.push_back(pnewBB);
  40. pnewBB->Parent = parent;
  41. if ( r.begin() != parent->Icode.end() ) /* Only for code BB's */
  42. stats.numBBbef++;
  43. }
  44. return pnewBB;
  45. }
  46. BB *BB::CreateIntervalBB(Function *parent)
  47. {
  48. iICODE endOfParent = parent->Icode.end();
  49. return Create(make_iterator_range(endOfParent,endOfParent),INTERVAL_NODE,nullptr);
  50. }
  51. static const char *const s_nodeType[] = {"branch", "if", "case", "fall", "return", "call",
  52. "loop", "repeat", "interval", "cycleHead",
  53. "caseHead", "terminate",
  54. "nowhere" };
  55. static const char *const s_loopType[] = {"noLoop", "while", "repeat", "loop", "for"};
  56. void BB::display()
  57. {
  58. printf("\nnode type = %s, ", s_nodeType[nodeType]);
  59. printf("start = %d, length = %zd, #out edges = %zd\n", begin()->loc_ip, size(), edges.size());
  60. for (size_t i = 0; i < edges.size(); i++)
  61. {
  62. if(edges[i].BBptr==nullptr)
  63. printf(" outEdge[%2zd] = Unlinked out edge to %d\n",i, edges[i].ip);
  64. else
  65. printf(" outEdge[%2zd] = %d\n",i, edges[i].BBptr->begin()->loc_ip);
  66. }
  67. }
  68. /*****************************************************************************
  69. * displayDfs - Displays the CFG using a depth first traversal
  70. ****************************************************************************/
  71. void BB::displayDfs()
  72. {
  73. int i;
  74. assert(this);
  75. traversed = DFS_DISP;
  76. printf("node type = %s, ", s_nodeType[nodeType]);
  77. printf("start = %d, length = %zd, #in-edges = %zd, #out-edges = %zd\n",
  78. begin()->loc_ip, size(), inEdges.size(), edges.size());
  79. printf("dfsFirst = %d, dfsLast = %d, immed dom = %d\n",
  80. dfsFirstNum, dfsLastNum,
  81. immedDom == MAX ? -1 : immedDom);
  82. printf("loopType = %s, loopHead = %d, latchNode = %d, follow = %d\n",
  83. s_loopType[(int)loopType],
  84. loopHead == MAX ? -1 : loopHead,
  85. latchNode == MAX ? -1 : latchNode,
  86. loopFollow == MAX ? -1 : loopFollow);
  87. printf ("ifFollow = %d, caseHead = %d, caseTail = %d\n",
  88. ifFollow == MAX ? -1 : ifFollow,
  89. caseHead == MAX ? -1 : caseHead,
  90. caseTail == MAX ? -1 : caseTail);
  91. if (nodeType == INTERVAL_NODE)
  92. printf("corresponding interval = %d\n", correspInt->numInt);
  93. else
  94. {
  95. int edge_idx=0;
  96. for(BB *node : inEdges)
  97. {
  98. printf (" inEdge[%d] = %d\n", edge_idx, node->begin()->loc_ip);
  99. edge_idx++;
  100. }
  101. }
  102. /* Display out edges information */
  103. i=0;
  104. for(TYPEADR_TYPE &edg : edges)
  105. {
  106. if (nodeType == INTERVAL_NODE)
  107. printf(" outEdge[%d] = %d\n", i, edg.BBptr->correspInt->numInt);
  108. else
  109. printf(" outEdge[%d] = %d\n", i, edg.BBptr->begin()->loc_ip);
  110. ++i;
  111. }
  112. printf("----\n");
  113. /* Recursive call on successors of current node */
  114. for(TYPEADR_TYPE &pb : edges)
  115. {
  116. if (pb.BBptr->traversed != DFS_DISP)
  117. pb.BBptr->displayDfs();
  118. }
  119. }
  120. /** Recursive procedure that writes the code for the given procedure, pointed
  121. to by pBB.
  122. \param indLevel indentation level - used for formatting.
  123. \param numLoc: last # assigned to local variables
  124. */
  125. ICODE* BB::writeLoopHeader(int &indLevel, Function* pProc, int *numLoc, BB *&latch, bool &repCond)
  126. {
  127. if(loopType == eNodeHeaderType::NO_TYPE)
  128. return nullptr;
  129. latch = pProc->m_dfsLast[this->latchNode];
  130. std::ostringstream ostr;
  131. ICODE* picode;
  132. switch (loopType)
  133. {
  134. case eNodeHeaderType::WHILE_TYPE:
  135. picode = &this->back();
  136. /* Check for error in while condition */
  137. if (picode->hl()->opcode != HLI_JCOND)
  138. reportError (WHILE_FAIL);
  139. /* Check if condition is more than 1 HL instruction */
  140. if (numHlIcodes > 1)
  141. {
  142. /* Write the code for this basic block */
  143. writeBB(ostr,indLevel, pProc, numLoc);
  144. repCond = true;
  145. }
  146. /* Condition needs to be inverted if the loop body is along
  147. * the THEN path of the header node */
  148. if (edges[ELSE].BBptr->dfsLastNum == loopFollow)
  149. {
  150. picode->hlU()->replaceExpr(picode->hl()->expr()->inverse());
  151. }
  152. {
  153. string e=picode->hl()->expr()->walkCondExpr (pProc, numLoc);
  154. ostr << "\n"<<indentStr(indLevel)<<"while ("<<e<<") {\n";
  155. }
  156. picode->invalidate();
  157. break;
  158. case eNodeHeaderType::REPEAT_TYPE:
  159. ostr << "\n"<<indentStr(indLevel)<<"do {\n";
  160. picode = &latch->back();
  161. picode->invalidate();
  162. break;
  163. case eNodeHeaderType::ENDLESS_TYPE:
  164. ostr << "\n"<<indentStr(indLevel)<<"for (;;) {\n";
  165. picode = &latch->back();
  166. break;
  167. }
  168. cCode.appendCode(ostr.str());
  169. stats.numHLIcode += 1;
  170. indLevel++;
  171. return picode;
  172. }
  173. bool BB::isEndOfPath(int latch_node_idx) const
  174. {
  175. return nodeType == RETURN_NODE || nodeType == TERMINATE_NODE ||
  176. nodeType == NOWHERE_NODE || (dfsLastNum == latch_node_idx);
  177. }
  178. void BB::writeCode (int indLevel, Function * pProc , int *numLoc,int _latchNode, int _ifFollow)
  179. {
  180. int follow; /* ifFollow */
  181. BB * succ, *latch; /* Successor and latching node */
  182. ICODE * picode; /* Pointer to HLI_JCOND instruction */
  183. std::string l; /* Pointer to HLI_JCOND expression */
  184. bool emptyThen, /* THEN clause is empty */
  185. repCond; /* Repeat condition for while() */
  186. /* Check if this basic block should be analysed */
  187. if ((_ifFollow != UN_INIT) && (this == pProc->m_dfsLast[_ifFollow]))
  188. return;
  189. if (wasTraversedAtLevel(DFS_ALPHA))
  190. return;
  191. traversed = DFS_ALPHA;
  192. /* Check for start of loop */
  193. repCond = false;
  194. latch = nullptr;
  195. picode=writeLoopHeader(indLevel, pProc, numLoc, latch, repCond);
  196. /* Write the code for this basic block */
  197. if (repCond == false)
  198. {
  199. std::ostringstream ostr;
  200. writeBB(ostr,indLevel, pProc, numLoc);
  201. cCode.appendCode(ostr.str());
  202. }
  203. /* Check for end of path */
  204. if (isEndOfPath(_latchNode))
  205. return;
  206. /* Check type of loop/node and process code */
  207. if ( loopType!=eNodeHeaderType::NO_TYPE ) /* there is a loop */
  208. {
  209. assert(latch);
  210. if (this != latch) /* loop is over several bbs */
  211. {
  212. if (loopType == eNodeHeaderType::WHILE_TYPE)
  213. {
  214. succ = edges[THEN].BBptr;
  215. if (succ->dfsLastNum == loopFollow)
  216. succ = edges[ELSE].BBptr;
  217. }
  218. else
  219. succ = edges[0].BBptr;
  220. if (succ->traversed != DFS_ALPHA)
  221. succ->writeCode (indLevel, pProc, numLoc, latch->dfsLastNum,_ifFollow);
  222. else /* has been traversed so we need a goto */
  223. succ->front().ll()->emitGotoLabel (indLevel);
  224. }
  225. /* Loop epilogue: generate the loop trailer */
  226. indLevel--;
  227. if (loopType == eNodeHeaderType::WHILE_TYPE)
  228. {
  229. std::ostringstream ostr;
  230. /* Check if there is need to repeat other statements involved
  231. * in while condition, then, emit the loop trailer */
  232. if (repCond)
  233. {
  234. writeBB(ostr,indLevel+1, pProc, numLoc);
  235. }
  236. ostr <<indentStr(indLevel)<< "} /* end of while */\n";
  237. cCode.appendCode(ostr.str());
  238. }
  239. else if (loopType == eNodeHeaderType::ENDLESS_TYPE)
  240. cCode.appendCode( "%s} /* end of loop */\n",indentStr(indLevel));
  241. else if (loopType == eNodeHeaderType::REPEAT_TYPE)
  242. {
  243. string e = "//*failed*//";
  244. if (picode->hl()->opcode != HLI_JCOND)
  245. {
  246. reportError (REPEAT_FAIL);
  247. }
  248. else
  249. {
  250. e=picode->hl()->expr()->walkCondExpr (pProc, numLoc);
  251. }
  252. cCode.appendCode( "%s} while (%s);\n", indentStr(indLevel),e.c_str());
  253. }
  254. /* Recurse on the loop follow */
  255. if (loopFollow != MAX)
  256. {
  257. succ = pProc->m_dfsLast[loopFollow];
  258. if (succ->traversed != DFS_ALPHA)
  259. succ->writeCode (indLevel, pProc, numLoc, _latchNode, _ifFollow);
  260. else /* has been traversed so we need a goto */
  261. succ->front().ll()->emitGotoLabel (indLevel);
  262. }
  263. }
  264. else /* no loop, process nodeType of the graph */
  265. {
  266. if (nodeType == TWO_BRANCH) /* if-then[-else] */
  267. {
  268. stats.numHLIcode++;
  269. indLevel++;
  270. emptyThen = false;
  271. if (ifFollow != MAX) /* there is a follow */
  272. {
  273. /* process the THEN part */
  274. follow = ifFollow;
  275. succ = edges[THEN].BBptr;
  276. if (succ->traversed != DFS_ALPHA) /* not visited */
  277. {
  278. if (succ->dfsLastNum != follow) /* THEN part */
  279. {
  280. l = writeJcond ( *back().hl(), pProc, numLoc);
  281. cCode.appendCode( "\n%s%s", indentStr(indLevel-1), l.c_str());
  282. succ->writeCode (indLevel, pProc, numLoc, _latchNode,follow);
  283. }
  284. else /* empty THEN part => negate ELSE part */
  285. {
  286. l = writeJcondInv ( *back().hl(), pProc, numLoc);
  287. cCode.appendCode( "\n%s%s", indentStr(indLevel-1), l.c_str());
  288. edges[ELSE].BBptr->writeCode (indLevel, pProc, numLoc, _latchNode, follow);
  289. emptyThen = true;
  290. }
  291. }
  292. else /* already visited => emit label */
  293. succ->front().ll()->emitGotoLabel(indLevel);
  294. /* process the ELSE part */
  295. succ = edges[ELSE].BBptr;
  296. if (succ->traversed != DFS_ALPHA) /* not visited */
  297. {
  298. if (succ->dfsLastNum != follow) /* ELSE part */
  299. {
  300. cCode.appendCode( "%s}\n%selse {\n",
  301. indentStr(indLevel-1), indentStr(indLevel - 1));
  302. succ->writeCode (indLevel, pProc, numLoc, _latchNode, follow);
  303. }
  304. /* else (empty ELSE part) */
  305. }
  306. else if (! emptyThen) /* already visited => emit label */
  307. {
  308. cCode.appendCode( "%s}\n%selse {\n",
  309. indentStr(indLevel-1), indentStr(indLevel - 1));
  310. succ->front().ll()->emitGotoLabel (indLevel);
  311. }
  312. cCode.appendCode( "%s}\n", indentStr(--indLevel));
  313. /* Continue with the follow */
  314. succ = pProc->m_dfsLast[follow];
  315. if (succ->traversed != DFS_ALPHA)
  316. succ->writeCode (indLevel, pProc, numLoc, _latchNode,_ifFollow);
  317. }
  318. else /* no follow => if..then..else */
  319. {
  320. l = writeJcond ( *back().hl(), pProc, numLoc);
  321. cCode.appendCode( "%s%s", indentStr(indLevel-1), l.c_str());
  322. edges[THEN].BBptr->writeCode (indLevel, pProc, numLoc, _latchNode, _ifFollow);
  323. cCode.appendCode( "%s}\n%selse {\n", indentStr(indLevel-1), indentStr(indLevel - 1));
  324. edges[ELSE].BBptr->writeCode (indLevel, pProc, numLoc, _latchNode, _ifFollow);
  325. cCode.appendCode( "%s}\n", indentStr(--indLevel));
  326. }
  327. }
  328. else /* fall, call, 1w */
  329. {
  330. succ = edges[0].BBptr; /* fall-through edge */
  331. assert(succ->size()>0);
  332. if (succ->traversed != DFS_ALPHA)
  333. {
  334. succ->writeCode (indLevel, pProc,numLoc, _latchNode,_ifFollow);
  335. }
  336. }
  337. }
  338. }
  339. /* Writes the code for the current basic block.
  340. * Args: pBB: pointer to the current basic block.
  341. * Icode: pointer to the array of icodes for current procedure.
  342. * lev: indentation level - used for formatting. */
  343. void BB::writeBB(std::ostream &ostr,int lev, Function * pProc, int *numLoc)
  344. {
  345. /* Save the index into the code table in case there is a later goto
  346. * into this instruction (first instruction of the BB) */
  347. front().ll()->codeIdx = cCode.code.nextIdx();
  348. /* Generate code for each hlicode that is not a HLI_JCOND */
  349. for(ICODE &pHli : instructions)
  350. {
  351. if ((pHli.type == HIGH_LEVEL) && ( pHli.valid() )) //TODO: use filtering range here.
  352. {
  353. std::string line = pHli.hl()->write1HlIcode(pProc, numLoc);
  354. if (!line.empty())
  355. {
  356. ostr<<indentStr(lev)<<line;
  357. stats.numHLIcode++;
  358. }
  359. if (option.verbose)
  360. pHli.writeDU();
  361. }
  362. }
  363. }
  364. iICODE BB::begin()
  365. {
  366. return instructions.begin();
  367. }
  368. iICODE BB::end() const
  369. {
  370. return instructions.end();
  371. }
  372. ICODE &BB::back()
  373. {
  374. return instructions.back();
  375. }
  376. size_t BB::size()
  377. {
  378. return distance(instructions.begin(),instructions.end());
  379. }
  380. ICODE &BB::front()
  381. {
  382. return instructions.front();
  383. }
  384. riICODE BB::rbegin()
  385. {
  386. return riICODE( instructions.end() );
  387. }
  388. riICODE BB::rend()
  389. {
  390. return riICODE( instructions.begin() );
  391. }