blob: fa4669dec63ed269249d8070e04f5480ff248c02 [file] [log] [blame]
Chris Lattnerfe11a972002-12-23 23:59:41 +00001//===- lli.cpp - LLVM Interpreter / Dynamic compiler ----------------------===//
Misha Brukman3da94ae2005-04-22 00:00:37 +00002//
John Criswell7c0e0222003-10-20 17:47:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner21c62da2007-12-29 20:44:31 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman3da94ae2005-04-22 00:00:37 +00007//
John Criswell7c0e0222003-10-20 17:47:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner92101ac2001-08-23 17:05:04 +00009//
Chris Lattner7efea1d2003-12-26 05:07:35 +000010// This utility provides a simple wrapper around the LLVM Execution Engines,
11// which allow the direct execution of LLVM programs through a Just-In-Time
Torok Edwindb9c0282009-07-03 12:11:32 +000012// compiler, or through an interpreter if no JIT is available for this platform.
Chris Lattner92101ac2001-08-23 17:05:04 +000013//
14//===----------------------------------------------------------------------===//
15
Jim Grosbach706f03a2012-09-05 16:50:34 +000016#define DEBUG_TYPE "lli"
17#include "RecordingMemoryManager.h"
18#include "RemoteTarget.h"
Owen Anderson8b477ed2009-07-01 16:58:40 +000019#include "llvm/LLVMContext.h"
Chris Lattnerfd131292003-09-05 20:08:15 +000020#include "llvm/Module.h"
Chris Lattner269a4282003-12-26 06:49:53 +000021#include "llvm/Type.h"
Duncan Sands75ebbce2010-08-28 01:30:02 +000022#include "llvm/ADT/Triple.h"
Chris Lattnerc1e6d682007-05-06 04:58:26 +000023#include "llvm/Bitcode/ReaderWriter.h"
Chris Lattnerd3a680a2006-08-01 22:34:35 +000024#include "llvm/CodeGen/LinkAllCodegenComponents.h"
Brian Gaeked1cab3e2003-09-05 19:42:34 +000025#include "llvm/ExecutionEngine/GenericValue.h"
Jeffrey Yasskindf5a7da2009-06-25 02:04:04 +000026#include "llvm/ExecutionEngine/Interpreter.h"
27#include "llvm/ExecutionEngine/JIT.h"
28#include "llvm/ExecutionEngine/JITEventListener.h"
Jim Grosbachbf9ab932012-01-11 21:12:51 +000029#include "llvm/ExecutionEngine/JITMemoryManager.h"
Daniel Dunbar6aec2982010-11-17 16:06:43 +000030#include "llvm/ExecutionEngine/MCJIT.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000031#include "llvm/Support/CommandLine.h"
Daniel Dunbar46a27162010-11-13 00:28:01 +000032#include "llvm/Support/IRReader.h"
Chris Lattnerc30598b2006-12-06 01:18:01 +000033#include "llvm/Support/ManagedStatic.h"
Chris Lattnerc1e6d682007-05-06 04:58:26 +000034#include "llvm/Support/MemoryBuffer.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000035#include "llvm/Support/PluginLoader.h"
Chris Lattnercc14d252009-03-06 05:34:10 +000036#include "llvm/Support/PrettyStackTrace.h"
Chris Lattner74382b72009-08-23 22:45:37 +000037#include "llvm/Support/raw_ostream.h"
Jim Grosbach706f03a2012-09-05 16:50:34 +000038#include "llvm/Support/Format.h"
Michael J. Spencer1f6efa32010-11-29 18:16:10 +000039#include "llvm/Support/Process.h"
40#include "llvm/Support/Signals.h"
Evan Cheng3e74d6f2011-08-24 18:08:43 +000041#include "llvm/Support/TargetSelect.h"
Jim Grosbach706f03a2012-09-05 16:50:34 +000042#include "llvm/Support/Debug.h"
Danil Malyshev068c65b2012-05-16 18:50:11 +000043#include "llvm/Support/DynamicLibrary.h"
44#include "llvm/Support/Memory.h"
Tim Northoverb210e6f2012-10-29 10:47:07 +000045#include "llvm/Support/MathExtras.h"
Chris Lattner02040322007-04-27 17:02:33 +000046#include <cerrno>
NAKAMURA Takumia13d14a2010-10-22 14:53:59 +000047
Danil Malyshev068c65b2012-05-16 18:50:11 +000048#ifdef __linux__
49// These includes used by LLIMCJITMemoryManager::getPointerToNamedFunction()
50// for Glibc trickery. Look comments in this function for more information.
51#ifdef HAVE_SYS_STAT_H
52#include <sys/stat.h>
53#endif
54#include <fcntl.h>
55#include <unistd.h>
56#endif
57
NAKAMURA Takumia13d14a2010-10-22 14:53:59 +000058#ifdef __CYGWIN__
59#include <cygwin/version.h>
60#if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
61#define DO_NOTHING_ATEXIT 1
62#endif
63#endif
64
Brian Gaeked0fde302003-11-11 22:41:34 +000065using namespace llvm;
66
Chris Lattnerfe11a972002-12-23 23:59:41 +000067namespace {
68 cl::opt<std::string>
Gabor Greifa99be512007-07-05 17:07:56 +000069 InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
Chris Lattner5ff62e92002-07-22 02:10:13 +000070
Chris Lattnerfe11a972002-12-23 23:59:41 +000071 cl::list<std::string>
72 InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
Chris Lattner5ff62e92002-07-22 02:10:13 +000073
Chris Lattnerfe11a972002-12-23 23:59:41 +000074 cl::opt<bool> ForceInterpreter("force-interpreter",
Misha Brukman3d8a54d2003-09-25 18:10:34 +000075 cl::desc("Force interpretation: disable JIT"),
76 cl::init(false));
Evan Chenge1a4eda2008-08-08 08:12:06 +000077
Daniel Dunbar6d135972010-11-17 16:06:37 +000078 cl::opt<bool> UseMCJIT(
79 "use-mcjit", cl::desc("Enable use of the MC-based JIT (if available)"),
80 cl::init(false));
81
Jim Grosbach706f03a2012-09-05 16:50:34 +000082 // The MCJIT supports building for a target address space separate from
83 // the JIT compilation process. Use a forked process and a copying
84 // memory manager with IPC to execute using this functionality.
85 cl::opt<bool> RemoteMCJIT("remote-mcjit",
86 cl::desc("Execute MCJIT'ed code in a separate process."),
87 cl::init(false));
88
Evan Cheng712e80e2009-05-04 23:05:19 +000089 // Determine optimization level.
90 cl::opt<char>
91 OptLevel("O",
92 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
93 "(default = '-O2')"),
94 cl::Prefix,
95 cl::ZeroOrMore,
96 cl::init(' '));
Evan Chenge1a4eda2008-08-08 08:12:06 +000097
Chris Lattner3015e602005-12-16 05:00:21 +000098 cl::opt<std::string>
Chris Lattner60844d42005-12-16 05:19:18 +000099 TargetTriple("mtriple", cl::desc("Override target triple for module"));
Evan Chengec740e32008-11-05 23:21:52 +0000100
101 cl::opt<std::string>
Jeffrey Yasskin46882612010-02-05 16:19:36 +0000102 MArch("march",
103 cl::desc("Architecture to generate assembly for (see --version)"));
104
105 cl::opt<std::string>
106 MCPU("mcpu",
107 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
108 cl::value_desc("cpu-name"),
109 cl::init(""));
110
111 cl::list<std::string>
112 MAttrs("mattr",
113 cl::CommaSeparated,
114 cl::desc("Target specific attributes (-mattr=help for details)"),
115 cl::value_desc("a1,+a2,-a3,..."));
116
117 cl::opt<std::string>
Evan Chengec740e32008-11-05 23:21:52 +0000118 EntryFunc("entry-function",
119 cl::desc("Specify the entry function (default = 'main') "
120 "of the executable"),
121 cl::value_desc("function"),
122 cl::init("main"));
Eli Benderskya66a1852012-01-16 08:56:09 +0000123
Chris Lattnere69671d2003-10-28 22:51:44 +0000124 cl::opt<std::string>
125 FakeArgv0("fake-argv0",
126 cl::desc("Override the 'argv[0]' value passed into the executing"
127 " program"), cl::value_desc("executable"));
Eli Benderskya66a1852012-01-16 08:56:09 +0000128
Chris Lattner43f249a2006-09-14 06:17:09 +0000129 cl::opt<bool>
130 DisableCoreFiles("disable-core-files", cl::Hidden,
131 cl::desc("Disable emission of core files if possible"));
Evan Chengc290a5b2008-04-22 06:51:41 +0000132
133 cl::opt<bool>
Evan Cheng03dace82008-05-21 18:20:21 +0000134 NoLazyCompilation("disable-lazy-compilation",
Evan Chengc290a5b2008-04-22 06:51:41 +0000135 cl::desc("Disable JIT lazy compilation"),
136 cl::init(false));
Evan Cheng43966132011-07-19 06:37:02 +0000137
138 cl::opt<Reloc::Model>
139 RelocModel("relocation-model",
140 cl::desc("Choose relocation model"),
141 cl::init(Reloc::Default),
142 cl::values(
143 clEnumValN(Reloc::Default, "default",
144 "Target default relocation model"),
145 clEnumValN(Reloc::Static, "static",
146 "Non-relocatable code"),
147 clEnumValN(Reloc::PIC_, "pic",
148 "Fully relocatable, position independent code"),
149 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
150 "Relocatable external references, non-relocatable code"),
151 clEnumValEnd));
Evan Cheng34ad6db2011-07-20 07:51:56 +0000152
153 cl::opt<llvm::CodeModel::Model>
154 CMModel("code-model",
155 cl::desc("Choose code model"),
156 cl::init(CodeModel::JITDefault),
157 cl::values(clEnumValN(CodeModel::JITDefault, "default",
158 "Target default JIT code model"),
159 clEnumValN(CodeModel::Small, "small",
160 "Small code model"),
161 clEnumValN(CodeModel::Kernel, "kernel",
162 "Kernel code model"),
163 clEnumValN(CodeModel::Medium, "medium",
164 "Medium code model"),
165 clEnumValN(CodeModel::Large, "large",
166 "Large code model"),
167 clEnumValEnd));
168
Nick Lewycky9a148412012-04-18 08:34:12 +0000169 cl::opt<bool>
170 EnableJITExceptionHandling("jit-enable-eh",
171 cl::desc("Emit exception handling information"),
172 cl::init(false));
173
174 cl::opt<bool>
Tim Northover77b4c692012-10-12 09:55:13 +0000175 GenerateSoftFloatCalls("soft-float",
176 cl::desc("Generate software floating point library calls"),
177 cl::init(false));
178
179 cl::opt<llvm::FloatABI::ABIType>
180 FloatABIForCalls("float-abi",
181 cl::desc("Choose float ABI type"),
182 cl::init(FloatABI::Default),
183 cl::values(
184 clEnumValN(FloatABI::Default, "default",
185 "Target default float ABI type"),
186 clEnumValN(FloatABI::Soft, "soft",
187 "Soft float ABI (implied by -soft-float)"),
188 clEnumValN(FloatABI::Hard, "hard",
189 "Hard float ABI (uses FP registers)"),
190 clEnumValEnd));
191 cl::opt<bool>
Nick Lewycky9a148412012-04-18 08:34:12 +0000192// In debug builds, make this default to true.
193#ifdef NDEBUG
194#define EMIT_DEBUG false
195#else
196#define EMIT_DEBUG true
197#endif
198 EmitJitDebugInfo("jit-emit-debug",
199 cl::desc("Emit debug information to debugger"),
200 cl::init(EMIT_DEBUG));
201#undef EMIT_DEBUG
202
203 static cl::opt<bool>
204 EmitJitDebugInfoToDisk("jit-emit-debug-to-disk",
205 cl::Hidden,
206 cl::desc("Emit debug info objfiles to disk"),
207 cl::init(false));
Chris Lattnerfe11a972002-12-23 23:59:41 +0000208}
Chris Lattner43e3f7c2001-10-27 08:43:52 +0000209
Reid Spencerf70d6772007-03-03 18:21:44 +0000210static ExecutionEngine *EE = 0;
211
212static void do_shutdown() {
NAKAMURA Takumia13d14a2010-10-22 14:53:59 +0000213 // Cygwin-1.5 invokes DLL's dtors before atexit handler.
214#ifndef DO_NOTHING_ATEXIT
Reid Spencerf70d6772007-03-03 18:21:44 +0000215 delete EE;
216 llvm_shutdown();
NAKAMURA Takumia13d14a2010-10-22 14:53:59 +0000217#endif
Reid Spencerf70d6772007-03-03 18:21:44 +0000218}
219
Danil Malyshev068c65b2012-05-16 18:50:11 +0000220// Memory manager for MCJIT
221class LLIMCJITMemoryManager : public JITMemoryManager {
222public:
223 SmallVector<sys::MemoryBlock, 16> AllocatedDataMem;
224 SmallVector<sys::MemoryBlock, 16> AllocatedCodeMem;
225 SmallVector<sys::MemoryBlock, 16> FreeCodeMem;
226
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000227 LLIMCJITMemoryManager() { }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000228 ~LLIMCJITMemoryManager();
229
230 virtual uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
231 unsigned SectionID);
232
233 virtual uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
Andrew Kaylor53608a32012-11-15 23:50:01 +0000234 unsigned SectionID, bool IsReadOnly);
Danil Malyshev068c65b2012-05-16 18:50:11 +0000235
236 virtual void *getPointerToNamedFunction(const std::string &Name,
237 bool AbortOnFailure = true);
238
Andrew Kaylor53608a32012-11-15 23:50:01 +0000239 virtual bool applyPermissions(std::string *ErrMsg) { return false; }
240
Danil Malyshev068c65b2012-05-16 18:50:11 +0000241 // Invalidate instruction cache for code sections. Some platforms with
242 // separate data cache and instruction cache require explicit cache flush,
243 // otherwise JIT code manipulations (like resolved relocations) will get to
244 // the data cache but not to the instruction cache.
245 virtual void invalidateInstructionCache();
246
Andrew Kaylor647d6d72012-11-01 00:46:04 +0000247 // The RTDyldMemoryManager doesn't use the following functions, so we don't
Danil Malyshev068c65b2012-05-16 18:50:11 +0000248 // need implement them.
249 virtual void setMemoryWritable() {
250 llvm_unreachable("Unexpected call!");
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000251 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000252 virtual void setMemoryExecutable() {
253 llvm_unreachable("Unexpected call!");
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000254 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000255 virtual void setPoisonMemory(bool poison) {
256 llvm_unreachable("Unexpected call!");
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000257 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000258 virtual void AllocateGOT() {
259 llvm_unreachable("Unexpected call!");
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000260 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000261 virtual uint8_t *getGOTBase() const {
262 llvm_unreachable("Unexpected call!");
263 return 0;
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000264 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000265 virtual uint8_t *startFunctionBody(const Function *F,
266 uintptr_t &ActualSize){
267 llvm_unreachable("Unexpected call!");
268 return 0;
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000269 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000270 virtual uint8_t *allocateStub(const GlobalValue* F, unsigned StubSize,
271 unsigned Alignment) {
272 llvm_unreachable("Unexpected call!");
273 return 0;
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000274 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000275 virtual void endFunctionBody(const Function *F, uint8_t *FunctionStart,
276 uint8_t *FunctionEnd) {
277 llvm_unreachable("Unexpected call!");
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000278 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000279 virtual uint8_t *allocateSpace(intptr_t Size, unsigned Alignment) {
280 llvm_unreachable("Unexpected call!");
281 return 0;
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000282 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000283 virtual uint8_t *allocateGlobal(uintptr_t Size, unsigned Alignment) {
284 llvm_unreachable("Unexpected call!");
285 return 0;
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000286 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000287 virtual void deallocateFunctionBody(void *Body) {
288 llvm_unreachable("Unexpected call!");
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000289 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000290 virtual uint8_t* startExceptionTable(const Function* F,
291 uintptr_t &ActualSize) {
292 llvm_unreachable("Unexpected call!");
293 return 0;
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000294 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000295 virtual void endExceptionTable(const Function *F, uint8_t *TableStart,
296 uint8_t *TableEnd, uint8_t* FrameRegister) {
297 llvm_unreachable("Unexpected call!");
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000298 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000299 virtual void deallocateExceptionTable(void *ET) {
300 llvm_unreachable("Unexpected call!");
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000301 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000302};
303
304uint8_t *LLIMCJITMemoryManager::allocateDataSection(uintptr_t Size,
305 unsigned Alignment,
Andrew Kaylor53608a32012-11-15 23:50:01 +0000306 unsigned SectionID,
307 bool IsReadOnly) {
Danil Malyshev068c65b2012-05-16 18:50:11 +0000308 if (!Alignment)
309 Alignment = 16;
Tim Northoverb210e6f2012-10-29 10:47:07 +0000310 // Ensure that enough memory is requested to allow aligning.
311 size_t NumElementsAligned = 1 + (Size + Alignment - 1)/Alignment;
312 uint8_t *Addr = (uint8_t*)calloc(NumElementsAligned, Alignment);
313
314 // Honour the alignment requirement.
315 uint8_t *AlignedAddr = (uint8_t*)RoundUpToAlignment((uint64_t)Addr, Alignment);
316
317 // Store the original address from calloc so we can free it later.
318 AllocatedDataMem.push_back(sys::MemoryBlock(Addr, NumElementsAligned*Alignment));
319 return AlignedAddr;
Danil Malyshev068c65b2012-05-16 18:50:11 +0000320}
321
322uint8_t *LLIMCJITMemoryManager::allocateCodeSection(uintptr_t Size,
323 unsigned Alignment,
324 unsigned SectionID) {
325 if (!Alignment)
326 Alignment = 16;
327 unsigned NeedAllocate = Alignment * ((Size + Alignment - 1)/Alignment + 1);
328 uintptr_t Addr = 0;
329 // Look in the list of free code memory regions and use a block there if one
330 // is available.
331 for (int i = 0, e = FreeCodeMem.size(); i != e; ++i) {
332 sys::MemoryBlock &MB = FreeCodeMem[i];
333 if (MB.size() >= NeedAllocate) {
334 Addr = (uintptr_t)MB.base();
335 uintptr_t EndOfBlock = Addr + MB.size();
336 // Align the address.
337 Addr = (Addr + Alignment - 1) & ~(uintptr_t)(Alignment - 1);
338 // Store cutted free memory block.
339 FreeCodeMem[i] = sys::MemoryBlock((void*)(Addr + Size),
340 EndOfBlock - Addr - Size);
341 return (uint8_t*)Addr;
342 }
343 }
344
345 // No pre-allocated free block was large enough. Allocate a new memory region.
346 sys::MemoryBlock MB = sys::Memory::AllocateRWX(NeedAllocate, 0, 0);
347
348 AllocatedCodeMem.push_back(MB);
349 Addr = (uintptr_t)MB.base();
350 uintptr_t EndOfBlock = Addr + MB.size();
351 // Align the address.
352 Addr = (Addr + Alignment - 1) & ~(uintptr_t)(Alignment - 1);
353 // The AllocateRWX may allocate much more memory than we need. In this case,
354 // we store the unused memory as a free memory block.
355 unsigned FreeSize = EndOfBlock-Addr-Size;
356 if (FreeSize > 16)
357 FreeCodeMem.push_back(sys::MemoryBlock((void*)(Addr + Size), FreeSize));
358
359 // Return aligned address
360 return (uint8_t*)Addr;
361}
362
363void LLIMCJITMemoryManager::invalidateInstructionCache() {
364 for (int i = 0, e = AllocatedCodeMem.size(); i != e; ++i)
365 sys::Memory::InvalidateInstructionCache(AllocatedCodeMem[i].base(),
366 AllocatedCodeMem[i].size());
367}
368
NAKAMURA Takumi55587cf2012-10-05 14:10:23 +0000369static int jit_noop() {
370 return 0;
371}
372
Danil Malyshev068c65b2012-05-16 18:50:11 +0000373void *LLIMCJITMemoryManager::getPointerToNamedFunction(const std::string &Name,
374 bool AbortOnFailure) {
375#if defined(__linux__)
376 //===--------------------------------------------------------------------===//
377 // Function stubs that are invoked instead of certain library calls
378 //
379 // Force the following functions to be linked in to anything that uses the
380 // JIT. This is a hack designed to work around the all-too-clever Glibc
381 // strategy of making these functions work differently when inlined vs. when
382 // not inlined, and hiding their real definitions in a separate archive file
383 // that the dynamic linker can't see. For more info, search for
384 // 'libc_nonshared.a' on Google, or read http://llvm.org/PR274.
385 if (Name == "stat") return (void*)(intptr_t)&stat;
386 if (Name == "fstat") return (void*)(intptr_t)&fstat;
387 if (Name == "lstat") return (void*)(intptr_t)&lstat;
388 if (Name == "stat64") return (void*)(intptr_t)&stat64;
389 if (Name == "fstat64") return (void*)(intptr_t)&fstat64;
390 if (Name == "lstat64") return (void*)(intptr_t)&lstat64;
391 if (Name == "atexit") return (void*)(intptr_t)&atexit;
392 if (Name == "mknod") return (void*)(intptr_t)&mknod;
393#endif // __linux__
394
NAKAMURA Takumi55587cf2012-10-05 14:10:23 +0000395 // We should not invoke parent's ctors/dtors from generated main()!
396 // On Mingw and Cygwin, the symbol __main is resolved to
397 // callee's(eg. tools/lli) one, to invoke wrong duplicated ctors
398 // (and register wrong callee's dtors with atexit(3)).
399 // We expect ExecutionEngine::runStaticConstructorsDestructors()
400 // is called before ExecutionEngine::runFunctionAsMain() is called.
401 if (Name == "__main") return (void*)(intptr_t)&jit_noop;
402
Danil Malyshev068c65b2012-05-16 18:50:11 +0000403 const char *NameStr = Name.c_str();
404 void *Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(NameStr);
405 if (Ptr) return Ptr;
406
407 // If it wasn't found and if it starts with an underscore ('_') character,
408 // try again without the underscore.
409 if (NameStr[0] == '_') {
410 Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(NameStr+1);
411 if (Ptr) return Ptr;
412 }
413
414 if (AbortOnFailure)
415 report_fatal_error("Program used external function '" + Name +
416 "' which could not be resolved!");
417 return 0;
418}
419
420LLIMCJITMemoryManager::~LLIMCJITMemoryManager() {
421 for (unsigned i = 0, e = AllocatedCodeMem.size(); i != e; ++i)
422 sys::Memory::ReleaseRWX(AllocatedCodeMem[i]);
423 for (unsigned i = 0, e = AllocatedDataMem.size(); i != e; ++i)
424 free(AllocatedDataMem[i].base());
425}
426
Jim Grosbach706f03a2012-09-05 16:50:34 +0000427
428void layoutRemoteTargetMemory(RemoteTarget *T, RecordingMemoryManager *JMM) {
429 // Lay out our sections in order, with all the code sections first, then
430 // all the data sections.
431 uint64_t CurOffset = 0;
432 unsigned MaxAlign = T->getPageAlignment();
433 SmallVector<std::pair<const void*, uint64_t>, 16> Offsets;
434 SmallVector<unsigned, 16> Sizes;
435 for (RecordingMemoryManager::const_code_iterator I = JMM->code_begin(),
436 E = JMM->code_end();
437 I != E; ++I) {
438 DEBUG(dbgs() << "code region: size " << I->first.size()
439 << ", alignment " << I->second << "\n");
440 // Align the current offset up to whatever is needed for the next
441 // section.
442 unsigned Align = I->second;
443 CurOffset = (CurOffset + Align - 1) / Align * Align;
444 // Save off the address of the new section and allocate its space.
445 Offsets.push_back(std::pair<const void*,uint64_t>(I->first.base(), CurOffset));
446 Sizes.push_back(I->first.size());
447 CurOffset += I->first.size();
448 }
449 // Adjust to keep code and data aligned on seperate pages.
450 CurOffset = (CurOffset + MaxAlign - 1) / MaxAlign * MaxAlign;
451 unsigned FirstDataIndex = Offsets.size();
452 for (RecordingMemoryManager::const_data_iterator I = JMM->data_begin(),
453 E = JMM->data_end();
454 I != E; ++I) {
455 DEBUG(dbgs() << "data region: size " << I->first.size()
456 << ", alignment " << I->second << "\n");
457 // Align the current offset up to whatever is needed for the next
458 // section.
459 unsigned Align = I->second;
460 CurOffset = (CurOffset + Align - 1) / Align * Align;
461 // Save off the address of the new section and allocate its space.
462 Offsets.push_back(std::pair<const void*,uint64_t>(I->first.base(), CurOffset));
463 Sizes.push_back(I->first.size());
464 CurOffset += I->first.size();
465 }
466
467 // Allocate space in the remote target.
468 uint64_t RemoteAddr;
469 if (T->allocateSpace(CurOffset, MaxAlign, RemoteAddr))
470 report_fatal_error(T->getErrorMsg());
471 // Map the section addresses so relocations will get updated in the local
472 // copies of the sections.
473 for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
474 uint64_t Addr = RemoteAddr + Offsets[i].second;
475 EE->mapSectionAddress(const_cast<void*>(Offsets[i].first), Addr);
476
477 DEBUG(dbgs() << " Mapping local: " << Offsets[i].first
Andrew Kaylor3037a582012-11-01 00:17:11 +0000478 << " to remote: " << format("%p", Addr) << "\n");
Jim Grosbach706f03a2012-09-05 16:50:34 +0000479
480 }
Andrew Kaylor28989882012-11-05 20:57:16 +0000481
482 // Trigger application of relocations
483 EE->finalizeObject();
484
Jim Grosbach706f03a2012-09-05 16:50:34 +0000485 // Now load it all to the target.
486 for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
487 uint64_t Addr = RemoteAddr + Offsets[i].second;
488
489 if (i < FirstDataIndex) {
490 T->loadCode(Addr, Offsets[i].first, Sizes[i]);
491
492 DEBUG(dbgs() << " loading code: " << Offsets[i].first
Andrew Kaylor3037a582012-11-01 00:17:11 +0000493 << " to remote: " << format("%p", Addr) << "\n");
Jim Grosbach706f03a2012-09-05 16:50:34 +0000494 } else {
495 T->loadData(Addr, Offsets[i].first, Sizes[i]);
496
497 DEBUG(dbgs() << " loading data: " << Offsets[i].first
Andrew Kaylor3037a582012-11-01 00:17:11 +0000498 << " to remote: " << format("%p", Addr) << "\n");
Jim Grosbach706f03a2012-09-05 16:50:34 +0000499 }
500
501 }
502}
503
Chris Lattner92101ac2001-08-23 17:05:04 +0000504//===----------------------------------------------------------------------===//
Chris Lattner92101ac2001-08-23 17:05:04 +0000505// main Driver function
506//
Misha Brukmanc4fb6fd2003-10-14 21:39:53 +0000507int main(int argc, char **argv, char * const *envp) {
Chris Lattnercc14d252009-03-06 05:34:10 +0000508 sys::PrintStackTraceOnErrorSignal();
509 PrettyStackTraceProgram X(argc, argv);
Eli Benderskya66a1852012-01-16 08:56:09 +0000510
Owen Anderson0d7c6952009-07-15 22:16:10 +0000511 LLVMContext &Context = getGlobalContext();
Reid Spencerf70d6772007-03-03 18:21:44 +0000512 atexit(do_shutdown); // Call llvm_shutdown() on exit.
Daniel Dunbar494d6632009-07-16 02:04:54 +0000513
514 // If we have a native target, initialize it to ensure it is linked in and
515 // usable by the JIT.
516 InitializeNativeTarget();
Jim Grosbach31649e62011-03-18 22:48:41 +0000517 InitializeNativeTargetAsmPrinter();
Jim Grosbach68372322012-11-05 19:06:05 +0000518 InitializeNativeTargetAsmParser();
Daniel Dunbar494d6632009-07-16 02:04:54 +0000519
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000520 cl::ParseCommandLineOptions(argc, argv,
Dan Gohman82a13c92007-10-08 15:45:12 +0000521 "llvm interpreter & dynamic compiler\n");
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000522
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000523 // If the user doesn't want core files, disable them.
524 if (DisableCoreFiles)
525 sys::Process::PreventCoreFiles();
Eli Benderskya66a1852012-01-16 08:56:09 +0000526
Gabor Greifa99be512007-07-05 17:07:56 +0000527 // Load the bitcode...
Daniel Dunbar46a27162010-11-13 00:28:01 +0000528 SMDiagnostic Err;
529 Module *Mod = ParseIRFile(InputFile, Err, Context);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000530 if (!Mod) {
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000531 Err.print(argv[0], errs());
Daniel Dunbar46a27162010-11-13 00:28:01 +0000532 return 1;
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000533 }
534
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000535 // If not jitting lazily, load the whole bitcode file eagerly too.
Daniel Dunbar46a27162010-11-13 00:28:01 +0000536 std::string ErrorMsg;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000537 if (NoLazyCompilation) {
538 if (Mod->MaterializeAllPermanently(&ErrorMsg)) {
539 errs() << argv[0] << ": bitcode didn't read correctly.\n";
540 errs() << "Reason: " << ErrorMsg << "\n";
541 exit(1);
542 }
Evan Chengc290a5b2008-04-22 06:51:41 +0000543 }
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000544
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000545 EngineBuilder builder(Mod);
Jeffrey Yasskin46882612010-02-05 16:19:36 +0000546 builder.setMArch(MArch);
547 builder.setMCPU(MCPU);
548 builder.setMAttrs(MAttrs);
Evan Cheng43966132011-07-19 06:37:02 +0000549 builder.setRelocationModel(RelocModel);
Evan Cheng34ad6db2011-07-20 07:51:56 +0000550 builder.setCodeModel(CMModel);
Daniel Dunbar4dc31362009-07-18 08:07:13 +0000551 builder.setErrorStr(&ErrorMsg);
552 builder.setEngineKind(ForceInterpreter
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000553 ? EngineKind::Interpreter
554 : EngineKind::JIT);
555
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000556 // If we are supposed to override the target triple, do so now.
557 if (!TargetTriple.empty())
Duncan Sands75ebbce2010-08-28 01:30:02 +0000558 Mod->setTargetTriple(Triple::normalize(TargetTriple));
Evan Chengc290a5b2008-04-22 06:51:41 +0000559
Eli Benderskya66a1852012-01-16 08:56:09 +0000560 // Enable MCJIT if desired.
Jim Grosbach706f03a2012-09-05 16:50:34 +0000561 JITMemoryManager *JMM = 0;
Eli Benderskya66a1852012-01-16 08:56:09 +0000562 if (UseMCJIT && !ForceInterpreter) {
Daniel Dunbar6d135972010-11-17 16:06:37 +0000563 builder.setUseMCJIT(true);
Jim Grosbach706f03a2012-09-05 16:50:34 +0000564 if (RemoteMCJIT)
565 JMM = new RecordingMemoryManager();
566 else
567 JMM = new LLIMCJITMemoryManager();
Danil Malyshev068c65b2012-05-16 18:50:11 +0000568 builder.setJITMemoryManager(JMM);
Benjamin Kramer65145512012-05-20 17:24:08 +0000569 } else {
Jim Grosbach706f03a2012-09-05 16:50:34 +0000570 if (RemoteMCJIT) {
571 errs() << "error: Remote process execution requires -use-mcjit\n";
572 exit(1);
573 }
Benjamin Kramer65145512012-05-20 17:24:08 +0000574 builder.setJITMemoryManager(ForceInterpreter ? 0 :
575 JITMemoryManager::CreateDefaultMemManager());
Eli Benderskya66a1852012-01-16 08:56:09 +0000576 }
Daniel Dunbar6d135972010-11-17 16:06:37 +0000577
Evan Cheng712e80e2009-05-04 23:05:19 +0000578 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
579 switch (OptLevel) {
580 default:
Dan Gohman65f57c22009-07-15 16:35:29 +0000581 errs() << argv[0] << ": invalid optimization level.\n";
Evan Cheng712e80e2009-05-04 23:05:19 +0000582 return 1;
583 case ' ': break;
584 case '0': OLvl = CodeGenOpt::None; break;
Evan Chengbf57b522009-10-16 21:02:20 +0000585 case '1': OLvl = CodeGenOpt::Less; break;
Evan Cheng712e80e2009-05-04 23:05:19 +0000586 case '2': OLvl = CodeGenOpt::Default; break;
587 case '3': OLvl = CodeGenOpt::Aggressive; break;
588 }
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000589 builder.setOptLevel(OLvl);
590
Tim Northover77b4c692012-10-12 09:55:13 +0000591 TargetOptions Options;
592 Options.UseSoftFloat = GenerateSoftFloatCalls;
593 if (FloatABIForCalls != FloatABI::Default)
594 Options.FloatABIType = FloatABIForCalls;
595 if (GenerateSoftFloatCalls)
596 FloatABIForCalls = FloatABI::Soft;
597
Jim Grosbach706f03a2012-09-05 16:50:34 +0000598 // Remote target execution doesn't handle EH or debug registration.
599 if (!RemoteMCJIT) {
Jim Grosbach706f03a2012-09-05 16:50:34 +0000600 Options.JITExceptionHandling = EnableJITExceptionHandling;
601 Options.JITEmitDebugInfo = EmitJitDebugInfo;
602 Options.JITEmitDebugInfoToDisk = EmitJitDebugInfoToDisk;
Jim Grosbach706f03a2012-09-05 16:50:34 +0000603 }
Nick Lewycky9a148412012-04-18 08:34:12 +0000604
Tim Northover77b4c692012-10-12 09:55:13 +0000605 builder.setTargetOptions(Options);
606
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000607 EE = builder.create();
Chris Lattnerfd15bee2009-07-07 18:31:09 +0000608 if (!EE) {
609 if (!ErrorMsg.empty())
Dan Gohman65f57c22009-07-15 16:35:29 +0000610 errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n";
Chris Lattnerfd15bee2009-07-07 18:31:09 +0000611 else
Dan Gohman65f57c22009-07-15 16:35:29 +0000612 errs() << argv[0] << ": unknown error creating EE!\n";
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000613 exit(1);
614 }
615
Eli Bendersky61b18512012-03-13 08:33:15 +0000616 // The following functions have no effect if their respective profiling
617 // support wasn't enabled in the build configuration.
618 EE->RegisterJITEventListener(
619 JITEventListener::createOProfileJITEventListener());
620 EE->RegisterJITEventListener(
621 JITEventListener::createIntelJITEventListener());
Jeffrey Yasskindf5a7da2009-06-25 02:04:04 +0000622
Jim Grosbach706f03a2012-09-05 16:50:34 +0000623 if (!NoLazyCompilation && RemoteMCJIT) {
624 errs() << "warning: remote mcjit does not support lazy compilation\n";
625 NoLazyCompilation = true;
626 }
Jeffrey Yasskin18fec732009-10-27 22:39:42 +0000627 EE->DisableLazyCompilation(NoLazyCompilation);
Evan Chengc290a5b2008-04-22 06:51:41 +0000628
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000629 // If the user specifically requested an argv[0] to pass into the program,
630 // do it now.
631 if (!FakeArgv0.empty()) {
632 InputFile = FakeArgv0;
633 } else {
634 // Otherwise, if there is a .bc suffix on the executable strip it off, it
635 // might confuse the program.
Benjamin Kramer3bb37e92010-04-15 11:33:14 +0000636 if (StringRef(InputFile).endswith(".bc"))
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000637 InputFile.erase(InputFile.length() - 3);
638 }
639
640 // Add the module's name to the start of the vector of arguments to main().
641 InputArgv.insert(InputArgv.begin(), InputFile);
642
643 // Call the main function from M as if its signature were:
644 // int main (int argc, char **argv, const char **envp)
645 // using the contents of Args to determine argc & argv, and the contents of
646 // EnvVars to determine envp.
647 //
Evan Chengec740e32008-11-05 23:21:52 +0000648 Function *EntryFn = Mod->getFunction(EntryFunc);
649 if (!EntryFn) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000650 errs() << '\'' << EntryFunc << "\' function not found in module.\n";
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000651 return -1;
652 }
653
Eli Benderskya66a1852012-01-16 08:56:09 +0000654 // If the program doesn't explicitly call exit, we will need the Exit
655 // function later on to make an explicit call, so get the function now.
Owen Anderson1d0be152009-08-13 21:58:54 +0000656 Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
657 Type::getInt32Ty(Context),
658 NULL);
Eli Benderskya66a1852012-01-16 08:56:09 +0000659
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000660 // Reset errno to zero on entry to main.
661 errno = 0;
Eli Benderskya66a1852012-01-16 08:56:09 +0000662
Jim Grosbach706f03a2012-09-05 16:50:34 +0000663 // Remote target MCJIT doesn't (yet) support static constructors. No reason
664 // it couldn't. This is a limitation of the LLI implemantation, not the
665 // MCJIT itself. FIXME.
666 //
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000667 // Run static constructors.
Jim Grosbach706f03a2012-09-05 16:50:34 +0000668 if (!RemoteMCJIT)
669 EE->runStaticConstructorsDestructors(false);
Evan Chengc290a5b2008-04-22 06:51:41 +0000670
671 if (NoLazyCompilation) {
672 for (Module::iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) {
673 Function *Fn = &*I;
Evan Chengec740e32008-11-05 23:21:52 +0000674 if (Fn != EntryFn && !Fn->isDeclaration())
Evan Chengc290a5b2008-04-22 06:51:41 +0000675 EE->getPointerToFunction(Fn);
676 }
677 }
678
Jim Grosbach706f03a2012-09-05 16:50:34 +0000679 int Result;
680 if (RemoteMCJIT) {
681 RecordingMemoryManager *MM = static_cast<RecordingMemoryManager*>(JMM);
682 // Everything is prepared now, so lay out our program for the target
683 // address space, assign the section addresses to resolve any relocations,
684 // and send it to the target.
685 RemoteTarget Target;
686 Target.create();
Jim Grosbach5da959d2012-08-28 23:22:30 +0000687
Jim Grosbach706f03a2012-09-05 16:50:34 +0000688 // Ask for a pointer to the entry function. This triggers the actual
689 // compilation.
690 (void)EE->getPointerToFunction(EntryFn);
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000691
Jim Grosbach706f03a2012-09-05 16:50:34 +0000692 // Enough has been compiled to execute the entry function now, so
693 // layout the target memory.
694 layoutRemoteTargetMemory(&Target, MM);
Eli Benderskya66a1852012-01-16 08:56:09 +0000695
Jim Grosbach706f03a2012-09-05 16:50:34 +0000696 // Since we're executing in a (at least simulated) remote address space,
697 // we can't use the ExecutionEngine::runFunctionAsMain(). We have to
698 // grab the function address directly here and tell the remote target
699 // to execute the function.
700 // FIXME: argv and envp handling.
701 uint64_t Entry = (uint64_t)EE->getPointerToFunction(EntryFn);
702
703 DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at "
Andrew Kaylor3037a582012-11-01 00:17:11 +0000704 << format("%p", Entry) << "\n");
Jim Grosbach706f03a2012-09-05 16:50:34 +0000705
706 if (Target.executeCode(Entry, Result))
707 errs() << "ERROR: " << Target.getErrorMsg() << "\n";
708
709 Target.stop();
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000710 } else {
Tim Northovera668b462012-09-20 08:46:30 +0000711 // Trigger compilation separately so code regions that need to be
712 // invalidated will be known.
713 (void)EE->getPointerToFunction(EntryFn);
Jim Grosbach706f03a2012-09-05 16:50:34 +0000714 // Clear instruction cache before code will be executed.
715 if (JMM)
716 static_cast<LLIMCJITMemoryManager*>(JMM)->invalidateInstructionCache();
717
718 // Run main.
719 Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000720 }
Jim Grosbach706f03a2012-09-05 16:50:34 +0000721
722 // Like static constructors, the remote target MCJIT support doesn't handle
723 // this yet. It could. FIXME.
724 if (!RemoteMCJIT) {
725 // Run static destructors.
726 EE->runStaticConstructorsDestructors(true);
727
728 // If the program didn't call exit explicitly, we should call it now.
729 // This ensures that any atexit handlers get called correctly.
730 if (Function *ExitF = dyn_cast<Function>(Exit)) {
731 std::vector<GenericValue> Args;
732 GenericValue ResultGV;
733 ResultGV.IntVal = APInt(32, Result);
734 Args.push_back(ResultGV);
735 EE->runFunction(ExitF, Args);
736 errs() << "ERROR: exit(" << Result << ") returned!\n";
737 abort();
738 } else {
739 errs() << "ERROR: exit defined with wrong prototype!\n";
740 abort();
741 }
742 }
743 return Result;
Chris Lattner92101ac2001-08-23 17:05:04 +0000744}