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