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