backend.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. /*****************************************************************************
  2. * Project: dcc
  3. * File: backend.c
  4. * Purpose: Back-end module. Generates C code for each procedure.
  5. * (C) Cristina Cifuentes
  6. ****************************************************************************/
  7. #include <cassert>
  8. #include <string>
  9. #include "dcc.h"
  10. #include "disassem.h"
  11. #include <fstream>
  12. #include <iostream>
  13. #include <sstream>
  14. #include <string.h>
  15. #include <stdio.h>
  16. bundle cCode; /* Procedure declaration and code */
  17. using namespace std;
  18. /* Returns a unique index to the next label */
  19. int getNextLabel()
  20. {
  21. static int labelIdx = 1; /* index of the next label */
  22. return (labelIdx++);
  23. }
  24. /* displays statistics on the subroutine */
  25. void Function::displayStats ()
  26. {
  27. printf("\nStatistics - Subroutine %s\n", name.c_str());
  28. printf ("Number of Icode instructions:\n");
  29. printf (" Low-level : %4d\n", stats.numLLIcode);
  30. if (! (flg & PROC_ASM))
  31. {
  32. printf (" High-level: %4d\n", stats.numHLIcode);
  33. printf (" Percentage reduction: %2.2f%%\n", 100.0 - (stats.numHLIcode *
  34. 100.0) / stats.numLLIcode);
  35. }
  36. }
  37. /**** this proc is not required any more?? ****/
  38. #if 0
  39. static void fixupLabels (PPROC pProc)
  40. /* Checks the graph (pProc->cfg) for any nodes that have labels, and gives
  41. * a unique label number for it. This label is placed in the associated
  42. * icode for the node (pProc->Icode). The procedure is done in sequential
  43. * order of dsfLast numbering. */
  44. { int i; /* index into the dfsLast array */
  45. PBB *dfsLast; /* pointer to the dfsLast array */
  46. dfsLast = pProc->dfsLast;
  47. for (i = 0; i < pProc->numBBs; i++)
  48. if (dfsLast[i]->flg/* & BB_HAS_LABEL*/) {
  49. pProc->Icode.icode[dfsLast[i]->start].ll()->flg |= HLL_LABEL;
  50. pProc->Icode.icode[dfsLast[i]->start].ll()->hllLabNum = getNextLabel();
  51. }
  52. }
  53. #endif
  54. /* Returns the corresponding C string for the given character c. Character
  55. * constants such as carriage return and line feed, require 2 C characters. */
  56. char *cChar (uint8_t c)
  57. {
  58. static char res[3];
  59. switch (c) {
  60. case 0x8: /* backspace */
  61. sprintf (res, "\\b");
  62. break;
  63. case 0x9: /* horizontal tab */
  64. sprintf (res, "\\t");
  65. break;
  66. case 0x0A: /* new line */
  67. sprintf (res, "\\n");
  68. break;
  69. case 0x0C: /* form feed */
  70. sprintf (res, "\\f");
  71. break;
  72. case 0x0D: /* carriage return */
  73. sprintf (res, "\\r");
  74. break;
  75. default: /* any other character*/
  76. sprintf (res, "%c", c);
  77. }
  78. return (res);
  79. }
  80. /* Prints the variable's name and initial contents on the file.
  81. * Note: to get to the value of the variable:
  82. * com file: prog.Image[operand]
  83. * exe file: prog.Image[operand+0x100] */
  84. static void printGlobVar (std::ostream &ostr,SYM * psym);
  85. static void printGlobVar (SYM * psym)
  86. {
  87. std::ostringstream ostr;
  88. printGlobVar(ostr,psym);
  89. cCode.appendDecl(ostr.str());
  90. }
  91. static void printGlobVar (std::ostream &ostr,SYM * psym)
  92. {
  93. int j;
  94. uint32_t relocOp = prog.fCOM ? psym->label : psym->label + 0x100;
  95. switch (psym->size)
  96. {
  97. case 1:
  98. ostr << "uint8_t\t"<<psym->name<<" = "<<prog.Image[relocOp]<<";\n";
  99. break;
  100. case 2:
  101. ostr << "uint16_t\t"<<psym->name<<" = "<<LH(prog.Image+relocOp)<<";\n";
  102. break;
  103. case 4: if (psym->type == TYPE_PTR) /* pointer */
  104. ostr << "uint16_t *\t"<<psym->name<<" = "<<LH(prog.Image+relocOp)<<";\n";
  105. else /* char */
  106. ostr << "char\t"<<psym->name<<"[4] = \""<<
  107. prog.Image[relocOp]<<prog.Image[relocOp+1]<<
  108. prog.Image[relocOp+2]<<prog.Image[relocOp+3]<<";\n";
  109. break;
  110. default:
  111. {
  112. ostringstream strContents;
  113. for (j=0; j < psym->size; j++)
  114. strContents << cChar(prog.Image[relocOp + j]);
  115. ostr << "char\t*"<<psym->name<<" = \""<<strContents.str()<<"\";\n";
  116. }
  117. }
  118. }
  119. // Note: Not called at present.
  120. /* Writes the contents of the symbol table, along with any variable
  121. * initialization. */
  122. static void writeGlobSymTable()
  123. {
  124. std::ostringstream ostr;
  125. if (symtab.empty())
  126. return;
  127. ostr<<"/* Global variables */\n";
  128. for (SYM &sym : symtab)
  129. {
  130. if (sym.duVal.isUSE_VAL()) /* first used */
  131. printGlobVar (ostr,&sym);
  132. else { /* first defined */
  133. switch (sym.size) {
  134. case 1: ostr<<"uint8_t\t"; break;
  135. case 2: ostr<<"int\t"; break;
  136. case 4: if (sym.type == TYPE_PTR)
  137. ostr<<"int\t*";
  138. else
  139. ostr<<"char\t*";
  140. break;
  141. default: ostr<<"char\t*";
  142. }
  143. ostr<<sym.name<<";\t/* size = "<<sym.size<<" */\n";
  144. }
  145. }
  146. ostr<< "\n";
  147. cCode.appendDecl( ostr.str() );
  148. }
  149. /* Writes the header information and global variables to the output C file
  150. * fp. */
  151. static void writeHeader (std::ostream &_ios, char *fileName)
  152. {
  153. /* Write header information */
  154. newBundle (&cCode);
  155. cCode.appendDecl( "/*\n");
  156. cCode.appendDecl( " * Input file\t: %s\n", fileName);
  157. cCode.appendDecl( " * File type\t: %s\n", (prog.fCOM)?"COM":"EXE");
  158. cCode.appendDecl( " */\n\n#include \"dcc.h\"\n\n");
  159. /* Write global symbol table */
  160. /** writeGlobSymTable(); *** need to change them into locident fmt ***/
  161. writeBundle (_ios, cCode);
  162. freeBundle (&cCode);
  163. }
  164. // Note: Not currently called!
  165. /* Checks the given icode to determine whether it has a label associated
  166. * to it. If so, a goto is emitted to this label; otherwise, a new label
  167. * is created and a goto is also emitted.
  168. * Note: this procedure is to be used when the label is to be forward on
  169. * the code; that is, the target code has not been traversed yet. */
  170. static void emitFwdGotoLabel (ICODE * pt, int indLevel)
  171. {
  172. if ( not pt->ll()->testFlags(HLL_LABEL)) /* node hasn't got a lab */
  173. {
  174. /* Generate new label */
  175. pt->ll()->hllLabNum = getNextLabel();
  176. pt->ll()->setFlags(HLL_LABEL);
  177. }
  178. cCode.appendCode( "%sgoto l%ld;\n", indentStr(indLevel), pt->ll()->hllLabNum);
  179. }
  180. /* Writes the procedure's declaration (including arguments), local variables,
  181. * and invokes the procedure that writes the code of the given record *hli */
  182. void Function::codeGen (std::ostream &fs)
  183. {
  184. int numLoc;
  185. ostringstream ostr;
  186. //STKFRAME * args; /* Procedure arguments */
  187. //char buf[200], /* Procedure's definition */
  188. // arg[30]; /* One argument */
  189. BB *pBB; /* Pointer to basic block */
  190. /* Write procedure/function header */
  191. newBundle (&cCode);
  192. if (flg & PROC_IS_FUNC) /* Function */
  193. ostr<< "\n"<<TypeContainer::typeName(retVal.type)<<" "<<name<<" (";
  194. else /* Procedure */
  195. ostr<< "\nvoid "<<name<<" (";
  196. /* Write arguments */
  197. for (size_t i = 0; i < args.size(); i++)
  198. {
  199. if ( args[i].invalid )
  200. continue;
  201. ostr<<hlTypes[args[i].type]<<" "<<args[i].name;
  202. if (i < (args.size() - 1))
  203. ostr<<", ";
  204. }
  205. ostr<<")\n";
  206. cCode.appendDecl( ostr.str() );
  207. /* Write comments */
  208. writeProcComments();
  209. /* Write local variables */
  210. if (! (flg & PROC_ASM))
  211. {
  212. numLoc = 0;
  213. for (ID &refId : localId )
  214. {
  215. /* Output only non-invalidated entries */
  216. if ( refId.illegal )
  217. continue;
  218. if (refId.loc == REG_FRAME)
  219. {
  220. /* Register variables are assigned to a local variable */
  221. if (((flg & SI_REGVAR) && (refId.id.regi == rSI)) ||
  222. ((flg & DI_REGVAR) && (refId.id.regi == rDI)))
  223. {
  224. refId.setLocalName(++numLoc);
  225. cCode.appendDecl( "int %s;\n", refId.name.c_str());
  226. }
  227. /* Other registers are named when they are first used in
  228. * the output C code, and appended to the proc decl. */
  229. }
  230. else if (refId.loc == STK_FRAME)
  231. {
  232. /* Name local variables and output appropriate type */
  233. refId.setLocalName(++numLoc);
  234. cCode.appendDecl( "%s %s;\n",hlTypes[refId.type], refId.name.c_str());
  235. }
  236. }
  237. }
  238. /* Write procedure's code */
  239. if (flg & PROC_ASM) /* generate assembler */
  240. {
  241. Disassembler ds(3);
  242. ds.disassem(this);
  243. }
  244. else /* generate C */
  245. {
  246. m_cfg.front()->writeCode (1, this, &numLoc, MAX, UN_INIT);
  247. }
  248. cCode.appendCode( "}\n\n");
  249. writeBundle (fs, cCode);
  250. freeBundle (&cCode);
  251. /* Write Live register analysis information */
  252. if (option.verbose)
  253. for (size_t i = 0; i < numBBs; i++)
  254. {
  255. pBB = m_dfsLast[i];
  256. if (pBB->flg & INVALID_BB) continue; /* skip invalid BBs */
  257. cout << "BB "<<i<<"\n";
  258. cout << " Start = "<<pBB->begin()->loc_ip;
  259. cout << ", end = "<<pBB->begin()->loc_ip+pBB->size()<<"\n";
  260. cout << " LiveUse = ";
  261. Machine_X86::writeBitVector(cout,pBB->liveUse);
  262. cout << "\n Def = ";
  263. Machine_X86::writeBitVector(cout,pBB->def);
  264. cout << "\n LiveOut = ";
  265. Machine_X86::writeBitVector(cout,pBB->liveOut);
  266. cout << "\n LiveIn = ";
  267. Machine_X86::writeBitVector(cout,pBB->liveIn);
  268. cout <<"\n\n";
  269. }
  270. }
  271. /* Recursive procedure. Displays the procedure's code in depth-first order
  272. * of the call graph. */
  273. static void backBackEnd (char *filename, CALL_GRAPH * pcallGraph, std::ostream &_ios)
  274. {
  275. // IFace.Yield(); /* This is a good place to yield to other apps */
  276. /* Check if this procedure has been processed already */
  277. if ((pcallGraph->proc->flg & PROC_OUTPUT) ||
  278. (pcallGraph->proc->flg & PROC_ISLIB))
  279. return;
  280. pcallGraph->proc->flg |= PROC_OUTPUT;
  281. /* Dfs if this procedure has any successors */
  282. for (size_t i = 0; i < pcallGraph->outEdges.size(); i++)
  283. {
  284. backBackEnd (filename, pcallGraph->outEdges[i], _ios);
  285. }
  286. /* Generate code for this procedure */
  287. stats.numLLIcode = pcallGraph->proc->Icode.size();
  288. stats.numHLIcode = 0;
  289. pcallGraph->proc->codeGen (_ios);
  290. /* Generate statistics */
  291. if (option.Stats)
  292. pcallGraph->proc->displayStats ();
  293. if (! (pcallGraph->proc->flg & PROC_ASM))
  294. {
  295. stats.totalLL += stats.numLLIcode;
  296. stats.totalHL += stats.numHLIcode;
  297. }
  298. }
  299. /* Invokes the necessary routines to produce code one procedure at a time. */
  300. void BackEnd (char *fileName, CALL_GRAPH * pcallGraph)
  301. {
  302. std::ofstream fs; /* Output C file */
  303. /* Get output file name */
  304. std::string outNam(fileName);
  305. outNam = outNam.substr(0,outNam.rfind("."))+".b"; /* b for beta */
  306. /* Open output file */
  307. fs.open(outNam);
  308. if(!fs.is_open())
  309. fatalError (CANNOT_OPEN, outNam.c_str());
  310. printf ("dcc: Writing C beta file %s\n", outNam.c_str());
  311. /* Header information */
  312. writeHeader (fs, fileName);
  313. /* Initialize total Icode instructions statistics */
  314. stats.totalLL = 0;
  315. stats.totalHL = 0;
  316. /* Process each procedure at a time */
  317. backBackEnd (fileName, pcallGraph, fs);
  318. /* Close output file */
  319. fs.close();
  320. printf ("dcc: Finished writing C beta file\n");
  321. }