X86 JIT PIC jumptable support.
[oota-llvm.git] / lib / Target / X86 / X86JITInfo.cpp
1 //===-- X86JITInfo.cpp - Implement the JIT interfaces for the X86 target --===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the JIT interfaces for the X86 target.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "jit"
15 #include "X86JITInfo.h"
16 #include "X86Relocations.h"
17 #include "X86Subtarget.h"
18 #include "llvm/CodeGen/MachineCodeEmitter.h"
19 #include "llvm/Config/alloca.h"
20 #include <cstdlib>
21 using namespace llvm;
22
23 #ifdef _MSC_VER
24   extern "C" void *_AddressOfReturnAddress(void);
25   #pragma intrinsic(_AddressOfReturnAddress)
26 #endif
27
28 void X86JITInfo::replaceMachineCodeForFunction(void *Old, void *New) {
29   unsigned char *OldByte = (unsigned char *)Old;
30   *OldByte++ = 0xE9;                // Emit JMP opcode.
31   unsigned *OldWord = (unsigned *)OldByte;
32   unsigned NewAddr = (intptr_t)New;
33   unsigned OldAddr = (intptr_t)OldWord;
34   *OldWord = NewAddr - OldAddr - 4; // Emit PC-relative addr of New code.
35 }
36
37
38 /// JITCompilerFunction - This contains the address of the JIT function used to
39 /// compile a function lazily.
40 static TargetJITInfo::JITCompilerFn JITCompilerFunction;
41
42 // Get the ASMPREFIX for the current host.  This is often '_'.
43 #ifndef __USER_LABEL_PREFIX__
44 #define __USER_LABEL_PREFIX__
45 #endif
46 #define GETASMPREFIX2(X) #X
47 #define GETASMPREFIX(X) GETASMPREFIX2(X)
48 #define ASMPREFIX GETASMPREFIX(__USER_LABEL_PREFIX__)
49
50 // Provide a convenient way for disabling usage of CFI directives.
51 // This is needed for old/broken assemblers (for example, gas on
52 // Darwin is pretty old and doesn't support these directives)
53 #if defined(__APPLE__)
54 # define CFI(x)
55 #else
56 // FIXME: Disable this until we really want to use it. Also, we will
57 //        need to add some workarounds for compilers, which support
58 //        only subset of these directives.
59 # define CFI(x)
60 #endif
61
62 // Provide a wrapper for X86CompilationCallback2 that saves non-traditional
63 // callee saved registers, for the fastcc calling convention.
64 extern "C" {
65 #if defined(__x86_64__)
66   // No need to save EAX/EDX for X86-64.
67   void X86CompilationCallback(void);
68   asm(
69     ".text\n"
70     ".align 8\n"
71     ".globl " ASMPREFIX "X86CompilationCallback\n"
72   ASMPREFIX "X86CompilationCallback:\n"
73     CFI(".cfi_startproc\n")
74     // Save RBP
75     "pushq   %rbp\n"
76     CFI(".cfi_def_cfa_offset 16\n")
77     CFI(".cfi_offset %rbp, -16\n")
78     // Save RSP
79     "movq    %rsp, %rbp\n"
80     CFI(".cfi_def_cfa_register %rbp\n")
81     // Save all int arg registers
82     "pushq   %rdi\n"
83     CFI(".cfi_rel_offset %rdi, 0\n")
84     "pushq   %rsi\n"
85     CFI(".cfi_rel_offset %rsi, 8\n")
86     "pushq   %rdx\n"
87     CFI(".cfi_rel_offset %rdx, 16\n")
88     "pushq   %rcx\n"
89     CFI(".cfi_rel_offset %rcx, 24\n")
90     "pushq   %r8\n"
91     CFI(".cfi_rel_offset %r8, 32\n")
92     "pushq   %r9\n"
93     CFI(".cfi_rel_offset %r9, 40\n")
94     // Align stack on 16-byte boundary. ESP might not be properly aligned
95     // (8 byte) if this is called from an indirect stub.
96     "andq    $-16, %rsp\n"
97     // Save all XMM arg registers
98     "subq    $128, %rsp\n"
99     "movaps  %xmm0, (%rsp)\n"
100     "movaps  %xmm1, 16(%rsp)\n"
101     "movaps  %xmm2, 32(%rsp)\n"
102     "movaps  %xmm3, 48(%rsp)\n"
103     "movaps  %xmm4, 64(%rsp)\n"
104     "movaps  %xmm5, 80(%rsp)\n"
105     "movaps  %xmm6, 96(%rsp)\n"
106     "movaps  %xmm7, 112(%rsp)\n"
107     // JIT callee
108     "movq    %rbp, %rdi\n"    // Pass prev frame and return address
109     "movq    8(%rbp), %rsi\n"
110     "call    " ASMPREFIX "X86CompilationCallback2\n"
111     // Restore all XMM arg registers
112     "movaps  112(%rsp), %xmm7\n"
113     "movaps  96(%rsp), %xmm6\n"
114     "movaps  80(%rsp), %xmm5\n"
115     "movaps  64(%rsp), %xmm4\n"
116     "movaps  48(%rsp), %xmm3\n"
117     "movaps  32(%rsp), %xmm2\n"
118     "movaps  16(%rsp), %xmm1\n"
119     "movaps  (%rsp), %xmm0\n"
120     // Restore RSP
121     "movq    %rbp, %rsp\n"
122     CFI(".cfi_def_cfa_register %rsp\n")
123     // Restore all int arg registers
124     "subq    $48, %rsp\n"
125     CFI(".cfi_adjust_cfa_offset 48\n")
126     "popq    %r9\n"
127     CFI(".cfi_adjust_cfa_offset -8\n")
128     CFI(".cfi_restore %r9\n")
129     "popq    %r8\n"
130     CFI(".cfi_adjust_cfa_offset -8\n")
131     CFI(".cfi_restore %r8\n")
132     "popq    %rcx\n"
133     CFI(".cfi_adjust_cfa_offset -8\n")
134     CFI(".cfi_restore %rcx\n")
135     "popq    %rdx\n"
136     CFI(".cfi_adjust_cfa_offset -8\n")
137     CFI(".cfi_restore %rdx\n")
138     "popq    %rsi\n"
139     CFI(".cfi_adjust_cfa_offset -8\n")
140     CFI(".cfi_restore %rsi\n")
141     "popq    %rdi\n"
142     CFI(".cfi_adjust_cfa_offset -8\n")
143     CFI(".cfi_restore %rdi\n")
144     // Restore RBP
145     "popq    %rbp\n"
146     CFI(".cfi_adjust_cfa_offset -8\n")
147     CFI(".cfi_restore %rbp\n")
148     "ret\n"
149     CFI(".cfi_endproc\n")
150   );
151 #elif defined(__i386__) || defined(i386) || defined(_M_IX86)
152 #ifndef _MSC_VER
153   void X86CompilationCallback(void);
154   asm(
155     ".text\n"
156     ".align 8\n"
157     ".globl " ASMPREFIX  "X86CompilationCallback\n"
158   ASMPREFIX "X86CompilationCallback:\n"
159     CFI(".cfi_startproc\n")
160     "pushl   %ebp\n"
161     CFI(".cfi_def_cfa_offset 8\n")
162     CFI(".cfi_offset %ebp, -8\n")
163     "movl    %esp, %ebp\n"    // Standard prologue
164     CFI(".cfi_def_cfa_register %ebp\n")
165     "pushl   %eax\n"
166     CFI(".cfi_rel_offset %eax, 0\n")
167     "pushl   %edx\n"          // Save EAX/EDX/ECX
168     CFI(".cfi_rel_offset %edx, 4\n")
169     "pushl   %ecx\n"
170     CFI(".cfi_rel_offset %ecx, 8\n")
171 #if defined(__APPLE__)
172     "andl    $-16, %esp\n"    // Align ESP on 16-byte boundary
173 #endif
174     "subl    $16, %esp\n"
175     "movl    4(%ebp), %eax\n" // Pass prev frame and return address
176     "movl    %eax, 4(%esp)\n"
177     "movl    %ebp, (%esp)\n"
178     "call    " ASMPREFIX "X86CompilationCallback2\n"
179     "movl    %ebp, %esp\n"    // Restore ESP
180     CFI(".cfi_def_cfa_register %esp\n")
181     "subl    $12, %esp\n"
182     CFI(".cfi_adjust_cfa_offset 12\n")
183     "popl    %ecx\n"
184     CFI(".cfi_adjust_cfa_offset -4\n")
185     CFI(".cfi_restore %ecx\n")
186     "popl    %edx\n"
187     CFI(".cfi_adjust_cfa_offset -4\n")
188     CFI(".cfi_restore %edx\n")
189     "popl    %eax\n"
190     CFI(".cfi_adjust_cfa_offset -4\n")
191     CFI(".cfi_restore %eax\n")
192     "popl    %ebp\n"
193     CFI(".cfi_adjust_cfa_offset -4\n")
194     CFI(".cfi_restore %ebp\n")
195     "ret\n"
196     CFI(".cfi_endproc\n")
197   );
198
199   // Same as X86CompilationCallback but also saves XMM argument registers.
200   void X86CompilationCallback_SSE(void);
201   asm(
202     ".text\n"
203     ".align 8\n"
204     ".globl " ASMPREFIX  "X86CompilationCallback_SSE\n"
205   ASMPREFIX "X86CompilationCallback_SSE:\n"
206     CFI(".cfi_startproc\n")
207     "pushl   %ebp\n"
208     CFI(".cfi_def_cfa_offset 8\n")
209     CFI(".cfi_offset %ebp, -8\n")
210     "movl    %esp, %ebp\n"    // Standard prologue
211     CFI(".cfi_def_cfa_register %ebp\n")
212     "pushl   %eax\n"
213     CFI(".cfi_rel_offset %eax, 0\n")
214     "pushl   %edx\n"          // Save EAX/EDX/ECX
215     CFI(".cfi_rel_offset %edx, 4\n")
216     "pushl   %ecx\n"
217     CFI(".cfi_rel_offset %ecx, 8\n")
218     "andl    $-16, %esp\n"    // Align ESP on 16-byte boundary
219     // Save all XMM arg registers
220     "subl    $64, %esp\n"
221     // FIXME: provide frame move information for xmm registers.
222     // This can be tricky, because CFA register is ebp (unaligned)
223     // and we need to produce offsets relative to it.
224     "movaps  %xmm0, (%esp)\n"
225     "movaps  %xmm1, 16(%esp)\n"
226     "movaps  %xmm2, 32(%esp)\n"
227     "movaps  %xmm3, 48(%esp)\n"
228     "subl    $16, %esp\n"
229     "movl    4(%ebp), %eax\n" // Pass prev frame and return address
230     "movl    %eax, 4(%esp)\n"
231     "movl    %ebp, (%esp)\n"
232     "call    " ASMPREFIX "X86CompilationCallback2\n"
233     "addl    $16, %esp\n"
234     "movaps  48(%esp), %xmm3\n"
235     CFI(".cfi_restore %xmm3\n")
236     "movaps  32(%esp), %xmm2\n"
237     CFI(".cfi_restore %xmm2\n")
238     "movaps  16(%esp), %xmm1\n"
239     CFI(".cfi_restore %xmm1\n")
240     "movaps  (%esp), %xmm0\n"
241     CFI(".cfi_restore %xmm0\n")
242     "movl    %ebp, %esp\n"    // Restore ESP
243     CFI(".cfi_def_cfa_register esp\n")
244     "subl    $12, %esp\n"
245     CFI(".cfi_adjust_cfa_offset 12\n")
246     "popl    %ecx\n"
247     CFI(".cfi_adjust_cfa_offset -4\n")
248     CFI(".cfi_restore %ecx\n")
249     "popl    %edx\n"
250     CFI(".cfi_adjust_cfa_offset -4\n")
251     CFI(".cfi_restore %edx\n")
252     "popl    %eax\n"
253     CFI(".cfi_adjust_cfa_offset -4\n")
254     CFI(".cfi_restore %eax\n")
255     "popl    %ebp\n"
256     CFI(".cfi_adjust_cfa_offset -4\n")
257     CFI(".cfi_restore %ebp\n")
258     "ret\n"
259     CFI(".cfi_endproc\n")
260   );
261 #else
262   void X86CompilationCallback2(void);
263
264   _declspec(naked) void X86CompilationCallback(void) {
265     __asm {
266       push  eax
267       push  edx
268       push  ecx
269       call  X86CompilationCallback2
270       pop   ecx
271       pop   edx
272       pop   eax
273       ret
274     }
275   }
276 #endif // _MSC_VER
277
278 #else // Not an i386 host
279   void X86CompilationCallback() {
280     assert(0 && "Cannot call X86CompilationCallback() on a non-x86 arch!\n");
281     abort();
282   }
283 #endif
284 }
285
286 /// X86CompilationCallback - This is the target-specific function invoked by the
287 /// function stub when we did not know the real target of a call.  This function
288 /// must locate the start of the stub or call site and pass it into the JIT
289 /// compiler function.
290 #ifdef _MSC_VER
291 extern "C" void X86CompilationCallback2() {
292   assert(sizeof(size_t) == 4); // FIXME: handle Win64
293   intptr_t *RetAddrLoc = (intptr_t *)_AddressOfReturnAddress();
294   RetAddrLoc += 4;  // skip over ret addr, edx, eax, ecx
295   intptr_t RetAddr = *RetAddrLoc;
296 #else
297 extern "C" void X86CompilationCallback2(intptr_t *StackPtr, intptr_t RetAddr) {
298   intptr_t *RetAddrLoc = &StackPtr[1];
299 #endif
300   assert(*RetAddrLoc == RetAddr &&
301          "Could not find return address on the stack!");
302
303   // It's a stub if there is an interrupt marker after the call.
304   bool isStub = ((unsigned char*)RetAddr)[0] == 0xCD;
305
306   // The call instruction should have pushed the return value onto the stack...
307 #ifdef __x86_64__
308   RetAddr--;     // Backtrack to the reference itself...
309 #else
310   RetAddr -= 4;  // Backtrack to the reference itself...
311 #endif
312
313 #if 0
314   DOUT << "In callback! Addr=" << (void*)RetAddr
315        << " ESP=" << (void*)StackPtr
316        << ": Resolving call to function: "
317        << TheVM->getFunctionReferencedName((void*)RetAddr) << "\n";
318 #endif
319
320   // Sanity check to make sure this really is a call instruction.
321 #ifdef __x86_64__
322   assert(((unsigned char*)RetAddr)[-2] == 0x41 &&"Not a call instr!");
323   assert(((unsigned char*)RetAddr)[-1] == 0xFF &&"Not a call instr!");
324 #else
325   assert(((unsigned char*)RetAddr)[-1] == 0xE8 &&"Not a call instr!");
326 #endif
327
328   intptr_t NewVal = (intptr_t)JITCompilerFunction((void*)RetAddr);
329
330   // Rewrite the call target... so that we don't end up here every time we
331   // execute the call.
332 #ifdef __x86_64__
333   *(intptr_t *)(RetAddr - 0xa) = NewVal;
334 #else
335   *(intptr_t *)RetAddr = (intptr_t)(NewVal-RetAddr-4);
336 #endif
337
338   if (isStub) {
339     // If this is a stub, rewrite the call into an unconditional branch
340     // instruction so that two return addresses are not pushed onto the stack
341     // when the requested function finally gets called.  This also makes the
342     // 0xCD byte (interrupt) dead, so the marker doesn't effect anything.
343 #ifdef __x86_64__
344     ((unsigned char*)RetAddr)[0] = (2 | (4 << 3) | (3 << 6));
345 #else
346     ((unsigned char*)RetAddr)[-1] = 0xE9;
347 #endif
348   }
349
350   // Change the return address to reexecute the call instruction...
351 #ifdef __x86_64__
352   *RetAddrLoc -= 0xd;
353 #else
354   *RetAddrLoc -= 5;
355 #endif
356 }
357
358 TargetJITInfo::LazyResolverFn
359 X86JITInfo::getLazyResolverFunction(JITCompilerFn F) {
360   JITCompilerFunction = F;
361
362 #if (defined(__i386__) || defined(i386) || defined(_M_IX86)) && \
363   !defined(_MSC_VER) && !defined(__x86_64__)
364   unsigned EAX = 0, EBX = 0, ECX = 0, EDX = 0;
365   union {
366     unsigned u[3];
367     char     c[12];
368   } text;
369
370   if (!X86::GetCpuIDAndInfo(0, &EAX, text.u+0, text.u+2, text.u+1)) {
371     // FIXME: support for AMD family of processors.
372     if (memcmp(text.c, "GenuineIntel", 12) == 0) {
373       X86::GetCpuIDAndInfo(0x1, &EAX, &EBX, &ECX, &EDX);
374       if ((EDX >> 25) & 0x1)
375         return X86CompilationCallback_SSE;
376     }
377   }
378 #endif
379
380   return X86CompilationCallback;
381 }
382
383 void *X86JITInfo::emitGlobalValueLazyPtr(void *GV, MachineCodeEmitter &MCE) {
384 #ifdef __x86_64__
385   MCE.startFunctionStub(8, 8);
386   MCE.emitWordLE(((unsigned *)&GV)[0]);
387   MCE.emitWordLE(((unsigned *)&GV)[1]);
388 #else
389   MCE.startFunctionStub(4, 4);
390   MCE.emitWordLE((unsigned)GV);
391 #endif
392   return MCE.finishFunctionStub(0);
393 }
394
395 void *X86JITInfo::emitFunctionStub(void *Fn, MachineCodeEmitter &MCE) {
396   // Note, we cast to intptr_t here to silence a -pedantic warning that 
397   // complains about casting a function pointer to a normal pointer.
398 #if (defined(__i386__) || defined(i386) || defined(_M_IX86)) && \
399   !defined(_MSC_VER) && !defined(__x86_64__)
400   bool NotCC = (Fn != (void*)(intptr_t)X86CompilationCallback &&
401                 Fn != (void*)(intptr_t)X86CompilationCallback_SSE);
402 #else
403   bool NotCC = Fn != (void*)(intptr_t)X86CompilationCallback;
404 #endif
405   if (NotCC) {
406 #ifdef __x86_64__
407     MCE.startFunctionStub(13, 4);
408     MCE.emitByte(0x49);          // REX prefix
409     MCE.emitByte(0xB8+2);        // movabsq r10
410     MCE.emitWordLE(((unsigned *)&Fn)[0]);
411     MCE.emitWordLE(((unsigned *)&Fn)[1]);
412     MCE.emitByte(0x41);          // REX prefix
413     MCE.emitByte(0xFF);          // jmpq *r10
414     MCE.emitByte(2 | (4 << 3) | (3 << 6));
415 #else
416     MCE.startFunctionStub(5, 4);
417     MCE.emitByte(0xE9);
418     MCE.emitWordLE((intptr_t)Fn-MCE.getCurrentPCValue()-4);
419 #endif
420     return MCE.finishFunctionStub(0);
421   }
422
423 #ifdef __x86_64__
424   MCE.startFunctionStub(14, 4);
425   MCE.emitByte(0x49);          // REX prefix
426   MCE.emitByte(0xB8+2);        // movabsq r10
427   MCE.emitWordLE(((unsigned *)&Fn)[0]);
428   MCE.emitWordLE(((unsigned *)&Fn)[1]);
429   MCE.emitByte(0x41);          // REX prefix
430   MCE.emitByte(0xFF);          // callq *r10
431   MCE.emitByte(2 | (2 << 3) | (3 << 6));
432 #else
433   MCE.startFunctionStub(6, 4);
434   MCE.emitByte(0xE8);   // Call with 32 bit pc-rel destination...
435
436   MCE.emitWordLE((intptr_t)Fn-MCE.getCurrentPCValue()-4);
437 #endif
438
439   MCE.emitByte(0xCD);   // Interrupt - Just a marker identifying the stub!
440   return MCE.finishFunctionStub(0);
441 }
442
443 /// getPICJumpTableEntry - Returns the value of the jumptable entry for the
444 /// specific basic block.
445 intptr_t X86JITInfo::getPICJumpTableEntry(intptr_t BB, intptr_t Entry) {
446   return BB - PICBase;
447 }
448
449 /// relocate - Before the JIT can run a block of code that has been emitted,
450 /// it must rewrite the code to contain the actual addresses of any
451 /// referenced global symbols.
452 void X86JITInfo::relocate(void *Function, MachineRelocation *MR,
453                           unsigned NumRelocs, unsigned char* GOTBase) {
454   for (unsigned i = 0; i != NumRelocs; ++i, ++MR) {
455     void *RelocPos = (char*)Function + MR->getMachineCodeOffset();
456     intptr_t ResultPtr = (intptr_t)MR->getResultPointer();
457     switch ((X86::RelocationType)MR->getRelocationType()) {
458     case X86::reloc_pcrel_word: {
459       // PC relative relocation, add the relocated value to the value already in
460       // memory, after we adjust it for where the PC is.
461       ResultPtr = ResultPtr -(intptr_t)RelocPos - 4 - MR->getConstantVal();
462       *((unsigned*)RelocPos) += (unsigned)ResultPtr;
463       break;
464     }
465     case X86::reloc_picrel_word: {
466       // PIC base relative relocation, add the relocated value to the value
467       // already in memory, after we adjust it for where the PIC base is.
468       ResultPtr = ResultPtr - ((intptr_t)Function + MR->getConstantVal());
469       *((unsigned*)RelocPos) += (unsigned)ResultPtr;
470       break;
471     }
472     case X86::reloc_absolute_word:
473       // Absolute relocation, just add the relocated value to the value already
474       // in memory.
475       *((unsigned*)RelocPos) += (unsigned)ResultPtr;
476       break;
477     case X86::reloc_absolute_dword:
478       *((intptr_t*)RelocPos) += ResultPtr;
479       break;
480     }
481   }
482 }