blob: 0227261f4859d236d1339c0aae50bc2a00882dfd [file] [log] [blame]
Chris Lattnera0d7b082002-12-23 23:59:41 +00001//===- lli.cpp - LLVM Interpreter / Dynamic compiler ----------------------===//
Misha Brukman650ba8e2005-04-22 00:00:37 +00002//
John Criswell09344dc2003-10-20 17:47:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner345353d2007-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 Brukman650ba8e2005-04-22 00:00:37 +00007//
John Criswell09344dc2003-10-20 17:47:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerd7ff5782001-08-23 17:05:04 +00009//
Chris Lattner141ea3a2003-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 Edwinf011f282009-07-03 12:11:32 +000012// compiler, or through an interpreter if no JIT is available for this platform.
Chris Lattnerd7ff5782001-08-23 17:05:04 +000013//
14//===----------------------------------------------------------------------===//
15
Jim Grosbach0f435d02012-09-05 16:50:34 +000016#define DEBUG_TYPE "lli"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000017#include "llvm/IR/LLVMContext.h"
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +000018#include "RemoteMemoryManager.h"
Jim Grosbach0f435d02012-09-05 16:50:34 +000019#include "RemoteTarget.h"
Duncan Sands3bd97fe2010-08-28 01:30:02 +000020#include "llvm/ADT/Triple.h"
Chris Lattner2785bdb2007-05-06 04:58:26 +000021#include "llvm/Bitcode/ReaderWriter.h"
Chris Lattner5af6a3f2006-08-01 22:34:35 +000022#include "llvm/CodeGen/LinkAllCodegenComponents.h"
Brian Gaekee99ca442003-09-05 19:42:34 +000023#include "llvm/ExecutionEngine/GenericValue.h"
Jeffrey Yasskin0b08f3d2009-06-25 02:04:04 +000024#include "llvm/ExecutionEngine/Interpreter.h"
25#include "llvm/ExecutionEngine/JIT.h"
26#include "llvm/ExecutionEngine/JITEventListener.h"
Jim Grosbachbf570b92012-01-11 21:12:51 +000027#include "llvm/ExecutionEngine/JITMemoryManager.h"
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000028#include "llvm/ExecutionEngine/MCJIT.h"
Lang Hames173c69f2014-01-08 04:09:09 +000029#include "llvm/ExecutionEngine/ObjectCache.h"
Andrew Kaylor58365b92012-11-27 19:49:00 +000030#include "llvm/ExecutionEngine/SectionMemoryManager.h"
Andrew Kaylor1ca510e2013-10-29 01:29:56 +000031#include "llvm/IR/IRBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/Module.h"
33#include "llvm/IR/Type.h"
Andrew Kaylor1ca510e2013-10-29 01:29:56 +000034#include "llvm/IR/TypeBuilder.h"
Chandler Carruthe60e57b2013-03-26 02:25:37 +000035#include "llvm/IRReader/IRReader.h"
Lang Hames173c69f2014-01-08 04:09:09 +000036#include "llvm/Object/Archive.h"
37#include "llvm/Object/ObjectFile.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000038#include "llvm/Support/CommandLine.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000039#include "llvm/Support/Debug.h"
40#include "llvm/Support/DynamicLibrary.h"
41#include "llvm/Support/Format.h"
Chris Lattner76d46322006-12-06 01:18:01 +000042#include "llvm/Support/ManagedStatic.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000043#include "llvm/Support/MathExtras.h"
44#include "llvm/Support/Memory.h"
Chris Lattner2785bdb2007-05-06 04:58:26 +000045#include "llvm/Support/MemoryBuffer.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000046#include "llvm/Support/PluginLoader.h"
Chris Lattnere3fc2d12009-03-06 05:34:10 +000047#include "llvm/Support/PrettyStackTrace.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000048#include "llvm/Support/Process.h"
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +000049#include "llvm/Support/Program.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000050#include "llvm/Support/Signals.h"
Chandler Carruthe60e57b2013-03-26 02:25:37 +000051#include "llvm/Support/SourceMgr.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000052#include "llvm/Support/TargetSelect.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000053#include "llvm/Support/raw_ostream.h"
Daniel Maleaa960c542013-06-28 19:11:40 +000054#include "llvm/Transforms/Instrumentation.h"
Chris Lattner4c522b92007-04-27 17:02:33 +000055#include <cerrno>
NAKAMURA Takumi15304872010-10-22 14:53:59 +000056
57#ifdef __CYGWIN__
58#include <cygwin/version.h>
59#if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
60#define DO_NOTHING_ATEXIT 1
61#endif
62#endif
63
Brian Gaeke960707c2003-11-11 22:41:34 +000064using namespace llvm;
65
Chris Lattnera0d7b082002-12-23 23:59:41 +000066namespace {
67 cl::opt<std::string>
Gabor Greife16561c2007-07-05 17:07:56 +000068 InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
Chris Lattnerf5cad152002-07-22 02:10:13 +000069
Chris Lattnera0d7b082002-12-23 23:59:41 +000070 cl::list<std::string>
71 InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
Chris Lattnerf5cad152002-07-22 02:10:13 +000072
Chris Lattnera0d7b082002-12-23 23:59:41 +000073 cl::opt<bool> ForceInterpreter("force-interpreter",
Misha Brukmanc2186e32003-09-25 18:10:34 +000074 cl::desc("Force interpretation: disable JIT"),
75 cl::init(false));
Evan Cheng06d988e2008-08-08 08:12:06 +000076
Daniel Dunbar70ff8b02010-11-17 16:06:37 +000077 cl::opt<bool> UseMCJIT(
78 "use-mcjit", cl::desc("Enable use of the MC-based JIT (if available)"),
79 cl::init(false));
80
Daniel Maleaa960c542013-06-28 19:11:40 +000081 cl::opt<bool> DebugIR(
82 "debug-ir", cl::desc("Generate debug information to allow debugging IR."),
83 cl::init(false));
84
Jim Grosbach0f435d02012-09-05 16:50:34 +000085 // The MCJIT supports building for a target address space separate from
86 // the JIT compilation process. Use a forked process and a copying
87 // memory manager with IPC to execute using this functionality.
88 cl::opt<bool> RemoteMCJIT("remote-mcjit",
89 cl::desc("Execute MCJIT'ed code in a separate process."),
90 cl::init(false));
91
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +000092 // Manually specify the child process for remote execution. This overrides
93 // the simulated remote execution that allocates address space for child
Andrew Kaylor89352582013-10-29 01:33:14 +000094 // execution. The child process will be executed and will communicate with
95 // lli via stdin/stdout pipes.
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +000096 cl::opt<std::string>
97 MCJITRemoteProcess("mcjit-remote-process",
98 cl::desc("Specify the filename of the process to launch "
99 "for remote MCJIT execution. If none is specified,"
100 "\n\tremote execution will be simulated in-process."),
101 cl::value_desc("filename"),
102 cl::init(""));
103
Evan Cheng09bd0b12009-05-04 23:05:19 +0000104 // Determine optimization level.
105 cl::opt<char>
106 OptLevel("O",
107 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
108 "(default = '-O2')"),
109 cl::Prefix,
110 cl::ZeroOrMore,
111 cl::init(' '));
Evan Cheng06d988e2008-08-08 08:12:06 +0000112
Chris Lattner76766cb2005-12-16 05:00:21 +0000113 cl::opt<std::string>
Chris Lattner78e9e102005-12-16 05:19:18 +0000114 TargetTriple("mtriple", cl::desc("Override target triple for module"));
Evan Cheng61582542008-11-05 23:21:52 +0000115
116 cl::opt<std::string>
Jeffrey Yasskin31faeff2010-02-05 16:19:36 +0000117 MArch("march",
118 cl::desc("Architecture to generate assembly for (see --version)"));
119
120 cl::opt<std::string>
121 MCPU("mcpu",
122 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
123 cl::value_desc("cpu-name"),
124 cl::init(""));
125
126 cl::list<std::string>
127 MAttrs("mattr",
128 cl::CommaSeparated,
129 cl::desc("Target specific attributes (-mattr=help for details)"),
130 cl::value_desc("a1,+a2,-a3,..."));
131
132 cl::opt<std::string>
Evan Cheng61582542008-11-05 23:21:52 +0000133 EntryFunc("entry-function",
134 cl::desc("Specify the entry function (default = 'main') "
135 "of the executable"),
136 cl::value_desc("function"),
137 cl::init("main"));
Eli Bendersky4c647582012-01-16 08:56:09 +0000138
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000139 cl::list<std::string>
Andrew Kaylor4404eb42013-10-28 21:58:15 +0000140 ExtraModules("extra-module",
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000141 cl::desc("Extra modules to be loaded"),
Alp Toker0a09ebf2013-10-28 22:51:25 +0000142 cl::value_desc("input bitcode"));
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000143
Lang Hames173c69f2014-01-08 04:09:09 +0000144 cl::list<std::string>
145 ExtraObjects("extra-object",
146 cl::desc("Extra object files to be loaded"),
147 cl::value_desc("input object"));
148
149 cl::list<std::string>
150 ExtraArchives("extra-archive",
151 cl::desc("Extra archive files to be loaded"),
152 cl::value_desc("input archive"));
153
154 cl::opt<bool>
155 EnableCacheManager("enable-cache-manager",
Lang Hames1ddecc02014-01-09 05:24:05 +0000156 cl::desc("Use cache manager to save/load mdoules"),
Lang Hames173c69f2014-01-08 04:09:09 +0000157 cl::init(false));
158
Chris Lattner55644062003-10-28 22:51:44 +0000159 cl::opt<std::string>
Lang Hames1ddecc02014-01-09 05:24:05 +0000160 ObjectCacheDir("object-cache-dir",
161 cl::desc("Directory to store cached object files "
162 "(must be user writable)"),
163 cl::init(""));
164
165 cl::opt<std::string>
Chris Lattner55644062003-10-28 22:51:44 +0000166 FakeArgv0("fake-argv0",
167 cl::desc("Override the 'argv[0]' value passed into the executing"
168 " program"), cl::value_desc("executable"));
Eli Bendersky4c647582012-01-16 08:56:09 +0000169
Chris Lattner3f0ffd32006-09-14 06:17:09 +0000170 cl::opt<bool>
171 DisableCoreFiles("disable-core-files", cl::Hidden,
172 cl::desc("Disable emission of core files if possible"));
Evan Cheng0422bef2008-04-22 06:51:41 +0000173
174 cl::opt<bool>
Evan Cheng16f036c2008-05-21 18:20:21 +0000175 NoLazyCompilation("disable-lazy-compilation",
Evan Cheng0422bef2008-04-22 06:51:41 +0000176 cl::desc("Disable JIT lazy compilation"),
177 cl::init(false));
Evan Cheng2129f592011-07-19 06:37:02 +0000178
179 cl::opt<Reloc::Model>
180 RelocModel("relocation-model",
181 cl::desc("Choose relocation model"),
182 cl::init(Reloc::Default),
183 cl::values(
184 clEnumValN(Reloc::Default, "default",
185 "Target default relocation model"),
186 clEnumValN(Reloc::Static, "static",
187 "Non-relocatable code"),
188 clEnumValN(Reloc::PIC_, "pic",
189 "Fully relocatable, position independent code"),
190 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
191 "Relocatable external references, non-relocatable code"),
192 clEnumValEnd));
Evan Chengefd9b422011-07-20 07:51:56 +0000193
194 cl::opt<llvm::CodeModel::Model>
195 CMModel("code-model",
196 cl::desc("Choose code model"),
197 cl::init(CodeModel::JITDefault),
198 cl::values(clEnumValN(CodeModel::JITDefault, "default",
199 "Target default JIT code model"),
200 clEnumValN(CodeModel::Small, "small",
201 "Small code model"),
202 clEnumValN(CodeModel::Kernel, "kernel",
203 "Kernel code model"),
204 clEnumValN(CodeModel::Medium, "medium",
205 "Medium code model"),
206 clEnumValN(CodeModel::Large, "large",
207 "Large code model"),
208 clEnumValEnd));
209
Nick Lewyckyb0e97892012-04-18 08:34:12 +0000210 cl::opt<bool>
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000211 GenerateSoftFloatCalls("soft-float",
212 cl::desc("Generate software floating point library calls"),
213 cl::init(false));
214
215 cl::opt<llvm::FloatABI::ABIType>
216 FloatABIForCalls("float-abi",
217 cl::desc("Choose float ABI type"),
218 cl::init(FloatABI::Default),
219 cl::values(
220 clEnumValN(FloatABI::Default, "default",
221 "Target default float ABI type"),
222 clEnumValN(FloatABI::Soft, "soft",
223 "Soft float ABI (implied by -soft-float)"),
224 clEnumValN(FloatABI::Hard, "hard",
225 "Hard float ABI (uses FP registers)"),
226 clEnumValEnd));
227 cl::opt<bool>
Nick Lewyckyb0e97892012-04-18 08:34:12 +0000228// In debug builds, make this default to true.
229#ifdef NDEBUG
230#define EMIT_DEBUG false
231#else
232#define EMIT_DEBUG true
233#endif
234 EmitJitDebugInfo("jit-emit-debug",
235 cl::desc("Emit debug information to debugger"),
236 cl::init(EMIT_DEBUG));
237#undef EMIT_DEBUG
238
239 static cl::opt<bool>
240 EmitJitDebugInfoToDisk("jit-emit-debug-to-disk",
241 cl::Hidden,
242 cl::desc("Emit debug info objfiles to disk"),
243 cl::init(false));
Chris Lattnera0d7b082002-12-23 23:59:41 +0000244}
Chris Lattner009f8102001-10-27 08:43:52 +0000245
Lang Hames173c69f2014-01-08 04:09:09 +0000246//===----------------------------------------------------------------------===//
247// Object cache
248//
Lang Hames1ddecc02014-01-09 05:24:05 +0000249// This object cache implementation writes cached objects to disk to the
250// directory specified by CacheDir, using a filename provided in the module
251// descriptor. The cache tries to load a saved object using that path if the
252// file exists. CacheDir defaults to "", in which case objects are cached
253// alongside their originating bitcodes.
Lang Hames173c69f2014-01-08 04:09:09 +0000254//
255class LLIObjectCache : public ObjectCache {
256public:
Lang Hames1ddecc02014-01-09 05:24:05 +0000257 LLIObjectCache(const std::string& CacheDir) : CacheDir(CacheDir) {
258 // Add trailing '/' to cache dir if necessary.
Lang Hamesf9dd8fd2014-01-09 05:29:59 +0000259 if (!this->CacheDir.empty() &&
260 this->CacheDir[this->CacheDir.size() - 1] != '/')
Lang Hames1ddecc02014-01-09 05:24:05 +0000261 this->CacheDir += '/';
262 }
Lang Hames173c69f2014-01-08 04:09:09 +0000263 virtual ~LLIObjectCache() {}
264
265 virtual void notifyObjectCompiled(const Module *M, const MemoryBuffer *Obj) {
266 const std::string ModuleID = M->getModuleIdentifier();
267 std::string CacheName;
268 if (!getCacheFilename(ModuleID, CacheName))
269 return;
Lang Hameseecd2dc2014-01-09 00:47:54 +0000270 std::string errStr;
Lang Hames1ddecc02014-01-09 05:24:05 +0000271 if (!CacheDir.empty()) // Create user-defined cache dir.
272 sys::fs::create_directories(CacheName.substr(0, CacheName.rfind('/')));
Lang Hameseecd2dc2014-01-09 00:47:54 +0000273 raw_fd_ostream outfile(CacheName.c_str(), errStr, sys::fs::F_Binary);
Lang Hames173c69f2014-01-08 04:09:09 +0000274 outfile.write(Obj->getBufferStart(), Obj->getBufferSize());
275 outfile.close();
276 }
277
278 virtual MemoryBuffer* getObject(const Module* M) {
279 const std::string ModuleID = M->getModuleIdentifier();
280 std::string CacheName;
281 if (!getCacheFilename(ModuleID, CacheName))
282 return NULL;
283 // Load the object from the cache filename
284 OwningPtr<MemoryBuffer> IRObjectBuffer;
285 MemoryBuffer::getFile(CacheName.c_str(), IRObjectBuffer, -1, false);
286 // If the file isn't there, that's OK.
287 if (!IRObjectBuffer)
288 return NULL;
289 // MCJIT will want to write into this buffer, and we don't want that
290 // because the file has probably just been mmapped. Instead we make
291 // a copy. The filed-based buffer will be released when it goes
292 // out of scope.
293 return MemoryBuffer::getMemBufferCopy(IRObjectBuffer->getBuffer());
294 }
295
296private:
Lang Hames1ddecc02014-01-09 05:24:05 +0000297 std::string CacheDir;
298
Lang Hames173c69f2014-01-08 04:09:09 +0000299 bool getCacheFilename(const std::string &ModID, std::string &CacheName) {
300 std::string Prefix("file:");
301 size_t PrefixLength = Prefix.length();
302 if (ModID.substr(0, PrefixLength) != Prefix)
303 return false;
Lang Hames1ddecc02014-01-09 05:24:05 +0000304 CacheName = CacheDir + ModID.substr(PrefixLength);
Lang Hames173c69f2014-01-08 04:09:09 +0000305 size_t pos = CacheName.rfind('.');
306 CacheName.replace(pos, CacheName.length() - pos, ".o");
307 return true;
308 }
309};
310
Reid Spencere586f2e2007-03-03 18:21:44 +0000311static ExecutionEngine *EE = 0;
Lang Hames173c69f2014-01-08 04:09:09 +0000312static LLIObjectCache *CacheManager = 0;
Reid Spencere586f2e2007-03-03 18:21:44 +0000313
314static void do_shutdown() {
NAKAMURA Takumi15304872010-10-22 14:53:59 +0000315 // Cygwin-1.5 invokes DLL's dtors before atexit handler.
316#ifndef DO_NOTHING_ATEXIT
Reid Spencere586f2e2007-03-03 18:21:44 +0000317 delete EE;
Lang Hames173c69f2014-01-08 04:09:09 +0000318 if (CacheManager)
319 delete CacheManager;
Reid Spencere586f2e2007-03-03 18:21:44 +0000320 llvm_shutdown();
NAKAMURA Takumi15304872010-10-22 14:53:59 +0000321#endif
Reid Spencere586f2e2007-03-03 18:21:44 +0000322}
323
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000324// On Mingw and Cygwin, an external symbol named '__main' is called from the
325// generated 'main' function to allow static intialization. To avoid linking
326// problems with remote targets (because lli's remote target support does not
327// currently handle external linking) we add a secondary module which defines
328// an empty '__main' function.
329static void addCygMingExtraModule(ExecutionEngine *EE,
330 LLVMContext &Context,
331 StringRef TargetTripleStr) {
332 IRBuilder<> Builder(Context);
333 Triple TargetTriple(TargetTripleStr);
334
335 // Create a new module.
336 Module *M = new Module("CygMingHelper", Context);
337 M->setTargetTriple(TargetTripleStr);
338
339 // Create an empty function named "__main".
340 Function *Result;
341 if (TargetTriple.isArch64Bit()) {
342 Result = Function::Create(
343 TypeBuilder<int64_t(void), false>::get(Context),
344 GlobalValue::ExternalLinkage, "__main", M);
345 } else {
346 Result = Function::Create(
347 TypeBuilder<int32_t(void), false>::get(Context),
348 GlobalValue::ExternalLinkage, "__main", M);
349 }
350 BasicBlock *BB = BasicBlock::Create(Context, "__main", Result);
351 Builder.SetInsertPoint(BB);
352 Value *ReturnVal;
353 if (TargetTriple.isArch64Bit())
354 ReturnVal = ConstantInt::get(Context, APInt(64, 0));
355 else
356 ReturnVal = ConstantInt::get(Context, APInt(32, 0));
357 Builder.CreateRet(ReturnVal);
358
359 // Add this new module to the ExecutionEngine.
360 EE->addModule(M);
361}
362
363
Chris Lattnerd7ff5782001-08-23 17:05:04 +0000364//===----------------------------------------------------------------------===//
Chris Lattnerd7ff5782001-08-23 17:05:04 +0000365// main Driver function
366//
Misha Brukman5b255e52003-10-14 21:39:53 +0000367int main(int argc, char **argv, char * const *envp) {
Chris Lattnere3fc2d12009-03-06 05:34:10 +0000368 sys::PrintStackTraceOnErrorSignal();
369 PrettyStackTraceProgram X(argc, argv);
Eli Bendersky4c647582012-01-16 08:56:09 +0000370
Owen Anderson19251ec2009-07-15 22:16:10 +0000371 LLVMContext &Context = getGlobalContext();
Reid Spencere586f2e2007-03-03 18:21:44 +0000372 atexit(do_shutdown); // Call llvm_shutdown() on exit.
Daniel Dunbar3d92d932009-07-16 02:04:54 +0000373
374 // If we have a native target, initialize it to ensure it is linked in and
375 // usable by the JIT.
376 InitializeNativeTarget();
Jim Grosbach7b162492011-03-18 22:48:41 +0000377 InitializeNativeTargetAsmPrinter();
Jim Grosbach2cce3f92012-11-05 19:06:05 +0000378 InitializeNativeTargetAsmParser();
Daniel Dunbar3d92d932009-07-16 02:04:54 +0000379
Chris Lattner2785bdb2007-05-06 04:58:26 +0000380 cl::ParseCommandLineOptions(argc, argv,
Dan Gohman2c6a8212007-10-08 15:45:12 +0000381 "llvm interpreter & dynamic compiler\n");
Reid Spencer996ec722004-12-30 05:36:08 +0000382
Chris Lattner2785bdb2007-05-06 04:58:26 +0000383 // If the user doesn't want core files, disable them.
384 if (DisableCoreFiles)
385 sys::Process::PreventCoreFiles();
Eli Bendersky4c647582012-01-16 08:56:09 +0000386
Gabor Greife16561c2007-07-05 17:07:56 +0000387 // Load the bitcode...
Daniel Dunbar9589bf82010-11-13 00:28:01 +0000388 SMDiagnostic Err;
389 Module *Mod = ParseIRFile(InputFile, Err, Context);
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000390 if (!Mod) {
Chris Lattnera3a06812011-10-16 04:47:35 +0000391 Err.print(argv[0], errs());
Daniel Dunbar9589bf82010-11-13 00:28:01 +0000392 return 1;
Chris Lattner2785bdb2007-05-06 04:58:26 +0000393 }
394
Lang Hames173c69f2014-01-08 04:09:09 +0000395 if (EnableCacheManager) {
396 if (UseMCJIT) {
397 std::string CacheName("file:");
398 CacheName.append(InputFile);
399 Mod->setModuleIdentifier(CacheName);
400 } else
401 errs() << "warning: -enable-cache-manager can only be used with MCJIT.";
402 }
403
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000404 // If not jitting lazily, load the whole bitcode file eagerly too.
Daniel Dunbar9589bf82010-11-13 00:28:01 +0000405 std::string ErrorMsg;
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000406 if (NoLazyCompilation) {
407 if (Mod->MaterializeAllPermanently(&ErrorMsg)) {
408 errs() << argv[0] << ": bitcode didn't read correctly.\n";
409 errs() << "Reason: " << ErrorMsg << "\n";
410 exit(1);
411 }
Evan Cheng0422bef2008-04-22 06:51:41 +0000412 }
Chris Lattner2785bdb2007-05-06 04:58:26 +0000413
Daniel Maleaa960c542013-06-28 19:11:40 +0000414 if (DebugIR) {
415 if (!UseMCJIT) {
416 errs() << "warning: -debug-ir used without -use-mcjit. Only partial debug"
417 << " information will be emitted by the non-MC JIT engine. To see full"
418 << " source debug information, enable the flag '-use-mcjit'.\n";
419
420 }
421 ModulePass *DebugIRPass = createDebugIRPass();
422 DebugIRPass->runOnModule(*Mod);
423 }
424
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000425 EngineBuilder builder(Mod);
Jeffrey Yasskin31faeff2010-02-05 16:19:36 +0000426 builder.setMArch(MArch);
427 builder.setMCPU(MCPU);
428 builder.setMAttrs(MAttrs);
Evan Cheng2129f592011-07-19 06:37:02 +0000429 builder.setRelocationModel(RelocModel);
Evan Chengefd9b422011-07-20 07:51:56 +0000430 builder.setCodeModel(CMModel);
Daniel Dunbara78d8092009-07-18 08:07:13 +0000431 builder.setErrorStr(&ErrorMsg);
432 builder.setEngineKind(ForceInterpreter
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000433 ? EngineKind::Interpreter
434 : EngineKind::JIT);
435
Chris Lattner2785bdb2007-05-06 04:58:26 +0000436 // If we are supposed to override the target triple, do so now.
437 if (!TargetTriple.empty())
Duncan Sands3bd97fe2010-08-28 01:30:02 +0000438 Mod->setTargetTriple(Triple::normalize(TargetTriple));
Evan Cheng0422bef2008-04-22 06:51:41 +0000439
Eli Bendersky4c647582012-01-16 08:56:09 +0000440 // Enable MCJIT if desired.
Filip Pizlo9bc53e82013-05-14 19:29:00 +0000441 RTDyldMemoryManager *RTDyldMM = 0;
Eli Bendersky4c647582012-01-16 08:56:09 +0000442 if (UseMCJIT && !ForceInterpreter) {
Daniel Dunbar70ff8b02010-11-17 16:06:37 +0000443 builder.setUseMCJIT(true);
Jim Grosbach0f435d02012-09-05 16:50:34 +0000444 if (RemoteMCJIT)
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000445 RTDyldMM = new RemoteMemoryManager();
Jim Grosbach0f435d02012-09-05 16:50:34 +0000446 else
Filip Pizlo9bc53e82013-05-14 19:29:00 +0000447 RTDyldMM = new SectionMemoryManager();
448 builder.setMCJITMemoryManager(RTDyldMM);
Benjamin Kramer76004e62012-05-20 17:24:08 +0000449 } else {
Jim Grosbach0f435d02012-09-05 16:50:34 +0000450 if (RemoteMCJIT) {
451 errs() << "error: Remote process execution requires -use-mcjit\n";
452 exit(1);
453 }
Benjamin Kramer76004e62012-05-20 17:24:08 +0000454 builder.setJITMemoryManager(ForceInterpreter ? 0 :
455 JITMemoryManager::CreateDefaultMemManager());
Eli Bendersky4c647582012-01-16 08:56:09 +0000456 }
Daniel Dunbar70ff8b02010-11-17 16:06:37 +0000457
Evan Cheng09bd0b12009-05-04 23:05:19 +0000458 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
459 switch (OptLevel) {
460 default:
Dan Gohmand8db3762009-07-15 16:35:29 +0000461 errs() << argv[0] << ": invalid optimization level.\n";
Evan Cheng09bd0b12009-05-04 23:05:19 +0000462 return 1;
463 case ' ': break;
464 case '0': OLvl = CodeGenOpt::None; break;
Evan Cheng5a286382009-10-16 21:02:20 +0000465 case '1': OLvl = CodeGenOpt::Less; break;
Evan Cheng09bd0b12009-05-04 23:05:19 +0000466 case '2': OLvl = CodeGenOpt::Default; break;
467 case '3': OLvl = CodeGenOpt::Aggressive; break;
468 }
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000469 builder.setOptLevel(OLvl);
470
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000471 TargetOptions Options;
472 Options.UseSoftFloat = GenerateSoftFloatCalls;
473 if (FloatABIForCalls != FloatABI::Default)
474 Options.FloatABIType = FloatABIForCalls;
475 if (GenerateSoftFloatCalls)
476 FloatABIForCalls = FloatABI::Soft;
477
Jim Grosbach0f435d02012-09-05 16:50:34 +0000478 // Remote target execution doesn't handle EH or debug registration.
479 if (!RemoteMCJIT) {
Jim Grosbach0f435d02012-09-05 16:50:34 +0000480 Options.JITEmitDebugInfo = EmitJitDebugInfo;
481 Options.JITEmitDebugInfoToDisk = EmitJitDebugInfoToDisk;
Jim Grosbach0f435d02012-09-05 16:50:34 +0000482 }
Nick Lewyckyb0e97892012-04-18 08:34:12 +0000483
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000484 builder.setTargetOptions(Options);
485
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000486 EE = builder.create();
Chris Lattnerf840ed72009-07-07 18:31:09 +0000487 if (!EE) {
488 if (!ErrorMsg.empty())
Dan Gohmand8db3762009-07-15 16:35:29 +0000489 errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n";
Chris Lattnerf840ed72009-07-07 18:31:09 +0000490 else
Dan Gohmand8db3762009-07-15 16:35:29 +0000491 errs() << argv[0] << ": unknown error creating EE!\n";
Chris Lattner2785bdb2007-05-06 04:58:26 +0000492 exit(1);
493 }
494
Lang Hames173c69f2014-01-08 04:09:09 +0000495 if (EnableCacheManager) {
Lang Hames1ddecc02014-01-09 05:24:05 +0000496 CacheManager = new LLIObjectCache(ObjectCacheDir);
Lang Hames173c69f2014-01-08 04:09:09 +0000497 EE->setObjectCache(CacheManager);
498 }
499
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000500 // Load any additional modules specified on the command line.
501 for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) {
502 Module *XMod = ParseIRFile(ExtraModules[i], Err, Context);
503 if (!XMod) {
504 Err.print(argv[0], errs());
505 return 1;
506 }
Lang Hames173c69f2014-01-08 04:09:09 +0000507 if (EnableCacheManager) {
508 if (UseMCJIT) {
509 std::string CacheName("file:");
510 CacheName.append(ExtraModules[i]);
511 XMod->setModuleIdentifier(CacheName);
512 }
513 // else, we already printed a warning above.
514 }
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000515 EE->addModule(XMod);
516 }
517
Lang Hames173c69f2014-01-08 04:09:09 +0000518 for (unsigned i = 0, e = ExtraObjects.size(); i != e; ++i) {
519 object::ObjectFile *Obj = object::ObjectFile::createObjectFile(
520 ExtraObjects[i]);
521 if (!Obj) {
522 Err.print(argv[0], errs());
523 return 1;
524 }
525 EE->addObjectFile(Obj);
526 }
527
528 for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) {
529 OwningPtr<MemoryBuffer> ArBuf;
530 error_code ec;
531 ec = MemoryBuffer::getFileOrSTDIN(ExtraArchives[i], ArBuf);
532 if (ec) {
533 Err.print(argv[0], errs());
534 return 1;
535 }
536 object::Archive *Ar = new object::Archive(ArBuf.take(), ec);
537 if (ec || !Ar) {
538 Err.print(argv[0], errs());
539 return 1;
540 }
541 EE->addArchive(Ar);
542 }
543
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000544 // If the target is Cygwin/MingW and we are generating remote code, we
545 // need an extra module to help out with linking.
546 if (RemoteMCJIT && Triple(Mod->getTargetTriple()).isOSCygMing()) {
547 addCygMingExtraModule(EE, Context, Mod->getTargetTriple());
548 }
549
Eli Bendersky5262ad22012-03-13 08:33:15 +0000550 // The following functions have no effect if their respective profiling
551 // support wasn't enabled in the build configuration.
552 EE->RegisterJITEventListener(
553 JITEventListener::createOProfileJITEventListener());
554 EE->RegisterJITEventListener(
555 JITEventListener::createIntelJITEventListener());
Jeffrey Yasskin0b08f3d2009-06-25 02:04:04 +0000556
Jim Grosbach0f435d02012-09-05 16:50:34 +0000557 if (!NoLazyCompilation && RemoteMCJIT) {
558 errs() << "warning: remote mcjit does not support lazy compilation\n";
559 NoLazyCompilation = true;
560 }
Jeffrey Yasskinaa8814a2009-10-27 22:39:42 +0000561 EE->DisableLazyCompilation(NoLazyCompilation);
Evan Cheng0422bef2008-04-22 06:51:41 +0000562
Chris Lattner2785bdb2007-05-06 04:58:26 +0000563 // If the user specifically requested an argv[0] to pass into the program,
564 // do it now.
565 if (!FakeArgv0.empty()) {
566 InputFile = FakeArgv0;
567 } else {
568 // Otherwise, if there is a .bc suffix on the executable strip it off, it
569 // might confuse the program.
Benjamin Kramera944a9a2010-04-15 11:33:14 +0000570 if (StringRef(InputFile).endswith(".bc"))
Chris Lattner2785bdb2007-05-06 04:58:26 +0000571 InputFile.erase(InputFile.length() - 3);
572 }
573
574 // Add the module's name to the start of the vector of arguments to main().
575 InputArgv.insert(InputArgv.begin(), InputFile);
576
577 // Call the main function from M as if its signature were:
578 // int main (int argc, char **argv, const char **envp)
579 // using the contents of Args to determine argc & argv, and the contents of
580 // EnvVars to determine envp.
581 //
Evan Cheng61582542008-11-05 23:21:52 +0000582 Function *EntryFn = Mod->getFunction(EntryFunc);
583 if (!EntryFn) {
Dan Gohmand8db3762009-07-15 16:35:29 +0000584 errs() << '\'' << EntryFunc << "\' function not found in module.\n";
Chris Lattner2785bdb2007-05-06 04:58:26 +0000585 return -1;
586 }
587
Chris Lattner2785bdb2007-05-06 04:58:26 +0000588 // Reset errno to zero on entry to main.
589 errno = 0;
Eli Bendersky4c647582012-01-16 08:56:09 +0000590
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000591 int Result;
592
Andrew Kaylor58365b92012-11-27 19:49:00 +0000593 if (!RemoteMCJIT) {
Andrew Kaylor6587bcf2013-10-11 22:47:10 +0000594 // If the program doesn't explicitly call exit, we will need the Exit
595 // function later on to make an explicit call, so get the function now.
596 Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
597 Type::getInt32Ty(Context),
598 NULL);
599
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000600 // Run static constructors.
Andrew Kaylorea395922013-10-01 01:47:35 +0000601 if (UseMCJIT && !ForceInterpreter) {
602 // Give MCJIT a chance to apply relocations and set page permissions.
603 EE->finalizeObject();
604 }
605 EE->runStaticConstructorsDestructors(false);
Evan Cheng0422bef2008-04-22 06:51:41 +0000606
Andrew Kaylorea395922013-10-01 01:47:35 +0000607 if (!UseMCJIT && NoLazyCompilation) {
608 for (Module::iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) {
609 Function *Fn = &*I;
610 if (Fn != EntryFn && !Fn->isDeclaration())
611 EE->getPointerToFunction(Fn);
612 }
Evan Cheng0422bef2008-04-22 06:51:41 +0000613 }
Evan Cheng0422bef2008-04-22 06:51:41 +0000614
NAKAMURA Takumi87e08802013-12-07 11:21:42 +0000615 // Trigger compilation separately so code regions that need to be
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000616 // invalidated will be known.
617 (void)EE->getPointerToFunction(EntryFn);
618 // Clear instruction cache before code will be executed.
619 if (RTDyldMM)
620 static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
621
622 // Run main.
623 Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
624
625 // Run static destructors.
626 EE->runStaticConstructorsDestructors(true);
627
628 // If the program didn't call exit explicitly, we should call it now.
629 // This ensures that any atexit handlers get called correctly.
630 if (Function *ExitF = dyn_cast<Function>(Exit)) {
631 std::vector<GenericValue> Args;
632 GenericValue ResultGV;
633 ResultGV.IntVal = APInt(32, Result);
634 Args.push_back(ResultGV);
635 EE->runFunction(ExitF, Args);
636 errs() << "ERROR: exit(" << Result << ") returned!\n";
637 abort();
638 } else {
639 errs() << "ERROR: exit defined with wrong prototype!\n";
640 abort();
641 }
642 } else {
643 // else == "if (RemoteMCJIT)"
644
645 // Remote target MCJIT doesn't (yet) support static constructors. No reason
646 // it couldn't. This is a limitation of the LLI implemantation, not the
647 // MCJIT itself. FIXME.
648 //
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000649 RemoteMemoryManager *MM = static_cast<RemoteMemoryManager*>(RTDyldMM);
Jim Grosbach0f435d02012-09-05 16:50:34 +0000650 // Everything is prepared now, so lay out our program for the target
651 // address space, assign the section addresses to resolve any relocations,
652 // and send it to the target.
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000653
654 OwningPtr<RemoteTarget> Target;
655 if (!MCJITRemoteProcess.empty()) { // Remote execution on a child process
656 if (!RemoteTarget::hostSupportsExternalRemoteTarget()) {
657 errs() << "Warning: host does not support external remote targets.\n"
658 << " Defaulting to simulated remote execution\n";
659 Target.reset(RemoteTarget::createRemoteTarget());
660 } else {
661 std::string ChildEXE = sys::FindProgramByName(MCJITRemoteProcess);
662 if (ChildEXE == "") {
663 errs() << "Unable to find child target: '\''" << MCJITRemoteProcess << "\'\n";
664 return -1;
665 }
Richard Smith2f1c87b2013-10-02 21:33:12 +0000666 Target.reset(RemoteTarget::createExternalRemoteTarget(ChildEXE));
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000667 }
668 } else {
669 // No child process name provided, use simulated remote execution.
670 Target.reset(RemoteTarget::createRemoteTarget());
671 }
672
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000673 // Give the memory manager a pointer to our remote target interface object.
674 MM->setRemoteTarget(Target.get());
675
676 // Create the remote target.
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000677 Target->create();
Jim Grosbach748b9472012-08-28 23:22:30 +0000678
Jim Grosbach0f435d02012-09-05 16:50:34 +0000679 // Since we're executing in a (at least simulated) remote address space,
680 // we can't use the ExecutionEngine::runFunctionAsMain(). We have to
681 // grab the function address directly here and tell the remote target
682 // to execute the function.
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000683 //
684 // Our memory manager will map generated code into the remote address
685 // space as it is loaded and copy the bits over during the finalizeMemory
686 // operation.
687 //
Jim Grosbach0f435d02012-09-05 16:50:34 +0000688 // FIXME: argv and envp handling.
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000689 uint64_t Entry = EE->getFunctionAddress(EntryFn->getName().str());
Jim Grosbach0f435d02012-09-05 16:50:34 +0000690
Tim Northover79ab7f72013-05-19 09:55:06 +0000691 DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"
692 << format("%llx", Entry) << "\n");
Jim Grosbach0f435d02012-09-05 16:50:34 +0000693
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000694 if (Target->executeCode(Entry, Result))
695 errs() << "ERROR: " << Target->getErrorMsg() << "\n";
Jim Grosbach0f435d02012-09-05 16:50:34 +0000696
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000697 // Like static constructors, the remote target MCJIT support doesn't handle
698 // this yet. It could. FIXME.
699
700 // Stop the remote target
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000701 Target->stop();
Chris Lattner2785bdb2007-05-06 04:58:26 +0000702 }
Jim Grosbach0f435d02012-09-05 16:50:34 +0000703
Jim Grosbach0f435d02012-09-05 16:50:34 +0000704 return Result;
Chris Lattnerd7ff5782001-08-23 17:05:04 +0000705}