Mon May 10 17:21:00 CEST 2004 Paolo Molaro <lupus@ximian.com>
[mono.git] / mono / mini / driver.c
1 /*
2  * driver.c: The new mono JIT compiler.
3  *
4  * Author:
5  *   Paolo Molaro (lupus@ximian.com)
6  *   Dietmar Maurer (dietmar@ximian.com)
7  *
8  * (C) 2002-2003 Ximian, Inc.
9  * (C) 2003-2004 Novell, Inc.
10  */
11
12 #include <config.h>
13 #include <signal.h>
14 #include <unistd.h>
15
16 #include <mono/metadata/assembly.h>
17 #include <mono/metadata/loader.h>
18 #include <mono/metadata/cil-coff.h>
19 #include <mono/metadata/tabledefs.h>
20 #include <mono/metadata/class.h>
21 #include <mono/metadata/object.h>
22 #include <mono/metadata/exception.h>
23 #include <mono/metadata/opcodes.h>
24 #include <mono/metadata/mono-endian.h>
25 #include <mono/metadata/tokentype.h>
26 #include <mono/metadata/tabledefs.h>
27 #include <mono/metadata/threads.h>
28 #include <mono/metadata/marshal.h>
29 #include <mono/metadata/socket-io.h>
30 #include <mono/metadata/appdomain.h>
31 #include <mono/metadata/debug-helpers.h>
32 #include <mono/io-layer/io-layer.h>
33 #include "mono/metadata/profiler.h"
34 #include <mono/metadata/profiler-private.h>
35 #include <mono/metadata/mono-config.h>
36 #include <mono/metadata/environment.h>
37 #include <mono/metadata/verify.h>
38 #include <mono/metadata/mono-debug.h>
39 #include <mono/metadata/mono-debug-debugger.h>
40
41 #include "mini.h"
42 #include "jit.h"
43 #include <string.h>
44 #include <ctype.h>
45 #include "inssel.h"
46 #include <locale.h>
47
48 static FILE *mini_stats_fd = NULL;
49
50 static void mini_usage (void);
51
52 typedef void (*OptFunc) (const char *p);
53
54 /* keep in sync with enum in mini.h */
55 typedef struct {
56         const char* name;
57         const char* desc;
58         const OptFunc func;
59 } OptName;
60
61 static const OptName 
62 opt_names [] = {
63         {"peephole", "Peephole postpass"},
64         {"branch",   "Branch optimizations"},
65         {"inline",   "Inline method calls"},
66         {"cfold",    "Constant folding"},
67         {"consprop", "Constant propagation"},
68         {"copyprop", "Copy propagation"},
69         {"deadce",   "Dead code elimination"},
70         {"linears",  "Linear scan global reg allocation"},
71         {"cmov",     "Conditional moves"},
72         {"shared",   "Emit per-domain code"},
73         {"sched",    "Instruction scheduling"},
74         {"intrins",  "Intrinsic method implementations"},
75         {"tailc",    "Tail recursion and tail calls"},
76         {"loop",     "Loop related optimizations"},
77         {"fcmov",    "Fast x86 FP compares"},
78         {"leaf",     "Leaf procedures optimizations"},
79         {"aot",      "Usage of Ahead Of Time compiled code"},
80         {"precomp",  "Precompile all methods before executing Main"}
81 };
82
83 #define DEFAULT_OPTIMIZATIONS ( \
84         MONO_OPT_PEEPHOLE |     \
85         MONO_OPT_CFOLD |        \
86         MONO_OPT_BRANCH |       \
87         MONO_OPT_LINEARS |      \
88         MONO_OPT_INTRINS |  \
89     MONO_OPT_AOT)
90
91
92 static guint32
93 parse_optimizations (const char* p)
94 {
95         /* the default value */
96         guint32 opt = DEFAULT_OPTIMIZATIONS;
97         guint32 exclude = 0;
98         const char *n;
99         int i, invert, len;
100
101         /* call out to cpu detection code here that sets the defaults ... */
102         opt |= mono_arch_cpu_optimizazions (&exclude);
103         opt &= ~exclude;
104         if (!p)
105                 return opt;
106
107         while (*p) {
108                 if (*p == '-') {
109                         p++;
110                         invert = TRUE;
111                 } else {
112                         invert = FALSE;
113                 }
114                 for (i = 0; i < G_N_ELEMENTS (opt_names); ++i) {
115                         n = opt_names [i].name;
116                         len = strlen (n);
117                         if (strncmp (p, n, len) == 0) {
118                                 if (invert)
119                                         opt &= ~ (1 << i);
120                                 else
121                                         opt |= 1 << i;
122                                 p += len;
123                                 if (*p == ',') {
124                                         p++;
125                                         break;
126                                 } else if (*p == '=') {
127                                         p++;
128                                         if (opt_names [i].func)
129                                                 opt_names [i].func (p);
130                                         while (*p && *p++ != ',');
131                                         break;
132                                 }
133                                 /* error out */
134                                 break;
135                         }
136                 }
137                 if (i == G_N_ELEMENTS (opt_names)) {
138                         if (strncmp (p, "all", 3) == 0) {
139                                 if (invert)
140                                         opt = 0;
141                                 else
142                                         opt = ~(MONO_OPT_SHARED | MONO_OPT_PRECOMP | exclude);
143                                 p += 3;
144                                 if (*p == ',')
145                                         p++;
146                         } else {
147                                 fprintf (stderr, "Invalid optimization name `%s'\n", p);
148                                 exit (1);
149                         }
150                 }
151         }
152         return opt;
153 }
154
155 typedef struct {
156         const char* name;
157         const char* desc;
158         MonoGraphOptions value;
159 } GraphName;
160
161 static const GraphName 
162 graph_names [] = {
163         {"cfg",      "Control Flow Graph (CFG)" ,               MONO_GRAPH_CFG},
164         {"dtree",    "Dominator Tree",                          MONO_GRAPH_DTREE},
165         {"code",     "CFG showing code",                        MONO_GRAPH_CFG_CODE},
166         {"ssa",      "CFG showing code after SSA translation",  MONO_GRAPH_CFG_SSA},
167         {"optcode",  "CFG showing code after IR optimizations", MONO_GRAPH_CFG_OPTCODE}
168 };
169
170 static MonoGraphOptions
171 mono_parse_graph_options (const char* p)
172 {
173         const char *n;
174         int i, len;
175
176         for (i = 0; i < G_N_ELEMENTS (graph_names); ++i) {
177                 n = graph_names [i].name;
178                 len = strlen (n);
179                 if (strncmp (p, n, len) == 0)
180                         return graph_names [i].value;
181         }
182
183         fprintf (stderr, "Invalid graph name provided: %s\n", p);
184         exit (1);
185 }
186
187 int
188 mono_parse_default_optimizations (const char* p)
189 {
190         guint32 opt;
191
192         opt = parse_optimizations (p);
193         return opt;
194 }
195
196 static char*
197 opt_descr (guint32 flags) {
198         GString *str = g_string_new ("");
199         int i, need_comma;
200
201         need_comma = 0;
202         for (i = 0; i < G_N_ELEMENTS (opt_names); ++i) {
203                 if (flags & (1 << i)) {
204                         if (need_comma)
205                                 g_string_append_c (str, ',');
206                         g_string_append (str, opt_names [i].name);
207                         need_comma = 1;
208                 }
209         }
210         return g_string_free (str, FALSE);
211 }
212
213 static const guint32
214 opt_sets [] = {
215        0,
216        MONO_OPT_PEEPHOLE,
217        MONO_OPT_BRANCH,
218        MONO_OPT_CFOLD,
219        MONO_OPT_FCMOV,
220        MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_INTRINS,
221        MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS,
222        MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP,
223        MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_CFOLD,
224        MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP | MONO_OPT_DEADCE,
225        MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP | MONO_OPT_DEADCE | MONO_OPT_LOOP | MONO_OPT_INLINE | MONO_OPT_INTRINS
226 };
227
228 typedef int (*TestMethod) (void);
229
230 #if 0
231 static void
232 domain_dump_native_code (MonoDomain *domain) {
233         // need to poke into the domain, move to metadata/domain.c
234         // need to empty jit_info_table and code_mp
235 }
236 #endif
237
238 static int
239 mini_regression (MonoImage *image, int verbose, int *total_run) {
240         guint32 i, opt, opt_flags;
241         MonoMethod *method;
242         MonoCompile *cfg;
243         char *n;
244         int result, expected, failed, cfailed, run, code_size, total;
245         TestMethod func;
246         GTimer *timer = g_timer_new ();
247
248         if (mini_stats_fd) {
249                 fprintf (mini_stats_fd, "$stattitle = \'Mono Benchmark Results (various optimizations)\';\n");
250
251                 fprintf (mini_stats_fd, "$graph->set_legend(qw(");
252                 for (opt = 0; opt < G_N_ELEMENTS (opt_sets); opt++) {
253                         opt_flags = opt_sets [opt];
254                         n = opt_descr (opt_flags);
255                         if (!n [0])
256                                 n = (char *)"none";
257                         if (opt)
258                                 fprintf (mini_stats_fd, " ");
259                         fprintf (mini_stats_fd, "%s", n);
260                 
261
262                 }
263                 fprintf (mini_stats_fd, "));\n");
264
265                 fprintf (mini_stats_fd, "@data = (\n");
266                 fprintf (mini_stats_fd, "[");
267         }
268
269         /* load the metadata */
270         for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
271                 method = mono_get_method (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL);
272                 mono_class_init (method->klass);
273
274                 if (!strncmp (method->name, "test_", 5) && mini_stats_fd) {
275                         fprintf (mini_stats_fd, "\"%s\",", method->name);
276                 }
277         }
278         if (mini_stats_fd)
279                 fprintf (mini_stats_fd, "],\n");
280
281
282         total = 0;
283         *total_run = 0;
284         for (opt = 0; opt < G_N_ELEMENTS (opt_sets); ++opt) {
285                 double elapsed, comp_time, start_time;
286                 MonoJitInfo *jinfo;
287
288                 opt_flags = opt_sets [opt];
289                 mono_set_defaults (verbose, opt_flags);
290                 n = opt_descr (opt_flags);
291                 g_print ("Test run: image=%s, opts=%s\n", image->name, n);
292                 g_free (n);
293                 cfailed = failed = run = code_size = 0;
294                 comp_time = elapsed = 0.0;
295
296                 /* fixme: ugly hack - delete all previously compiled methods */
297                 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
298                         method = mono_get_method (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL);
299                         method->info = NULL;
300                 }
301
302                 g_timer_start (timer);
303                 if (mini_stats_fd)
304                         fprintf (mini_stats_fd, "[");
305                 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
306                         method = mono_get_method (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL);
307                         if (strncmp (method->name, "test_", 5) == 0) {
308                                 expected = atoi (method->name + 5);
309                                 run++;
310                                 start_time = g_timer_elapsed (timer, NULL);
311                                 comp_time -= start_time; 
312                                 cfg = mini_method_compile (method, opt_flags, mono_root_domain, TRUE, 0);
313                                 comp_time += g_timer_elapsed (timer, NULL);
314                                 if (cfg) {
315                                         if (verbose >= 2)
316                                                 g_print ("Running '%s' ...\n", method->name);
317 #ifdef MONO_USE_AOT_COMPILER
318                                         if ((jinfo = mono_aot_get_method (mono_root_domain, method)))
319                                                 func = jinfo->code_start;
320                                         else
321 #endif
322                                                 func = (TestMethod)cfg->native_code;
323                                         result = func ();
324                                         if (result != expected) {
325                                                 failed++;
326                                                 if (verbose)
327                                                         g_print ("Test '%s' failed result (got %d, expected %d).\n", method->name, result, expected);
328                                         }
329                                         code_size += cfg->code_len;
330                                         mono_destroy_compile (cfg);
331
332                                 } else {
333                                         cfailed++;
334                                         if (verbose)
335                                                 g_print ("Test '%s' failed compilation.\n", method->name);
336                                 }
337                                 if (mini_stats_fd)
338                                         fprintf (mini_stats_fd, "%f, ", 
339                                                  g_timer_elapsed (timer, NULL) - start_time);
340                         }
341                 }
342                 if (mini_stats_fd)
343                         fprintf (mini_stats_fd, "],\n");
344                 g_timer_stop (timer);
345                 elapsed = g_timer_elapsed (timer, NULL);
346                 g_print ("Results: total tests: %d, failed: %d, cfailed: %d (pass: %.2f%%)\n", 
347                         run, failed, cfailed, 100.0*(run-failed-cfailed)/run);
348                 g_print ("Elapsed time: %f secs (%f, %f), Code size: %d\n\n", elapsed, 
349                          elapsed - comp_time, comp_time, code_size);
350                 total += failed + cfailed;
351                 *total_run += run;
352         }
353
354         if (mini_stats_fd) {
355                 fprintf (mini_stats_fd, ");\n");
356                 fflush (mini_stats_fd);
357         }
358
359         g_timer_destroy (timer);
360         return total;
361 }
362
363 static int
364 mini_regression_list (int verbose, int count, char *images [])
365 {
366         int i, total, total_run, run;
367         MonoAssembly *ass;
368         
369         total_run =  total = 0;
370         for (i = 0; i < count; ++i) {
371                 ass = mono_assembly_open (images [i], NULL);
372                 if (!ass) {
373                         g_warning ("failed to load assembly: %s", images [i]);
374                         continue;
375                 }
376                 total += mini_regression (ass->image, verbose, &run);
377                 total_run += run;
378                 mono_assembly_close (ass);
379         }
380         g_print ("Overall results: tests: %d, failed: %d, opt combinations: %d (pass: %.2f%%)\n", 
381                 total_run, total, G_N_ELEMENTS (opt_sets), 100.0*(total_run-total)/total_run);
382         return total;
383 }
384
385 enum {
386         DO_BENCH,
387         DO_REGRESSION,
388         DO_COMPILE,
389         DO_EXEC,
390         DO_DRAW
391 };
392
393 typedef struct CompileAllThreadArgs {
394         MonoAssembly *ass;
395         int verbose;
396 } CompileAllThreadArgs;
397
398 static void
399 compile_all_methods_thread_main (CompileAllThreadArgs *args)
400 {
401         MonoAssembly *ass = args->ass;
402         int verbose = args->verbose;
403         MonoImage *image = ass->image;
404         MonoMethod *method;
405         int i, count = 0;
406
407         for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
408                 method = mono_get_method (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL);
409                 if (method->flags & METHOD_ATTRIBUTE_ABSTRACT)
410                         continue;
411                 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
412                         continue;
413
414                 count++;
415                 if (verbose) {
416                         char * desc = mono_method_full_name (method, TRUE);
417                         g_print ("Compiling %d %s\n", count, desc);
418                         g_free (desc);
419                 }
420                 mono_compile_method (method);
421         }
422
423 }
424
425 static void
426 compile_all_methods (MonoAssembly *ass, int verbose)
427 {
428         CompileAllThreadArgs args;
429
430         args.ass = ass;
431         args.verbose = verbose;
432
433         /* 
434          * Need to create a mono thread since compilation might trigger
435          * running of managed code.
436          */
437         mono_thread_create (mono_domain_get (), compile_all_methods_thread_main, &args);
438
439         mono_thread_manage ();
440 }
441
442 /**
443  * mono_jit_exec:
444  * @assembly: reference to an assembly
445  * @argc: argument count
446  * @argv: argument vector
447  *
448  * Start execution of a program.
449  */
450 int 
451 mono_jit_exec (MonoDomain *domain, MonoAssembly *assembly, int argc, char *argv[])
452 {
453         MonoImage *image = assembly->image;
454         MonoMethod *method;
455         guint32 entry = mono_image_get_entry_point (image);
456
457         if (!entry) {
458                 g_print ("Assembly '%s' doesn't have an entry point.\n", image->name);
459                 /* FIXME: remove this silly requirement. */
460                 mono_environment_exitcode_set (1);
461                 return 1;
462         }
463
464         method = mono_get_method (image, entry, NULL);
465
466         return mono_runtime_run_main (method, argc, argv, NULL);
467 }
468
469 typedef struct 
470 {
471         MonoDomain *domain;
472         const char *file;
473         int argc;
474         char **argv;
475         guint32 opts;
476 } MainThreadArgs;
477
478 static void main_thread_handler (gpointer user_data)
479 {
480         MainThreadArgs *main_args = user_data;
481         MonoAssembly *assembly;
482
483         assembly = mono_domain_assembly_open (main_args->domain, main_args->file);
484         if (!assembly){
485                 fprintf (stderr, "Can not open image %s\n", main_args->file);
486                 exit (1);
487         }
488
489         if (mono_compile_aot) {
490                 int res = mono_compile_assembly (assembly, main_args->opts);
491                 printf ("AOT RESULT %d\n", res);
492         } else {
493                 /* 
494                  * This must be done in a thread managed by mono since it can invoke
495                  * managed code.
496                  */
497                 if (main_args->opts & MONO_OPT_PRECOMP)
498                         mono_precompile_assemblies ();
499
500                 mono_jit_exec (main_args->domain, assembly, main_args->argc, main_args->argv);
501         }
502 }
503
504 static void
505 mini_usage (void)
506 {
507         int i;
508
509         fprintf (stdout,
510                 "Usage is: mono [options] assembly\n\n"
511                 "Runtime and JIT debugging:\n"
512                 "    --compile METHOD       Just compile METHOD in assembly\n"
513                 "    --ncompile N           Number of times to compile METHOD (default: 1)\n"
514                 "    --regression           Runs the regression test contained in the assembly\n"
515                 "    --print-vtable         Print the vtable of all used classes\n"
516                 "    --trace[=EXPR]         Enable tracing, use --help-trace for details\n"
517                 "    --compile-all          Compiles all the methods in the assembly\n"
518                 "    --breakonex            Inserts a breakpoint on exceptions\n"
519                 "    --break METHOD         Inserts a breakpoint at METHOD entry\n"
520                 "    --debug                Enable debugging support\n"
521                 "    --stats                Print statistics about the JIT operations\n"
522                 "\n"
523                 "Development:\n"
524                 "    --statfile FILE        Sets the stat file to FILE\n"
525                 "    --aot                  Compiles the assembly to native code\n"
526                 "    --profile[=profiler]   Runs in profiling mode with the specified profiler module\n"
527                 "    --graph[=TYPE] METHOD  Draws a graph of the specified method:\n");
528         
529         for (i = 0; i < G_N_ELEMENTS (graph_names); ++i) {
530                 fprintf (stdout, "                           %-10s %s\n", graph_names [i].name, graph_names [i].desc);
531         }
532
533         fprintf (stdout,
534                 "\n"
535                 "Runtime:\n"
536                 "    --config FILE          Loads FILE as the Mono config\n"
537                 "    --verbose, -v          Increases the verbosity level\n"
538                 "    --help, -h             Show usage information\n"
539                 "    --version, -V          Show version information\n"
540                 "    --optimize=OPT         Turns on a specific optimization:\n");
541
542         for (i = 0; i < G_N_ELEMENTS (opt_names); ++i)
543                 fprintf (stdout, "                           %-10s %s\n", opt_names [i].name, opt_names [i].desc);
544 }
545
546 static void
547 mini_trace_usage (void)
548 {
549         fprintf (stdout,
550                  "Tracing options:\n"
551                  "   --trace[=EXPR]        Trace every call, optional EXPR controls the scope\n"
552                  "\n"
553                  "EXPR is composed of:\n"
554                  "    all                  All assemblies\n"
555                  "    none                 No assemblies\n"
556                  "    program              Entry point assembly\n"
557                  "    assembly             Specifies an assembly\n"
558                  "    M:Type:Method        Specifies a method\n"
559                  "    N:Namespace          Specifies a namespace\n"
560                  "    T:Type               Specifies a type\n"
561                  "    +EXPR                Includes expression\n"
562                  "    -EXPR                Excludes expression\n");
563 }
564
565 static const char *info = ""
566 #ifdef HAVE_KW_THREAD
567         "\tTLS:           NPTL\n"
568 #else
569         "\tTLS:           normal\n"
570 #endif /* HAVE_KW_THREAD */
571 #ifdef HAVE_BOEHM_GC
572 #ifdef USE_INCLUDED_LIBGC
573         "\tGC:            Included Boehm (with typed GC)\n"
574 #else
575 #if HAVE_GC_GCJ_MALLOC
576         "\tGC:            System Boehm (with typed GC)\n"
577 #else
578         "\tGC:            System Boehm (no typed GC available)\n"
579 #endif
580 #endif
581 #else
582         "\tGC:            none\n"
583 #endif /* HAVE_BOEHM_GC */
584 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
585     "\tSIGSEGV      : altstack\n"
586 #else
587     "\tSIGSEGV      : normal\n"
588 #endif
589 #ifdef HAVE_ICU
590         "\tGlobalization: ICU\n"
591 #else
592         "\tGlobalization: none\n"
593 #endif /* HAVE_ICU */
594         "";
595
596 int
597 mono_main (int argc, char* argv[])
598 {
599         MainThreadArgs main_args;
600         MonoAssembly *assembly;
601         MonoMethodDesc *desc;
602         MonoMethod *method;
603         MonoCompile *cfg;
604         MonoDomain *domain;
605         const char* aname, *mname = NULL;
606         char *config_file = NULL;
607         int i, count = 1;
608         int enable_debugging = FALSE;
609         guint32 opt, action = DO_EXEC;
610         MonoGraphOptions mono_graph_options = 0;
611         int mini_verbose = 0;
612         char *trace_options = NULL;
613
614         setlocale (LC_ALL, "");
615         g_log_set_always_fatal (G_LOG_LEVEL_ERROR);
616         g_log_set_fatal_mask (G_LOG_DOMAIN, G_LOG_LEVEL_ERROR);
617         
618         opt = parse_optimizations (NULL);
619
620         for (i = 1; i < argc; ++i) {
621                 if (argv [i] [0] != '-')
622                         break;
623                 if (strcmp (argv [i], "--regression") == 0) {
624                         action = DO_REGRESSION;
625                 } else if (strcmp (argv [i], "--verbose") == 0 || strcmp (argv [i], "-v") == 0) {
626                         mini_verbose++;
627                 } else if (strcmp (argv [i], "--version") == 0 || strcmp (argv [i], "-V") == 0) {
628                         g_print ("Mono JIT compiler version %s, (C) 2002-2004 Novell, Inc and Contributors. www.go-mono.com\n", VERSION);
629                         g_print (info);
630                         if (mini_verbose) {
631                                 const guchar *cerror;
632                                 const guchar *clibpath;
633                                 mono_init ("mono");
634                                 cerror = mono_check_corlib_version ();
635                                 clibpath = mono_defaults.corlib? mono_defaults.corlib->name: "unknown";
636                                 if (cerror) {
637                                         g_print ("The currently installed mscorlib doesn't match this runtime version.\n");
638                                         g_print ("The error is: %s\n", cerror);
639                                         g_print ("mscorlib.dll loaded at: %s\n", clibpath);
640                                         return 1;
641                                 }
642                         }
643                         return 0;
644                 } else if (strcmp (argv [i], "--help") == 0 || strcmp (argv [i], "-h") == 0) {
645                         mini_usage ();
646                         return 0;
647                 } else if (strcmp (argv [i], "--help-trace") == 0){
648                         mini_trace_usage ();
649                         return 0;
650                 } else if (strncmp (argv [i], "--statfile", 10) == 0) {
651                         mini_stats_fd = fopen (argv [++i], "w+");
652                 } else if (strncmp (argv [i], "--optimize=", 11) == 0) {
653                         opt = parse_optimizations (argv [i] + 11);
654                 } else if (strncmp (argv [i], "-O=", 3) == 0) {
655                         opt = parse_optimizations (argv [i] + 3);
656                 } else if (strcmp (argv [i], "--config") == 0) {
657                         config_file = argv [++i];
658                 } else if (strcmp (argv [i], "--ncompile") == 0) {
659                         count = atoi (argv [++i]);
660                         action = DO_BENCH;
661                 } else if (strcmp (argv [i], "--trace") == 0) {
662                         trace_options = "";
663                 } else if (strncmp (argv [i], "--trace=", 8) == 0) {
664                         trace_options = &argv [i][8];
665                 } else if (strcmp (argv [i], "--breakonex") == 0) {
666                         mono_break_on_exc = TRUE;
667                 } else if (strcmp (argv [i], "--break") == 0) {
668                         if (!mono_debugger_insert_breakpoint (argv [++i], FALSE))
669                                 g_error ("Invalid method name '%s'", argv [i]);
670                 } else if (strcmp (argv [i], "--print-vtable") == 0) {
671                         mono_print_vtable = TRUE;
672                 } else if (strcmp (argv [i], "--stats") == 0) {
673                         mono_jit_stats.enabled = TRUE;
674                 } else if (strcmp (argv [i], "--aot") == 0) {
675                         mono_compile_aot = TRUE;
676                 } else if (strcmp (argv [i], "--compile-all") == 0) {
677                         action = DO_COMPILE;
678                 } else if (strcmp (argv [i], "--profile") == 0) {
679                         mono_profiler_load (NULL);
680                 } else if (strncmp (argv [i], "--profile=", 10) == 0) {
681                         mono_profiler_load (argv [i] + 10);
682                 } else if (strcmp (argv [i], "--compile") == 0) {
683                         mname = argv [++i];
684                         action = DO_BENCH;
685                 } else if (strncmp (argv [i], "--graph=", 8) == 0) {
686                         mono_graph_options = mono_parse_graph_options (argv [i] + 8);
687                         mname = argv [++i];
688                         action = DO_DRAW;
689                 } else if (strcmp (argv [i], "--graph") == 0) {
690                         mname = argv [++i];
691                         mono_graph_options = MONO_GRAPH_CFG;
692                         action = DO_DRAW;
693                 } else if (strcmp (argv [i], "--debug") == 0) {
694                         enable_debugging = TRUE;
695                 } else {
696                         fprintf (stderr, "Unknown command line option: '%s'\n", argv [i]);
697                         return 1;
698                 }
699         }
700
701         if (!argv [i]) {
702                 mini_usage ();
703                 return 1;
704         }
705
706         if (mono_compile_aot || action == DO_EXEC) {
707                 g_set_prgname (argv[i]);
708         }
709
710         mono_set_defaults (mini_verbose, opt);
711         domain = mini_init (argv [i]);
712         
713         switch (action) {
714         case DO_REGRESSION:
715                 if (mini_regression_list (mini_verbose, argc -i, argv + i)) {
716                         g_print ("Regression ERRORS!\n");
717                         mini_cleanup (domain);
718                         return 1;
719                 }
720                 mini_cleanup (domain);
721                 return 0;
722         case DO_BENCH:
723                 if (argc - i != 1 || mname == NULL) {
724                         g_print ("Usage: mini --ncompile num --compile method assembly\n");
725                         mini_cleanup (domain);
726                         return 1;
727                 }
728                 aname = argv [i];
729                 break;
730         case DO_COMPILE:
731                 if (argc - i != 1) {
732                         mini_usage ();
733                         mini_cleanup (domain);
734                         return 1;
735                 }
736                 aname = argv [i];
737                 break;
738         case DO_DRAW:
739                 if (argc - i != 1 || mname == NULL) {
740                         mini_usage ();
741                         mini_cleanup (domain);
742                         return 1;
743                 }
744                 aname = argv [i];
745                 break;
746         default:
747                 if (argc - i < 1) {
748                         mini_usage ();
749                         mini_cleanup (domain);
750                         return 1;
751                 }
752                 aname = argv [i];
753                 break;
754         }
755
756         if (enable_debugging)
757                 mono_debug_init (domain, MONO_DEBUG_FORMAT_MONO);
758
759         /* Parse gac loading options before loading assemblies. */
760         if (mono_compile_aot || action == DO_EXEC) {
761                 mono_config_parse (config_file);
762         }
763
764         assembly = mono_assembly_open (aname, NULL);
765         if (!assembly) {
766                 fprintf (stderr, "cannot open assembly %s\n", aname);
767                 mini_cleanup (domain);
768                 return 2;
769         }
770
771         if (trace_options != NULL){
772                 mono_jit_trace_calls = mono_trace_parse_options (assembly, trace_options);
773                 if (mono_jit_trace_calls == NULL)
774                         exit (1);
775         }
776
777         if (enable_debugging)
778                 mono_debug_init_2 (assembly);
779
780         if (mono_compile_aot || action == DO_EXEC) {
781                 const guchar *error;
782
783                 //mono_set_rootdir ();
784
785                 error = mono_check_corlib_version ();
786                 if (error) {
787                         fprintf (stderr, "Corlib not in sync with this runtime: %s\n", error);
788                         fprintf (stderr, "Download a newer corlib or a newer runtime at http://www.go-mono.com/daily.\n");
789                         exit (1);
790                 }
791
792                 main_args.domain = domain;
793                 main_args.file = aname;         
794                 main_args.argc = argc - i;
795                 main_args.argv = argv + i;
796                 main_args.opts = opt;
797              
798                 mono_runtime_exec_managed_code (domain, main_thread_handler, &main_args);
799                 mini_cleanup (domain);
800
801                 /* Look up return value from System.Environment.ExitCode */
802                 i = mono_environment_exitcode_get ();
803                 return i;
804         } else if (action == DO_COMPILE) {
805                 compile_all_methods (assembly, mini_verbose);
806                 mini_cleanup (domain);
807                 return 0;
808         }
809         desc = mono_method_desc_new (mname, 0);
810         if (!desc) {
811                 g_print ("Invalid method name %s\n", mname);
812                 mini_cleanup (domain);
813                 return 3;
814         }
815         method = mono_method_desc_search_in_image (desc, assembly->image);
816         if (!method) {
817                 g_print ("Cannot find method %s\n", mname);
818                 mini_cleanup (domain);
819                 return 3;
820         }
821
822         if (action == DO_DRAW) {
823                 int part = 0;
824
825                 switch (mono_graph_options) {
826                 case MONO_GRAPH_DTREE:
827                         part = 1;
828                         opt |= MONO_OPT_LOOP;
829                         break;
830                 case MONO_GRAPH_CFG_CODE:
831                         part = 1;
832                         break;
833                 case MONO_GRAPH_CFG_SSA:
834                         part = 2;
835                         break;
836                 case MONO_GRAPH_CFG_OPTCODE:
837                         part = 3;
838                         break;
839                 default:
840                         break;
841                 }
842
843                 cfg = mini_method_compile (method, opt, mono_root_domain, FALSE, part);
844                 if ((mono_graph_options & MONO_GRAPH_CFG_SSA) && !(cfg->comp_done & MONO_COMP_SSA)) {
845                         g_warning ("no SSA info available (use -O=deadce)");
846                         return 1;
847                 }
848                 mono_draw_graph (cfg, mono_graph_options);
849                 mono_destroy_compile (cfg);
850
851         } else if (action == DO_BENCH) {
852                 if (mini_stats_fd) {
853                         const char *n;
854                         double no_opt_time = 0.0;
855                         GTimer *timer = g_timer_new ();
856                         fprintf (mini_stats_fd, "$stattitle = \'Compilations times for %s\';\n", 
857                                  mono_method_full_name (method, TRUE));
858                         fprintf (mini_stats_fd, "@data = (\n");
859                         fprintf (mini_stats_fd, "[");
860                         for (i = 0; i < G_N_ELEMENTS (opt_sets); i++) {
861                                 opt = opt_sets [i];
862                                 n = opt_descr (opt);
863                                 if (!n [0])
864                                         n = "none";
865                                 fprintf (mini_stats_fd, "\"%s\",", n);
866                         }
867                         fprintf (mini_stats_fd, "],\n[");
868
869                         for (i = 0; i < G_N_ELEMENTS (opt_sets); i++) {
870                                 int j;
871                                 double elapsed;
872                                 opt = opt_sets [i];
873                                 g_timer_start (timer);
874                                 for (j = 0; j < count; ++j) {
875                                         cfg = mini_method_compile (method, opt, mono_root_domain, FALSE, 0);
876                                         mono_destroy_compile (cfg);
877                                 }
878                                 g_timer_stop (timer);
879                                 elapsed = g_timer_elapsed (timer, NULL);
880                                 if (!opt)
881                                         no_opt_time = elapsed;
882                                 fprintf (mini_stats_fd, "%f, ", elapsed);
883                         }
884                         fprintf (mini_stats_fd, "]");
885                         if (no_opt_time > 0.0) {
886                                 fprintf (mini_stats_fd, ", \n[");
887                                 for (i = 0; i < G_N_ELEMENTS (opt_sets); i++) 
888                                         fprintf (mini_stats_fd, "%f,", no_opt_time);
889                                 fprintf (mini_stats_fd, "]");
890                         }
891                         fprintf (mini_stats_fd, ");\n");
892                 } else {
893                         for (i = 0; i < count; ++i) {
894                                 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
895                                         (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
896                                         method = mono_marshal_get_native_wrapper (method);
897
898                                 cfg = mini_method_compile (method, opt, mono_root_domain, FALSE, 0);
899                                 mono_destroy_compile (cfg);
900                         }
901                 }
902         } else {
903                 cfg = mini_method_compile (method, opt, mono_root_domain, FALSE, 0);
904                 mono_destroy_compile (cfg);
905         }
906
907         mini_cleanup (domain);
908         return 0;
909 }
910
911 MonoDomain * 
912 mono_jit_init (const char *file)
913 {
914         return mini_init (file);
915 }
916
917 void        
918 mono_jit_cleanup (MonoDomain *domain)
919 {
920         mini_cleanup (domain);
921 }
922
923