backend.cpp 13 KB

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