VFP fld / fst immediate field is multiplied by 4.
[oota-llvm.git] / lib / Target / ARM / ARMJITInfo.cpp
1 //===-- ARMJITInfo.cpp - Implement the JIT interfaces for the ARM 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 ARM target.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "jit"
15 #include "ARMJITInfo.h"
16 #include "ARMInstrInfo.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMRelocations.h"
19 #include "ARMSubtarget.h"
20 #include "llvm/Function.h"
21 #include "llvm/CodeGen/MachineCodeEmitter.h"
22 #include "llvm/Config/alloca.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/Streams.h"
25 #include "llvm/System/Memory.h"
26 #include <cstdlib>
27 using namespace llvm;
28
29 void ARMJITInfo::replaceMachineCodeForFunction(void *Old, void *New) {
30   abort();
31 }
32
33 /// JITCompilerFunction - This contains the address of the JIT function used to
34 /// compile a function lazily.
35 static TargetJITInfo::JITCompilerFn JITCompilerFunction;
36
37 // Get the ASMPREFIX for the current host.  This is often '_'.
38 #ifndef __USER_LABEL_PREFIX__
39 #define __USER_LABEL_PREFIX__
40 #endif
41 #define GETASMPREFIX2(X) #X
42 #define GETASMPREFIX(X) GETASMPREFIX2(X)
43 #define ASMPREFIX GETASMPREFIX(__USER_LABEL_PREFIX__)
44
45 // CompilationCallback stub - We can't use a C function with inline assembly in
46 // it, because we the prolog/epilog inserted by GCC won't work for us (we need
47 // to preserve more context and manipulate the stack directly).  Instead,
48 // write our own wrapper, which does things our way, so we have complete 
49 // control over register saving and restoring.
50 extern "C" {
51 #if defined(__arm__)
52   void ARMCompilationCallback(void);
53   asm(
54     ".text\n"
55     ".align 2\n"
56     ".globl " ASMPREFIX "ARMCompilationCallback\n"
57     ASMPREFIX "ARMCompilationCallback:\n"
58     // Save caller saved registers since they may contain stuff
59     // for the real target function right now. We have to act as if this
60     // whole compilation callback doesn't exist as far as the caller is
61     // concerned, so we can't just preserve the callee saved regs.
62     "stmdb sp!, {r0, r1, r2, r3, lr}\n"
63     // The LR contains the address of the stub function on entry.
64     // pass it as the argument to the C part of the callback
65     "mov  r0, lr\n"
66     "sub  sp, sp, #4\n"
67     // Call the C portion of the callback
68     "bl   " ASMPREFIX "ARMCompilationCallbackC\n"
69     "add  sp, sp, #4\n"
70     // Restoring the LR to the return address of the function that invoked
71     // the stub and de-allocating the stack space for it requires us to
72     // swap the two saved LR values on the stack, as they're backwards
73     // for what we need since the pop instruction has a pre-determined
74     // order for the registers.
75     //      +--------+
76     //   0  | LR     | Original return address
77     //      +--------+    
78     //   1  | LR     | Stub address (start of stub)
79     // 2-5  | R3..R0 | Saved registers (we need to preserve all regs)
80     //      +--------+    
81     //
82     //      We need to exchange the values in slots 0 and 1 so we can
83     //      return to the address in slot 1 with the address in slot 0
84     //      restored to the LR.
85     "ldr  r0, [sp,#20]\n"
86     "ldr  r1, [sp,#16]\n"
87     "str  r1, [sp,#20]\n"
88     "str  r0, [sp,#16]\n"
89     // Return to the (newly modified) stub to invoke the real function.
90     // The above twiddling of the saved return addresses allows us to
91     // deallocate everything, including the LR the stub saved, all in one
92     // pop instruction.
93     "ldmia  sp!, {r0, r1, r2, r3, lr, pc}\n"
94       );
95 #else  // Not an ARM host
96   void ARMCompilationCallback() {
97     assert(0 && "Cannot call ARMCompilationCallback() on a non-ARM arch!\n");
98     abort();
99   }
100 #endif
101 }
102
103 /// ARMCompilationCallbackC - This is the target-specific function invoked 
104 /// by the function stub when we did not know the real target of a call.  
105 /// This function must locate the start of the stub or call site and pass 
106 /// it into the JIT compiler function.
107 extern "C" void ARMCompilationCallbackC(intptr_t StubAddr) {
108   // Get the address of the compiled code for this function.
109   intptr_t NewVal = (intptr_t)JITCompilerFunction((void*)StubAddr);
110
111   // Rewrite the call target... so that we don't end up here every time we
112   // execute the call. We're replacing the first two instructions of the
113   // stub with:
114   //   ldr pc, [pc,#-4]
115   //   <addr>
116   if (!sys::Memory::setRangeWritable((void*)StubAddr, 8)) {
117     cerr << "ERROR: Unable to mark stub writable\n";
118     abort();
119   }
120   *(intptr_t *)StubAddr = 0xe51ff004;  // ldr pc, [pc, #-4]
121   *(intptr_t *)(StubAddr+4) = NewVal;
122   if (!sys::Memory::setRangeExecutable((void*)StubAddr, 8)) {
123     cerr << "ERROR: Unable to mark stub executable\n";
124     abort();
125   }
126 }
127
128 TargetJITInfo::LazyResolverFn
129 ARMJITInfo::getLazyResolverFunction(JITCompilerFn F) {
130   JITCompilerFunction = F;
131   return ARMCompilationCallback;
132 }
133
134 void *ARMJITInfo::emitGlobalValueIndirectSym(const GlobalValue *GV, void *Ptr,
135                                              MachineCodeEmitter &MCE) {
136   MCE.startGVStub(GV, 4, 4);
137   MCE.emitWordLE((intptr_t)Ptr);
138   void *PtrAddr = MCE.finishGVStub(GV);
139   addIndirectSymAddr(Ptr, (intptr_t)PtrAddr);
140   return PtrAddr;
141 }
142
143 void *ARMJITInfo::emitFunctionStub(const Function* F, void *Fn,
144                                    MachineCodeEmitter &MCE) {
145   // If this is just a call to an external function, emit a branch instead of a
146   // call.  The code is the same except for one bit of the last instruction.
147   if (Fn != (void*)(intptr_t)ARMCompilationCallback) {
148     // Branch to the corresponding function addr.
149     if (IsPIC) {
150       // The stub is 8-byte size and 4-aligned.
151       intptr_t LazyPtr = getIndirectSymAddr(Fn);
152       if (!LazyPtr) {
153         // In PIC mode, the function stub is loading a lazy-ptr.
154         LazyPtr= (intptr_t)emitGlobalValueIndirectSym((GlobalValue*)F, Fn, MCE);
155         if (F)
156           DOUT << "JIT: Indirect symbol emitted at [" << LazyPtr << "] for GV '"
157                << F->getName() << "'\n";
158         else
159           DOUT << "JIT: Stub emitted at [" << LazyPtr
160                << "] for external function at '" << Fn << "'\n";
161       }
162       MCE.startGVStub(F, 16, 4);
163       intptr_t Addr = (intptr_t)MCE.getCurrentPCValue();
164       MCE.emitWordLE(0xe59fc004);            // ldr pc, [pc, #+4]
165       MCE.emitWordLE(0xe08fc00c);            // L_func$scv: add ip, pc, ip
166       MCE.emitWordLE(0xe59cf000);            // ldr pc, [ip]
167       MCE.emitWordLE(LazyPtr - (Addr+4+8));  // func - (L_func$scv+8)
168       sys::Memory::InvalidateInstructionCache((void*)Addr, 16);
169     } else {
170       // The stub is 8-byte size and 4-aligned.
171       MCE.startGVStub(F, 8, 4);
172       intptr_t Addr = (intptr_t)MCE.getCurrentPCValue();
173       MCE.emitWordLE(0xe51ff004);    // ldr pc, [pc, #-4]
174       MCE.emitWordLE((intptr_t)Fn);  // addr of function
175       sys::Memory::InvalidateInstructionCache((void*)Addr, 8);
176     }
177   } else {
178     // The compilation callback will overwrite the first two words of this
179     // stub with indirect branch instructions targeting the compiled code. 
180     // This stub sets the return address to restart the stub, so that
181     // the new branch will be invoked when we come back.
182     //
183     // Branch and link to the compilation callback.
184     // The stub is 16-byte size and 4-byte aligned.
185     MCE.startGVStub(F, 16, 4);
186     intptr_t Addr = (intptr_t)MCE.getCurrentPCValue();
187     // Save LR so the callback can determine which stub called it.
188     // The compilation callback is responsible for popping this prior
189     // to returning.
190     MCE.emitWordLE(0xe92d4000); // push {lr}
191     // Set the return address to go back to the start of this stub.
192     MCE.emitWordLE(0xe24fe00c); // sub lr, pc, #12
193     // Invoke the compilation callback.
194     MCE.emitWordLE(0xe51ff004); // ldr pc, [pc, #-4]
195     // The address of the compilation callback.
196     MCE.emitWordLE((intptr_t)ARMCompilationCallback);
197     sys::Memory::InvalidateInstructionCache((void*)Addr, 16);
198   }
199
200   return MCE.finishGVStub(F);
201 }
202
203 intptr_t ARMJITInfo::resolveRelocDestAddr(MachineRelocation *MR) const {
204   ARM::RelocationType RT = (ARM::RelocationType)MR->getRelocationType();
205   switch (RT) {
206   default:
207     return (intptr_t)(MR->getResultPointer());
208   case ARM::reloc_arm_pic_jt:
209     // Destination address - jump table base.
210     return (intptr_t)(MR->getResultPointer()) - MR->getConstantVal();
211   case ARM::reloc_arm_jt_base:
212     // Jump table base address.
213     return getJumpTableBaseAddr(MR->getJumpTableIndex());
214   case ARM::reloc_arm_cp_entry:
215   case ARM::reloc_arm_vfp_cp_entry:
216     // Constant pool entry address.
217     return getConstantPoolEntryAddr(MR->getConstantPoolIndex());
218   case ARM::reloc_arm_machine_cp_entry: {
219     ARMConstantPoolValue *ACPV = (ARMConstantPoolValue*)MR->getConstantVal();
220     assert((!ACPV->hasModifier() && !ACPV->mustAddCurrentAddress()) &&
221            "Can't handle this machine constant pool entry yet!");
222     intptr_t Addr = (intptr_t)(MR->getResultPointer());
223     Addr -= getPCLabelAddr(ACPV->getLabelId()) + ACPV->getPCAdjustment();
224     return Addr;
225   }
226   }
227 }
228
229 /// relocate - Before the JIT can run a block of code that has been emitted,
230 /// it must rewrite the code to contain the actual addresses of any
231 /// referenced global symbols.
232 void ARMJITInfo::relocate(void *Function, MachineRelocation *MR,
233                           unsigned NumRelocs, unsigned char* GOTBase) {
234   for (unsigned i = 0; i != NumRelocs; ++i, ++MR) {
235     void *RelocPos = (char*)Function + MR->getMachineCodeOffset();
236     intptr_t ResultPtr = resolveRelocDestAddr(MR);
237     switch ((ARM::RelocationType)MR->getRelocationType()) {
238     case ARM::reloc_arm_cp_entry:
239     case ARM::reloc_arm_vfp_cp_entry:
240     case ARM::reloc_arm_relative: {
241       // It is necessary to calculate the correct PC relative value. We
242       // subtract the base addr from the target addr to form a byte offset.
243       ResultPtr = ResultPtr - (intptr_t)RelocPos - 8;
244       // If the result is positive, set bit U(23) to 1.
245       if (ResultPtr >= 0)
246         *((intptr_t*)RelocPos) |= 1 << ARMII::U_BitShift;
247       else {
248         // Otherwise, obtain the absolute value and set bit U(23) to 0.
249         assert((*((intptr_t*)RelocPos) & (1 << ARMII::U_BitShift)) == 0 &&
250                "U bit is not zero?");
251         ResultPtr = - ResultPtr;
252       }
253       // Set the immed value calculated.
254       // VFP immediate offset is multiplied by 4.
255       if (MR->getRelocationType() == ARM::reloc_arm_vfp_cp_entry)
256         ResultPtr = ResultPtr >> 2;
257       *((intptr_t*)RelocPos) |= ResultPtr;
258       // Set register Rn to PC.
259       *((intptr_t*)RelocPos) |=
260         ARMRegisterInfo::getRegisterNumbering(ARM::PC) << ARMII::RegRnShift;
261       break;
262     }
263     case ARM::reloc_arm_pic_jt:
264     case ARM::reloc_arm_machine_cp_entry:
265     case ARM::reloc_arm_absolute: {
266       // These addresses have already been resolved.
267       *((intptr_t*)RelocPos) |= (intptr_t)ResultPtr;
268       break;
269     }
270     case ARM::reloc_arm_branch: {
271       // It is necessary to calculate the correct value of signed_immed_24
272       // field. We subtract the base addr from the target addr to form a
273       // byte offset, which must be inside the range -33554432 and +33554428.
274       // Then, we set the signed_immed_24 field of the instruction to bits
275       // [25:2] of the byte offset. More details ARM-ARM p. A4-11.
276       ResultPtr = ResultPtr - (intptr_t)RelocPos - 8;
277       ResultPtr = (ResultPtr & 0x03FFFFFC) >> 2;
278       assert(ResultPtr >= -33554432 && ResultPtr <= 33554428);
279       *((intptr_t*)RelocPos) |= ResultPtr;
280       break;
281     }
282     case ARM::reloc_arm_jt_base: {
283       // JT base - (instruction addr + 8)
284       ResultPtr = ResultPtr - (intptr_t)RelocPos - 8;
285       *((intptr_t*)RelocPos) |= ResultPtr;
286       break;
287     }
288     }
289   }
290 }