graph.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. /*****************************************************************************
  2. * dcc project CFG related functions
  3. * (C) Cristina Cifuentes
  4. ****************************************************************************/
  5. #include <string.h>
  6. #include <boost/range/rbegin.hpp>
  7. #include <boost/range/rend.hpp>
  8. #include <boost/range/adaptors.hpp>
  9. #include "dcc.h"
  10. #include "graph.h"
  11. #include "project.h"
  12. using namespace std;
  13. using namespace boost;
  14. extern Project g_proj;
  15. //static BB * rmJMP(Function * pProc, int marker, BB * pBB);
  16. //static void mergeFallThrough(Function * pProc, BB * pBB);
  17. //static void dfsNumbering(BB * pBB, std::vector<BB*> &dfsLast, int *first, int *last);
  18. /*****************************************************************************
  19. * createCFG - Create the basic control flow graph
  20. ****************************************************************************/
  21. void Function::createCFG()
  22. {
  23. /* Splits Icode associated with the procedure into Basic Blocks.
  24. * The links between BBs represent the control flow graph of the
  25. * procedure.
  26. * A Basic Block is defined to end on one of the following instructions:
  27. * 1) Conditional and unconditional jumps
  28. * 2) CALL(F)
  29. * 3) RET(F)
  30. * 4) On the instruction before a join (a flagged TARGET)
  31. * 5) Repeated string instructions
  32. * 6) End of procedure
  33. */
  34. int i;
  35. BB * psBB;
  36. BB * pBB;
  37. iICODE pIcode = Icode.begin();
  38. stats.numBBbef = stats.numBBaft = 0;
  39. rICODE current_range=make_iterator_range(pIcode,++iICODE(pIcode));
  40. for (; pIcode!=Icode.end(); ++pIcode,current_range.advance_end(1))
  41. {
  42. iICODE nextIcode = ++iICODE(pIcode);
  43. pBB = nullptr;
  44. LLInst *ll = pIcode->ll();
  45. /* Only process icodes that have valid instructions */
  46. if(ll->testFlags(NO_CODE))
  47. continue;
  48. /* Stick a NOWHERE_NODE on the end if we terminate
  49. * with anything other than a ret, jump or terminate */
  50. if (nextIcode == Icode.end() and
  51. (not ll->testFlags(TERMINATES)) and
  52. (not ll->match(iJMP)) and (not ll->match(iJMPF)) and
  53. (not ll->match(iRET)) and (not ll->match(iRETF)))
  54. {
  55. pBB=BB::Create(current_range, NOWHERE_NODE, this);
  56. }
  57. else
  58. switch (ll->getOpcode()) {
  59. case iJB: case iJBE: case iJAE: case iJA:
  60. case iJL: case iJLE: case iJGE: case iJG:
  61. case iJE: case iJNE: case iJS: case iJNS:
  62. case iJO: case iJNO: case iJP: case iJNP:
  63. case iJCXZ:
  64. pBB = BB::Create(current_range, TWO_BRANCH, this);
  65. CondJumps:
  66. pBB->addOutEdge(nextIcode->loc_ip);
  67. /* This is checking for jumps off into nowhere */
  68. if ( not ll->testFlags(NO_LABEL) )
  69. pBB->addOutEdge(ll->src().getImm2());
  70. break;
  71. case iLOOP: case iLOOPE: case iLOOPNE:
  72. pBB = BB::Create(current_range, LOOP_NODE, this);
  73. goto CondJumps;
  74. case iJMPF: case iJMP:
  75. if (ll->testFlags(SWITCH))
  76. {
  77. pBB = BB::Create(current_range, MULTI_BRANCH, this);
  78. for (size_t i = 0; i < ll->caseTbl2.size(); i++)
  79. pBB->addOutEdge(ll->caseTbl2[i]);
  80. hasCase = true;
  81. }
  82. else if ((ll->getFlag() & (I | NO_LABEL)) == I) //TODO: WHY NO_LABEL TESTIT
  83. {
  84. pBB = BB::Create(current_range, ONE_BRANCH, this);
  85. pBB->addOutEdge(ll->src().getImm2());
  86. }
  87. else
  88. pBB = BB::Create(current_range, NOWHERE_NODE, this);
  89. break;
  90. case iCALLF: case iCALL:
  91. {
  92. Function * p = ll->src().proc.proc;
  93. pBB = BB::Create(current_range, CALL_NODE, this);
  94. if (p && not ((p->flg) & TERMINATES) )
  95. pBB->addOutEdge(nextIcode->loc_ip);
  96. break;
  97. }
  98. case iRET: case iRETF:
  99. pBB = BB::Create(current_range, RETURN_NODE, this);
  100. break;
  101. default:
  102. /* Check for exit to DOS */
  103. if ( ll->testFlags(TERMINATES) )
  104. {
  105. pBB = BB::Create(current_range, TERMINATE_NODE, this);
  106. }
  107. /* Check for a fall through */
  108. else if (nextIcode != Icode.end())
  109. {
  110. if (nextIcode->ll()->testFlags(TARGET | CASE))
  111. {
  112. pBB = BB::Create(current_range, FALL_NODE, this);
  113. pBB->addOutEdge(nextIcode->loc_ip);
  114. }
  115. }
  116. break;
  117. }
  118. if(pBB!=nullptr) // created a new Basic block
  119. {
  120. // restart the range
  121. // end iterator will be updated by expression in for statement
  122. current_range=make_iterator_range(nextIcode,nextIcode);
  123. }
  124. }
  125. auto iter=heldBBs.begin();
  126. /* Convert list of BBs into a graph */
  127. for (; iter!=heldBBs.end(); ++iter)
  128. {
  129. pBB = *iter;
  130. for (size_t edeg_idx = 0; edeg_idx < pBB->edges.size(); edeg_idx++)
  131. {
  132. int32_t ip = pBB->edges[edeg_idx].ip;
  133. if (ip >= SYNTHESIZED_MIN)
  134. {
  135. fatalError (INVALID_SYNTHETIC_BB);
  136. return;
  137. }
  138. auto iter2=std::find_if(heldBBs.begin(),heldBBs.end(),
  139. [ip](BB *psBB)->bool {return psBB->begin()->loc_ip==ip;});
  140. if(iter2==heldBBs.end())
  141. fatalError(NO_BB, ip, name.c_str());
  142. psBB = *iter2;
  143. pBB->edges[edeg_idx].BBptr = psBB;
  144. psBB->inEdges.push_back((BB *)nullptr);
  145. }
  146. }
  147. }
  148. void Function::markImpure()
  149. {
  150. PROG &prog(Project::get()->prog);
  151. for(ICODE &icod : Icode)
  152. {
  153. if ( not icod.ll()->testFlags(SYM_USE | SYM_DEF))
  154. continue;
  155. //assert that case tbl has less entries then symbol table ????
  156. //WARNING: Case entries are held in symbol table !
  157. assert(Project::get()->validSymIdx(icod.ll()->caseEntry));
  158. const SYM &psym(Project::get()->getSymByIdx(icod.ll()->caseEntry));
  159. for (int c = (int)psym.label; c < (int)psym.label+psym.size; c++)
  160. {
  161. if (BITMAP(c, BM_CODE))
  162. {
  163. icod.ll()->setFlags(IMPURE);
  164. flg |= IMPURE;
  165. break;
  166. }
  167. }
  168. }
  169. }
  170. /*****************************************************************************
  171. * newBB - Allocate new BB and link to end of list
  172. *****************************************************************************/
  173. /*****************************************************************************
  174. * freeCFG - Deallocates a cfg
  175. ****************************************************************************/
  176. void Function::freeCFG()
  177. {
  178. for(BB *p : heldBBs)
  179. {
  180. delete p;
  181. }
  182. }
  183. /*****************************************************************************
  184. * compressCFG - Remove redundancies and add in-edge information
  185. ****************************************************************************/
  186. void Function::compressCFG()
  187. {
  188. BB *pNxt;
  189. int ip, first=0, last;
  190. /* First pass over BB list removes redundant jumps of the form
  191. * (Un)Conditional -> Unconditional jump */
  192. for (BB *pBB : m_cfg)
  193. {
  194. if(pBB->inEdges.empty() || (pBB->nodeType != ONE_BRANCH && pBB->nodeType != TWO_BRANCH))
  195. continue;
  196. for (TYPEADR_TYPE &edgeRef : pBB->edges)
  197. {
  198. ip = pBB->rbegin()->loc_ip;
  199. pNxt = edgeRef.BBptr->rmJMP(ip, edgeRef.BBptr);
  200. if (not pBB->edges.empty()) /* Might have been clobbered */
  201. {
  202. edgeRef.BBptr = pNxt;
  203. assert(pBB->back().loc_ip==ip);
  204. pBB->back().ll()->SetImmediateOp((uint32_t)pNxt->begin()->loc_ip);
  205. //Icode[ip].SetImmediateOp((uint32_t)pNxt->begin());
  206. }
  207. }
  208. }
  209. /* Next is a depth-first traversal merging any FALL_NODE or
  210. * ONE_BRANCH that fall through to a node with that as their only
  211. * in-edge. */
  212. m_cfg.front()->mergeFallThrough(Icode);
  213. /* Remove redundant BBs created by the above compressions
  214. * and allocate in-edge arrays as required. */
  215. stats.numBBaft = stats.numBBbef;
  216. for(auto iter=m_cfg.begin(); iter!=m_cfg.end(); ++iter)
  217. {
  218. BB * pBB = *iter;
  219. if (pBB->inEdges.empty())
  220. {
  221. if (iter == m_cfg.begin()) /* Init it misses out on */
  222. pBB->index = UN_INIT;
  223. else
  224. {
  225. delete pBB;
  226. stats.numBBaft--;
  227. }
  228. }
  229. else
  230. {
  231. pBB->inEdgeCount = pBB->inEdges.size();
  232. }
  233. }
  234. /* Allocate storage for dfsLast[] array */
  235. numBBs = stats.numBBaft;
  236. m_dfsLast.resize(numBBs,0); // = (BB **)allocMem(numBBs * sizeof(BB *))
  237. /* Now do a dfs numbering traversal and fill in the inEdges[] array */
  238. last = numBBs - 1;
  239. m_cfg.front()->dfsNumbering(m_dfsLast, &first, &last);
  240. }
  241. /****************************************************************************
  242. * rmJMP - If BB addressed is just a JMP it is replaced with its target
  243. ***************************************************************************/
  244. BB *BB::rmJMP(int marker, BB * pBB)
  245. {
  246. marker += (int)DFS_JMP;
  247. while (pBB->nodeType == ONE_BRANCH && pBB->size() == 1)
  248. {
  249. if (pBB->traversed != marker)
  250. {
  251. pBB->traversed = (eDFS)marker;
  252. pBB->inEdges.pop_back();
  253. if (not pBB->inEdges.empty())
  254. {
  255. pBB->edges[0].BBptr->inEdges.push_back((BB *)nullptr);
  256. }
  257. else
  258. {
  259. pBB->front().ll()->setFlags(NO_CODE);
  260. pBB->front().invalidate(); //pProc->Icode.SetLlInvalid(pBB->begin(), true);
  261. }
  262. pBB = pBB->edges[0].BBptr;
  263. }
  264. else
  265. {
  266. /* We are going around in circles */
  267. pBB->nodeType = NOWHERE_NODE;
  268. pBB->front().ll()->replaceSrc(LLOperand::CreateImm2(pBB->front().loc_ip));
  269. //pBB->front().ll()->src.immed.op = pBB->front().loc_ip;
  270. do {
  271. pBB = pBB->edges[0].BBptr;
  272. pBB->inEdges.pop_back(); // was --numInedges
  273. if (! pBB->inEdges.empty())
  274. {
  275. pBB->front().ll()->setFlags(NO_CODE);
  276. pBB->front().invalidate();
  277. // pProc->Icode.setFlags(pBB->start, NO_CODE);
  278. // pProc->Icode.SetLlInvalid(pBB->start, true);
  279. }
  280. } while (pBB->nodeType != NOWHERE_NODE);
  281. pBB->edges.clear();
  282. }
  283. }
  284. return pBB;
  285. }
  286. /*****************************************************************************
  287. * mergeFallThrough
  288. ****************************************************************************/
  289. void BB::mergeFallThrough( CIcodeRec &Icode)
  290. {
  291. BB * pChild;
  292. if (!this)
  293. {
  294. printf("mergeFallThrough on empty BB!\n");
  295. }
  296. while (nodeType == FALL_NODE || nodeType == ONE_BRANCH)
  297. {
  298. pChild = edges[0].BBptr;
  299. /* Jump to next instruction can always be removed */
  300. if (nodeType == ONE_BRANCH)
  301. {
  302. assert(Parent==pChild->Parent);
  303. if(back().loc_ip>pChild->front().loc_ip) // back edege
  304. break;
  305. auto iter=std::find_if(this->end(),pChild->begin(),[](ICODE &c)
  306. {return not c.ll()->testFlags(NO_CODE);});
  307. if (iter != pChild->begin())
  308. break;
  309. back().ll()->setFlags(NO_CODE);
  310. back().invalidate();
  311. nodeType = FALL_NODE;
  312. //instructions.advance_end(-1); //TODO: causes creation of empty BB
  313. }
  314. /* If there's no other edges into child can merge */
  315. if (pChild->inEdges.size() != 1)
  316. break;
  317. nodeType = pChild->nodeType;
  318. instructions = boost::make_iterator_range(begin(),pChild->end());
  319. pChild->front().ll()->clrFlags(TARGET);
  320. edges.swap(pChild->edges);
  321. pChild->inEdges.clear();
  322. pChild->edges.clear();
  323. }
  324. traversed = DFS_MERGE;
  325. /* Process all out edges recursively */
  326. for (size_t i = 0; i < edges.size(); i++)
  327. {
  328. if (edges[i].BBptr->traversed != DFS_MERGE)
  329. edges[i].BBptr->mergeFallThrough(Icode);
  330. }
  331. }
  332. /*****************************************************************************
  333. * dfsNumbering - Numbers nodes during first and last visits and determine
  334. * in-edges
  335. ****************************************************************************/
  336. void BB::dfsNumbering(std::vector<BB *> &dfsLast, int *first, int *last)
  337. {
  338. BB * pChild;
  339. traversed = DFS_NUM;
  340. dfsFirstNum = (*first)++;
  341. /* index is being used as an index to inEdges[]. */
  342. // for (i = 0; i < edges.size(); i++)
  343. for(auto edge : edges)
  344. {
  345. pChild = edge.BBptr;
  346. pChild->inEdges[pChild->index++] = this;
  347. /* Is this the last visit? */
  348. if (pChild->index == int(pChild->inEdges.size()))
  349. pChild->index = UN_INIT;
  350. if (pChild->traversed != DFS_NUM)
  351. pChild->dfsNumbering(dfsLast, first, last);
  352. }
  353. dfsLastNum = *last;
  354. dfsLast[(*last)--] = this;
  355. }