blob: 74ab2f3cd5ac4d5cdd526d00286d830b2d4792f9 [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
Lang Hames9d7a2692016-01-11 16:35:55 +000016#include "RemoteJITUtils.h"
NAKAMURA Takumicef0a8212016-01-15 02:14:46 +000017#include "llvm/ADT/StringExtras.h"
Duncan Sands3bd97fe2010-08-28 01:30:02 +000018#include "llvm/ADT/Triple.h"
Teresa Johnsonad176792016-11-11 05:34:58 +000019#include "llvm/Bitcode/BitcodeReader.h"
David Blaikie4333f972018-04-11 18:49:37 +000020#include "llvm/CodeGen/CommandFlags.inc"
Chris Lattner5af6a3f2006-08-01 22:34:35 +000021#include "llvm/CodeGen/LinkAllCodegenComponents.h"
Nico Weber432a3882018-04-30 14:59:11 +000022#include "llvm/Config/llvm-config.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 Hames6a941342018-06-26 21:35:48 +000028#include "llvm/ExecutionEngine/Orc/ExecutionUtils.h"
29#include "llvm/ExecutionEngine/Orc/LLJIT.h"
Rafael Espindola79e238a2017-08-03 02:16:21 +000030#include "llvm/ExecutionEngine/Orc/OrcRemoteTargetClient.h"
Lang Hames93de2a12015-01-23 21:25:00 +000031#include "llvm/ExecutionEngine/OrcMCJITReplacement.h"
Andrew Kaylor58365b92012-11-27 19:49:00 +000032#include "llvm/ExecutionEngine/SectionMemoryManager.h"
Andrew Kaylor1ca510e2013-10-29 01:29:56 +000033#include "llvm/IR/IRBuilder.h"
Rafael Espindola79e238a2017-08-03 02:16:21 +000034#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000035#include "llvm/IR/Module.h"
36#include "llvm/IR/Type.h"
Andrew Kaylor1ca510e2013-10-29 01:29:56 +000037#include "llvm/IR/TypeBuilder.h"
Lang Hamesadae9bf2018-07-02 22:30:18 +000038#include "llvm/IR/Verifier.h"
Chandler Carruthe60e57b2013-03-26 02:25:37 +000039#include "llvm/IRReader/IRReader.h"
Lang Hames173c69f2014-01-08 04:09:09 +000040#include "llvm/Object/Archive.h"
41#include "llvm/Object/ObjectFile.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000042#include "llvm/Support/CommandLine.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000043#include "llvm/Support/Debug.h"
44#include "llvm/Support/DynamicLibrary.h"
45#include "llvm/Support/Format.h"
Rui Ueyama197194b2018-04-13 18:26:06 +000046#include "llvm/Support/InitLLVM.h"
Chris Lattner76d46322006-12-06 01:18:01 +000047#include "llvm/Support/ManagedStatic.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000048#include "llvm/Support/MathExtras.h"
49#include "llvm/Support/Memory.h"
Chris Lattner2785bdb2007-05-06 04:58:26 +000050#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer16132e62015-03-23 18:07:13 +000051#include "llvm/Support/Path.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000052#include "llvm/Support/PluginLoader.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000053#include "llvm/Support/Process.h"
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +000054#include "llvm/Support/Program.h"
Chandler Carruthe60e57b2013-03-26 02:25:37 +000055#include "llvm/Support/SourceMgr.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000056#include "llvm/Support/TargetSelect.h"
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +000057#include "llvm/Support/WithColor.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000058#include "llvm/Support/raw_ostream.h"
Daniel Maleaa960c542013-06-28 19:11:40 +000059#include "llvm/Transforms/Instrumentation.h"
Chris Lattner4c522b92007-04-27 17:02:33 +000060#include <cerrno>
NAKAMURA Takumi15304872010-10-22 14:53:59 +000061
62#ifdef __CYGWIN__
63#include <cygwin/version.h>
64#if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
65#define DO_NOTHING_ATEXIT 1
66#endif
67#endif
68
Brian Gaeke960707c2003-11-11 22:41:34 +000069using namespace llvm;
70
Chandler Carruthf98597a2014-04-22 03:10:36 +000071#define DEBUG_TYPE "lli"
72
Chris Lattnera0d7b082002-12-23 23:59:41 +000073namespace {
Lang Hames9528bba2015-03-25 12:11:48 +000074
75 enum class JITKind { MCJIT, OrcMCJITReplacement, OrcLazy };
76
Chris Lattnera0d7b082002-12-23 23:59:41 +000077 cl::opt<std::string>
Gabor Greife16561c2007-07-05 17:07:56 +000078 InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
Chris Lattnerf5cad152002-07-22 02:10:13 +000079
Chris Lattnera0d7b082002-12-23 23:59:41 +000080 cl::list<std::string>
81 InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
Chris Lattnerf5cad152002-07-22 02:10:13 +000082
Chris Lattnera0d7b082002-12-23 23:59:41 +000083 cl::opt<bool> ForceInterpreter("force-interpreter",
Misha Brukmanc2186e32003-09-25 18:10:34 +000084 cl::desc("Force interpretation: disable JIT"),
85 cl::init(false));
Evan Cheng06d988e2008-08-08 08:12:06 +000086
Lang Hames9528bba2015-03-25 12:11:48 +000087 cl::opt<JITKind> UseJITKind("jit-kind",
88 cl::desc("Choose underlying JIT kind."),
89 cl::init(JITKind::MCJIT),
90 cl::values(
91 clEnumValN(JITKind::MCJIT, "mcjit",
92 "MCJIT"),
93 clEnumValN(JITKind::OrcMCJITReplacement,
94 "orc-mcjit",
95 "Orc-based MCJIT replacement"),
96 clEnumValN(JITKind::OrcLazy,
97 "orc-lazy",
Mehdi Amini732afdd2016-10-08 19:41:06 +000098 "Orc-based lazy JIT.")));
Lang Hames93de2a12015-01-23 21:25:00 +000099
Jim Grosbach0f435d02012-09-05 16:50:34 +0000100 // The MCJIT supports building for a target address space separate from
101 // the JIT compilation process. Use a forked process and a copying
102 // memory manager with IPC to execute using this functionality.
103 cl::opt<bool> RemoteMCJIT("remote-mcjit",
104 cl::desc("Execute MCJIT'ed code in a separate process."),
105 cl::init(false));
106
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000107 // Manually specify the child process for remote execution. This overrides
108 // the simulated remote execution that allocates address space for child
Andrew Kaylor89352582013-10-29 01:33:14 +0000109 // execution. The child process will be executed and will communicate with
110 // lli via stdin/stdout pipes.
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000111 cl::opt<std::string>
Alp Tokera1186382014-01-22 21:52:35 +0000112 ChildExecPath("mcjit-remote-process",
113 cl::desc("Specify the filename of the process to launch "
114 "for remote MCJIT execution. If none is specified,"
115 "\n\tremote execution will be simulated in-process."),
116 cl::value_desc("filename"), cl::init(""));
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000117
Evan Cheng09bd0b12009-05-04 23:05:19 +0000118 // Determine optimization level.
119 cl::opt<char>
120 OptLevel("O",
121 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
122 "(default = '-O2')"),
123 cl::Prefix,
124 cl::ZeroOrMore,
125 cl::init(' '));
Evan Cheng06d988e2008-08-08 08:12:06 +0000126
Chris Lattner76766cb2005-12-16 05:00:21 +0000127 cl::opt<std::string>
Chris Lattner78e9e102005-12-16 05:19:18 +0000128 TargetTriple("mtriple", cl::desc("Override target triple for module"));
Evan Cheng61582542008-11-05 23:21:52 +0000129
130 cl::opt<std::string>
131 EntryFunc("entry-function",
132 cl::desc("Specify the entry function (default = 'main') "
133 "of the executable"),
134 cl::value_desc("function"),
135 cl::init("main"));
Eli Bendersky4c647582012-01-16 08:56:09 +0000136
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000137 cl::list<std::string>
Andrew Kaylor4404eb42013-10-28 21:58:15 +0000138 ExtraModules("extra-module",
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000139 cl::desc("Extra modules to be loaded"),
Alp Toker0a09ebf2013-10-28 22:51:25 +0000140 cl::value_desc("input bitcode"));
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000141
Lang Hames173c69f2014-01-08 04:09:09 +0000142 cl::list<std::string>
143 ExtraObjects("extra-object",
144 cl::desc("Extra object files to be loaded"),
145 cl::value_desc("input object"));
146
147 cl::list<std::string>
148 ExtraArchives("extra-archive",
149 cl::desc("Extra archive files to be loaded"),
150 cl::value_desc("input archive"));
151
152 cl::opt<bool>
153 EnableCacheManager("enable-cache-manager",
Lang Hames1ddecc02014-01-09 05:24:05 +0000154 cl::desc("Use cache manager to save/load mdoules"),
Lang Hames173c69f2014-01-08 04:09:09 +0000155 cl::init(false));
156
Chris Lattner55644062003-10-28 22:51:44 +0000157 cl::opt<std::string>
Lang Hames1ddecc02014-01-09 05:24:05 +0000158 ObjectCacheDir("object-cache-dir",
159 cl::desc("Directory to store cached object files "
160 "(must be user writable)"),
161 cl::init(""));
162
163 cl::opt<std::string>
Chris Lattner55644062003-10-28 22:51:44 +0000164 FakeArgv0("fake-argv0",
165 cl::desc("Override the 'argv[0]' value passed into the executing"
166 " program"), cl::value_desc("executable"));
Eli Bendersky4c647582012-01-16 08:56:09 +0000167
Chris Lattner3f0ffd32006-09-14 06:17:09 +0000168 cl::opt<bool>
169 DisableCoreFiles("disable-core-files", cl::Hidden,
170 cl::desc("Disable emission of core files if possible"));
Evan Cheng0422bef2008-04-22 06:51:41 +0000171
172 cl::opt<bool>
Evan Cheng16f036c2008-05-21 18:20:21 +0000173 NoLazyCompilation("disable-lazy-compilation",
Evan Cheng0422bef2008-04-22 06:51:41 +0000174 cl::desc("Disable JIT lazy compilation"),
175 cl::init(false));
Evan Cheng2129f592011-07-19 06:37:02 +0000176
Nick Lewyckyb0e97892012-04-18 08:34:12 +0000177 cl::opt<bool>
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000178 GenerateSoftFloatCalls("soft-float",
179 cl::desc("Generate software floating point library calls"),
180 cl::init(false));
181
Lang Hames6a941342018-06-26 21:35:48 +0000182 enum class DumpKind {
183 NoDump,
184 DumpFuncsToStdOut,
185 DumpModsToStdOut,
186 DumpModsToDisk
187 };
188
189 cl::opt<DumpKind> OrcDumpKind(
190 "orc-lazy-debug", cl::desc("Debug dumping for the orc-lazy JIT."),
191 cl::init(DumpKind::NoDump),
192 cl::values(clEnumValN(DumpKind::NoDump, "no-dump",
193 "Don't dump anything."),
194 clEnumValN(DumpKind::DumpFuncsToStdOut, "funcs-to-stdout",
195 "Dump function names to stdout."),
196 clEnumValN(DumpKind::DumpModsToStdOut, "mods-to-stdout",
197 "Dump modules to stdout."),
198 clEnumValN(DumpKind::DumpModsToDisk, "mods-to-disk",
199 "Dump modules to the current "
200 "working directory. (WARNING: "
201 "will overwrite existing files).")),
202 cl::Hidden);
203
Lang Hamesef5a0ee2016-04-25 19:56:45 +0000204 ExitOnError ExitOnErr;
Chris Lattnera0d7b082002-12-23 23:59:41 +0000205}
Chris Lattner009f8102001-10-27 08:43:52 +0000206
Lang Hames173c69f2014-01-08 04:09:09 +0000207//===----------------------------------------------------------------------===//
208// Object cache
209//
Lang Hames1ddecc02014-01-09 05:24:05 +0000210// This object cache implementation writes cached objects to disk to the
211// directory specified by CacheDir, using a filename provided in the module
212// descriptor. The cache tries to load a saved object using that path if the
213// file exists. CacheDir defaults to "", in which case objects are cached
NAKAMURA Takumif462f9c2014-01-10 10:38:28 +0000214// alongside their originating bitcodes.
Lang Hames173c69f2014-01-08 04:09:09 +0000215//
216class LLIObjectCache : public ObjectCache {
217public:
Lang Hames1ddecc02014-01-09 05:24:05 +0000218 LLIObjectCache(const std::string& CacheDir) : CacheDir(CacheDir) {
219 // Add trailing '/' to cache dir if necessary.
Lang Hamesf9dd8fd2014-01-09 05:29:59 +0000220 if (!this->CacheDir.empty() &&
221 this->CacheDir[this->CacheDir.size() - 1] != '/')
NAKAMURA Takumif462f9c2014-01-10 10:38:28 +0000222 this->CacheDir += '/';
Lang Hames1ddecc02014-01-09 05:24:05 +0000223 }
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000224 ~LLIObjectCache() override {}
Lang Hames173c69f2014-01-08 04:09:09 +0000225
Rafael Espindola48af1c22014-08-19 18:44:46 +0000226 void notifyObjectCompiled(const Module *M, MemoryBufferRef Obj) override {
Benjamin Kramer46e38f32016-06-08 10:01:20 +0000227 const std::string &ModuleID = M->getModuleIdentifier();
Lang Hames173c69f2014-01-08 04:09:09 +0000228 std::string CacheName;
229 if (!getCacheFilename(ModuleID, CacheName))
230 return;
NAKAMURA Takumi390e0602014-01-10 10:38:34 +0000231 if (!CacheDir.empty()) { // Create user-defined cache dir.
Rafael Espindolaf662e002015-07-15 21:24:07 +0000232 SmallString<128> dir(sys::path::parent_path(CacheName));
NAKAMURA Takumi390e0602014-01-10 10:38:34 +0000233 sys::fs::create_directories(Twine(dir));
234 }
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000235 std::error_code EC;
236 raw_fd_ostream outfile(CacheName, EC, sys::fs::F_None);
Rafael Espindola48af1c22014-08-19 18:44:46 +0000237 outfile.write(Obj.getBufferStart(), Obj.getBufferSize());
Lang Hames173c69f2014-01-08 04:09:09 +0000238 outfile.close();
239 }
240
Rafael Espindola5f2bb7d2014-08-13 18:49:01 +0000241 std::unique_ptr<MemoryBuffer> getObject(const Module* M) override {
Benjamin Kramer46e38f32016-06-08 10:01:20 +0000242 const std::string &ModuleID = M->getModuleIdentifier();
Lang Hames173c69f2014-01-08 04:09:09 +0000243 std::string CacheName;
244 if (!getCacheFilename(ModuleID, CacheName))
Craig Toppere6cb63e2014-04-25 04:24:47 +0000245 return nullptr;
Lang Hames173c69f2014-01-08 04:09:09 +0000246 // Load the object from the cache filename
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000247 ErrorOr<std::unique_ptr<MemoryBuffer>> IRObjectBuffer =
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000248 MemoryBuffer::getFile(CacheName, -1, false);
Lang Hames173c69f2014-01-08 04:09:09 +0000249 // If the file isn't there, that's OK.
250 if (!IRObjectBuffer)
Craig Toppere6cb63e2014-04-25 04:24:47 +0000251 return nullptr;
Lang Hames173c69f2014-01-08 04:09:09 +0000252 // MCJIT will want to write into this buffer, and we don't want that
253 // because the file has probably just been mmapped. Instead we make
254 // a copy. The filed-based buffer will be released when it goes
255 // out of scope.
Rafael Espindola3560ff22014-08-27 20:03:13 +0000256 return MemoryBuffer::getMemBufferCopy(IRObjectBuffer.get()->getBuffer());
Lang Hames173c69f2014-01-08 04:09:09 +0000257 }
258
259private:
Lang Hames1ddecc02014-01-09 05:24:05 +0000260 std::string CacheDir;
261
Lang Hames173c69f2014-01-08 04:09:09 +0000262 bool getCacheFilename(const std::string &ModID, std::string &CacheName) {
263 std::string Prefix("file:");
264 size_t PrefixLength = Prefix.length();
265 if (ModID.substr(0, PrefixLength) != Prefix)
266 return false;
NAKAMURA Takumid7fd6d92014-01-10 10:38:40 +0000267 std::string CacheSubdir = ModID.substr(PrefixLength);
268#if defined(_WIN32)
269 // Transform "X:\foo" => "/X\foo" for convenience.
270 if (isalpha(CacheSubdir[0]) && CacheSubdir[1] == ':') {
271 CacheSubdir[1] = CacheSubdir[0];
272 CacheSubdir[0] = '/';
273 }
274#endif
275 CacheName = CacheDir + CacheSubdir;
Lang Hames173c69f2014-01-08 04:09:09 +0000276 size_t pos = CacheName.rfind('.');
277 CacheName.replace(pos, CacheName.length() - pos, ".o");
278 return true;
279 }
280};
281
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000282// On Mingw and Cygwin, an external symbol named '__main' is called from the
Simon Pilgrimdae11f72016-11-20 13:31:13 +0000283// generated 'main' function to allow static initialization. To avoid linking
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000284// problems with remote targets (because lli's remote target support does not
285// currently handle external linking) we add a secondary module which defines
286// an empty '__main' function.
Mehdi Aminia7de8202016-04-18 18:52:39 +0000287static void addCygMingExtraModule(ExecutionEngine &EE, LLVMContext &Context,
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000288 StringRef TargetTripleStr) {
289 IRBuilder<> Builder(Context);
290 Triple TargetTriple(TargetTripleStr);
291
292 // Create a new module.
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000293 std::unique_ptr<Module> M = make_unique<Module>("CygMingHelper", Context);
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000294 M->setTargetTriple(TargetTripleStr);
295
296 // Create an empty function named "__main".
297 Function *Result;
298 if (TargetTriple.isArch64Bit()) {
299 Result = Function::Create(
300 TypeBuilder<int64_t(void), false>::get(Context),
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000301 GlobalValue::ExternalLinkage, "__main", M.get());
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000302 } else {
303 Result = Function::Create(
304 TypeBuilder<int32_t(void), false>::get(Context),
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000305 GlobalValue::ExternalLinkage, "__main", M.get());
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000306 }
307 BasicBlock *BB = BasicBlock::Create(Context, "__main", Result);
308 Builder.SetInsertPoint(BB);
309 Value *ReturnVal;
310 if (TargetTriple.isArch64Bit())
311 ReturnVal = ConstantInt::get(Context, APInt(64, 0));
312 else
313 ReturnVal = ConstantInt::get(Context, APInt(32, 0));
314 Builder.CreateRet(ReturnVal);
315
316 // Add this new module to the ExecutionEngine.
Mehdi Aminia7de8202016-04-18 18:52:39 +0000317 EE.addModule(std::move(M));
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000318}
319
Lang Hames1899d0c2015-06-09 02:43:27 +0000320CodeGenOpt::Level getOptLevel() {
321 switch (OptLevel) {
322 default:
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000323 WithColor::error(errs(), "lli") << "invalid optimization level.\n";
Lang Hames1899d0c2015-06-09 02:43:27 +0000324 exit(1);
325 case '0': return CodeGenOpt::None;
326 case '1': return CodeGenOpt::Less;
327 case ' ':
328 case '2': return CodeGenOpt::Default;
329 case '3': return CodeGenOpt::Aggressive;
330 }
331 llvm_unreachable("Unrecognized opt level.");
332}
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000333
Davide Italianoda8e6b22016-11-17 22:58:13 +0000334LLVM_ATTRIBUTE_NORETURN
335static void reportError(SMDiagnostic Err, const char *ProgName) {
336 Err.print(ProgName, errs());
337 exit(1);
338}
339
Lang Hames6a941342018-06-26 21:35:48 +0000340int runOrcLazyJIT(LLVMContext &Ctx, std::vector<std::unique_ptr<Module>> Ms,
341 const std::vector<std::string> &Args);
342
Chris Lattnerd7ff5782001-08-23 17:05:04 +0000343//===----------------------------------------------------------------------===//
Chris Lattnerd7ff5782001-08-23 17:05:04 +0000344// main Driver function
345//
Misha Brukman5b255e52003-10-14 21:39:53 +0000346int main(int argc, char **argv, char * const *envp) {
Rui Ueyama197194b2018-04-13 18:26:06 +0000347 InitLLVM X(argc, argv);
Daniel Dunbar3d92d932009-07-16 02:04:54 +0000348
Lang Hamesef5a0ee2016-04-25 19:56:45 +0000349 if (argc > 1)
350 ExitOnErr.setBanner(std::string(argv[0]) + ": ");
351
Daniel Dunbar3d92d932009-07-16 02:04:54 +0000352 // If we have a native target, initialize it to ensure it is linked in and
353 // usable by the JIT.
354 InitializeNativeTarget();
Jim Grosbach7b162492011-03-18 22:48:41 +0000355 InitializeNativeTargetAsmPrinter();
Jim Grosbach2cce3f92012-11-05 19:06:05 +0000356 InitializeNativeTargetAsmParser();
Daniel Dunbar3d92d932009-07-16 02:04:54 +0000357
Chris Lattner2785bdb2007-05-06 04:58:26 +0000358 cl::ParseCommandLineOptions(argc, argv,
Dan Gohman2c6a8212007-10-08 15:45:12 +0000359 "llvm interpreter & dynamic compiler\n");
Reid Spencer996ec722004-12-30 05:36:08 +0000360
Chris Lattner2785bdb2007-05-06 04:58:26 +0000361 // If the user doesn't want core files, disable them.
362 if (DisableCoreFiles)
363 sys::Process::PreventCoreFiles();
Eli Bendersky4c647582012-01-16 08:56:09 +0000364
Mehdi Aminia7de8202016-04-18 18:52:39 +0000365 LLVMContext Context;
366
Gabor Greife16561c2007-07-05 17:07:56 +0000367 // Load the bitcode...
Daniel Dunbar9589bf82010-11-13 00:28:01 +0000368 SMDiagnostic Err;
Rafael Espindolad233b062014-08-26 17:29:46 +0000369 std::unique_ptr<Module> Owner = parseIRFile(InputFile, Err, Context);
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000370 Module *Mod = Owner.get();
Davide Italianoda8e6b22016-11-17 22:58:13 +0000371 if (!Mod)
372 reportError(Err, argv[0]);
Chris Lattner2785bdb2007-05-06 04:58:26 +0000373
Lang Hames368c4222016-08-02 21:00:40 +0000374 if (UseJITKind == JITKind::OrcLazy) {
375 std::vector<std::unique_ptr<Module>> Ms;
376 Ms.push_back(std::move(Owner));
377 for (auto &ExtraMod : ExtraModules) {
378 Ms.push_back(parseIRFile(ExtraMod, Err, Context));
Davide Italianoda8e6b22016-11-17 22:58:13 +0000379 if (!Ms.back())
380 reportError(Err, argv[0]);
Lang Hames368c4222016-08-02 21:00:40 +0000381 }
Lang Hames1a2e6562016-10-28 16:52:34 +0000382 std::vector<std::string> Args;
383 Args.push_back(InputFile);
384 for (auto &Arg : InputArgv)
385 Args.push_back(Arg);
Lang Hames6a941342018-06-26 21:35:48 +0000386 return runOrcLazyJIT(Context, std::move(Ms), Args);
Lang Hames368c4222016-08-02 21:00:40 +0000387 }
Lang Hames9528bba2015-03-25 12:11:48 +0000388
Lang Hames173c69f2014-01-08 04:09:09 +0000389 if (EnableCacheManager) {
Eric Christopher79cc1e32014-09-02 22:28:02 +0000390 std::string CacheName("file:");
391 CacheName.append(InputFile);
392 Mod->setModuleIdentifier(CacheName);
Lang Hames173c69f2014-01-08 04:09:09 +0000393 }
394
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000395 // If not jitting lazily, load the whole bitcode file eagerly too.
396 if (NoLazyCompilation) {
Davide Italianob0e067b2016-11-09 21:30:33 +0000397 // Use *argv instead of argv[0] to work around a wrong GCC warning.
398 ExitOnError ExitOnErr(std::string(*argv) +
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000399 ": bitcode didn't read correctly: ");
400 ExitOnErr(Mod->materializeAll());
Evan Cheng0422bef2008-04-22 06:51:41 +0000401 }
Chris Lattner2785bdb2007-05-06 04:58:26 +0000402
Rafael Espindolae9fab9b2014-01-14 23:51:27 +0000403 std::string ErrorMsg;
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000404 EngineBuilder builder(std::move(Owner));
Jeffrey Yasskin31faeff2010-02-05 16:19:36 +0000405 builder.setMArch(MArch);
Craig Topper243f20f2018-01-09 18:14:18 +0000406 builder.setMCPU(getCPUStr());
407 builder.setMAttrs(getFeatureList());
Rafael Espindola8c34dd82016-05-18 22:04:49 +0000408 if (RelocModel.getNumOccurrences())
409 builder.setRelocationModel(RelocModel);
Rafael Espindola79e238a2017-08-03 02:16:21 +0000410 if (CMModel.getNumOccurrences())
411 builder.setCodeModel(CMModel);
Daniel Dunbara78d8092009-07-18 08:07:13 +0000412 builder.setErrorStr(&ErrorMsg);
413 builder.setEngineKind(ForceInterpreter
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000414 ? EngineKind::Interpreter
415 : EngineKind::JIT);
Lang Hames9528bba2015-03-25 12:11:48 +0000416 builder.setUseOrcMCJITReplacement(UseJITKind == JITKind::OrcMCJITReplacement);
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000417
Chris Lattner2785bdb2007-05-06 04:58:26 +0000418 // If we are supposed to override the target triple, do so now.
419 if (!TargetTriple.empty())
Duncan Sands3bd97fe2010-08-28 01:30:02 +0000420 Mod->setTargetTriple(Triple::normalize(TargetTriple));
Evan Cheng0422bef2008-04-22 06:51:41 +0000421
Eli Bendersky4c647582012-01-16 08:56:09 +0000422 // Enable MCJIT if desired.
Craig Toppere6cb63e2014-04-25 04:24:47 +0000423 RTDyldMemoryManager *RTDyldMM = nullptr;
Eric Christopher79cc1e32014-09-02 22:28:02 +0000424 if (!ForceInterpreter) {
Jim Grosbach0f435d02012-09-05 16:50:34 +0000425 if (RemoteMCJIT)
Lang Hames9d7a2692016-01-11 16:35:55 +0000426 RTDyldMM = new ForwardingMemoryManager();
Jim Grosbach0f435d02012-09-05 16:50:34 +0000427 else
Filip Pizlo9bc53e82013-05-14 19:29:00 +0000428 RTDyldMM = new SectionMemoryManager();
Lang Hames4a5697e2014-12-03 00:51:19 +0000429
430 // Deliberately construct a temp std::unique_ptr to pass in. Do not null out
431 // RTDyldMM: We still use it below, even though we don't own it.
432 builder.setMCJITMemoryManager(
433 std::unique_ptr<RTDyldMemoryManager>(RTDyldMM));
Lang Hames0f154902014-09-23 16:56:02 +0000434 } else if (RemoteMCJIT) {
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000435 WithColor::error(errs(), argv[0])
436 << "remote process execution does not work with the interpreter.\n";
Lang Hames0f154902014-09-23 16:56:02 +0000437 exit(1);
Eli Bendersky4c647582012-01-16 08:56:09 +0000438 }
Daniel Dunbar70ff8b02010-11-17 16:06:37 +0000439
Lang Hames1899d0c2015-06-09 02:43:27 +0000440 builder.setOptLevel(getOptLevel());
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000441
David Blaikiec14bfec2017-11-27 19:43:58 +0000442 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000443 if (FloatABIForCalls != FloatABI::Default)
444 Options.FloatABIType = FloatABIForCalls;
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000445
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000446 builder.setTargetOptions(Options);
447
Mehdi Aminia7de8202016-04-18 18:52:39 +0000448 std::unique_ptr<ExecutionEngine> EE(builder.create());
Chris Lattnerf840ed72009-07-07 18:31:09 +0000449 if (!EE) {
450 if (!ErrorMsg.empty())
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000451 WithColor::error(errs(), argv[0])
452 << "error creating EE: " << ErrorMsg << "\n";
Chris Lattnerf840ed72009-07-07 18:31:09 +0000453 else
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000454 WithColor::error(errs(), argv[0]) << "unknown error creating EE!\n";
Chris Lattner2785bdb2007-05-06 04:58:26 +0000455 exit(1);
456 }
457
Mehdi Aminia7de8202016-04-18 18:52:39 +0000458 std::unique_ptr<LLIObjectCache> CacheManager;
Lang Hames173c69f2014-01-08 04:09:09 +0000459 if (EnableCacheManager) {
Mehdi Aminia7de8202016-04-18 18:52:39 +0000460 CacheManager.reset(new LLIObjectCache(ObjectCacheDir));
461 EE->setObjectCache(CacheManager.get());
Lang Hames173c69f2014-01-08 04:09:09 +0000462 }
463
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000464 // Load any additional modules specified on the command line.
465 for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) {
Rafael Espindolad233b062014-08-26 17:29:46 +0000466 std::unique_ptr<Module> XMod = parseIRFile(ExtraModules[i], Err, Context);
Davide Italianoda8e6b22016-11-17 22:58:13 +0000467 if (!XMod)
468 reportError(Err, argv[0]);
Lang Hames173c69f2014-01-08 04:09:09 +0000469 if (EnableCacheManager) {
Eric Christopher79cc1e32014-09-02 22:28:02 +0000470 std::string CacheName("file:");
471 CacheName.append(ExtraModules[i]);
472 XMod->setModuleIdentifier(CacheName);
Lang Hames173c69f2014-01-08 04:09:09 +0000473 }
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000474 EE->addModule(std::move(XMod));
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000475 }
476
Lang Hames173c69f2014-01-08 04:09:09 +0000477 for (unsigned i = 0, e = ExtraObjects.size(); i != e; ++i) {
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000478 Expected<object::OwningBinary<object::ObjectFile>> Obj =
Rafael Espindola51cc3602014-01-22 00:14:49 +0000479 object::ObjectFile::createObjectFile(ExtraObjects[i]);
Lang Hames173c69f2014-01-08 04:09:09 +0000480 if (!Obj) {
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000481 // TODO: Actually report errors helpfully.
482 consumeError(Obj.takeError());
Davide Italianoda8e6b22016-11-17 22:58:13 +0000483 reportError(Err, argv[0]);
Lang Hames173c69f2014-01-08 04:09:09 +0000484 }
Rafael Espindola061beab2014-08-20 15:19:37 +0000485 object::OwningBinary<object::ObjectFile> &O = Obj.get();
Rafael Espindola7271c192014-08-26 21:04:04 +0000486 EE->addObjectFile(std::move(O));
Lang Hames173c69f2014-01-08 04:09:09 +0000487 }
488
489 for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) {
Rafael Espindola48af1c22014-08-19 18:44:46 +0000490 ErrorOr<std::unique_ptr<MemoryBuffer>> ArBufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000491 MemoryBuffer::getFileOrSTDIN(ExtraArchives[i]);
Davide Italianoda8e6b22016-11-17 22:58:13 +0000492 if (!ArBufOrErr)
493 reportError(Err, argv[0]);
Rafael Espindola48af1c22014-08-19 18:44:46 +0000494 std::unique_ptr<MemoryBuffer> &ArBuf = ArBufOrErr.get();
Rafael Espindolae1923412014-08-01 18:31:17 +0000495
Kevin Enderbyc60a3212016-06-29 20:35:44 +0000496 Expected<std::unique_ptr<object::Archive>> ArOrErr =
Rafael Espindola48af1c22014-08-19 18:44:46 +0000497 object::Archive::create(ArBuf->getMemBufferRef());
Kevin Enderbyc60a3212016-06-29 20:35:44 +0000498 if (!ArOrErr) {
499 std::string Buf;
500 raw_string_ostream OS(Buf);
501 logAllUnhandledErrors(ArOrErr.takeError(), OS, "");
502 OS.flush();
503 errs() << Buf;
Davide Italiano86511442016-11-17 22:59:13 +0000504 exit(1);
Lang Hames173c69f2014-01-08 04:09:09 +0000505 }
Rafael Espindola48af1c22014-08-19 18:44:46 +0000506 std::unique_ptr<object::Archive> &Ar = ArOrErr.get();
507
508 object::OwningBinary<object::Archive> OB(std::move(Ar), std::move(ArBuf));
509
510 EE->addArchive(std::move(OB));
Lang Hames173c69f2014-01-08 04:09:09 +0000511 }
512
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000513 // If the target is Cygwin/MingW and we are generating remote code, we
514 // need an extra module to help out with linking.
515 if (RemoteMCJIT && Triple(Mod->getTargetTriple()).isOSCygMing()) {
Mehdi Aminia7de8202016-04-18 18:52:39 +0000516 addCygMingExtraModule(*EE, Context, Mod->getTargetTriple());
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000517 }
518
Eli Bendersky5262ad22012-03-13 08:33:15 +0000519 // The following functions have no effect if their respective profiling
520 // support wasn't enabled in the build configuration.
521 EE->RegisterJITEventListener(
522 JITEventListener::createOProfileJITEventListener());
523 EE->RegisterJITEventListener(
524 JITEventListener::createIntelJITEventListener());
Jeffrey Yasskin0b08f3d2009-06-25 02:04:04 +0000525
Jim Grosbach0f435d02012-09-05 16:50:34 +0000526 if (!NoLazyCompilation && RemoteMCJIT) {
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000527 WithColor::warning(errs(), argv[0])
528 << "remote mcjit does not support lazy compilation\n";
Jim Grosbach0f435d02012-09-05 16:50:34 +0000529 NoLazyCompilation = true;
530 }
Jeffrey Yasskinaa8814a2009-10-27 22:39:42 +0000531 EE->DisableLazyCompilation(NoLazyCompilation);
Evan Cheng0422bef2008-04-22 06:51:41 +0000532
Chris Lattner2785bdb2007-05-06 04:58:26 +0000533 // If the user specifically requested an argv[0] to pass into the program,
534 // do it now.
535 if (!FakeArgv0.empty()) {
Chris Bienemane71fb5c2015-01-22 01:49:59 +0000536 InputFile = static_cast<std::string>(FakeArgv0);
Chris Lattner2785bdb2007-05-06 04:58:26 +0000537 } else {
538 // Otherwise, if there is a .bc suffix on the executable strip it off, it
539 // might confuse the program.
Benjamin Kramera944a9a2010-04-15 11:33:14 +0000540 if (StringRef(InputFile).endswith(".bc"))
Chris Lattner2785bdb2007-05-06 04:58:26 +0000541 InputFile.erase(InputFile.length() - 3);
542 }
543
544 // Add the module's name to the start of the vector of arguments to main().
545 InputArgv.insert(InputArgv.begin(), InputFile);
546
547 // Call the main function from M as if its signature were:
548 // int main (int argc, char **argv, const char **envp)
549 // using the contents of Args to determine argc & argv, and the contents of
550 // EnvVars to determine envp.
551 //
Evan Cheng61582542008-11-05 23:21:52 +0000552 Function *EntryFn = Mod->getFunction(EntryFunc);
553 if (!EntryFn) {
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000554 WithColor::error(errs(), argv[0])
555 << '\'' << EntryFunc << "\' function not found in module.\n";
Chris Lattner2785bdb2007-05-06 04:58:26 +0000556 return -1;
557 }
558
Chris Lattner2785bdb2007-05-06 04:58:26 +0000559 // Reset errno to zero on entry to main.
560 errno = 0;
Eli Bendersky4c647582012-01-16 08:56:09 +0000561
Lang Hames3fde6522016-04-18 19:55:43 +0000562 int Result = -1;
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000563
Lang Hames9d7a2692016-01-11 16:35:55 +0000564 // Sanity check use of remote-jit: LLI currently only supports use of the
565 // remote JIT on Unix platforms.
Lang Hames9d7a2692016-01-11 16:35:55 +0000566 if (RemoteMCJIT) {
567#ifndef LLVM_ON_UNIX
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000568 WithColor::warning(errs(), argv[0])
Jonas Devlieghere7b5fa242018-04-22 08:35:00 +0000569 << "host does not support external remote targets.\n";
570 WithColor::note() << "defaulting to local execution\n";
Lang Hames4b6e0212016-01-11 21:41:34 +0000571 return -1;
Lang Hames9d7a2692016-01-11 16:35:55 +0000572#else
573 if (ChildExecPath.empty()) {
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000574 WithColor::error(errs(), argv[0])
575 << "-remote-mcjit requires -mcjit-remote-process.\n";
Lang Hames9d7a2692016-01-11 16:35:55 +0000576 exit(1);
577 } else if (!sys::fs::can_execute(ChildExecPath)) {
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000578 WithColor::error(errs(), argv[0])
579 << "unable to find usable child executable: '" << ChildExecPath
580 << "'\n";
Lang Hames9d7a2692016-01-11 16:35:55 +0000581 return -1;
582 }
583#endif
584 }
585
Andrew Kaylor58365b92012-11-27 19:49:00 +0000586 if (!RemoteMCJIT) {
Andrew Kaylor6587bcf2013-10-11 22:47:10 +0000587 // If the program doesn't explicitly call exit, we will need the Exit
588 // function later on to make an explicit call, so get the function now.
589 Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000590 Type::getInt32Ty(Context));
Andrew Kaylor6587bcf2013-10-11 22:47:10 +0000591
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000592 // Run static constructors.
Eric Christopher79cc1e32014-09-02 22:28:02 +0000593 if (!ForceInterpreter) {
Andrew Kaylorea395922013-10-01 01:47:35 +0000594 // Give MCJIT a chance to apply relocations and set page permissions.
595 EE->finalizeObject();
596 }
597 EE->runStaticConstructorsDestructors(false);
Evan Cheng0422bef2008-04-22 06:51:41 +0000598
NAKAMURA Takumi87e08802013-12-07 11:21:42 +0000599 // Trigger compilation separately so code regions that need to be
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000600 // invalidated will be known.
601 (void)EE->getPointerToFunction(EntryFn);
602 // Clear instruction cache before code will be executed.
603 if (RTDyldMM)
604 static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
605
606 // Run main.
607 Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
608
609 // Run static destructors.
610 EE->runStaticConstructorsDestructors(true);
611
612 // If the program didn't call exit explicitly, we should call it now.
613 // This ensures that any atexit handlers get called correctly.
614 if (Function *ExitF = dyn_cast<Function>(Exit)) {
615 std::vector<GenericValue> Args;
616 GenericValue ResultGV;
617 ResultGV.IntVal = APInt(32, Result);
618 Args.push_back(ResultGV);
619 EE->runFunction(ExitF, Args);
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000620 WithColor::error(errs(), argv[0]) << "exit(" << Result << ") returned!\n";
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000621 abort();
622 } else {
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000623 WithColor::error(errs(), argv[0])
624 << "exit defined with wrong prototype!\n";
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000625 abort();
626 }
627 } else {
628 // else == "if (RemoteMCJIT)"
629
630 // Remote target MCJIT doesn't (yet) support static constructors. No reason
Hiroshi Inoue0ca79dc2017-07-11 06:04:59 +0000631 // it couldn't. This is a limitation of the LLI implementation, not the
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000632 // MCJIT itself. FIXME.
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000633
Lang Hames9d7a2692016-01-11 16:35:55 +0000634 // Lanch the remote process and get a channel to it.
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000635 std::unique_ptr<FDRawChannel> C = launchRemote();
Lang Hames9d7a2692016-01-11 16:35:55 +0000636 if (!C) {
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000637 WithColor::error(errs(), argv[0]) << "failed to launch remote JIT.\n";
Lang Hames9d7a2692016-01-11 16:35:55 +0000638 exit(1);
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000639 }
640
Lang Hames9d7a2692016-01-11 16:35:55 +0000641 // Create a remote target client running over the channel.
Lang Hamesbd0cb782018-05-30 01:57:45 +0000642 llvm::orc::ExecutionSession ES;
643 ES.setErrorReporter([&](Error Err) { ExitOnErr(std::move(Err)); });
Lang Hames9e68b7342017-09-04 20:54:46 +0000644 typedef orc::remote::OrcRemoteTargetClient MyRemote;
Lang Hamesbd0cb782018-05-30 01:57:45 +0000645 auto R = ExitOnErr(MyRemote::Create(*C, ES));
Jim Grosbach748b9472012-08-28 23:22:30 +0000646
Lang Hames9d7a2692016-01-11 16:35:55 +0000647 // Create a remote memory manager.
Lang Hames9e68b7342017-09-04 20:54:46 +0000648 auto RemoteMM = ExitOnErr(R->createRemoteMemoryManager());
Lang Hames9d7a2692016-01-11 16:35:55 +0000649
650 // Forward MCJIT's memory manager calls to the remote memory manager.
651 static_cast<ForwardingMemoryManager*>(RTDyldMM)->setMemMgr(
652 std::move(RemoteMM));
653
654 // Forward MCJIT's symbol resolution calls to the remote.
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +0000655 static_cast<ForwardingMemoryManager *>(RTDyldMM)->setResolver(
656 orc::createLambdaResolver(
657 [](const std::string &Name) { return nullptr; },
658 [&](const std::string &Name) {
659 if (auto Addr = ExitOnErr(R->getSymbolAddress(Name)))
660 return JITSymbol(Addr, JITSymbolFlags::Exported);
661 return JITSymbol(nullptr);
662 }));
Lang Hames9d7a2692016-01-11 16:35:55 +0000663
664 // Grab the target address of the JIT'd main function on the remote and call
665 // it.
Jim Grosbach0f435d02012-09-05 16:50:34 +0000666 // FIXME: argv and envp handling.
Lang Hamesad4a9112016-08-01 20:49:11 +0000667 JITTargetAddress Entry = EE->getFunctionAddress(EntryFn->getName().str());
Lang Hames9d7a2692016-01-11 16:35:55 +0000668 EE->finalizeObject();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000669 LLVM_DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"
670 << format("%llx", Entry) << "\n");
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000671 Result = ExitOnErr(R->callIntVoid(Entry));
Jim Grosbach0f435d02012-09-05 16:50:34 +0000672
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000673 // Like static constructors, the remote target MCJIT support doesn't handle
674 // this yet. It could. FIXME.
675
Lang Hames9d7a2692016-01-11 16:35:55 +0000676 // Delete the EE - we need to tear it down *before* we terminate the session
677 // with the remote, otherwise it'll crash when it tries to release resources
678 // on a remote that has already been disconnected.
Mehdi Aminia7de8202016-04-18 18:52:39 +0000679 EE.reset();
Lang Hames9d7a2692016-01-11 16:35:55 +0000680
681 // Signal the remote target that we're done JITing.
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000682 ExitOnErr(R->terminateSession());
Chris Lattner2785bdb2007-05-06 04:58:26 +0000683 }
Jim Grosbach0f435d02012-09-05 16:50:34 +0000684
Jim Grosbach0f435d02012-09-05 16:50:34 +0000685 return Result;
Chris Lattnerd7ff5782001-08-23 17:05:04 +0000686}
Lang Hames9d7a2692016-01-11 16:35:55 +0000687
Lang Hames6a941342018-06-26 21:35:48 +0000688static orc::IRTransformLayer2::TransformFunction createDebugDumper() {
689 switch (OrcDumpKind) {
690 case DumpKind::NoDump:
691 return [](std::unique_ptr<Module> M) { return M; };
692
693 case DumpKind::DumpFuncsToStdOut:
694 return [](std::unique_ptr<Module> M) {
695 printf("[ ");
696
697 for (const auto &F : *M) {
698 if (F.isDeclaration())
699 continue;
700
701 if (F.hasName()) {
702 std::string Name(F.getName());
703 printf("%s ", Name.c_str());
704 } else
705 printf("<anon> ");
706 }
707
708 printf("]\n");
709 return M;
710 };
711
712 case DumpKind::DumpModsToStdOut:
713 return [](std::unique_ptr<Module> M) {
714 outs() << "----- Module Start -----\n"
715 << *M << "----- Module End -----\n";
716
717 return M;
718 };
719
720 case DumpKind::DumpModsToDisk:
721 return [](std::unique_ptr<Module> M) {
722 std::error_code EC;
723 raw_fd_ostream Out(M->getModuleIdentifier() + ".ll", EC, sys::fs::F_Text);
724 if (EC) {
725 errs() << "Couldn't open " << M->getModuleIdentifier()
726 << " for dumping.\nError:" << EC.message() << "\n";
727 exit(1);
728 }
729 Out << *M;
730 return M;
731 };
732 }
733 llvm_unreachable("Unknown DumpKind");
734}
735
736int runOrcLazyJIT(LLVMContext &Ctx, std::vector<std::unique_ptr<Module>> Ms,
737 const std::vector<std::string> &Args) {
738 // Bail out early if no modules loaded.
739 if (Ms.empty())
740 return 0;
741
742 // Add lli's symbols into the JIT's search space.
743 std::string ErrMsg;
744 sys::DynamicLibrary LibLLI =
745 sys::DynamicLibrary::getPermanentLibrary(nullptr, &ErrMsg);
746 if (!LibLLI.isValid()) {
747 errs() << "Error loading lli symbols: " << ErrMsg << ".\n";
748 return 1;
749 }
750
751 const auto &TT = Ms.front()->getTargetTriple();
752 orc::JITTargetMachineBuilder TMD =
753 TT.empty() ? ExitOnErr(orc::JITTargetMachineBuilder::detectHost())
754 : orc::JITTargetMachineBuilder(Triple(TT));
755
756 TMD.setArch(MArch)
757 .setCPU(getCPUStr())
758 .addFeatures(getFeatureList())
759 .setRelocationModel(RelocModel.getNumOccurrences()
760 ? Optional<Reloc::Model>(RelocModel)
761 : None)
762 .setCodeModel(CMModel.getNumOccurrences()
763 ? Optional<CodeModel::Model>(CMModel)
764 : None);
765 auto TM = ExitOnErr(TMD.createTargetMachine());
766 auto DL = TM->createDataLayout();
767 auto ES = llvm::make_unique<orc::ExecutionSession>();
768 auto J =
769 ExitOnErr(orc::LLLazyJIT::Create(std::move(ES), std::move(TM), DL, Ctx));
770
Lang Hamesadae9bf2018-07-02 22:30:18 +0000771 auto Dump = createDebugDumper();
772
773 J->setLazyCompileTransform(
774 [&](std::unique_ptr<Module> M) {
775 if (verifyModule(*M, &dbgs())) {
776 dbgs() << "Bad module: " << *M << "\n";
777 exit(1);
778 }
779 return Dump(std::move(M));
780 });
Lang Hames6a941342018-06-26 21:35:48 +0000781 J->getMainVSO().setFallbackDefinitionGenerator(
782 orc::DynamicLibraryFallbackGenerator(
783 std::move(LibLLI), DL, [](orc::SymbolStringPtr) { return true; }));
784
785 orc::MangleAndInterner Mangle(J->getExecutionSession(), DL);
786 orc::LocalCXXRuntimeOverrides2 CXXRuntimeOverrides;
787 ExitOnErr(CXXRuntimeOverrides.enable(J->getMainVSO(), Mangle));
788
Lang Hamesadae9bf2018-07-02 22:30:18 +0000789 for (auto &M : Ms) {
790 orc::makeAllSymbolsExternallyAccessible(*M);
Lang Hames6a941342018-06-26 21:35:48 +0000791 ExitOnErr(J->addLazyIRModule(std::move(M)));
Lang Hamesadae9bf2018-07-02 22:30:18 +0000792 }
Lang Hames6a941342018-06-26 21:35:48 +0000793
794 ExitOnErr(J->runConstructors());
795
796 auto MainSym = ExitOnErr(J->lookup("main"));
797 typedef int (*MainFnPtr)(int, const char *[]);
798 std::vector<const char *> ArgV;
799 for (auto &Arg : Args)
800 ArgV.push_back(Arg.c_str());
801 auto Main =
802 reinterpret_cast<MainFnPtr>(static_cast<uintptr_t>(MainSym.getAddress()));
803 auto Result = Main(ArgV.size(), (const char **)ArgV.data());
804
805 ExitOnErr(J->runDestructors());
806
807 CXXRuntimeOverrides.runDestructors();
808
809 return Result;
810}
811
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000812std::unique_ptr<FDRawChannel> launchRemote() {
Lang Hames9d7a2692016-01-11 16:35:55 +0000813#ifndef LLVM_ON_UNIX
814 llvm_unreachable("launchRemote not supported on non-Unix platforms");
815#else
816 int PipeFD[2][2];
817 pid_t ChildPID;
818
819 // Create two pipes.
820 if (pipe(PipeFD[0]) != 0 || pipe(PipeFD[1]) != 0)
821 perror("Error creating pipe: ");
822
823 ChildPID = fork();
824
825 if (ChildPID == 0) {
826 // In the child...
827
828 // Close the parent ends of the pipes
829 close(PipeFD[0][1]);
830 close(PipeFD[1][0]);
831
832
833 // Execute the child process.
834 std::unique_ptr<char[]> ChildPath, ChildIn, ChildOut;
835 {
836 ChildPath.reset(new char[ChildExecPath.size() + 1]);
837 std::copy(ChildExecPath.begin(), ChildExecPath.end(), &ChildPath[0]);
838 ChildPath[ChildExecPath.size()] = '\0';
NAKAMURA Takumicef0a8212016-01-15 02:14:46 +0000839 std::string ChildInStr = utostr(PipeFD[0][0]);
Lang Hames9d7a2692016-01-11 16:35:55 +0000840 ChildIn.reset(new char[ChildInStr.size() + 1]);
841 std::copy(ChildInStr.begin(), ChildInStr.end(), &ChildIn[0]);
842 ChildIn[ChildInStr.size()] = '\0';
NAKAMURA Takumicef0a8212016-01-15 02:14:46 +0000843 std::string ChildOutStr = utostr(PipeFD[1][1]);
Lang Hames9d7a2692016-01-11 16:35:55 +0000844 ChildOut.reset(new char[ChildOutStr.size() + 1]);
845 std::copy(ChildOutStr.begin(), ChildOutStr.end(), &ChildOut[0]);
846 ChildOut[ChildOutStr.size()] = '\0';
847 }
848
849 char * const args[] = { &ChildPath[0], &ChildIn[0], &ChildOut[0], nullptr };
850 int rc = execv(ChildExecPath.c_str(), args);
851 if (rc != 0)
852 perror("Error executing child process: ");
853 llvm_unreachable("Error executing child process");
854 }
855 // else we're the parent...
856
857 // Close the child ends of the pipes
858 close(PipeFD[0][0]);
859 close(PipeFD[1][1]);
860
861 // Return an RPC channel connected to our end of the pipes.
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000862 return llvm::make_unique<FDRawChannel>(PipeFD[1][0], PipeFD[0][1]);
Lang Hames9d7a2692016-01-11 16:35:55 +0000863#endif
864}