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