blob: b6c9299c65b58314df7827fb30ff0254abd11ff1 [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
Owen Anderson8b477ed2009-07-01 16:58:40 +000016#include "llvm/LLVMContext.h"
Chris Lattnerfd131292003-09-05 20:08:15 +000017#include "llvm/Module.h"
Chris Lattner269a4282003-12-26 06:49:53 +000018#include "llvm/Type.h"
Duncan Sands75ebbce2010-08-28 01:30:02 +000019#include "llvm/ADT/Triple.h"
Chris Lattnerc1e6d682007-05-06 04:58:26 +000020#include "llvm/Bitcode/ReaderWriter.h"
Chris Lattnerd3a680a2006-08-01 22:34:35 +000021#include "llvm/CodeGen/LinkAllCodegenComponents.h"
Brian Gaeked1cab3e2003-09-05 19:42:34 +000022#include "llvm/ExecutionEngine/GenericValue.h"
Jeffrey Yasskindf5a7da2009-06-25 02:04:04 +000023#include "llvm/ExecutionEngine/Interpreter.h"
24#include "llvm/ExecutionEngine/JIT.h"
25#include "llvm/ExecutionEngine/JITEventListener.h"
Jim Grosbachbf9ab932012-01-11 21:12:51 +000026#include "llvm/ExecutionEngine/JITMemoryManager.h"
Daniel Dunbar6aec2982010-11-17 16:06:43 +000027#include "llvm/ExecutionEngine/MCJIT.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000028#include "llvm/Support/CommandLine.h"
Daniel Dunbar46a27162010-11-13 00:28:01 +000029#include "llvm/Support/IRReader.h"
Chris Lattnerc30598b2006-12-06 01:18:01 +000030#include "llvm/Support/ManagedStatic.h"
Chris Lattnerc1e6d682007-05-06 04:58:26 +000031#include "llvm/Support/MemoryBuffer.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000032#include "llvm/Support/PluginLoader.h"
Chris Lattnercc14d252009-03-06 05:34:10 +000033#include "llvm/Support/PrettyStackTrace.h"
Chris Lattner74382b72009-08-23 22:45:37 +000034#include "llvm/Support/raw_ostream.h"
Michael J. Spencer1f6efa32010-11-29 18:16:10 +000035#include "llvm/Support/Process.h"
36#include "llvm/Support/Signals.h"
Evan Cheng3e74d6f2011-08-24 18:08:43 +000037#include "llvm/Support/TargetSelect.h"
Danil Malyshev068c65b2012-05-16 18:50:11 +000038#include "llvm/Support/DynamicLibrary.h"
39#include "llvm/Support/Memory.h"
Chris Lattner02040322007-04-27 17:02:33 +000040#include <cerrno>
NAKAMURA Takumia13d14a2010-10-22 14:53:59 +000041
Danil Malyshev068c65b2012-05-16 18:50:11 +000042#ifdef __linux__
43// These includes used by LLIMCJITMemoryManager::getPointerToNamedFunction()
44// for Glibc trickery. Look comments in this function for more information.
45#ifdef HAVE_SYS_STAT_H
46#include <sys/stat.h>
47#endif
48#include <fcntl.h>
49#include <unistd.h>
50#endif
51
NAKAMURA Takumia13d14a2010-10-22 14:53:59 +000052#ifdef __CYGWIN__
53#include <cygwin/version.h>
54#if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
55#define DO_NOTHING_ATEXIT 1
56#endif
57#endif
58
Brian Gaeked0fde302003-11-11 22:41:34 +000059using namespace llvm;
60
Chris Lattnerfe11a972002-12-23 23:59:41 +000061namespace {
62 cl::opt<std::string>
Gabor Greifa99be512007-07-05 17:07:56 +000063 InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
Chris Lattner5ff62e92002-07-22 02:10:13 +000064
Chris Lattnerfe11a972002-12-23 23:59:41 +000065 cl::list<std::string>
66 InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
Chris Lattner5ff62e92002-07-22 02:10:13 +000067
Chris Lattnerfe11a972002-12-23 23:59:41 +000068 cl::opt<bool> ForceInterpreter("force-interpreter",
Misha Brukman3d8a54d2003-09-25 18:10:34 +000069 cl::desc("Force interpretation: disable JIT"),
70 cl::init(false));
Evan Chenge1a4eda2008-08-08 08:12:06 +000071
Daniel Dunbar6d135972010-11-17 16:06:37 +000072 cl::opt<bool> UseMCJIT(
73 "use-mcjit", cl::desc("Enable use of the MC-based JIT (if available)"),
74 cl::init(false));
75
Evan Cheng712e80e2009-05-04 23:05:19 +000076 // Determine optimization level.
77 cl::opt<char>
78 OptLevel("O",
79 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
80 "(default = '-O2')"),
81 cl::Prefix,
82 cl::ZeroOrMore,
83 cl::init(' '));
Evan Chenge1a4eda2008-08-08 08:12:06 +000084
Chris Lattner3015e602005-12-16 05:00:21 +000085 cl::opt<std::string>
Chris Lattner60844d42005-12-16 05:19:18 +000086 TargetTriple("mtriple", cl::desc("Override target triple for module"));
Evan Chengec740e32008-11-05 23:21:52 +000087
88 cl::opt<std::string>
Jeffrey Yasskin46882612010-02-05 16:19:36 +000089 MArch("march",
90 cl::desc("Architecture to generate assembly for (see --version)"));
91
92 cl::opt<std::string>
93 MCPU("mcpu",
94 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
95 cl::value_desc("cpu-name"),
96 cl::init(""));
97
98 cl::list<std::string>
99 MAttrs("mattr",
100 cl::CommaSeparated,
101 cl::desc("Target specific attributes (-mattr=help for details)"),
102 cl::value_desc("a1,+a2,-a3,..."));
103
104 cl::opt<std::string>
Evan Chengec740e32008-11-05 23:21:52 +0000105 EntryFunc("entry-function",
106 cl::desc("Specify the entry function (default = 'main') "
107 "of the executable"),
108 cl::value_desc("function"),
109 cl::init("main"));
Eli Benderskya66a1852012-01-16 08:56:09 +0000110
Chris Lattnere69671d2003-10-28 22:51:44 +0000111 cl::opt<std::string>
112 FakeArgv0("fake-argv0",
113 cl::desc("Override the 'argv[0]' value passed into the executing"
114 " program"), cl::value_desc("executable"));
Eli Benderskya66a1852012-01-16 08:56:09 +0000115
Chris Lattner43f249a2006-09-14 06:17:09 +0000116 cl::opt<bool>
117 DisableCoreFiles("disable-core-files", cl::Hidden,
118 cl::desc("Disable emission of core files if possible"));
Evan Chengc290a5b2008-04-22 06:51:41 +0000119
120 cl::opt<bool>
Evan Cheng03dace82008-05-21 18:20:21 +0000121 NoLazyCompilation("disable-lazy-compilation",
Evan Chengc290a5b2008-04-22 06:51:41 +0000122 cl::desc("Disable JIT lazy compilation"),
123 cl::init(false));
Evan Cheng43966132011-07-19 06:37:02 +0000124
125 cl::opt<Reloc::Model>
126 RelocModel("relocation-model",
127 cl::desc("Choose relocation model"),
128 cl::init(Reloc::Default),
129 cl::values(
130 clEnumValN(Reloc::Default, "default",
131 "Target default relocation model"),
132 clEnumValN(Reloc::Static, "static",
133 "Non-relocatable code"),
134 clEnumValN(Reloc::PIC_, "pic",
135 "Fully relocatable, position independent code"),
136 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
137 "Relocatable external references, non-relocatable code"),
138 clEnumValEnd));
Evan Cheng34ad6db2011-07-20 07:51:56 +0000139
140 cl::opt<llvm::CodeModel::Model>
141 CMModel("code-model",
142 cl::desc("Choose code model"),
143 cl::init(CodeModel::JITDefault),
144 cl::values(clEnumValN(CodeModel::JITDefault, "default",
145 "Target default JIT code model"),
146 clEnumValN(CodeModel::Small, "small",
147 "Small code model"),
148 clEnumValN(CodeModel::Kernel, "kernel",
149 "Kernel code model"),
150 clEnumValN(CodeModel::Medium, "medium",
151 "Medium code model"),
152 clEnumValN(CodeModel::Large, "large",
153 "Large code model"),
154 clEnumValEnd));
155
Nick Lewycky9a148412012-04-18 08:34:12 +0000156 cl::opt<bool>
157 EnableJITExceptionHandling("jit-enable-eh",
158 cl::desc("Emit exception handling information"),
159 cl::init(false));
160
161 cl::opt<bool>
162// In debug builds, make this default to true.
163#ifdef NDEBUG
164#define EMIT_DEBUG false
165#else
166#define EMIT_DEBUG true
167#endif
168 EmitJitDebugInfo("jit-emit-debug",
169 cl::desc("Emit debug information to debugger"),
170 cl::init(EMIT_DEBUG));
171#undef EMIT_DEBUG
172
173 static cl::opt<bool>
174 EmitJitDebugInfoToDisk("jit-emit-debug-to-disk",
175 cl::Hidden,
176 cl::desc("Emit debug info objfiles to disk"),
177 cl::init(false));
Chris Lattnerfe11a972002-12-23 23:59:41 +0000178}
Chris Lattner43e3f7c2001-10-27 08:43:52 +0000179
Reid Spencerf70d6772007-03-03 18:21:44 +0000180static ExecutionEngine *EE = 0;
181
182static void do_shutdown() {
NAKAMURA Takumia13d14a2010-10-22 14:53:59 +0000183 // Cygwin-1.5 invokes DLL's dtors before atexit handler.
184#ifndef DO_NOTHING_ATEXIT
Reid Spencerf70d6772007-03-03 18:21:44 +0000185 delete EE;
186 llvm_shutdown();
NAKAMURA Takumia13d14a2010-10-22 14:53:59 +0000187#endif
Reid Spencerf70d6772007-03-03 18:21:44 +0000188}
189
Danil Malyshev068c65b2012-05-16 18:50:11 +0000190// Memory manager for MCJIT
191class LLIMCJITMemoryManager : public JITMemoryManager {
192public:
193 SmallVector<sys::MemoryBlock, 16> AllocatedDataMem;
194 SmallVector<sys::MemoryBlock, 16> AllocatedCodeMem;
195 SmallVector<sys::MemoryBlock, 16> FreeCodeMem;
196
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000197 LLIMCJITMemoryManager() { }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000198 ~LLIMCJITMemoryManager();
199
200 virtual uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
201 unsigned SectionID);
202
203 virtual uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
204 unsigned SectionID);
205
206 virtual void *getPointerToNamedFunction(const std::string &Name,
207 bool AbortOnFailure = true);
208
209 // Invalidate instruction cache for code sections. Some platforms with
210 // separate data cache and instruction cache require explicit cache flush,
211 // otherwise JIT code manipulations (like resolved relocations) will get to
212 // the data cache but not to the instruction cache.
213 virtual void invalidateInstructionCache();
214
215 // The MCJITMemoryManager doesn't use the following functions, so we don't
216 // need implement them.
217 virtual void setMemoryWritable() {
218 llvm_unreachable("Unexpected call!");
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000219 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000220 virtual void setMemoryExecutable() {
221 llvm_unreachable("Unexpected call!");
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000222 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000223 virtual void setPoisonMemory(bool poison) {
224 llvm_unreachable("Unexpected call!");
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000225 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000226 virtual void AllocateGOT() {
227 llvm_unreachable("Unexpected call!");
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000228 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000229 virtual uint8_t *getGOTBase() const {
230 llvm_unreachable("Unexpected call!");
231 return 0;
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000232 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000233 virtual uint8_t *startFunctionBody(const Function *F,
234 uintptr_t &ActualSize){
235 llvm_unreachable("Unexpected call!");
236 return 0;
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000237 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000238 virtual uint8_t *allocateStub(const GlobalValue* F, unsigned StubSize,
239 unsigned Alignment) {
240 llvm_unreachable("Unexpected call!");
241 return 0;
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000242 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000243 virtual void endFunctionBody(const Function *F, uint8_t *FunctionStart,
244 uint8_t *FunctionEnd) {
245 llvm_unreachable("Unexpected call!");
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000246 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000247 virtual uint8_t *allocateSpace(intptr_t Size, unsigned Alignment) {
248 llvm_unreachable("Unexpected call!");
249 return 0;
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000250 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000251 virtual uint8_t *allocateGlobal(uintptr_t Size, unsigned Alignment) {
252 llvm_unreachable("Unexpected call!");
253 return 0;
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000254 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000255 virtual void deallocateFunctionBody(void *Body) {
256 llvm_unreachable("Unexpected call!");
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000257 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000258 virtual uint8_t* startExceptionTable(const Function* F,
259 uintptr_t &ActualSize) {
260 llvm_unreachable("Unexpected call!");
261 return 0;
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000262 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000263 virtual void endExceptionTable(const Function *F, uint8_t *TableStart,
264 uint8_t *TableEnd, uint8_t* FrameRegister) {
265 llvm_unreachable("Unexpected call!");
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000266 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000267 virtual void deallocateExceptionTable(void *ET) {
268 llvm_unreachable("Unexpected call!");
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000269 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000270};
271
272uint8_t *LLIMCJITMemoryManager::allocateDataSection(uintptr_t Size,
273 unsigned Alignment,
274 unsigned SectionID) {
275 if (!Alignment)
276 Alignment = 16;
277 uint8_t *Addr = (uint8_t*)calloc((Size + Alignment - 1)/Alignment, Alignment);
278 AllocatedDataMem.push_back(sys::MemoryBlock(Addr, Size));
279 return Addr;
280}
281
282uint8_t *LLIMCJITMemoryManager::allocateCodeSection(uintptr_t Size,
283 unsigned Alignment,
284 unsigned SectionID) {
285 if (!Alignment)
286 Alignment = 16;
287 unsigned NeedAllocate = Alignment * ((Size + Alignment - 1)/Alignment + 1);
288 uintptr_t Addr = 0;
289 // Look in the list of free code memory regions and use a block there if one
290 // is available.
291 for (int i = 0, e = FreeCodeMem.size(); i != e; ++i) {
292 sys::MemoryBlock &MB = FreeCodeMem[i];
293 if (MB.size() >= NeedAllocate) {
294 Addr = (uintptr_t)MB.base();
295 uintptr_t EndOfBlock = Addr + MB.size();
296 // Align the address.
297 Addr = (Addr + Alignment - 1) & ~(uintptr_t)(Alignment - 1);
298 // Store cutted free memory block.
299 FreeCodeMem[i] = sys::MemoryBlock((void*)(Addr + Size),
300 EndOfBlock - Addr - Size);
301 return (uint8_t*)Addr;
302 }
303 }
304
305 // No pre-allocated free block was large enough. Allocate a new memory region.
306 sys::MemoryBlock MB = sys::Memory::AllocateRWX(NeedAllocate, 0, 0);
307
308 AllocatedCodeMem.push_back(MB);
309 Addr = (uintptr_t)MB.base();
310 uintptr_t EndOfBlock = Addr + MB.size();
311 // Align the address.
312 Addr = (Addr + Alignment - 1) & ~(uintptr_t)(Alignment - 1);
313 // The AllocateRWX may allocate much more memory than we need. In this case,
314 // we store the unused memory as a free memory block.
315 unsigned FreeSize = EndOfBlock-Addr-Size;
316 if (FreeSize > 16)
317 FreeCodeMem.push_back(sys::MemoryBlock((void*)(Addr + Size), FreeSize));
318
319 // Return aligned address
320 return (uint8_t*)Addr;
321}
322
323void LLIMCJITMemoryManager::invalidateInstructionCache() {
324 for (int i = 0, e = AllocatedCodeMem.size(); i != e; ++i)
325 sys::Memory::InvalidateInstructionCache(AllocatedCodeMem[i].base(),
326 AllocatedCodeMem[i].size());
327}
328
329void *LLIMCJITMemoryManager::getPointerToNamedFunction(const std::string &Name,
330 bool AbortOnFailure) {
331#if defined(__linux__)
332 //===--------------------------------------------------------------------===//
333 // Function stubs that are invoked instead of certain library calls
334 //
335 // Force the following functions to be linked in to anything that uses the
336 // JIT. This is a hack designed to work around the all-too-clever Glibc
337 // strategy of making these functions work differently when inlined vs. when
338 // not inlined, and hiding their real definitions in a separate archive file
339 // that the dynamic linker can't see. For more info, search for
340 // 'libc_nonshared.a' on Google, or read http://llvm.org/PR274.
341 if (Name == "stat") return (void*)(intptr_t)&stat;
342 if (Name == "fstat") return (void*)(intptr_t)&fstat;
343 if (Name == "lstat") return (void*)(intptr_t)&lstat;
344 if (Name == "stat64") return (void*)(intptr_t)&stat64;
345 if (Name == "fstat64") return (void*)(intptr_t)&fstat64;
346 if (Name == "lstat64") return (void*)(intptr_t)&lstat64;
347 if (Name == "atexit") return (void*)(intptr_t)&atexit;
348 if (Name == "mknod") return (void*)(intptr_t)&mknod;
349#endif // __linux__
350
351 const char *NameStr = Name.c_str();
352 void *Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(NameStr);
353 if (Ptr) return Ptr;
354
355 // If it wasn't found and if it starts with an underscore ('_') character,
356 // try again without the underscore.
357 if (NameStr[0] == '_') {
358 Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(NameStr+1);
359 if (Ptr) return Ptr;
360 }
361
362 if (AbortOnFailure)
363 report_fatal_error("Program used external function '" + Name +
364 "' which could not be resolved!");
365 return 0;
366}
367
368LLIMCJITMemoryManager::~LLIMCJITMemoryManager() {
369 for (unsigned i = 0, e = AllocatedCodeMem.size(); i != e; ++i)
370 sys::Memory::ReleaseRWX(AllocatedCodeMem[i]);
371 for (unsigned i = 0, e = AllocatedDataMem.size(); i != e; ++i)
372 free(AllocatedDataMem[i].base());
373}
374
Chris Lattner92101ac2001-08-23 17:05:04 +0000375//===----------------------------------------------------------------------===//
Chris Lattner92101ac2001-08-23 17:05:04 +0000376// main Driver function
377//
Misha Brukmanc4fb6fd2003-10-14 21:39:53 +0000378int main(int argc, char **argv, char * const *envp) {
Chris Lattnercc14d252009-03-06 05:34:10 +0000379 sys::PrintStackTraceOnErrorSignal();
380 PrettyStackTraceProgram X(argc, argv);
Eli Benderskya66a1852012-01-16 08:56:09 +0000381
Owen Anderson0d7c6952009-07-15 22:16:10 +0000382 LLVMContext &Context = getGlobalContext();
Reid Spencerf70d6772007-03-03 18:21:44 +0000383 atexit(do_shutdown); // Call llvm_shutdown() on exit.
Daniel Dunbar494d6632009-07-16 02:04:54 +0000384
385 // If we have a native target, initialize it to ensure it is linked in and
386 // usable by the JIT.
387 InitializeNativeTarget();
Jim Grosbach31649e62011-03-18 22:48:41 +0000388 InitializeNativeTargetAsmPrinter();
Daniel Dunbar494d6632009-07-16 02:04:54 +0000389
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000390 cl::ParseCommandLineOptions(argc, argv,
Dan Gohman82a13c92007-10-08 15:45:12 +0000391 "llvm interpreter & dynamic compiler\n");
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000392
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000393 // If the user doesn't want core files, disable them.
394 if (DisableCoreFiles)
395 sys::Process::PreventCoreFiles();
Eli Benderskya66a1852012-01-16 08:56:09 +0000396
Gabor Greifa99be512007-07-05 17:07:56 +0000397 // Load the bitcode...
Daniel Dunbar46a27162010-11-13 00:28:01 +0000398 SMDiagnostic Err;
399 Module *Mod = ParseIRFile(InputFile, Err, Context);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000400 if (!Mod) {
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000401 Err.print(argv[0], errs());
Daniel Dunbar46a27162010-11-13 00:28:01 +0000402 return 1;
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000403 }
404
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000405 // If not jitting lazily, load the whole bitcode file eagerly too.
Daniel Dunbar46a27162010-11-13 00:28:01 +0000406 std::string ErrorMsg;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000407 if (NoLazyCompilation) {
408 if (Mod->MaterializeAllPermanently(&ErrorMsg)) {
409 errs() << argv[0] << ": bitcode didn't read correctly.\n";
410 errs() << "Reason: " << ErrorMsg << "\n";
411 exit(1);
412 }
Evan Chengc290a5b2008-04-22 06:51:41 +0000413 }
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000414
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000415 EngineBuilder builder(Mod);
Jeffrey Yasskin46882612010-02-05 16:19:36 +0000416 builder.setMArch(MArch);
417 builder.setMCPU(MCPU);
418 builder.setMAttrs(MAttrs);
Evan Cheng43966132011-07-19 06:37:02 +0000419 builder.setRelocationModel(RelocModel);
Evan Cheng34ad6db2011-07-20 07:51:56 +0000420 builder.setCodeModel(CMModel);
Daniel Dunbar4dc31362009-07-18 08:07:13 +0000421 builder.setErrorStr(&ErrorMsg);
422 builder.setEngineKind(ForceInterpreter
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000423 ? EngineKind::Interpreter
424 : EngineKind::JIT);
425
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000426 // If we are supposed to override the target triple, do so now.
427 if (!TargetTriple.empty())
Duncan Sands75ebbce2010-08-28 01:30:02 +0000428 Mod->setTargetTriple(Triple::normalize(TargetTriple));
Evan Chengc290a5b2008-04-22 06:51:41 +0000429
Eli Benderskya66a1852012-01-16 08:56:09 +0000430 // Enable MCJIT if desired.
Danil Malyshev068c65b2012-05-16 18:50:11 +0000431 LLIMCJITMemoryManager *JMM = 0;
Eli Benderskya66a1852012-01-16 08:56:09 +0000432 if (UseMCJIT && !ForceInterpreter) {
Daniel Dunbar6d135972010-11-17 16:06:37 +0000433 builder.setUseMCJIT(true);
Danil Malyshev068c65b2012-05-16 18:50:11 +0000434 JMM = new LLIMCJITMemoryManager();
435 builder.setJITMemoryManager(JMM);
Benjamin Kramer65145512012-05-20 17:24:08 +0000436 } else {
437 builder.setJITMemoryManager(ForceInterpreter ? 0 :
438 JITMemoryManager::CreateDefaultMemManager());
Eli Benderskya66a1852012-01-16 08:56:09 +0000439 }
Daniel Dunbar6d135972010-11-17 16:06:37 +0000440
Evan Cheng712e80e2009-05-04 23:05:19 +0000441 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
442 switch (OptLevel) {
443 default:
Dan Gohman65f57c22009-07-15 16:35:29 +0000444 errs() << argv[0] << ": invalid optimization level.\n";
Evan Cheng712e80e2009-05-04 23:05:19 +0000445 return 1;
446 case ' ': break;
447 case '0': OLvl = CodeGenOpt::None; break;
Evan Chengbf57b522009-10-16 21:02:20 +0000448 case '1': OLvl = CodeGenOpt::Less; break;
Evan Cheng712e80e2009-05-04 23:05:19 +0000449 case '2': OLvl = CodeGenOpt::Default; break;
450 case '3': OLvl = CodeGenOpt::Aggressive; break;
451 }
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000452 builder.setOptLevel(OLvl);
453
Nick Lewycky9a148412012-04-18 08:34:12 +0000454 TargetOptions Options;
455 Options.JITExceptionHandling = EnableJITExceptionHandling;
456 Options.JITEmitDebugInfo = EmitJitDebugInfo;
457 Options.JITEmitDebugInfoToDisk = EmitJitDebugInfoToDisk;
458 builder.setTargetOptions(Options);
459
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000460 EE = builder.create();
Chris Lattnerfd15bee2009-07-07 18:31:09 +0000461 if (!EE) {
462 if (!ErrorMsg.empty())
Dan Gohman65f57c22009-07-15 16:35:29 +0000463 errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n";
Chris Lattnerfd15bee2009-07-07 18:31:09 +0000464 else
Dan Gohman65f57c22009-07-15 16:35:29 +0000465 errs() << argv[0] << ": unknown error creating EE!\n";
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000466 exit(1);
467 }
468
Danil Malyshev068c65b2012-05-16 18:50:11 +0000469 // Clear instruction cache before code will be executed.
470 if (JMM)
471 JMM->invalidateInstructionCache();
472
Eli Bendersky61b18512012-03-13 08:33:15 +0000473 // The following functions have no effect if their respective profiling
474 // support wasn't enabled in the build configuration.
475 EE->RegisterJITEventListener(
476 JITEventListener::createOProfileJITEventListener());
477 EE->RegisterJITEventListener(
478 JITEventListener::createIntelJITEventListener());
Jeffrey Yasskindf5a7da2009-06-25 02:04:04 +0000479
Jeffrey Yasskin18fec732009-10-27 22:39:42 +0000480 EE->DisableLazyCompilation(NoLazyCompilation);
Evan Chengc290a5b2008-04-22 06:51:41 +0000481
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000482 // If the user specifically requested an argv[0] to pass into the program,
483 // do it now.
484 if (!FakeArgv0.empty()) {
485 InputFile = FakeArgv0;
486 } else {
487 // Otherwise, if there is a .bc suffix on the executable strip it off, it
488 // might confuse the program.
Benjamin Kramer3bb37e92010-04-15 11:33:14 +0000489 if (StringRef(InputFile).endswith(".bc"))
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000490 InputFile.erase(InputFile.length() - 3);
491 }
492
493 // Add the module's name to the start of the vector of arguments to main().
494 InputArgv.insert(InputArgv.begin(), InputFile);
495
496 // Call the main function from M as if its signature were:
497 // int main (int argc, char **argv, const char **envp)
498 // using the contents of Args to determine argc & argv, and the contents of
499 // EnvVars to determine envp.
500 //
Evan Chengec740e32008-11-05 23:21:52 +0000501 Function *EntryFn = Mod->getFunction(EntryFunc);
502 if (!EntryFn) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000503 errs() << '\'' << EntryFunc << "\' function not found in module.\n";
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000504 return -1;
505 }
506
Eli Benderskya66a1852012-01-16 08:56:09 +0000507 // If the program doesn't explicitly call exit, we will need the Exit
508 // function later on to make an explicit call, so get the function now.
Owen Anderson1d0be152009-08-13 21:58:54 +0000509 Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
510 Type::getInt32Ty(Context),
511 NULL);
Eli Benderskya66a1852012-01-16 08:56:09 +0000512
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000513 // Reset errno to zero on entry to main.
514 errno = 0;
Eli Benderskya66a1852012-01-16 08:56:09 +0000515
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000516 // Run static constructors.
517 EE->runStaticConstructorsDestructors(false);
Evan Chengc290a5b2008-04-22 06:51:41 +0000518
519 if (NoLazyCompilation) {
520 for (Module::iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) {
521 Function *Fn = &*I;
Evan Chengec740e32008-11-05 23:21:52 +0000522 if (Fn != EntryFn && !Fn->isDeclaration())
Evan Chengc290a5b2008-04-22 06:51:41 +0000523 EE->getPointerToFunction(Fn);
524 }
525 }
526
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000527 // Run main.
Evan Chengec740e32008-11-05 23:21:52 +0000528 int Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000529
530 // Run static destructors.
531 EE->runStaticConstructorsDestructors(true);
Eli Benderskya66a1852012-01-16 08:56:09 +0000532
533 // If the program didn't call exit explicitly, we should call it now.
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000534 // This ensures that any atexit handlers get called correctly.
535 if (Function *ExitF = dyn_cast<Function>(Exit)) {
536 std::vector<GenericValue> Args;
537 GenericValue ResultGV;
538 ResultGV.IntVal = APInt(32, Result);
539 Args.push_back(ResultGV);
540 EE->runFunction(ExitF, Args);
Dan Gohman65f57c22009-07-15 16:35:29 +0000541 errs() << "ERROR: exit(" << Result << ") returned!\n";
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000542 abort();
543 } else {
Dan Gohman65f57c22009-07-15 16:35:29 +0000544 errs() << "ERROR: exit defined with wrong prototype!\n";
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000545 abort();
546 }
Chris Lattner92101ac2001-08-23 17:05:04 +0000547}