backend.cpp 11 KB

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