2 * driver.c: The new mono JIT compiler.
5 * Paolo Molaro (lupus@ximian.com)
6 * Dietmar Maurer (dietmar@ximian.com)
8 * (C) 2002 Ximian, Inc.
15 #include <mono/metadata/assembly.h>
16 #include <mono/metadata/loader.h>
17 #include <mono/metadata/cil-coff.h>
18 #include <mono/metadata/tabledefs.h>
19 #include <mono/metadata/class.h>
20 #include <mono/metadata/object.h>
21 #include <mono/metadata/exception.h>
22 #include <mono/metadata/opcodes.h>
23 #include <mono/metadata/mono-endian.h>
24 #include <mono/metadata/tokentype.h>
25 #include <mono/metadata/tabledefs.h>
26 #include <mono/metadata/threads.h>
27 #include <mono/metadata/marshal.h>
28 #include <mono/metadata/socket-io.h>
29 #include <mono/metadata/appdomain.h>
30 #include <mono/metadata/debug-helpers.h>
31 #include <mono/io-layer/io-layer.h>
32 #include "mono/metadata/profiler.h"
33 #include <mono/metadata/profiler-private.h>
34 #include <mono/metadata/mono-config.h>
35 #include <mono/metadata/environment.h>
36 #include <mono/metadata/mono-debug.h>
37 #include <mono/metadata/mono-debug-debugger.h>
46 static FILE *mini_stats_fd = NULL;
48 static void mini_usage (void);
50 typedef void (*OptFunc) (const char *p);
52 /* keep in sync with enum in mini.h */
61 {"peephole", "Peephole postpass"},
62 {"branch", "Branch optimizations"},
63 {"inline", "Inline method calls"},
64 {"cfold", "Constant folding"},
65 {"consprop", "Constant propagation"},
66 {"copyprop", "Copy propagation"},
67 {"deadce", "Dead code elimination"},
68 {"linears", "Linear scan global reg allocation"},
69 {"cmov", "Conditional moves"},
70 {"shared", "Emit per-domain code"},
71 {"sched", "Instruction scheduling"},
72 {"intrins", "Intrinsic method implementations"},
73 {"tailc", "Tail recursion and tail calls"},
74 {"loop", "Loop related optimizations"},
75 {"fcmov", "Fast x86 FP compares"},
76 {"leaf", "Leaf procedures optimizations"},
77 {"aot", "Usage of Ahead Of Time compiled code"},
78 {"precomp", "Precompile all methods before executing Main"}
81 #define DEFAULT_OPTIMIZATIONS ( \
90 parse_optimizations (const char* p)
92 /* the default value */
93 guint32 opt = DEFAULT_OPTIMIZATIONS;
98 /* call out to cpu detection code here that sets the defaults ... */
99 opt |= mono_arch_cpu_optimizazions (&exclude);
111 for (i = 0; i < G_N_ELEMENTS (opt_names); ++i) {
112 n = opt_names [i].name;
114 if (strncmp (p, n, len) == 0) {
123 } else if (*p == '=') {
125 if (opt_names [i].func)
126 opt_names [i].func (p);
127 while (*p && *p++ != ',');
134 if (i == G_N_ELEMENTS (opt_names)) {
135 if (strncmp (p, "all", 3) == 0) {
139 opt = ~(MONO_OPT_SHARED | MONO_OPT_PRECOMP | exclude);
144 fprintf (stderr, "Invalid optimization name `%s'\n", p);
155 MonoGraphOptions value;
158 static const GraphName
160 {"cfg", "Control Flow Graph (CFG)" , MONO_GRAPH_CFG},
161 {"dtree", "Dominator Tree", MONO_GRAPH_DTREE},
162 {"code", "CFG showing code", MONO_GRAPH_CFG_CODE},
163 {"ssa", "CFG showing code after SSA translation", MONO_GRAPH_CFG_SSA},
164 {"optcode", "CFG showing code after IR optimizations", MONO_GRAPH_CFG_OPTCODE}
167 static MonoGraphOptions
168 mono_parse_graph_options (const char* p)
173 for (i = 0; i < G_N_ELEMENTS (graph_names); ++i) {
174 n = graph_names [i].name;
176 if (strncmp (p, n, len) == 0)
177 return graph_names [i].value;
180 fprintf (stderr, "Invalid graph name provided: %s\n", p);
185 mono_parse_default_optimizations (const char* p)
189 opt = parse_optimizations (p);
194 opt_descr (guint32 flags) {
195 GString *str = g_string_new ("");
199 for (i = 0; i < G_N_ELEMENTS (opt_names); ++i) {
200 if (flags & (1 << i)) {
202 g_string_append_c (str, ',');
203 g_string_append (str, opt_names [i].name);
207 return g_string_free (str, FALSE);
217 MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_INTRINS,
218 MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS,
219 MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP,
220 MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_CFOLD,
221 MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP | MONO_OPT_DEADCE,
222 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
225 typedef int (*TestMethod) (void);
229 domain_dump_native_code (MonoDomain *domain) {
230 // need to poke into the domain, move to metadata/domain.c
231 // need to empty jit_info_table and code_mp
236 mini_regression (MonoImage *image, int verbose, int *total_run) {
237 guint32 i, opt, opt_flags;
241 int result, expected, failed, cfailed, run, code_size, total;
243 GTimer *timer = g_timer_new ();
246 fprintf (mini_stats_fd, "$stattitle = \'Mono Benchmark Results (various optimizations)\';\n");
248 fprintf (mini_stats_fd, "$graph->set_legend(qw(");
249 for (opt = 0; opt < G_N_ELEMENTS (opt_sets); opt++) {
250 opt_flags = opt_sets [opt];
251 n = opt_descr (opt_flags);
255 fprintf (mini_stats_fd, " ");
256 fprintf (mini_stats_fd, "%s", n);
260 fprintf (mini_stats_fd, "));\n");
262 fprintf (mini_stats_fd, "@data = (\n");
263 fprintf (mini_stats_fd, "[");
266 /* load the metadata */
267 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
268 method = mono_get_method (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL);
269 mono_class_init (method->klass);
271 if (!strncmp (method->name, "test_", 5) && mini_stats_fd) {
272 fprintf (mini_stats_fd, "\"%s\",", method->name);
276 fprintf (mini_stats_fd, "],\n");
281 for (opt = 0; opt < G_N_ELEMENTS (opt_sets); ++opt) {
282 double elapsed, comp_time, start_time;
285 opt_flags = opt_sets [opt];
286 mono_set_defaults (verbose, opt_flags);
287 n = opt_descr (opt_flags);
288 g_print ("Test run: image=%s, opts=%s\n", image->name, n);
290 cfailed = failed = run = code_size = 0;
291 comp_time = elapsed = 0.0;
293 /* fixme: ugly hack - delete all previously compiled methods */
294 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
295 method = mono_get_method (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL);
299 g_timer_start (timer);
301 fprintf (mini_stats_fd, "[");
302 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
303 method = mono_get_method (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL);
304 if (strncmp (method->name, "test_", 5) == 0) {
305 expected = atoi (method->name + 5);
307 start_time = g_timer_elapsed (timer, NULL);
308 comp_time -= start_time;
309 cfg = mini_method_compile (method, opt_flags, mono_root_domain, 0);
310 comp_time += g_timer_elapsed (timer, NULL);
313 g_print ("Running '%s' ...\n", method->name);
314 #ifdef MONO_USE_AOT_COMPILER
315 if ((jinfo = mono_aot_get_method (mono_root_domain, method)))
316 func = jinfo->code_start;
319 func = (TestMethod)cfg->native_code;
321 if (result != expected) {
324 g_print ("Test '%s' failed result (got %d, expected %d).\n", method->name, result, expected);
326 code_size += cfg->code_len;
327 mono_destroy_compile (cfg);
332 g_print ("Test '%s' failed compilation.\n", method->name);
335 fprintf (mini_stats_fd, "%f, ",
336 g_timer_elapsed (timer, NULL) - start_time);
340 fprintf (mini_stats_fd, "],\n");
341 g_timer_stop (timer);
342 elapsed = g_timer_elapsed (timer, NULL);
343 g_print ("Results: total tests: %d, failed: %d, cfailed: %d (pass: %.2f%%)\n",
344 run, failed, cfailed, 100.0*(run-failed-cfailed)/run);
345 g_print ("Elapsed time: %f secs (%f, %f), Code size: %d\n\n", elapsed,
346 elapsed - comp_time, comp_time, code_size);
347 total += failed + cfailed;
352 fprintf (mini_stats_fd, ");\n");
353 fflush (mini_stats_fd);
356 g_timer_destroy (timer);
361 mini_regression_list (int verbose, int count, char *images [])
363 int i, total, total_run, run;
366 total_run = total = 0;
367 for (i = 0; i < count; ++i) {
368 ass = mono_assembly_open (images [i], NULL);
370 g_warning ("failed to load assembly: %s", images [i]);
373 total += mini_regression (ass->image, verbose, &run);
375 mono_assembly_close (ass);
377 g_print ("Overall results: tests: %d, failed: %d, opt combinations: %d (pass: %.2f%%)\n",
378 total_run, total, G_N_ELEMENTS (opt_sets), 100.0*(total_run-total)/total_run);
390 typedef struct CompileAllThreadArgs {
393 } CompileAllThreadArgs;
396 compile_all_methods_thread_main (CompileAllThreadArgs *args)
398 MonoAssembly *ass = args->ass;
399 int verbose = args->verbose;
400 MonoImage *image = ass->image;
404 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
405 method = mono_get_method (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL);
406 if (method->flags & METHOD_ATTRIBUTE_ABSTRACT)
408 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
413 char * desc = mono_method_full_name (method, TRUE);
414 g_print ("Compiling %d %s\n", count, desc);
417 mono_compile_method (method);
423 compile_all_methods (MonoAssembly *ass, int verbose)
425 CompileAllThreadArgs args;
428 args.verbose = verbose;
431 * Need to create a mono thread since compilation might trigger
432 * running of managed code.
434 mono_thread_create (mono_domain_get (), compile_all_methods_thread_main, &args);
436 mono_thread_manage ();
441 * @assembly: reference to an assembly
442 * @argc: argument count
443 * @argv: argument vector
445 * Start execution of a program.
448 mono_jit_exec (MonoDomain *domain, MonoAssembly *assembly, int argc, char *argv[])
450 MonoImage *image = assembly->image;
452 guint32 entry = mono_image_get_entry_point (image);
455 g_print ("Assembly '%s' doesn't have an entry point.\n", image->name);
456 /* FIXME: remove this silly requirement. */
457 mono_environment_exitcode_set (1);
461 method = mono_get_method (image, entry, NULL);
463 return mono_runtime_run_main (method, argc, argv, NULL);
475 static void main_thread_handler (gpointer user_data)
477 MainThreadArgs *main_args = user_data;
478 MonoAssembly *assembly;
480 assembly = mono_domain_assembly_open (main_args->domain, main_args->file);
482 fprintf (stderr, "Can not open image %s\n", main_args->file);
486 if (mono_compile_aot) {
487 int res = mono_compile_assembly (assembly, main_args->opts);
488 printf ("AOT RESULT %d\n", res);
491 * This must be done in a thread managed by mono since it can invoke
494 if (main_args->opts & MONO_OPT_PRECOMP)
495 mono_precompile_assemblies ();
497 mono_jit_exec (main_args->domain, assembly, main_args->argc, main_args->argv);
507 "Usage is: mono [options] assembly\n\n"
508 "Runtime and JIT debugging:\n"
509 " --compile METHOD Just compile METHOD in assembly\n"
510 " --ncompile N Number of times to compile METHOD (default: 1)\n"
511 " --regression Runs the regression test contained in the assembly\n"
512 " --print-vtable Print the vtable of all used classes\n"
513 " --trace[=EXPR] Enable tracing, use --help-trace for details\n"
514 " --compile-all Compiles all the methods in the assembly\n"
515 " --breakonex Inserts a breakpoint on exceptions\n"
516 " --break METHOD Inserts a breakpoint at METHOD entry\n"
517 " --debug Enable debugging support\n"
518 " --stats Print statistics about the JIT operations\n"
521 " --statfile FILE Sets the stat file to FILE\n"
522 " --aot Compiles the assembly to native code\n"
523 " --profile[=profiler] Runs in profiling mode with the specified profiler module\n"
524 " --graph[=TYPE] METHOD Draws a graph of the specified method:\n");
526 for (i = 0; i < G_N_ELEMENTS (graph_names); ++i) {
527 fprintf (stderr, " %-10s %s\n", graph_names [i].name, graph_names [i].desc);
533 " --config FILE Loads FILE as the Mono config\n"
534 " --verbose, -v Increases the verbosity level\n"
535 " --help, -h Show usage information\n"
536 " --version, -V Show version information\n"
537 " --optimize=OPT Turns on a specific optimization:\n");
539 for (i = 0; i < G_N_ELEMENTS (opt_names); ++i)
540 fprintf (stderr, " %-10s %s\n", opt_names [i].name, opt_names [i].desc);
544 mini_trace_usage (void)
548 " --trace[=EXPR] Trace every call, optional EXPR controls the scope\n"
550 "EXPR is composed of:\n"
551 " all All assemblies\n"
552 " none No assemblies\n"
553 " program Entry point assembly\n"
554 " assembly Specifies an assembly\n"
555 " M:Type:Method Specifies a method\n"
556 " N:Namespace Specifies a namespace\n"
557 " T:Type Specifies a type\n"
558 " +EXPR Includes expression\n"
559 " -EXPR Excludes expression\n");
563 mono_main (int argc, char* argv[])
565 MainThreadArgs main_args;
566 MonoAssembly *assembly;
567 MonoMethodDesc *desc;
571 const char* aname, *mname = NULL;
572 char *config_file = NULL;
574 int enable_debugging = FALSE;
575 guint32 opt, action = DO_EXEC;
576 MonoGraphOptions mono_graph_options = 0;
577 int mini_verbose = 0;
578 char *trace_options = NULL;
580 setlocale (LC_ALL, "");
581 g_log_set_always_fatal (G_LOG_LEVEL_ERROR);
582 g_log_set_fatal_mask (G_LOG_DOMAIN, G_LOG_LEVEL_ERROR);
584 opt = parse_optimizations (NULL);
586 for (i = 1; i < argc; ++i) {
587 if (argv [i] [0] != '-')
589 if (strcmp (argv [i], "--regression") == 0) {
590 action = DO_REGRESSION;
591 } else if (strcmp (argv [i], "--verbose") == 0 || strcmp (argv [i], "-v") == 0) {
593 } else if (strcmp (argv [i], "--version") == 0 || strcmp (argv [i], "-V") == 0) {
594 g_print ("Mono JIT compiler version %s, (C) 2002, 2003 Ximian, Inc.\n", VERSION);
596 } else if (strcmp (argv [i], "--help") == 0 || strcmp (argv [i], "-h") == 0) {
599 } else if (strcmp (argv [i], "--help-trace") == 0){
602 } else if (strncmp (argv [i], "--statfile", 10) == 0) {
603 mini_stats_fd = fopen (argv [++i], "w+");
604 } else if (strncmp (argv [i], "--optimize=", 11) == 0) {
605 opt = parse_optimizations (argv [i] + 11);
606 } else if (strncmp (argv [i], "-O=", 3) == 0) {
607 opt = parse_optimizations (argv [i] + 3);
608 } else if (strcmp (argv [i], "--config") == 0) {
609 config_file = argv [++i];
610 } else if (strcmp (argv [i], "--ncompile") == 0) {
611 count = atoi (argv [++i]);
613 } else if (strcmp (argv [i], "--trace") == 0) {
615 } else if (strncmp (argv [i], "--trace=", 8) == 0) {
616 trace_options = &argv [i][8];
617 } else if (strcmp (argv [i], "--breakonex") == 0) {
618 mono_break_on_exc = TRUE;
619 } else if (strcmp (argv [i], "--break") == 0) {
620 if (!mono_debugger_insert_breakpoint (argv [++i], FALSE))
621 g_error ("Invalid method name '%s'", argv [i]);
622 } else if (strcmp (argv [i], "--print-vtable") == 0) {
623 mono_print_vtable = TRUE;
624 } else if (strcmp (argv [i], "--stats") == 0) {
625 mono_jit_stats.enabled = TRUE;
626 } else if (strcmp (argv [i], "--aot") == 0) {
627 mono_compile_aot = TRUE;
628 } else if (strcmp (argv [i], "--compile-all") == 0) {
630 } else if (strcmp (argv [i], "--profile") == 0) {
631 mono_profiler_load (NULL);
632 } else if (strncmp (argv [i], "--profile=", 10) == 0) {
633 mono_profiler_load (argv [i] + 10);
634 } else if (strcmp (argv [i], "--compile") == 0) {
637 } else if (strncmp (argv [i], "--graph=", 8) == 0) {
638 mono_graph_options = mono_parse_graph_options (argv [i] + 8);
641 } else if (strcmp (argv [i], "--graph") == 0) {
643 mono_graph_options = MONO_GRAPH_CFG;
645 } else if (strcmp (argv [i], "--debug") == 0) {
646 enable_debugging = TRUE;
648 fprintf (stderr, "Unknown command line option: '%s'\n", argv [i]);
658 if (mono_compile_aot || action == DO_EXEC) {
659 g_set_prgname (argv[i]);
662 mono_set_defaults (mini_verbose, opt);
663 domain = mini_init (argv [i]);
667 if (mini_regression_list (mini_verbose, argc -i, argv + i)) {
668 g_print ("Regression ERRORS!\n");
669 mini_cleanup (domain);
672 mini_cleanup (domain);
675 if (argc - i != 1 || mname == NULL) {
676 g_print ("Usage: mini --ncompile num --compile method assembly\n");
677 mini_cleanup (domain);
685 mini_cleanup (domain);
691 if (argc - i != 1 || mname == NULL) {
693 mini_cleanup (domain);
701 mini_cleanup (domain);
708 if (enable_debugging)
709 mono_debug_init (domain, MONO_DEBUG_FORMAT_MONO);
711 assembly = mono_assembly_open (aname, NULL);
713 fprintf (stderr, "cannot open assembly %s\n", aname);
714 mini_cleanup (domain);
718 if (trace_options != NULL){
719 mono_jit_trace_calls = mono_trace_parse_options (assembly, trace_options);
720 if (mono_jit_trace_calls == NULL)
724 if (enable_debugging)
725 mono_debug_init_2 (assembly);
727 if (mono_compile_aot || action == DO_EXEC) {
728 mono_config_parse (config_file);
729 //mono_set_rootdir ();
731 main_args.domain = domain;
732 main_args.file = aname;
733 main_args.argc = argc - i;
734 main_args.argv = argv + i;
735 main_args.opts = opt;
737 mono_runtime_exec_managed_code (domain, main_thread_handler, &main_args);
738 mini_cleanup (domain);
739 /* Look up return value from System.Environment.ExitCode */
740 i = mono_environment_exitcode_get ();
742 } else if (action == DO_COMPILE) {
743 compile_all_methods (assembly, mini_verbose);
744 mini_cleanup (domain);
747 desc = mono_method_desc_new (mname, 0);
749 g_print ("Invalid method name %s\n", mname);
750 mini_cleanup (domain);
753 method = mono_method_desc_search_in_image (desc, assembly->image);
755 g_print ("Cannot find method %s\n", mname);
756 mini_cleanup (domain);
760 if (action == DO_DRAW) {
763 switch (mono_graph_options) {
764 case MONO_GRAPH_DTREE:
766 opt |= MONO_OPT_LOOP;
768 case MONO_GRAPH_CFG_CODE:
771 case MONO_GRAPH_CFG_SSA:
774 case MONO_GRAPH_CFG_OPTCODE:
781 cfg = mini_method_compile (method, opt, mono_root_domain, part);
782 if ((mono_graph_options & MONO_GRAPH_CFG_SSA) && !(cfg->comp_done & MONO_COMP_SSA)) {
783 g_warning ("no SSA info available (use -O=deadce)");
786 mono_draw_graph (cfg, mono_graph_options);
787 mono_destroy_compile (cfg);
789 } else if (action == DO_BENCH) {
792 double no_opt_time = 0.0;
793 GTimer *timer = g_timer_new ();
794 fprintf (mini_stats_fd, "$stattitle = \'Compilations times for %s\';\n",
795 mono_method_full_name (method, TRUE));
796 fprintf (mini_stats_fd, "@data = (\n");
797 fprintf (mini_stats_fd, "[");
798 for (i = 0; i < G_N_ELEMENTS (opt_sets); i++) {
803 fprintf (mini_stats_fd, "\"%s\",", n);
805 fprintf (mini_stats_fd, "],\n[");
807 for (i = 0; i < G_N_ELEMENTS (opt_sets); i++) {
811 g_timer_start (timer);
812 for (j = 0; j < count; ++j) {
813 cfg = mini_method_compile (method, opt, mono_root_domain, 0);
814 mono_destroy_compile (cfg);
816 g_timer_stop (timer);
817 elapsed = g_timer_elapsed (timer, NULL);
819 no_opt_time = elapsed;
820 fprintf (mini_stats_fd, "%f, ", elapsed);
822 fprintf (mini_stats_fd, "]");
823 if (no_opt_time > 0.0) {
824 fprintf (mini_stats_fd, ", \n[");
825 for (i = 0; i < G_N_ELEMENTS (opt_sets); i++)
826 fprintf (mini_stats_fd, "%f,", no_opt_time);
827 fprintf (mini_stats_fd, "]");
829 fprintf (mini_stats_fd, ");\n");
831 for (i = 0; i < count; ++i) {
832 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
833 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
834 method = mono_marshal_get_native_wrapper (method);
836 cfg = mini_method_compile (method, opt, mono_root_domain, 0);
837 mono_destroy_compile (cfg);
841 cfg = mini_method_compile (method, opt, mono_root_domain, 0);
842 mono_destroy_compile (cfg);
845 mini_cleanup (domain);
850 mono_jit_init (const char *file)
852 return mini_init (file);
856 mono_jit_cleanup (MonoDomain *domain)
858 mini_cleanup (domain);