2005-01-31 Zoltan Varga <vargaz@freemail.hu>
[mono.git] / docs / jit-trampolines
1 Author: Dietmar Maurer (dietmar@ximian.com)
2 (C) 2001 Ximian, Inc.
3  
4 Howto trigger JIT compilation
5 =============================
6
7 The JIT translates CIL code to native code on a per method basis. For example
8 if you have this simple program:
9
10 public class Test {
11         public static void Main () {            
12                 System.Console.WriteLine ("Hello");
13         }
14 }
15
16 the JIT first compiles the Main function. Unfortunately Main() contains another
17 reference to System.Console.WriteLine(), so the JIT also needs the address for
18 WriteLine() to generate a call instruction.
19
20 The simplest solution would be to JIT compile System.Console.WriteLine()
21 to generate that address. But that would mean that we JIT compile half of our
22 class library at once, since WriteLine() uses many other classes and function,
23 and we have to call the JIT for each of them. Even worse there is the
24 possibility of cyclic references, and we would end up in an endless loop.
25
26 Thus we need some kind of trampoline function for JIT compilation. Such a
27 trampoline first calls the JIT compiler to create native code, and then jumps
28 directly into that code. Whenever the JIT needs the address of a function (to
29 emit a call instruction) it uses the address of those trampoline functions.
30
31 One drawback of this approach is that it requires an additional indirection. We
32 always call the trampoline. Inside the trampoline we need to check if the
33 method is already compiled or not, and when not compiled we start JIT
34 compilation. After that we call the code. This process is quite time consuming
35 and shows very bad performance.
36
37 The solution is to add some logic to the trampoline function to detect from
38 where it is called. It is then possible for the JIT to patch the call
39 instruction in the caller, so that it directly calls the JIT compiled code
40 next time.
41
42 Implementation for x86
43 ======================
44
45 emit-x86.c (arch_create_jit_trampoline): return the JIT trampoline function
46
47 emit-x86.c (x86_magic_trampoline): contains the code to detect the caller and
48 patch the call instruction.
49
50 emit-x86.c (arch_compile_method): JIT compile a method
51
52