blob: cc8117d6e7a8667bb5ad74c17a054d4725f4f28b [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
Chandler Carruth9fb823b2013-01-02 11:36:10 +000016#include "llvm/IR/LLVMContext.h"
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +000017#include "RemoteMemoryManager.h"
Jim Grosbach0f435d02012-09-05 16:50:34 +000018#include "RemoteTarget.h"
Alp Tokerce4ab592014-01-23 19:57:16 +000019#include "RemoteTargetExternal.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"
Jeffrey Yasskin0b08f3d2009-06-25 02:04:04 +000025#include "llvm/ExecutionEngine/JITEventListener.h"
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000026#include "llvm/ExecutionEngine/MCJIT.h"
Lang Hames173c69f2014-01-08 04:09:09 +000027#include "llvm/ExecutionEngine/ObjectCache.h"
Lang Hames93de2a12015-01-23 21:25:00 +000028#include "llvm/ExecutionEngine/OrcMCJITReplacement.h"
Andrew Kaylor58365b92012-11-27 19:49:00 +000029#include "llvm/ExecutionEngine/SectionMemoryManager.h"
Andrew Kaylor1ca510e2013-10-29 01:29:56 +000030#include "llvm/IR/IRBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000031#include "llvm/IR/Module.h"
32#include "llvm/IR/Type.h"
Andrew Kaylor1ca510e2013-10-29 01:29:56 +000033#include "llvm/IR/TypeBuilder.h"
Chandler Carruthe60e57b2013-03-26 02:25:37 +000034#include "llvm/IRReader/IRReader.h"
Lang Hames173c69f2014-01-08 04:09:09 +000035#include "llvm/Object/Archive.h"
36#include "llvm/Object/ObjectFile.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000037#include "llvm/Support/CommandLine.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000038#include "llvm/Support/Debug.h"
39#include "llvm/Support/DynamicLibrary.h"
40#include "llvm/Support/Format.h"
Chris Lattner76d46322006-12-06 01:18:01 +000041#include "llvm/Support/ManagedStatic.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000042#include "llvm/Support/MathExtras.h"
43#include "llvm/Support/Memory.h"
Chris Lattner2785bdb2007-05-06 04:58:26 +000044#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer16132e62015-03-23 18:07:13 +000045#include "llvm/Support/Path.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
Chandler Carruthf98597a2014-04-22 03:10:36 +000066#define DEBUG_TYPE "lli"
67
Chris Lattnera0d7b082002-12-23 23:59:41 +000068namespace {
69 cl::opt<std::string>
Gabor Greife16561c2007-07-05 17:07:56 +000070 InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
Chris Lattnerf5cad152002-07-22 02:10:13 +000071
Chris Lattnera0d7b082002-12-23 23:59:41 +000072 cl::list<std::string>
73 InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
Chris Lattnerf5cad152002-07-22 02:10:13 +000074
Chris Lattnera0d7b082002-12-23 23:59:41 +000075 cl::opt<bool> ForceInterpreter("force-interpreter",
Misha Brukmanc2186e32003-09-25 18:10:34 +000076 cl::desc("Force interpretation: disable JIT"),
77 cl::init(false));
Evan Cheng06d988e2008-08-08 08:12:06 +000078
Lang Hames93de2a12015-01-23 21:25:00 +000079 cl::opt<bool> UseOrcMCJITReplacement("use-orcmcjit",
80 cl::desc("Use the experimental "
81 "OrcMCJITReplacement as a "
82 "drop-in replacement for "
83 "MCJIT."),
84 cl::init(false));
85
Jim Grosbach0f435d02012-09-05 16:50:34 +000086 // The MCJIT supports building for a target address space separate from
87 // the JIT compilation process. Use a forked process and a copying
88 // memory manager with IPC to execute using this functionality.
89 cl::opt<bool> RemoteMCJIT("remote-mcjit",
90 cl::desc("Execute MCJIT'ed code in a separate process."),
91 cl::init(false));
92
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +000093 // Manually specify the child process for remote execution. This overrides
94 // the simulated remote execution that allocates address space for child
Andrew Kaylor89352582013-10-29 01:33:14 +000095 // execution. The child process will be executed and will communicate with
96 // lli via stdin/stdout pipes.
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +000097 cl::opt<std::string>
Alp Tokera1186382014-01-22 21:52:35 +000098 ChildExecPath("mcjit-remote-process",
99 cl::desc("Specify the filename of the process to launch "
100 "for remote MCJIT execution. If none is specified,"
101 "\n\tremote execution will be simulated in-process."),
102 cl::value_desc("filename"), cl::init(""));
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000103
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
NAKAMURA Takumif462f9c2014-01-10 10:38:28 +0000253// 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] != '/')
NAKAMURA Takumif462f9c2014-01-10 10:38:28 +0000261 this->CacheDir += '/';
Lang Hames1ddecc02014-01-09 05:24:05 +0000262 }
Lang Hames173c69f2014-01-08 04:09:09 +0000263 virtual ~LLIObjectCache() {}
264
Rafael Espindola48af1c22014-08-19 18:44:46 +0000265 void notifyObjectCompiled(const Module *M, MemoryBufferRef Obj) override {
Lang Hames173c69f2014-01-08 04:09:09 +0000266 const std::string ModuleID = M->getModuleIdentifier();
267 std::string CacheName;
268 if (!getCacheFilename(ModuleID, CacheName))
269 return;
NAKAMURA Takumi390e0602014-01-10 10:38:34 +0000270 if (!CacheDir.empty()) { // Create user-defined cache dir.
271 SmallString<128> dir(CacheName);
272 sys::path::remove_filename(dir);
273 sys::fs::create_directories(Twine(dir));
274 }
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000275 std::error_code EC;
276 raw_fd_ostream outfile(CacheName, EC, sys::fs::F_None);
Rafael Espindola48af1c22014-08-19 18:44:46 +0000277 outfile.write(Obj.getBufferStart(), Obj.getBufferSize());
Lang Hames173c69f2014-01-08 04:09:09 +0000278 outfile.close();
279 }
280
Rafael Espindola5f2bb7d2014-08-13 18:49:01 +0000281 std::unique_ptr<MemoryBuffer> getObject(const Module* M) override {
Lang Hames173c69f2014-01-08 04:09:09 +0000282 const std::string ModuleID = M->getModuleIdentifier();
283 std::string CacheName;
284 if (!getCacheFilename(ModuleID, CacheName))
Craig Toppere6cb63e2014-04-25 04:24:47 +0000285 return nullptr;
Lang Hames173c69f2014-01-08 04:09:09 +0000286 // Load the object from the cache filename
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000287 ErrorOr<std::unique_ptr<MemoryBuffer>> IRObjectBuffer =
288 MemoryBuffer::getFile(CacheName.c_str(), -1, false);
Lang Hames173c69f2014-01-08 04:09:09 +0000289 // If the file isn't there, that's OK.
290 if (!IRObjectBuffer)
Craig Toppere6cb63e2014-04-25 04:24:47 +0000291 return nullptr;
Lang Hames173c69f2014-01-08 04:09:09 +0000292 // MCJIT will want to write into this buffer, and we don't want that
293 // because the file has probably just been mmapped. Instead we make
294 // a copy. The filed-based buffer will be released when it goes
295 // out of scope.
Rafael Espindola3560ff22014-08-27 20:03:13 +0000296 return MemoryBuffer::getMemBufferCopy(IRObjectBuffer.get()->getBuffer());
Lang Hames173c69f2014-01-08 04:09:09 +0000297 }
298
299private:
Lang Hames1ddecc02014-01-09 05:24:05 +0000300 std::string CacheDir;
301
Lang Hames173c69f2014-01-08 04:09:09 +0000302 bool getCacheFilename(const std::string &ModID, std::string &CacheName) {
303 std::string Prefix("file:");
304 size_t PrefixLength = Prefix.length();
305 if (ModID.substr(0, PrefixLength) != Prefix)
306 return false;
NAKAMURA Takumid7fd6d92014-01-10 10:38:40 +0000307 std::string CacheSubdir = ModID.substr(PrefixLength);
308#if defined(_WIN32)
309 // Transform "X:\foo" => "/X\foo" for convenience.
310 if (isalpha(CacheSubdir[0]) && CacheSubdir[1] == ':') {
311 CacheSubdir[1] = CacheSubdir[0];
312 CacheSubdir[0] = '/';
313 }
314#endif
315 CacheName = CacheDir + CacheSubdir;
Lang Hames173c69f2014-01-08 04:09:09 +0000316 size_t pos = CacheName.rfind('.');
317 CacheName.replace(pos, CacheName.length() - pos, ".o");
318 return true;
319 }
320};
321
Craig Toppere6cb63e2014-04-25 04:24:47 +0000322static ExecutionEngine *EE = nullptr;
323static LLIObjectCache *CacheManager = nullptr;
Reid Spencere586f2e2007-03-03 18:21:44 +0000324
325static void do_shutdown() {
NAKAMURA Takumi15304872010-10-22 14:53:59 +0000326 // Cygwin-1.5 invokes DLL's dtors before atexit handler.
327#ifndef DO_NOTHING_ATEXIT
Reid Spencere586f2e2007-03-03 18:21:44 +0000328 delete EE;
Lang Hames173c69f2014-01-08 04:09:09 +0000329 if (CacheManager)
330 delete CacheManager;
Reid Spencere586f2e2007-03-03 18:21:44 +0000331 llvm_shutdown();
NAKAMURA Takumi15304872010-10-22 14:53:59 +0000332#endif
Reid Spencere586f2e2007-03-03 18:21:44 +0000333}
334
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000335// On Mingw and Cygwin, an external symbol named '__main' is called from the
336// generated 'main' function to allow static intialization. To avoid linking
337// problems with remote targets (because lli's remote target support does not
338// currently handle external linking) we add a secondary module which defines
339// an empty '__main' function.
340static void addCygMingExtraModule(ExecutionEngine *EE,
341 LLVMContext &Context,
342 StringRef TargetTripleStr) {
343 IRBuilder<> Builder(Context);
344 Triple TargetTriple(TargetTripleStr);
345
346 // Create a new module.
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000347 std::unique_ptr<Module> M = make_unique<Module>("CygMingHelper", Context);
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000348 M->setTargetTriple(TargetTripleStr);
349
350 // Create an empty function named "__main".
351 Function *Result;
352 if (TargetTriple.isArch64Bit()) {
353 Result = Function::Create(
354 TypeBuilder<int64_t(void), false>::get(Context),
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000355 GlobalValue::ExternalLinkage, "__main", M.get());
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000356 } else {
357 Result = Function::Create(
358 TypeBuilder<int32_t(void), false>::get(Context),
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000359 GlobalValue::ExternalLinkage, "__main", M.get());
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000360 }
361 BasicBlock *BB = BasicBlock::Create(Context, "__main", Result);
362 Builder.SetInsertPoint(BB);
363 Value *ReturnVal;
364 if (TargetTriple.isArch64Bit())
365 ReturnVal = ConstantInt::get(Context, APInt(64, 0));
366 else
367 ReturnVal = ConstantInt::get(Context, APInt(32, 0));
368 Builder.CreateRet(ReturnVal);
369
370 // Add this new module to the ExecutionEngine.
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000371 EE->addModule(std::move(M));
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000372}
373
374
Chris Lattnerd7ff5782001-08-23 17:05:04 +0000375//===----------------------------------------------------------------------===//
Chris Lattnerd7ff5782001-08-23 17:05:04 +0000376// main Driver function
377//
Misha Brukman5b255e52003-10-14 21:39:53 +0000378int main(int argc, char **argv, char * const *envp) {
Chris Lattnere3fc2d12009-03-06 05:34:10 +0000379 sys::PrintStackTraceOnErrorSignal();
380 PrettyStackTraceProgram X(argc, argv);
Eli Bendersky4c647582012-01-16 08:56:09 +0000381
Owen Anderson19251ec2009-07-15 22:16:10 +0000382 LLVMContext &Context = getGlobalContext();
Reid Spencere586f2e2007-03-03 18:21:44 +0000383 atexit(do_shutdown); // Call llvm_shutdown() on exit.
Daniel Dunbar3d92d932009-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 Grosbach7b162492011-03-18 22:48:41 +0000388 InitializeNativeTargetAsmPrinter();
Jim Grosbach2cce3f92012-11-05 19:06:05 +0000389 InitializeNativeTargetAsmParser();
Daniel Dunbar3d92d932009-07-16 02:04:54 +0000390
Chris Lattner2785bdb2007-05-06 04:58:26 +0000391 cl::ParseCommandLineOptions(argc, argv,
Dan Gohman2c6a8212007-10-08 15:45:12 +0000392 "llvm interpreter & dynamic compiler\n");
Reid Spencer996ec722004-12-30 05:36:08 +0000393
Chris Lattner2785bdb2007-05-06 04:58:26 +0000394 // If the user doesn't want core files, disable them.
395 if (DisableCoreFiles)
396 sys::Process::PreventCoreFiles();
Eli Bendersky4c647582012-01-16 08:56:09 +0000397
Gabor Greife16561c2007-07-05 17:07:56 +0000398 // Load the bitcode...
Daniel Dunbar9589bf82010-11-13 00:28:01 +0000399 SMDiagnostic Err;
Rafael Espindolad233b062014-08-26 17:29:46 +0000400 std::unique_ptr<Module> Owner = parseIRFile(InputFile, Err, Context);
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000401 Module *Mod = Owner.get();
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000402 if (!Mod) {
Chris Lattnera3a06812011-10-16 04:47:35 +0000403 Err.print(argv[0], errs());
Daniel Dunbar9589bf82010-11-13 00:28:01 +0000404 return 1;
Chris Lattner2785bdb2007-05-06 04:58:26 +0000405 }
406
Lang Hames173c69f2014-01-08 04:09:09 +0000407 if (EnableCacheManager) {
Eric Christopher79cc1e32014-09-02 22:28:02 +0000408 std::string CacheName("file:");
409 CacheName.append(InputFile);
410 Mod->setModuleIdentifier(CacheName);
Lang Hames173c69f2014-01-08 04:09:09 +0000411 }
412
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000413 // If not jitting lazily, load the whole bitcode file eagerly too.
414 if (NoLazyCompilation) {
Rafael Espindola4453e42942014-06-13 03:07:50 +0000415 if (std::error_code EC = Mod->materializeAllPermanently()) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000416 errs() << argv[0] << ": bitcode didn't read correctly.\n";
Rafael Espindolae9fab9b2014-01-14 23:51:27 +0000417 errs() << "Reason: " << EC.message() << "\n";
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000418 exit(1);
419 }
Evan Cheng0422bef2008-04-22 06:51:41 +0000420 }
Chris Lattner2785bdb2007-05-06 04:58:26 +0000421
Rafael Espindolae9fab9b2014-01-14 23:51:27 +0000422 std::string ErrorMsg;
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000423 EngineBuilder builder(std::move(Owner));
Jeffrey Yasskin31faeff2010-02-05 16:19:36 +0000424 builder.setMArch(MArch);
425 builder.setMCPU(MCPU);
426 builder.setMAttrs(MAttrs);
Evan Cheng2129f592011-07-19 06:37:02 +0000427 builder.setRelocationModel(RelocModel);
Evan Chengefd9b422011-07-20 07:51:56 +0000428 builder.setCodeModel(CMModel);
Daniel Dunbara78d8092009-07-18 08:07:13 +0000429 builder.setErrorStr(&ErrorMsg);
430 builder.setEngineKind(ForceInterpreter
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000431 ? EngineKind::Interpreter
432 : EngineKind::JIT);
Lang Hames93de2a12015-01-23 21:25:00 +0000433 builder.setUseOrcMCJITReplacement(UseOrcMCJITReplacement);
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000434
Chris Lattner2785bdb2007-05-06 04:58:26 +0000435 // If we are supposed to override the target triple, do so now.
436 if (!TargetTriple.empty())
Duncan Sands3bd97fe2010-08-28 01:30:02 +0000437 Mod->setTargetTriple(Triple::normalize(TargetTriple));
Evan Cheng0422bef2008-04-22 06:51:41 +0000438
Eli Bendersky4c647582012-01-16 08:56:09 +0000439 // Enable MCJIT if desired.
Craig Toppere6cb63e2014-04-25 04:24:47 +0000440 RTDyldMemoryManager *RTDyldMM = nullptr;
Eric Christopher79cc1e32014-09-02 22:28:02 +0000441 if (!ForceInterpreter) {
Jim Grosbach0f435d02012-09-05 16:50:34 +0000442 if (RemoteMCJIT)
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000443 RTDyldMM = new RemoteMemoryManager();
Jim Grosbach0f435d02012-09-05 16:50:34 +0000444 else
Filip Pizlo9bc53e82013-05-14 19:29:00 +0000445 RTDyldMM = new SectionMemoryManager();
Lang Hames4a5697e2014-12-03 00:51:19 +0000446
447 // Deliberately construct a temp std::unique_ptr to pass in. Do not null out
448 // RTDyldMM: We still use it below, even though we don't own it.
449 builder.setMCJITMemoryManager(
450 std::unique_ptr<RTDyldMemoryManager>(RTDyldMM));
Lang Hames0f154902014-09-23 16:56:02 +0000451 } else if (RemoteMCJIT) {
452 errs() << "error: Remote process execution does not work with the "
453 "interpreter.\n";
454 exit(1);
Eli Bendersky4c647582012-01-16 08:56:09 +0000455 }
Daniel Dunbar70ff8b02010-11-17 16:06:37 +0000456
Evan Cheng09bd0b12009-05-04 23:05:19 +0000457 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
458 switch (OptLevel) {
459 default:
Dan Gohmand8db3762009-07-15 16:35:29 +0000460 errs() << argv[0] << ": invalid optimization level.\n";
Evan Cheng09bd0b12009-05-04 23:05:19 +0000461 return 1;
462 case ' ': break;
463 case '0': OLvl = CodeGenOpt::None; break;
Evan Cheng5a286382009-10-16 21:02:20 +0000464 case '1': OLvl = CodeGenOpt::Less; break;
Evan Cheng09bd0b12009-05-04 23:05:19 +0000465 case '2': OLvl = CodeGenOpt::Default; break;
466 case '3': OLvl = CodeGenOpt::Aggressive; break;
467 }
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000468 builder.setOptLevel(OLvl);
469
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000470 TargetOptions Options;
471 Options.UseSoftFloat = GenerateSoftFloatCalls;
472 if (FloatABIForCalls != FloatABI::Default)
473 Options.FloatABIType = FloatABIForCalls;
474 if (GenerateSoftFloatCalls)
475 FloatABIForCalls = FloatABI::Soft;
476
Jim Grosbach0f435d02012-09-05 16:50:34 +0000477 // Remote target execution doesn't handle EH or debug registration.
478 if (!RemoteMCJIT) {
Jim Grosbach0f435d02012-09-05 16:50:34 +0000479 Options.JITEmitDebugInfo = EmitJitDebugInfo;
480 Options.JITEmitDebugInfoToDisk = EmitJitDebugInfoToDisk;
Jim Grosbach0f435d02012-09-05 16:50:34 +0000481 }
Nick Lewyckyb0e97892012-04-18 08:34:12 +0000482
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000483 builder.setTargetOptions(Options);
484
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000485 EE = builder.create();
Chris Lattnerf840ed72009-07-07 18:31:09 +0000486 if (!EE) {
487 if (!ErrorMsg.empty())
Dan Gohmand8db3762009-07-15 16:35:29 +0000488 errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n";
Chris Lattnerf840ed72009-07-07 18:31:09 +0000489 else
Dan Gohmand8db3762009-07-15 16:35:29 +0000490 errs() << argv[0] << ": unknown error creating EE!\n";
Chris Lattner2785bdb2007-05-06 04:58:26 +0000491 exit(1);
492 }
493
Lang Hames173c69f2014-01-08 04:09:09 +0000494 if (EnableCacheManager) {
Lang Hames1ddecc02014-01-09 05:24:05 +0000495 CacheManager = new LLIObjectCache(ObjectCacheDir);
Lang Hames173c69f2014-01-08 04:09:09 +0000496 EE->setObjectCache(CacheManager);
497 }
498
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000499 // Load any additional modules specified on the command line.
500 for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) {
Rafael Espindolad233b062014-08-26 17:29:46 +0000501 std::unique_ptr<Module> XMod = parseIRFile(ExtraModules[i], Err, Context);
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000502 if (!XMod) {
503 Err.print(argv[0], errs());
504 return 1;
505 }
Lang Hames173c69f2014-01-08 04:09:09 +0000506 if (EnableCacheManager) {
Eric Christopher79cc1e32014-09-02 22:28:02 +0000507 std::string CacheName("file:");
508 CacheName.append(ExtraModules[i]);
509 XMod->setModuleIdentifier(CacheName);
Lang Hames173c69f2014-01-08 04:09:09 +0000510 }
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000511 EE->addModule(std::move(XMod));
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000512 }
513
Lang Hames173c69f2014-01-08 04:09:09 +0000514 for (unsigned i = 0, e = ExtraObjects.size(); i != e; ++i) {
Rafael Espindola48af1c22014-08-19 18:44:46 +0000515 ErrorOr<object::OwningBinary<object::ObjectFile>> Obj =
Rafael Espindola51cc3602014-01-22 00:14:49 +0000516 object::ObjectFile::createObjectFile(ExtraObjects[i]);
Lang Hames173c69f2014-01-08 04:09:09 +0000517 if (!Obj) {
518 Err.print(argv[0], errs());
519 return 1;
520 }
Rafael Espindola061beab2014-08-20 15:19:37 +0000521 object::OwningBinary<object::ObjectFile> &O = Obj.get();
Rafael Espindola7271c192014-08-26 21:04:04 +0000522 EE->addObjectFile(std::move(O));
Lang Hames173c69f2014-01-08 04:09:09 +0000523 }
524
525 for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) {
Rafael Espindola48af1c22014-08-19 18:44:46 +0000526 ErrorOr<std::unique_ptr<MemoryBuffer>> ArBufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000527 MemoryBuffer::getFileOrSTDIN(ExtraArchives[i]);
Rafael Espindola48af1c22014-08-19 18:44:46 +0000528 if (!ArBufOrErr) {
Lang Hames173c69f2014-01-08 04:09:09 +0000529 Err.print(argv[0], errs());
530 return 1;
531 }
Rafael Espindola48af1c22014-08-19 18:44:46 +0000532 std::unique_ptr<MemoryBuffer> &ArBuf = ArBufOrErr.get();
Rafael Espindolae1923412014-08-01 18:31:17 +0000533
534 ErrorOr<std::unique_ptr<object::Archive>> ArOrErr =
Rafael Espindola48af1c22014-08-19 18:44:46 +0000535 object::Archive::create(ArBuf->getMemBufferRef());
Rafael Espindolae1923412014-08-01 18:31:17 +0000536 if (std::error_code EC = ArOrErr.getError()) {
537 errs() << EC.message();
Lang Hames173c69f2014-01-08 04:09:09 +0000538 return 1;
539 }
Rafael Espindola48af1c22014-08-19 18:44:46 +0000540 std::unique_ptr<object::Archive> &Ar = ArOrErr.get();
541
542 object::OwningBinary<object::Archive> OB(std::move(Ar), std::move(ArBuf));
543
544 EE->addArchive(std::move(OB));
Lang Hames173c69f2014-01-08 04:09:09 +0000545 }
546
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000547 // If the target is Cygwin/MingW and we are generating remote code, we
548 // need an extra module to help out with linking.
549 if (RemoteMCJIT && Triple(Mod->getTargetTriple()).isOSCygMing()) {
550 addCygMingExtraModule(EE, Context, Mod->getTargetTriple());
551 }
552
Eli Bendersky5262ad22012-03-13 08:33:15 +0000553 // The following functions have no effect if their respective profiling
554 // support wasn't enabled in the build configuration.
555 EE->RegisterJITEventListener(
556 JITEventListener::createOProfileJITEventListener());
557 EE->RegisterJITEventListener(
558 JITEventListener::createIntelJITEventListener());
Jeffrey Yasskin0b08f3d2009-06-25 02:04:04 +0000559
Jim Grosbach0f435d02012-09-05 16:50:34 +0000560 if (!NoLazyCompilation && RemoteMCJIT) {
561 errs() << "warning: remote mcjit does not support lazy compilation\n";
562 NoLazyCompilation = true;
563 }
Jeffrey Yasskinaa8814a2009-10-27 22:39:42 +0000564 EE->DisableLazyCompilation(NoLazyCompilation);
Evan Cheng0422bef2008-04-22 06:51:41 +0000565
Chris Lattner2785bdb2007-05-06 04:58:26 +0000566 // If the user specifically requested an argv[0] to pass into the program,
567 // do it now.
568 if (!FakeArgv0.empty()) {
Chris Bienemane71fb5c2015-01-22 01:49:59 +0000569 InputFile = static_cast<std::string>(FakeArgv0);
Chris Lattner2785bdb2007-05-06 04:58:26 +0000570 } else {
571 // Otherwise, if there is a .bc suffix on the executable strip it off, it
572 // might confuse the program.
Benjamin Kramera944a9a2010-04-15 11:33:14 +0000573 if (StringRef(InputFile).endswith(".bc"))
Chris Lattner2785bdb2007-05-06 04:58:26 +0000574 InputFile.erase(InputFile.length() - 3);
575 }
576
577 // Add the module's name to the start of the vector of arguments to main().
578 InputArgv.insert(InputArgv.begin(), InputFile);
579
580 // Call the main function from M as if its signature were:
581 // int main (int argc, char **argv, const char **envp)
582 // using the contents of Args to determine argc & argv, and the contents of
583 // EnvVars to determine envp.
584 //
Evan Cheng61582542008-11-05 23:21:52 +0000585 Function *EntryFn = Mod->getFunction(EntryFunc);
586 if (!EntryFn) {
Dan Gohmand8db3762009-07-15 16:35:29 +0000587 errs() << '\'' << EntryFunc << "\' function not found in module.\n";
Chris Lattner2785bdb2007-05-06 04:58:26 +0000588 return -1;
589 }
590
Chris Lattner2785bdb2007-05-06 04:58:26 +0000591 // Reset errno to zero on entry to main.
592 errno = 0;
Eli Bendersky4c647582012-01-16 08:56:09 +0000593
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000594 int Result;
595
Andrew Kaylor58365b92012-11-27 19:49:00 +0000596 if (!RemoteMCJIT) {
Andrew Kaylor6587bcf2013-10-11 22:47:10 +0000597 // If the program doesn't explicitly call exit, we will need the Exit
598 // function later on to make an explicit call, so get the function now.
599 Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
600 Type::getInt32Ty(Context),
David Majnemer6539ed72015-02-26 01:10:49 +0000601 nullptr);
Andrew Kaylor6587bcf2013-10-11 22:47:10 +0000602
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000603 // Run static constructors.
Eric Christopher79cc1e32014-09-02 22:28:02 +0000604 if (!ForceInterpreter) {
Andrew Kaylorea395922013-10-01 01:47:35 +0000605 // Give MCJIT a chance to apply relocations and set page permissions.
606 EE->finalizeObject();
607 }
608 EE->runStaticConstructorsDestructors(false);
Evan Cheng0422bef2008-04-22 06:51:41 +0000609
NAKAMURA Takumi87e08802013-12-07 11:21:42 +0000610 // Trigger compilation separately so code regions that need to be
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000611 // invalidated will be known.
612 (void)EE->getPointerToFunction(EntryFn);
613 // Clear instruction cache before code will be executed.
614 if (RTDyldMM)
615 static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
616
617 // Run main.
618 Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
619
620 // Run static destructors.
621 EE->runStaticConstructorsDestructors(true);
622
623 // If the program didn't call exit explicitly, we should call it now.
624 // This ensures that any atexit handlers get called correctly.
625 if (Function *ExitF = dyn_cast<Function>(Exit)) {
626 std::vector<GenericValue> Args;
627 GenericValue ResultGV;
628 ResultGV.IntVal = APInt(32, Result);
629 Args.push_back(ResultGV);
630 EE->runFunction(ExitF, Args);
631 errs() << "ERROR: exit(" << Result << ") returned!\n";
632 abort();
633 } else {
634 errs() << "ERROR: exit defined with wrong prototype!\n";
635 abort();
636 }
637 } else {
638 // else == "if (RemoteMCJIT)"
639
640 // Remote target MCJIT doesn't (yet) support static constructors. No reason
641 // it couldn't. This is a limitation of the LLI implemantation, not the
642 // MCJIT itself. FIXME.
643 //
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000644 RemoteMemoryManager *MM = static_cast<RemoteMemoryManager*>(RTDyldMM);
Jim Grosbach0f435d02012-09-05 16:50:34 +0000645 // Everything is prepared now, so lay out our program for the target
646 // address space, assign the section addresses to resolve any relocations,
647 // and send it to the target.
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000648
Ahmed Charles56440fd2014-03-06 05:51:42 +0000649 std::unique_ptr<RemoteTarget> Target;
Alp Tokera1186382014-01-22 21:52:35 +0000650 if (!ChildExecPath.empty()) { // Remote execution on a child process
Alp Tokerce4ab592014-01-23 19:57:16 +0000651#ifndef LLVM_ON_UNIX
652 // FIXME: Remove this pointless fallback mode which causes tests to "pass"
653 // on platforms where they should XFAIL.
654 errs() << "Warning: host does not support external remote targets.\n"
655 << " Defaulting to simulated remote execution\n";
656 Target.reset(new RemoteTarget);
657#else
658 if (!sys::fs::can_execute(ChildExecPath)) {
659 errs() << "Unable to find usable child executable: '" << ChildExecPath
660 << "'\n";
661 return -1;
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000662 }
Alp Tokerce4ab592014-01-23 19:57:16 +0000663 Target.reset(new RemoteTargetExternal(ChildExecPath));
664#endif
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000665 } else {
666 // No child process name provided, use simulated remote execution.
Alp Tokerce4ab592014-01-23 19:57:16 +0000667 Target.reset(new RemoteTarget);
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000668 }
669
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000670 // Give the memory manager a pointer to our remote target interface object.
671 MM->setRemoteTarget(Target.get());
672
673 // Create the remote target.
Renato Golin695895c2014-01-14 22:43:43 +0000674 if (!Target->create()) {
675 errs() << "ERROR: " << Target->getErrorMsg() << "\n";
676 return EXIT_FAILURE;
677 }
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
Renato Golin695895c2014-01-14 22:43:43 +0000694 if (!Target->executeCode(Entry, Result))
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000695 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}