BasicBlock.cpp 15 KB

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