MCJIT.cpp revision 5acfa9f0fd641906e520a6caaf644d03def27ae0
1//===-- MCJIT.cpp - MC-based Just-in-Time Compiler --------------------------===//
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#include "MCJIT.h"
11#include "llvm/DerivedTypes.h"
12#include "llvm/Function.h"
13#include "llvm/ExecutionEngine/GenericValue.h"
14#include "llvm/ExecutionEngine/MCJIT.h"
15#include "llvm/ExecutionEngine/JITMemoryManager.h"
16#include "llvm/MC/MCAsmInfo.h"
17#include "llvm/Support/ErrorHandling.h"
18#include "llvm/Support/DynamicLibrary.h"
19#include "llvm/Support/MemoryBuffer.h"
20#include "llvm/Target/TargetData.h"
21
22using namespace llvm;
23
24namespace {
25
26static struct RegisterJIT {
27  RegisterJIT() { MCJIT::Register(); }
28} JITRegistrator;
29
30}
31
32extern "C" void LLVMLinkInMCJIT() {
33}
34
35ExecutionEngine *MCJIT::createJIT(Module *M,
36                                  std::string *ErrorStr,
37                                  JITMemoryManager *JMM,
38                                  CodeGenOpt::Level OptLevel,
39                                  bool GVsWithCode,
40                                  CodeModel::Model CMM,
41                                  StringRef MArch,
42                                  StringRef MCPU,
43                                  const SmallVectorImpl<std::string>& MAttrs) {
44  // Try to register the program as a source of symbols to resolve against.
45  //
46  // FIXME: Don't do this here.
47  sys::DynamicLibrary::LoadLibraryPermanently(0, NULL);
48
49  // Pick a target either via -march or by guessing the native arch.
50  //
51  // FIXME: This should be lifted out of here, it isn't something which should
52  // be part of the JIT policy, rather the burden for this selection should be
53  // pushed to clients.
54  TargetMachine *TM = MCJIT::selectTarget(M, MArch, MCPU, MAttrs, ErrorStr);
55  if (!TM || (ErrorStr && ErrorStr->length() > 0)) return 0;
56  TM->setCodeModel(CMM);
57
58  // If the target supports JIT code generation, create the JIT.
59  if (TargetJITInfo *TJ = TM->getJITInfo())
60    return new MCJIT(M, TM, *TJ, JMM, OptLevel, GVsWithCode);
61
62  if (ErrorStr)
63    *ErrorStr = "target does not support JIT code generation";
64  return 0;
65}
66
67MCJIT::MCJIT(Module *m, TargetMachine *tm, TargetJITInfo &tji,
68             JITMemoryManager *JMM, CodeGenOpt::Level OptLevel,
69             bool AllocateGVsWithCode)
70  : ExecutionEngine(m), TM(tm), M(m), OS(Buffer), Dyld(JMM) {
71
72  PM.add(new TargetData(*TM->getTargetData()));
73
74  // Turn the machine code intermediate representation into bytes in memory
75  // that may be executed.
76  if (TM->addPassesToEmitMC(PM, Ctx, OS, CodeGenOpt::Default, false)) {
77    report_fatal_error("Target does not support MC emission!");
78  }
79
80  // Initialize passes.
81  // FIXME: When we support multiple modules, we'll want to move the code
82  // gen and finalization out of the constructor here and do it more
83  // on-demand as part of getPointerToFunction().
84  PM.run(*M);
85  // Flush the output buffer so the SmallVector gets its data.
86  OS.flush();
87
88  // Load the object into the dynamic linker.
89  // FIXME: It would be nice to avoid making yet another copy.
90  MemoryBuffer *MB = MemoryBuffer::getMemBufferCopy(StringRef(Buffer.data(),
91                                                              Buffer.size()));
92  if (Dyld.loadObject(MB))
93    report_fatal_error(Dyld.getErrorString());
94}
95
96MCJIT::~MCJIT() {
97}
98
99void *MCJIT::getPointerToBasicBlock(BasicBlock *BB) {
100  report_fatal_error("not yet implemented");
101  return 0;
102}
103
104void *MCJIT::getPointerToFunction(Function *F) {
105  if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
106    bool AbortOnFailure = !F->hasExternalWeakLinkage();
107    void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
108    addGlobalMapping(F, Addr);
109    return Addr;
110  }
111
112  Twine Name = TM->getMCAsmInfo()->getGlobalPrefix() + F->getName();
113  return Dyld.getSymbolAddress(Name.str());
114}
115
116void *MCJIT::recompileAndRelinkFunction(Function *F) {
117  report_fatal_error("not yet implemented");
118}
119
120void MCJIT::freeMachineCodeForFunction(Function *F) {
121  report_fatal_error("not yet implemented");
122}
123
124GenericValue MCJIT::runFunction(Function *F,
125                                const std::vector<GenericValue> &ArgValues) {
126  assert(F && "Function *F was null at entry to run()");
127
128  void *FPtr = getPointerToFunction(F);
129  assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
130  const FunctionType *FTy = F->getFunctionType();
131  const Type *RetTy = FTy->getReturnType();
132
133  assert((FTy->getNumParams() == ArgValues.size() ||
134          (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
135         "Wrong number of arguments passed into function!");
136  assert(FTy->getNumParams() == ArgValues.size() &&
137         "This doesn't support passing arguments through varargs (yet)!");
138
139  // Handle some common cases first.  These cases correspond to common `main'
140  // prototypes.
141  if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
142    switch (ArgValues.size()) {
143    case 3:
144      if (FTy->getParamType(0)->isIntegerTy(32) &&
145          FTy->getParamType(1)->isPointerTy() &&
146          FTy->getParamType(2)->isPointerTy()) {
147        int (*PF)(int, char **, const char **) =
148          (int(*)(int, char **, const char **))(intptr_t)FPtr;
149
150        // Call the function.
151        GenericValue rv;
152        rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
153                                 (char **)GVTOP(ArgValues[1]),
154                                 (const char **)GVTOP(ArgValues[2])));
155        return rv;
156      }
157      break;
158    case 2:
159      if (FTy->getParamType(0)->isIntegerTy(32) &&
160          FTy->getParamType(1)->isPointerTy()) {
161        int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
162
163        // Call the function.
164        GenericValue rv;
165        rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
166                                 (char **)GVTOP(ArgValues[1])));
167        return rv;
168      }
169      break;
170    case 1:
171      if (FTy->getNumParams() == 1 &&
172          FTy->getParamType(0)->isIntegerTy(32)) {
173        GenericValue rv;
174        int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
175        rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
176        return rv;
177      }
178      break;
179    }
180  }
181
182  // Handle cases where no arguments are passed first.
183  if (ArgValues.empty()) {
184    GenericValue rv;
185    switch (RetTy->getTypeID()) {
186    default: llvm_unreachable("Unknown return type for function call!");
187    case Type::IntegerTyID: {
188      unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
189      if (BitWidth == 1)
190        rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
191      else if (BitWidth <= 8)
192        rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
193      else if (BitWidth <= 16)
194        rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
195      else if (BitWidth <= 32)
196        rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
197      else if (BitWidth <= 64)
198        rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
199      else
200        llvm_unreachable("Integer types > 64 bits not supported");
201      return rv;
202    }
203    case Type::VoidTyID:
204      rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
205      return rv;
206    case Type::FloatTyID:
207      rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
208      return rv;
209    case Type::DoubleTyID:
210      rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
211      return rv;
212    case Type::X86_FP80TyID:
213    case Type::FP128TyID:
214    case Type::PPC_FP128TyID:
215      llvm_unreachable("long double not supported yet");
216      return rv;
217    case Type::PointerTyID:
218      return PTOGV(((void*(*)())(intptr_t)FPtr)());
219    }
220  }
221
222  assert("Full-featured argument passing not supported yet!");
223  return GenericValue();
224}
225