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