- 2009 patch
[cparser] / driver / firm_codegen.c
1 /**
2  * @file firm_codegen.c
3  *
4  * Compile when BACK_END_IS_CP_FIRM_BE is defined
5  *
6  * (C) 2005-2009  Michael Beck  beck@ipd.info.uni-karlsruhe.de
7  *
8  * $Id$
9  */
10 #include <string.h>
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <libfirm/dbginfo.h>
14 #include <libfirm/adt/xmalloc.h>
15 #include <libfirm/be.h>
16
17 #ifdef FIRM2C_BACKEND
18 #include "cbackend.h"
19 #endif
20
21 #include "firm_codegen.h"
22 #include "firm_cmdline.h"
23 #include "firm_opt.h"
24 #include "firm_timing.h"
25
26 /**
27  * Substitutes '.c' for '.s'.
28  */
29 static char *generate_asm_file_name(const char *file_name) {
30   int len             = strlen(file_name);
31   char *asm_file_name = xmalloc(len + 5);   /* .asm + \0 */
32
33   strcpy(asm_file_name, file_name);
34   if (asm_file_name[len - 2] == '.' && asm_file_name[len - 1] == 'c')
35     asm_file_name[len - 2] = '\0';
36
37   switch (firm_be_opt.selection) {
38 #ifdef FIRM2C_BACKEND
39   case BE_FIRM2C:
40     strncat(asm_file_name, ".s.c", 4);
41     break;
42 #endif
43
44 #ifdef FIRM_BACKEND
45   case BE_FIRM_BE:
46     strncat(asm_file_name, ".s", 4);
47     break;
48 #endif
49   }
50
51   return asm_file_name;
52 }  /* generate_asm_file_name */
53
54 /**
55  * Calls the specified backend.
56  * Code is written to file <file_name> ('.c' is substituted for '.asm')
57  */
58 void do_codegen(FILE *out, const char *file_name) {
59   FILE *close_out = NULL;
60   if (out == NULL) {
61     char *asm_file_name = generate_asm_file_name(file_name);
62
63     if ((out = fopen(asm_file_name, "w")) == NULL) {
64       fprintf(stderr, "Could not open output file %s\n", asm_file_name);
65       exit(1);
66     }
67     free(asm_file_name);
68     close_out = out;
69   }
70
71   switch (firm_be_opt.selection) {
72 #ifdef FIRM2C_BACKEND
73   case BE_FIRM2C:
74     timer_start(TV_FIRM2C_BE);
75       cbackend_set_debug_retrieve(dbg_retrieve);
76       generate_code_file(out);
77     timer_stop(TV_FIRM2C_BE);
78     break;
79 #endif
80
81 #ifdef FIRM_BACKEND
82   case BE_FIRM_BE:
83     timer_start(TV_FIRM_BE);
84       ir_set_debug_retrieve(dbg_retrieve);
85       be_main(out, file_name);
86     timer_stop(TV_FIRM_BE);
87     break;
88 #endif
89
90   default:
91     fprintf(stderr, "Fatal: Unknown backend %d\n", firm_be_opt.selection);
92   } /* switch (firm_be_opt.selection) */
93
94   if (close_out)
95     fclose(close_out);
96 } /* do_codegen() */