Fixed some bugs in register stack pass.
[llvm/zpu.git] / lib / Target / X86 / X86JITInfo.cpp
blobe83f3595852a443c17e095acb1cfc0b0e18fa0f2
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.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "jit"
15 #include "X86JITInfo.h"
16 #include "X86Relocations.h"
17 #include "X86Subtarget.h"
18 #include "X86TargetMachine.h"
19 #include "llvm/Function.h"
20 #include "llvm/Support/Compiler.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/System/Valgrind.h"
23 #include <cstdlib>
24 #include <cstring>
25 using namespace llvm;
27 // Determine the platform we're running on
28 #if defined (__x86_64__) || defined (_M_AMD64) || defined (_M_X64)
29 # define X86_64_JIT
30 #elif defined(__i386__) || defined(i386) || defined(_M_IX86)
31 # define X86_32_JIT
32 #endif
34 void X86JITInfo::replaceMachineCodeForFunction(void *Old, void *New) {
35 unsigned char *OldByte = (unsigned char *)Old;
36 *OldByte++ = 0xE9; // Emit JMP opcode.
37 unsigned *OldWord = (unsigned *)OldByte;
38 unsigned NewAddr = (intptr_t)New;
39 unsigned OldAddr = (intptr_t)OldWord;
40 *OldWord = NewAddr - OldAddr - 4; // Emit PC-relative addr of New code.
42 // X86 doesn't need to invalidate the processor cache, so just invalidate
43 // Valgrind's cache directly.
44 sys::ValgrindDiscardTranslations(Old, 5);
48 /// JITCompilerFunction - This contains the address of the JIT function used to
49 /// compile a function lazily.
50 static TargetJITInfo::JITCompilerFn JITCompilerFunction;
52 // Get the ASMPREFIX for the current host. This is often '_'.
53 #ifndef __USER_LABEL_PREFIX__
54 #define __USER_LABEL_PREFIX__
55 #endif
56 #define GETASMPREFIX2(X) #X
57 #define GETASMPREFIX(X) GETASMPREFIX2(X)
58 #define ASMPREFIX GETASMPREFIX(__USER_LABEL_PREFIX__)
60 // For ELF targets, use a .size and .type directive, to let tools
61 // know the extent of functions defined in assembler.
62 #if defined(__ELF__)
63 # define SIZE(sym) ".size " #sym ", . - " #sym "\n"
64 # define TYPE_FUNCTION(sym) ".type " #sym ", @function\n"
65 #else
66 # define SIZE(sym)
67 # define TYPE_FUNCTION(sym)
68 #endif
70 // Provide a convenient way for disabling usage of CFI directives.
71 // This is needed for old/broken assemblers (for example, gas on
72 // Darwin is pretty old and doesn't support these directives)
73 #if defined(__APPLE__)
74 # define CFI(x)
75 #else
76 // FIXME: Disable this until we really want to use it. Also, we will
77 // need to add some workarounds for compilers, which support
78 // only subset of these directives.
79 # define CFI(x)
80 #endif
82 // Provide a wrapper for X86CompilationCallback2 that saves non-traditional
83 // callee saved registers, for the fastcc calling convention.
84 extern "C" {
85 #if defined(X86_64_JIT)
86 # ifndef _MSC_VER
87 // No need to save EAX/EDX for X86-64.
88 void X86CompilationCallback(void);
89 asm(
90 ".text\n"
91 ".align 8\n"
92 ".globl " ASMPREFIX "X86CompilationCallback\n"
93 TYPE_FUNCTION(X86CompilationCallback)
94 ASMPREFIX "X86CompilationCallback:\n"
95 CFI(".cfi_startproc\n")
96 // Save RBP
97 "pushq %rbp\n"
98 CFI(".cfi_def_cfa_offset 16\n")
99 CFI(".cfi_offset %rbp, -16\n")
100 // Save RSP
101 "movq %rsp, %rbp\n"
102 CFI(".cfi_def_cfa_register %rbp\n")
103 // Save all int arg registers
104 "pushq %rdi\n"
105 CFI(".cfi_rel_offset %rdi, 0\n")
106 "pushq %rsi\n"
107 CFI(".cfi_rel_offset %rsi, 8\n")
108 "pushq %rdx\n"
109 CFI(".cfi_rel_offset %rdx, 16\n")
110 "pushq %rcx\n"
111 CFI(".cfi_rel_offset %rcx, 24\n")
112 "pushq %r8\n"
113 CFI(".cfi_rel_offset %r8, 32\n")
114 "pushq %r9\n"
115 CFI(".cfi_rel_offset %r9, 40\n")
116 // Align stack on 16-byte boundary. ESP might not be properly aligned
117 // (8 byte) if this is called from an indirect stub.
118 "andq $-16, %rsp\n"
119 // Save all XMM arg registers
120 "subq $128, %rsp\n"
121 "movaps %xmm0, (%rsp)\n"
122 "movaps %xmm1, 16(%rsp)\n"
123 "movaps %xmm2, 32(%rsp)\n"
124 "movaps %xmm3, 48(%rsp)\n"
125 "movaps %xmm4, 64(%rsp)\n"
126 "movaps %xmm5, 80(%rsp)\n"
127 "movaps %xmm6, 96(%rsp)\n"
128 "movaps %xmm7, 112(%rsp)\n"
129 // JIT callee
130 "movq %rbp, %rdi\n" // Pass prev frame and return address
131 "movq 8(%rbp), %rsi\n"
132 "call " ASMPREFIX "X86CompilationCallback2\n"
133 // Restore all XMM arg registers
134 "movaps 112(%rsp), %xmm7\n"
135 "movaps 96(%rsp), %xmm6\n"
136 "movaps 80(%rsp), %xmm5\n"
137 "movaps 64(%rsp), %xmm4\n"
138 "movaps 48(%rsp), %xmm3\n"
139 "movaps 32(%rsp), %xmm2\n"
140 "movaps 16(%rsp), %xmm1\n"
141 "movaps (%rsp), %xmm0\n"
142 // Restore RSP
143 "movq %rbp, %rsp\n"
144 CFI(".cfi_def_cfa_register %rsp\n")
145 // Restore all int arg registers
146 "subq $48, %rsp\n"
147 CFI(".cfi_adjust_cfa_offset 48\n")
148 "popq %r9\n"
149 CFI(".cfi_adjust_cfa_offset -8\n")
150 CFI(".cfi_restore %r9\n")
151 "popq %r8\n"
152 CFI(".cfi_adjust_cfa_offset -8\n")
153 CFI(".cfi_restore %r8\n")
154 "popq %rcx\n"
155 CFI(".cfi_adjust_cfa_offset -8\n")
156 CFI(".cfi_restore %rcx\n")
157 "popq %rdx\n"
158 CFI(".cfi_adjust_cfa_offset -8\n")
159 CFI(".cfi_restore %rdx\n")
160 "popq %rsi\n"
161 CFI(".cfi_adjust_cfa_offset -8\n")
162 CFI(".cfi_restore %rsi\n")
163 "popq %rdi\n"
164 CFI(".cfi_adjust_cfa_offset -8\n")
165 CFI(".cfi_restore %rdi\n")
166 // Restore RBP
167 "popq %rbp\n"
168 CFI(".cfi_adjust_cfa_offset -8\n")
169 CFI(".cfi_restore %rbp\n")
170 "ret\n"
171 CFI(".cfi_endproc\n")
172 SIZE(X86CompilationCallback)
174 # else
175 // No inline assembler support on this platform. The routine is in external
176 // file.
177 void X86CompilationCallback();
179 # endif
180 #elif defined (X86_32_JIT)
181 # ifndef _MSC_VER
182 void X86CompilationCallback(void);
183 asm(
184 ".text\n"
185 ".align 8\n"
186 ".globl " ASMPREFIX "X86CompilationCallback\n"
187 TYPE_FUNCTION(X86CompilationCallback)
188 ASMPREFIX "X86CompilationCallback:\n"
189 CFI(".cfi_startproc\n")
190 "pushl %ebp\n"
191 CFI(".cfi_def_cfa_offset 8\n")
192 CFI(".cfi_offset %ebp, -8\n")
193 "movl %esp, %ebp\n" // Standard prologue
194 CFI(".cfi_def_cfa_register %ebp\n")
195 "pushl %eax\n"
196 CFI(".cfi_rel_offset %eax, 0\n")
197 "pushl %edx\n" // Save EAX/EDX/ECX
198 CFI(".cfi_rel_offset %edx, 4\n")
199 "pushl %ecx\n"
200 CFI(".cfi_rel_offset %ecx, 8\n")
201 # if defined(__APPLE__)
202 "andl $-16, %esp\n" // Align ESP on 16-byte boundary
203 # endif
204 "subl $16, %esp\n"
205 "movl 4(%ebp), %eax\n" // Pass prev frame and return address
206 "movl %eax, 4(%esp)\n"
207 "movl %ebp, (%esp)\n"
208 "call " ASMPREFIX "X86CompilationCallback2\n"
209 "movl %ebp, %esp\n" // Restore ESP
210 CFI(".cfi_def_cfa_register %esp\n")
211 "subl $12, %esp\n"
212 CFI(".cfi_adjust_cfa_offset 12\n")
213 "popl %ecx\n"
214 CFI(".cfi_adjust_cfa_offset -4\n")
215 CFI(".cfi_restore %ecx\n")
216 "popl %edx\n"
217 CFI(".cfi_adjust_cfa_offset -4\n")
218 CFI(".cfi_restore %edx\n")
219 "popl %eax\n"
220 CFI(".cfi_adjust_cfa_offset -4\n")
221 CFI(".cfi_restore %eax\n")
222 "popl %ebp\n"
223 CFI(".cfi_adjust_cfa_offset -4\n")
224 CFI(".cfi_restore %ebp\n")
225 "ret\n"
226 CFI(".cfi_endproc\n")
227 SIZE(X86CompilationCallback)
230 // Same as X86CompilationCallback but also saves XMM argument registers.
231 void X86CompilationCallback_SSE(void);
232 asm(
233 ".text\n"
234 ".align 8\n"
235 ".globl " ASMPREFIX "X86CompilationCallback_SSE\n"
236 TYPE_FUNCTION(X86CompilationCallback_SSE)
237 ASMPREFIX "X86CompilationCallback_SSE:\n"
238 CFI(".cfi_startproc\n")
239 "pushl %ebp\n"
240 CFI(".cfi_def_cfa_offset 8\n")
241 CFI(".cfi_offset %ebp, -8\n")
242 "movl %esp, %ebp\n" // Standard prologue
243 CFI(".cfi_def_cfa_register %ebp\n")
244 "pushl %eax\n"
245 CFI(".cfi_rel_offset %eax, 0\n")
246 "pushl %edx\n" // Save EAX/EDX/ECX
247 CFI(".cfi_rel_offset %edx, 4\n")
248 "pushl %ecx\n"
249 CFI(".cfi_rel_offset %ecx, 8\n")
250 "andl $-16, %esp\n" // Align ESP on 16-byte boundary
251 // Save all XMM arg registers
252 "subl $64, %esp\n"
253 // FIXME: provide frame move information for xmm registers.
254 // This can be tricky, because CFA register is ebp (unaligned)
255 // and we need to produce offsets relative to it.
256 "movaps %xmm0, (%esp)\n"
257 "movaps %xmm1, 16(%esp)\n"
258 "movaps %xmm2, 32(%esp)\n"
259 "movaps %xmm3, 48(%esp)\n"
260 "subl $16, %esp\n"
261 "movl 4(%ebp), %eax\n" // Pass prev frame and return address
262 "movl %eax, 4(%esp)\n"
263 "movl %ebp, (%esp)\n"
264 "call " ASMPREFIX "X86CompilationCallback2\n"
265 "addl $16, %esp\n"
266 "movaps 48(%esp), %xmm3\n"
267 CFI(".cfi_restore %xmm3\n")
268 "movaps 32(%esp), %xmm2\n"
269 CFI(".cfi_restore %xmm2\n")
270 "movaps 16(%esp), %xmm1\n"
271 CFI(".cfi_restore %xmm1\n")
272 "movaps (%esp), %xmm0\n"
273 CFI(".cfi_restore %xmm0\n")
274 "movl %ebp, %esp\n" // Restore ESP
275 CFI(".cfi_def_cfa_register esp\n")
276 "subl $12, %esp\n"
277 CFI(".cfi_adjust_cfa_offset 12\n")
278 "popl %ecx\n"
279 CFI(".cfi_adjust_cfa_offset -4\n")
280 CFI(".cfi_restore %ecx\n")
281 "popl %edx\n"
282 CFI(".cfi_adjust_cfa_offset -4\n")
283 CFI(".cfi_restore %edx\n")
284 "popl %eax\n"
285 CFI(".cfi_adjust_cfa_offset -4\n")
286 CFI(".cfi_restore %eax\n")
287 "popl %ebp\n"
288 CFI(".cfi_adjust_cfa_offset -4\n")
289 CFI(".cfi_restore %ebp\n")
290 "ret\n"
291 CFI(".cfi_endproc\n")
292 SIZE(X86CompilationCallback_SSE)
294 # else
295 void X86CompilationCallback2(intptr_t *StackPtr, intptr_t RetAddr);
297 _declspec(naked) void X86CompilationCallback(void) {
298 __asm {
299 push ebp
300 mov ebp, esp
301 push eax
302 push edx
303 push ecx
304 and esp, -16
305 sub esp, 16
306 mov eax, dword ptr [ebp+4]
307 mov dword ptr [esp+4], eax
308 mov dword ptr [esp], ebp
309 call X86CompilationCallback2
310 mov esp, ebp
311 sub esp, 12
312 pop ecx
313 pop edx
314 pop eax
315 pop ebp
320 # endif // _MSC_VER
322 #else // Not an i386 host
323 void X86CompilationCallback() {
324 llvm_unreachable("Cannot call X86CompilationCallback() on a non-x86 arch!");
326 #endif
329 /// X86CompilationCallback2 - This is the target-specific function invoked by the
330 /// function stub when we did not know the real target of a call. This function
331 /// must locate the start of the stub or call site and pass it into the JIT
332 /// compiler function.
333 extern "C" {
334 #if !(defined (X86_64_JIT) && defined(_MSC_VER))
335 // the following function is called only from this translation unit,
336 // unless we are under 64bit Windows with MSC, where there is
337 // no support for inline assembly
338 static
339 #endif
340 void LLVM_ATTRIBUTE_USED
341 X86CompilationCallback2(intptr_t *StackPtr, intptr_t RetAddr) {
342 intptr_t *RetAddrLoc = &StackPtr[1];
343 assert(*RetAddrLoc == RetAddr &&
344 "Could not find return address on the stack!");
346 // It's a stub if there is an interrupt marker after the call.
347 bool isStub = ((unsigned char*)RetAddr)[0] == 0xCE;
349 // The call instruction should have pushed the return value onto the stack...
350 #if defined (X86_64_JIT)
351 RetAddr--; // Backtrack to the reference itself...
352 #else
353 RetAddr -= 4; // Backtrack to the reference itself...
354 #endif
356 #if 0
357 DEBUG(dbgs() << "In callback! Addr=" << (void*)RetAddr
358 << " ESP=" << (void*)StackPtr
359 << ": Resolving call to function: "
360 << TheVM->getFunctionReferencedName((void*)RetAddr) << "\n");
361 #endif
363 // Sanity check to make sure this really is a call instruction.
364 #if defined (X86_64_JIT)
365 assert(((unsigned char*)RetAddr)[-2] == 0x41 &&"Not a call instr!");
366 assert(((unsigned char*)RetAddr)[-1] == 0xFF &&"Not a call instr!");
367 #else
368 assert(((unsigned char*)RetAddr)[-1] == 0xE8 &&"Not a call instr!");
369 #endif
371 intptr_t NewVal = (intptr_t)JITCompilerFunction((void*)RetAddr);
373 // Rewrite the call target... so that we don't end up here every time we
374 // execute the call.
375 #if defined (X86_64_JIT)
376 assert(isStub &&
377 "X86-64 doesn't support rewriting non-stub lazy compilation calls:"
378 " the call instruction varies too much.");
379 #else
380 *(intptr_t *)RetAddr = (intptr_t)(NewVal-RetAddr-4);
381 #endif
383 if (isStub) {
384 // If this is a stub, rewrite the call into an unconditional branch
385 // instruction so that two return addresses are not pushed onto the stack
386 // when the requested function finally gets called. This also makes the
387 // 0xCE byte (interrupt) dead, so the marker doesn't effect anything.
388 #if defined (X86_64_JIT)
389 // If the target address is within 32-bit range of the stub, use a
390 // PC-relative branch instead of loading the actual address. (This is
391 // considerably shorter than the 64-bit immediate load already there.)
392 // We assume here intptr_t is 64 bits.
393 intptr_t diff = NewVal-RetAddr+7;
394 if (diff >= -2147483648LL && diff <= 2147483647LL) {
395 *(unsigned char*)(RetAddr-0xc) = 0xE9;
396 *(intptr_t *)(RetAddr-0xb) = diff & 0xffffffff;
397 } else {
398 *(intptr_t *)(RetAddr - 0xa) = NewVal;
399 ((unsigned char*)RetAddr)[0] = (2 | (4 << 3) | (3 << 6));
401 sys::ValgrindDiscardTranslations((void*)(RetAddr-0xc), 0xd);
402 #else
403 ((unsigned char*)RetAddr)[-1] = 0xE9;
404 sys::ValgrindDiscardTranslations((void*)(RetAddr-1), 5);
405 #endif
408 // Change the return address to reexecute the call instruction...
409 #if defined (X86_64_JIT)
410 *RetAddrLoc -= 0xd;
411 #else
412 *RetAddrLoc -= 5;
413 #endif
417 TargetJITInfo::LazyResolverFn
418 X86JITInfo::getLazyResolverFunction(JITCompilerFn F) {
419 JITCompilerFunction = F;
421 #if defined (X86_32_JIT) && !defined (_MSC_VER)
422 if (Subtarget->hasSSE1())
423 return X86CompilationCallback_SSE;
424 #endif
426 return X86CompilationCallback;
429 X86JITInfo::X86JITInfo(X86TargetMachine &tm) : TM(tm) {
430 Subtarget = &TM.getSubtarget<X86Subtarget>();
431 useGOT = 0;
432 TLSOffset = 0;
435 void *X86JITInfo::emitGlobalValueIndirectSym(const GlobalValue* GV, void *ptr,
436 JITCodeEmitter &JCE) {
437 #if defined (X86_64_JIT)
438 const unsigned Alignment = 8;
439 uint8_t Buffer[8];
440 uint8_t *Cur = Buffer;
441 MachineCodeEmitter::emitWordLEInto(Cur, (unsigned)(intptr_t)ptr);
442 MachineCodeEmitter::emitWordLEInto(Cur, (unsigned)(((intptr_t)ptr) >> 32));
443 #else
444 const unsigned Alignment = 4;
445 uint8_t Buffer[4];
446 uint8_t *Cur = Buffer;
447 MachineCodeEmitter::emitWordLEInto(Cur, (intptr_t)ptr);
448 #endif
449 return JCE.allocIndirectGV(GV, Buffer, sizeof(Buffer), Alignment);
452 TargetJITInfo::StubLayout X86JITInfo::getStubLayout() {
453 // The 64-bit stub contains:
454 // movabs r10 <- 8-byte-target-address # 10 bytes
455 // call|jmp *r10 # 3 bytes
456 // The 32-bit stub contains a 5-byte call|jmp.
457 // If the stub is a call to the compilation callback, an extra byte is added
458 // to mark it as a stub.
459 StubLayout Result = {14, 4};
460 return Result;
463 void *X86JITInfo::emitFunctionStub(const Function* F, void *Target,
464 JITCodeEmitter &JCE) {
465 // Note, we cast to intptr_t here to silence a -pedantic warning that
466 // complains about casting a function pointer to a normal pointer.
467 #if defined (X86_32_JIT) && !defined (_MSC_VER)
468 bool NotCC = (Target != (void*)(intptr_t)X86CompilationCallback &&
469 Target != (void*)(intptr_t)X86CompilationCallback_SSE);
470 #else
471 bool NotCC = Target != (void*)(intptr_t)X86CompilationCallback;
472 #endif
473 JCE.emitAlignment(4);
474 void *Result = (void*)JCE.getCurrentPCValue();
475 if (NotCC) {
476 #if defined (X86_64_JIT)
477 JCE.emitByte(0x49); // REX prefix
478 JCE.emitByte(0xB8+2); // movabsq r10
479 JCE.emitWordLE((unsigned)(intptr_t)Target);
480 JCE.emitWordLE((unsigned)(((intptr_t)Target) >> 32));
481 JCE.emitByte(0x41); // REX prefix
482 JCE.emitByte(0xFF); // jmpq *r10
483 JCE.emitByte(2 | (4 << 3) | (3 << 6));
484 #else
485 JCE.emitByte(0xE9);
486 JCE.emitWordLE((intptr_t)Target-JCE.getCurrentPCValue()-4);
487 #endif
488 return Result;
491 #if defined (X86_64_JIT)
492 JCE.emitByte(0x49); // REX prefix
493 JCE.emitByte(0xB8+2); // movabsq r10
494 JCE.emitWordLE((unsigned)(intptr_t)Target);
495 JCE.emitWordLE((unsigned)(((intptr_t)Target) >> 32));
496 JCE.emitByte(0x41); // REX prefix
497 JCE.emitByte(0xFF); // callq *r10
498 JCE.emitByte(2 | (2 << 3) | (3 << 6));
499 #else
500 JCE.emitByte(0xE8); // Call with 32 bit pc-rel destination...
502 JCE.emitWordLE((intptr_t)Target-JCE.getCurrentPCValue()-4);
503 #endif
505 // This used to use 0xCD, but that value is used by JITMemoryManager to
506 // initialize the buffer with garbage, which means it may follow a
507 // noreturn function call, confusing X86CompilationCallback2. PR 4929.
508 JCE.emitByte(0xCE); // Interrupt - Just a marker identifying the stub!
509 return Result;
512 /// getPICJumpTableEntry - Returns the value of the jumptable entry for the
513 /// specific basic block.
514 uintptr_t X86JITInfo::getPICJumpTableEntry(uintptr_t BB, uintptr_t Entry) {
515 #if defined(X86_64_JIT)
516 return BB - Entry;
517 #else
518 return BB - PICBase;
519 #endif
522 /// relocate - Before the JIT can run a block of code that has been emitted,
523 /// it must rewrite the code to contain the actual addresses of any
524 /// referenced global symbols.
525 void X86JITInfo::relocate(void *Function, MachineRelocation *MR,
526 unsigned NumRelocs, unsigned char* GOTBase) {
527 for (unsigned i = 0; i != NumRelocs; ++i, ++MR) {
528 void *RelocPos = (char*)Function + MR->getMachineCodeOffset();
529 intptr_t ResultPtr = (intptr_t)MR->getResultPointer();
530 switch ((X86::RelocationType)MR->getRelocationType()) {
531 case X86::reloc_pcrel_word: {
532 // PC relative relocation, add the relocated value to the value already in
533 // memory, after we adjust it for where the PC is.
534 ResultPtr = ResultPtr -(intptr_t)RelocPos - 4 - MR->getConstantVal();
535 *((unsigned*)RelocPos) += (unsigned)ResultPtr;
536 break;
538 case X86::reloc_picrel_word: {
539 // PIC base relative relocation, add the relocated value to the value
540 // already in memory, after we adjust it for where the PIC base is.
541 ResultPtr = ResultPtr - ((intptr_t)Function + MR->getConstantVal());
542 *((unsigned*)RelocPos) += (unsigned)ResultPtr;
543 break;
545 case X86::reloc_absolute_word:
546 case X86::reloc_absolute_word_sext:
547 // Absolute relocation, just add the relocated value to the value already
548 // in memory.
549 *((unsigned*)RelocPos) += (unsigned)ResultPtr;
550 break;
551 case X86::reloc_absolute_dword:
552 *((intptr_t*)RelocPos) += ResultPtr;
553 break;
558 char* X86JITInfo::allocateThreadLocalMemory(size_t size) {
559 #if defined(X86_32_JIT) && !defined(__APPLE__) && !defined(_MSC_VER)
560 TLSOffset -= size;
561 return TLSOffset;
562 #else
563 llvm_unreachable("Cannot allocate thread local storage on this arch!");
564 return 0;
565 #endif