graph.cpp 14 KB

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