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