backend.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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. PROG &prog(Project::get()->prog);
  89. uint32_t relocOp = prog.fCOM ? psym->label : psym->label + 0x100;
  90. switch (psym->size)
  91. {
  92. case 1:
  93. ostr << "uint8_t\t"<<psym->name<<" = "<<prog.Image[relocOp]<<";\n";
  94. break;
  95. case 2:
  96. ostr << "uint16_t\t"<<psym->name<<" = "<<LH(prog.Image+relocOp)<<";\n";
  97. break;
  98. case 4: if (psym->type == TYPE_PTR) /* pointer */
  99. ostr << "uint16_t *\t"<<psym->name<<" = "<<LH(prog.Image+relocOp)<<";\n";
  100. else /* char */
  101. ostr << "char\t"<<psym->name<<"[4] = \""<<
  102. prog.Image[relocOp]<<prog.Image[relocOp+1]<<
  103. prog.Image[relocOp+2]<<prog.Image[relocOp+3]<<";\n";
  104. break;
  105. default:
  106. {
  107. ostringstream strContents;
  108. for (j=0; j < psym->size; j++)
  109. strContents << cChar(prog.Image[relocOp + j]);
  110. ostr << "char\t*"<<psym->name<<" = \""<<strContents.str()<<"\";\n";
  111. }
  112. }
  113. }
  114. // Note: Not called at present.
  115. /* Writes the contents of the symbol table, along with any variable
  116. * initialization. */
  117. void Project::writeGlobSymTable()
  118. {
  119. std::ostringstream ostr;
  120. if (symtab.empty())
  121. return;
  122. ostr<<"/* Global variables */\n";
  123. for (SYM &sym : symtab)
  124. {
  125. if (sym.duVal.isUSE_VAL()) /* first used */
  126. printGlobVar (ostr,&sym);
  127. else { /* first defined */
  128. switch (sym.size) {
  129. case 1: ostr<<"uint8_t\t"; break;
  130. case 2: ostr<<"int\t"; break;
  131. case 4: if (sym.type == TYPE_PTR)
  132. ostr<<"int\t*";
  133. else
  134. ostr<<"char\t*";
  135. break;
  136. default: ostr<<"char\t*";
  137. }
  138. ostr<<sym.name<<";\t/* size = "<<sym.size<<" */\n";
  139. }
  140. }
  141. ostr<< "\n";
  142. cCode.appendDecl( ostr.str() );
  143. }
  144. /* Writes the header information and global variables to the output C file
  145. * fp. */
  146. static void writeHeader (std::ostream &_ios, char *fileName)
  147. {
  148. PROG &prog(Project::get()->prog);
  149. /* Write header information */
  150. cCode.init();
  151. cCode.appendDecl( "/*\n");
  152. cCode.appendDecl( " * Input file\t: %s\n", fileName);
  153. cCode.appendDecl( " * File type\t: %s\n", (prog.fCOM)?"COM":"EXE");
  154. cCode.appendDecl( " */\n\n#include \"dcc.h\"\n\n");
  155. /* Write global symbol table */
  156. /** writeGlobSymTable(); *** need to change them into locident fmt ***/
  157. writeBundle (_ios, cCode);
  158. freeBundle (&cCode);
  159. }
  160. // Note: Not currently called!
  161. /* Checks the given icode to determine whether it has a label associated
  162. * to it. If so, a goto is emitted to this label; otherwise, a new label
  163. * is created and a goto is also emitted.
  164. * Note: this procedure is to be used when the label is to be forward on
  165. * the code; that is, the target code has not been traversed yet. */
  166. static void emitFwdGotoLabel (ICODE * pt, int indLevel)
  167. {
  168. if ( not pt->ll()->testFlags(HLL_LABEL)) /* node hasn't got a lab */
  169. {
  170. /* Generate new label */
  171. pt->ll()->hllLabNum = getNextLabel();
  172. pt->ll()->setFlags(HLL_LABEL);
  173. }
  174. cCode.appendCode( "%sgoto l%ld;\n", indentStr(indLevel), pt->ll()->hllLabNum);
  175. }
  176. /* Writes the procedure's declaration (including arguments), local variables,
  177. * and invokes the procedure that writes the code of the given record *hli */
  178. void Function::codeGen (std::ostream &fs)
  179. {
  180. int numLoc;
  181. ostringstream ostr;
  182. //STKFRAME * args; /* Procedure arguments */
  183. //char buf[200], /* Procedure's definition */
  184. // arg[30]; /* One argument */
  185. BB *pBB; /* Pointer to basic block */
  186. /* Write procedure/function header */
  187. cCode.init();
  188. if (flg & PROC_IS_FUNC) /* Function */
  189. ostr<< "\n"<<TypeContainer::typeName(retVal.type)<<" "<<name<<" (";
  190. else /* Procedure */
  191. ostr<< "\nvoid "<<name<<" (";
  192. /* Write arguments */
  193. for (size_t i = 0; i < args.size(); i++)
  194. {
  195. if ( args[i].invalid )
  196. continue;
  197. ostr<<hlTypes[args[i].type]<<" "<<args[i].name;
  198. if (i < (args.size() - 1))
  199. ostr<<", ";
  200. }
  201. ostr<<")\n";
  202. /* Write comments */
  203. writeProcComments( ostr );
  204. /* Write local variables */
  205. if (! (flg & PROC_ASM))
  206. {
  207. numLoc = 0;
  208. for (ID &refId : localId )
  209. {
  210. /* Output only non-invalidated entries */
  211. if ( refId.illegal )
  212. continue;
  213. if (refId.loc == REG_FRAME)
  214. {
  215. /* Register variables are assigned to a local variable */
  216. if (((flg & SI_REGVAR) && (refId.id.regi == rSI)) ||
  217. ((flg & DI_REGVAR) && (refId.id.regi == rDI)))
  218. {
  219. refId.setLocalName(++numLoc);
  220. ostr << "int "<<refId.name<<";\n";
  221. }
  222. /* Other registers are named when they are first used in
  223. * the output C code, and appended to the proc decl. */
  224. }
  225. else if (refId.loc == STK_FRAME)
  226. {
  227. /* Name local variables and output appropriate type */
  228. refId.setLocalName(++numLoc);
  229. ostr << TypeContainer::typeName(refId.type)<<" "<<refId.name<<";\n";
  230. }
  231. }
  232. }
  233. fs<<ostr.str();
  234. /* Write procedure's code */
  235. if (flg & PROC_ASM) /* generate assembler */
  236. {
  237. Disassembler ds(3);
  238. ds.disassem(this);
  239. }
  240. else /* generate C */
  241. {
  242. m_cfg.front()->writeCode (1, this, &numLoc, MAX, UN_INIT);
  243. }
  244. cCode.appendCode( "}\n\n");
  245. writeBundle (fs, cCode);
  246. freeBundle (&cCode);
  247. /* Write Live register analysis information */
  248. if (option.verbose)
  249. for (size_t i = 0; i < numBBs; i++)
  250. {
  251. pBB = m_dfsLast[i];
  252. if (pBB->flg & INVALID_BB) continue; /* skip invalid BBs */
  253. cout << "BB "<<i<<"\n";
  254. cout << " Start = "<<pBB->begin()->loc_ip;
  255. cout << ", end = "<<pBB->begin()->loc_ip+pBB->size()<<"\n";
  256. cout << " LiveUse = ";
  257. Machine_X86::writeRegVector(cout,pBB->liveUse);
  258. cout << "\n Def = ";
  259. Machine_X86::writeRegVector(cout,pBB->def);
  260. cout << "\n LiveOut = ";
  261. Machine_X86::writeRegVector(cout,pBB->liveOut);
  262. cout << "\n LiveIn = ";
  263. Machine_X86::writeRegVector(cout,pBB->liveIn);
  264. cout <<"\n\n";
  265. }
  266. }
  267. /* Recursive procedure. Displays the procedure's code in depth-first order
  268. * of the call graph. */
  269. static void backBackEnd (char *filename, CALL_GRAPH * pcallGraph, std::ostream &_ios)
  270. {
  271. // IFace.Yield(); /* This is a good place to yield to other apps */
  272. /* Check if this procedure has been processed already */
  273. if ((pcallGraph->proc->flg & PROC_OUTPUT) ||
  274. (pcallGraph->proc->flg & PROC_ISLIB))
  275. return;
  276. pcallGraph->proc->flg |= PROC_OUTPUT;
  277. /* Dfs if this procedure has any successors */
  278. for (size_t i = 0; i < pcallGraph->outEdges.size(); i++)
  279. {
  280. backBackEnd (filename, pcallGraph->outEdges[i], _ios);
  281. }
  282. /* Generate code for this procedure */
  283. stats.numLLIcode = pcallGraph->proc->Icode.size();
  284. stats.numHLIcode = 0;
  285. pcallGraph->proc->codeGen (_ios);
  286. /* Generate statistics */
  287. if (option.Stats)
  288. pcallGraph->proc->displayStats ();
  289. if (! (pcallGraph->proc->flg & PROC_ASM))
  290. {
  291. stats.totalLL += stats.numLLIcode;
  292. stats.totalHL += stats.numHLIcode;
  293. }
  294. }
  295. /* Invokes the necessary routines to produce code one procedure at a time. */
  296. void BackEnd (char *fileName, CALL_GRAPH * pcallGraph)
  297. {
  298. std::ofstream fs; /* Output C file */
  299. /* Get output file name */
  300. std::string outNam(fileName);
  301. outNam = outNam.substr(0,outNam.rfind("."))+".b"; /* b for beta */
  302. /* Open output file */
  303. fs.open(outNam);
  304. if(!fs.is_open())
  305. fatalError (CANNOT_OPEN, outNam.c_str());
  306. printf ("dcc: Writing C beta file %s\n", outNam.c_str());
  307. /* Header information */
  308. writeHeader (fs, fileName);
  309. /* Initialize total Icode instructions statistics */
  310. stats.totalLL = 0;
  311. stats.totalHL = 0;
  312. /* Process each procedure at a time */
  313. backBackEnd (fileName, pcallGraph, fs);
  314. /* Close output file */
  315. fs.close();
  316. printf ("dcc: Finished writing C beta file\n");
  317. }