backend.cpp 12 KB

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