backend.cpp 12 KB

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