blob: e4a7462a6352ad488a7717fd0167d52550307238 [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"
Lang Hamesd435ce42018-09-30 19:12:23 +000029#include "llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h"
Lang Hames6a941342018-06-26 21:35:48 +000030#include "llvm/ExecutionEngine/Orc/LLJIT.h"
Rafael Espindola79e238a2017-08-03 02:16:21 +000031#include "llvm/ExecutionEngine/Orc/OrcRemoteTargetClient.h"
Lang Hames93de2a12015-01-23 21:25:00 +000032#include "llvm/ExecutionEngine/OrcMCJITReplacement.h"
Andrew Kaylor58365b92012-11-27 19:49:00 +000033#include "llvm/ExecutionEngine/SectionMemoryManager.h"
Andrew Kaylor1ca510e2013-10-29 01:29:56 +000034#include "llvm/IR/IRBuilder.h"
Rafael Espindola79e238a2017-08-03 02:16:21 +000035#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000036#include "llvm/IR/Module.h"
37#include "llvm/IR/Type.h"
Andrew Kaylor1ca510e2013-10-29 01:29:56 +000038#include "llvm/IR/TypeBuilder.h"
Lang Hamesadae9bf2018-07-02 22:30:18 +000039#include "llvm/IR/Verifier.h"
Chandler Carruthe60e57b2013-03-26 02:25:37 +000040#include "llvm/IRReader/IRReader.h"
Lang Hames173c69f2014-01-08 04:09:09 +000041#include "llvm/Object/Archive.h"
42#include "llvm/Object/ObjectFile.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000043#include "llvm/Support/CommandLine.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000044#include "llvm/Support/Debug.h"
45#include "llvm/Support/DynamicLibrary.h"
46#include "llvm/Support/Format.h"
Rui Ueyama197194b2018-04-13 18:26:06 +000047#include "llvm/Support/InitLLVM.h"
Chris Lattner76d46322006-12-06 01:18:01 +000048#include "llvm/Support/ManagedStatic.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000049#include "llvm/Support/MathExtras.h"
50#include "llvm/Support/Memory.h"
Chris Lattner2785bdb2007-05-06 04:58:26 +000051#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer16132e62015-03-23 18:07:13 +000052#include "llvm/Support/Path.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000053#include "llvm/Support/PluginLoader.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000054#include "llvm/Support/Process.h"
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +000055#include "llvm/Support/Program.h"
Chandler Carruthe60e57b2013-03-26 02:25:37 +000056#include "llvm/Support/SourceMgr.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000057#include "llvm/Support/TargetSelect.h"
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +000058#include "llvm/Support/WithColor.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000059#include "llvm/Support/raw_ostream.h"
Daniel Maleaa960c542013-06-28 19:11:40 +000060#include "llvm/Transforms/Instrumentation.h"
Chris Lattner4c522b92007-04-27 17:02:33 +000061#include <cerrno>
NAKAMURA Takumi15304872010-10-22 14:53:59 +000062
63#ifdef __CYGWIN__
64#include <cygwin/version.h>
65#if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
66#define DO_NOTHING_ATEXIT 1
67#endif
68#endif
69
Brian Gaeke960707c2003-11-11 22:41:34 +000070using namespace llvm;
71
Chandler Carruthf98597a2014-04-22 03:10:36 +000072#define DEBUG_TYPE "lli"
73
Chris Lattnera0d7b082002-12-23 23:59:41 +000074namespace {
Lang Hames9528bba2015-03-25 12:11:48 +000075
76 enum class JITKind { MCJIT, OrcMCJITReplacement, OrcLazy };
77
Chris Lattnera0d7b082002-12-23 23:59:41 +000078 cl::opt<std::string>
Gabor Greife16561c2007-07-05 17:07:56 +000079 InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
Chris Lattnerf5cad152002-07-22 02:10:13 +000080
Chris Lattnera0d7b082002-12-23 23:59:41 +000081 cl::list<std::string>
82 InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
Chris Lattnerf5cad152002-07-22 02:10:13 +000083
Chris Lattnera0d7b082002-12-23 23:59:41 +000084 cl::opt<bool> ForceInterpreter("force-interpreter",
Misha Brukmanc2186e32003-09-25 18:10:34 +000085 cl::desc("Force interpretation: disable JIT"),
86 cl::init(false));
Evan Cheng06d988e2008-08-08 08:12:06 +000087
Lang Hames9528bba2015-03-25 12:11:48 +000088 cl::opt<JITKind> UseJITKind("jit-kind",
89 cl::desc("Choose underlying JIT kind."),
90 cl::init(JITKind::MCJIT),
91 cl::values(
92 clEnumValN(JITKind::MCJIT, "mcjit",
93 "MCJIT"),
94 clEnumValN(JITKind::OrcMCJITReplacement,
95 "orc-mcjit",
96 "Orc-based MCJIT replacement"),
97 clEnumValN(JITKind::OrcLazy,
98 "orc-lazy",
Mehdi Amini732afdd2016-10-08 19:41:06 +000099 "Orc-based lazy JIT.")));
Lang Hames93de2a12015-01-23 21:25:00 +0000100
Lang Hamesf0a3fd882018-09-26 16:26:59 +0000101 cl::opt<unsigned>
102 LazyJITCompileThreads("compile-threads",
103 cl::desc("Choose the number of compile threads "
104 "(jit-kind=orc-lazy only)"),
105 cl::init(0));
106
107 cl::list<std::string>
108 ThreadEntryPoints("thread-entry",
109 cl::desc("calls the given entry-point on a new thread "
110 "(jit-kind=orc-lazy only)"));
111
Lang Hames98440292018-09-29 23:49:57 +0000112 cl::opt<bool> PerModuleLazy(
113 "per-module-lazy",
114 cl::desc("Performs lazy compilation on whole module boundaries "
115 "rather than individual functions"),
116 cl::init(false));
117
Lang Hames23cb2e72018-10-23 23:01:39 +0000118 cl::list<std::string>
119 JITDylibs("jd",
120 cl::desc("Specifies the JITDylib to be used for any subsequent "
121 "-extra-module arguments."));
122
Jim Grosbach0f435d02012-09-05 16:50:34 +0000123 // The MCJIT supports building for a target address space separate from
124 // the JIT compilation process. Use a forked process and a copying
125 // memory manager with IPC to execute using this functionality.
126 cl::opt<bool> RemoteMCJIT("remote-mcjit",
127 cl::desc("Execute MCJIT'ed code in a separate process."),
128 cl::init(false));
129
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000130 // Manually specify the child process for remote execution. This overrides
131 // the simulated remote execution that allocates address space for child
Andrew Kaylor89352582013-10-29 01:33:14 +0000132 // execution. The child process will be executed and will communicate with
133 // lli via stdin/stdout pipes.
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000134 cl::opt<std::string>
Alp Tokera1186382014-01-22 21:52:35 +0000135 ChildExecPath("mcjit-remote-process",
136 cl::desc("Specify the filename of the process to launch "
137 "for remote MCJIT execution. If none is specified,"
138 "\n\tremote execution will be simulated in-process."),
139 cl::value_desc("filename"), cl::init(""));
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000140
Evan Cheng09bd0b12009-05-04 23:05:19 +0000141 // Determine optimization level.
142 cl::opt<char>
143 OptLevel("O",
144 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
145 "(default = '-O2')"),
146 cl::Prefix,
147 cl::ZeroOrMore,
148 cl::init(' '));
Evan Cheng06d988e2008-08-08 08:12:06 +0000149
Chris Lattner76766cb2005-12-16 05:00:21 +0000150 cl::opt<std::string>
Chris Lattner78e9e102005-12-16 05:19:18 +0000151 TargetTriple("mtriple", cl::desc("Override target triple for module"));
Evan Cheng61582542008-11-05 23:21:52 +0000152
153 cl::opt<std::string>
154 EntryFunc("entry-function",
155 cl::desc("Specify the entry function (default = 'main') "
156 "of the executable"),
157 cl::value_desc("function"),
158 cl::init("main"));
Eli Bendersky4c647582012-01-16 08:56:09 +0000159
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000160 cl::list<std::string>
Andrew Kaylor4404eb42013-10-28 21:58:15 +0000161 ExtraModules("extra-module",
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000162 cl::desc("Extra modules to be loaded"),
Alp Toker0a09ebf2013-10-28 22:51:25 +0000163 cl::value_desc("input bitcode"));
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000164
Lang Hames173c69f2014-01-08 04:09:09 +0000165 cl::list<std::string>
166 ExtraObjects("extra-object",
167 cl::desc("Extra object files to be loaded"),
168 cl::value_desc("input object"));
169
170 cl::list<std::string>
171 ExtraArchives("extra-archive",
172 cl::desc("Extra archive files to be loaded"),
173 cl::value_desc("input archive"));
174
175 cl::opt<bool>
176 EnableCacheManager("enable-cache-manager",
Lang Hames1ddecc02014-01-09 05:24:05 +0000177 cl::desc("Use cache manager to save/load mdoules"),
Lang Hames173c69f2014-01-08 04:09:09 +0000178 cl::init(false));
179
Chris Lattner55644062003-10-28 22:51:44 +0000180 cl::opt<std::string>
Lang Hames1ddecc02014-01-09 05:24:05 +0000181 ObjectCacheDir("object-cache-dir",
182 cl::desc("Directory to store cached object files "
183 "(must be user writable)"),
184 cl::init(""));
185
186 cl::opt<std::string>
Chris Lattner55644062003-10-28 22:51:44 +0000187 FakeArgv0("fake-argv0",
188 cl::desc("Override the 'argv[0]' value passed into the executing"
189 " program"), cl::value_desc("executable"));
Eli Bendersky4c647582012-01-16 08:56:09 +0000190
Chris Lattner3f0ffd32006-09-14 06:17:09 +0000191 cl::opt<bool>
192 DisableCoreFiles("disable-core-files", cl::Hidden,
193 cl::desc("Disable emission of core files if possible"));
Evan Cheng0422bef2008-04-22 06:51:41 +0000194
195 cl::opt<bool>
Evan Cheng16f036c2008-05-21 18:20:21 +0000196 NoLazyCompilation("disable-lazy-compilation",
Evan Cheng0422bef2008-04-22 06:51:41 +0000197 cl::desc("Disable JIT lazy compilation"),
198 cl::init(false));
Evan Cheng2129f592011-07-19 06:37:02 +0000199
Nick Lewyckyb0e97892012-04-18 08:34:12 +0000200 cl::opt<bool>
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000201 GenerateSoftFloatCalls("soft-float",
202 cl::desc("Generate software floating point library calls"),
203 cl::init(false));
204
Lang Hames6a941342018-06-26 21:35:48 +0000205 enum class DumpKind {
206 NoDump,
207 DumpFuncsToStdOut,
208 DumpModsToStdOut,
209 DumpModsToDisk
210 };
211
212 cl::opt<DumpKind> OrcDumpKind(
213 "orc-lazy-debug", cl::desc("Debug dumping for the orc-lazy JIT."),
214 cl::init(DumpKind::NoDump),
215 cl::values(clEnumValN(DumpKind::NoDump, "no-dump",
216 "Don't dump anything."),
217 clEnumValN(DumpKind::DumpFuncsToStdOut, "funcs-to-stdout",
218 "Dump function names to stdout."),
219 clEnumValN(DumpKind::DumpModsToStdOut, "mods-to-stdout",
220 "Dump modules to stdout."),
221 clEnumValN(DumpKind::DumpModsToDisk, "mods-to-disk",
222 "Dump modules to the current "
223 "working directory. (WARNING: "
224 "will overwrite existing files).")),
225 cl::Hidden);
226
Lang Hamesef5a0ee2016-04-25 19:56:45 +0000227 ExitOnError ExitOnErr;
Chris Lattnera0d7b082002-12-23 23:59:41 +0000228}
Chris Lattner009f8102001-10-27 08:43:52 +0000229
Lang Hames173c69f2014-01-08 04:09:09 +0000230//===----------------------------------------------------------------------===//
231// Object cache
232//
Lang Hames1ddecc02014-01-09 05:24:05 +0000233// This object cache implementation writes cached objects to disk to the
234// directory specified by CacheDir, using a filename provided in the module
235// descriptor. The cache tries to load a saved object using that path if the
236// file exists. CacheDir defaults to "", in which case objects are cached
NAKAMURA Takumif462f9c2014-01-10 10:38:28 +0000237// alongside their originating bitcodes.
Lang Hames173c69f2014-01-08 04:09:09 +0000238//
239class LLIObjectCache : public ObjectCache {
240public:
Lang Hames1ddecc02014-01-09 05:24:05 +0000241 LLIObjectCache(const std::string& CacheDir) : CacheDir(CacheDir) {
242 // Add trailing '/' to cache dir if necessary.
Lang Hamesf9dd8fd2014-01-09 05:29:59 +0000243 if (!this->CacheDir.empty() &&
244 this->CacheDir[this->CacheDir.size() - 1] != '/')
NAKAMURA Takumif462f9c2014-01-10 10:38:28 +0000245 this->CacheDir += '/';
Lang Hames1ddecc02014-01-09 05:24:05 +0000246 }
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000247 ~LLIObjectCache() override {}
Lang Hames173c69f2014-01-08 04:09:09 +0000248
Rafael Espindola48af1c22014-08-19 18:44:46 +0000249 void notifyObjectCompiled(const Module *M, MemoryBufferRef Obj) override {
Benjamin Kramer46e38f32016-06-08 10:01:20 +0000250 const std::string &ModuleID = M->getModuleIdentifier();
Lang Hames173c69f2014-01-08 04:09:09 +0000251 std::string CacheName;
252 if (!getCacheFilename(ModuleID, CacheName))
253 return;
NAKAMURA Takumi390e0602014-01-10 10:38:34 +0000254 if (!CacheDir.empty()) { // Create user-defined cache dir.
Rafael Espindolaf662e002015-07-15 21:24:07 +0000255 SmallString<128> dir(sys::path::parent_path(CacheName));
NAKAMURA Takumi390e0602014-01-10 10:38:34 +0000256 sys::fs::create_directories(Twine(dir));
257 }
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000258 std::error_code EC;
259 raw_fd_ostream outfile(CacheName, EC, sys::fs::F_None);
Rafael Espindola48af1c22014-08-19 18:44:46 +0000260 outfile.write(Obj.getBufferStart(), Obj.getBufferSize());
Lang Hames173c69f2014-01-08 04:09:09 +0000261 outfile.close();
262 }
263
Rafael Espindola5f2bb7d2014-08-13 18:49:01 +0000264 std::unique_ptr<MemoryBuffer> getObject(const Module* M) override {
Benjamin Kramer46e38f32016-06-08 10:01:20 +0000265 const std::string &ModuleID = M->getModuleIdentifier();
Lang Hames173c69f2014-01-08 04:09:09 +0000266 std::string CacheName;
267 if (!getCacheFilename(ModuleID, CacheName))
Craig Toppere6cb63e2014-04-25 04:24:47 +0000268 return nullptr;
Lang Hames173c69f2014-01-08 04:09:09 +0000269 // Load the object from the cache filename
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000270 ErrorOr<std::unique_ptr<MemoryBuffer>> IRObjectBuffer =
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000271 MemoryBuffer::getFile(CacheName, -1, false);
Lang Hames173c69f2014-01-08 04:09:09 +0000272 // If the file isn't there, that's OK.
273 if (!IRObjectBuffer)
Craig Toppere6cb63e2014-04-25 04:24:47 +0000274 return nullptr;
Lang Hames173c69f2014-01-08 04:09:09 +0000275 // MCJIT will want to write into this buffer, and we don't want that
276 // because the file has probably just been mmapped. Instead we make
277 // a copy. The filed-based buffer will be released when it goes
278 // out of scope.
Rafael Espindola3560ff22014-08-27 20:03:13 +0000279 return MemoryBuffer::getMemBufferCopy(IRObjectBuffer.get()->getBuffer());
Lang Hames173c69f2014-01-08 04:09:09 +0000280 }
281
282private:
Lang Hames1ddecc02014-01-09 05:24:05 +0000283 std::string CacheDir;
284
Lang Hames173c69f2014-01-08 04:09:09 +0000285 bool getCacheFilename(const std::string &ModID, std::string &CacheName) {
286 std::string Prefix("file:");
287 size_t PrefixLength = Prefix.length();
288 if (ModID.substr(0, PrefixLength) != Prefix)
289 return false;
NAKAMURA Takumid7fd6d92014-01-10 10:38:40 +0000290 std::string CacheSubdir = ModID.substr(PrefixLength);
291#if defined(_WIN32)
292 // Transform "X:\foo" => "/X\foo" for convenience.
293 if (isalpha(CacheSubdir[0]) && CacheSubdir[1] == ':') {
294 CacheSubdir[1] = CacheSubdir[0];
295 CacheSubdir[0] = '/';
296 }
297#endif
298 CacheName = CacheDir + CacheSubdir;
Lang Hames173c69f2014-01-08 04:09:09 +0000299 size_t pos = CacheName.rfind('.');
300 CacheName.replace(pos, CacheName.length() - pos, ".o");
301 return true;
302 }
303};
304
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000305// On Mingw and Cygwin, an external symbol named '__main' is called from the
Simon Pilgrimdae11f72016-11-20 13:31:13 +0000306// generated 'main' function to allow static initialization. To avoid linking
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000307// problems with remote targets (because lli's remote target support does not
308// currently handle external linking) we add a secondary module which defines
309// an empty '__main' function.
Mehdi Aminia7de8202016-04-18 18:52:39 +0000310static void addCygMingExtraModule(ExecutionEngine &EE, LLVMContext &Context,
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000311 StringRef TargetTripleStr) {
312 IRBuilder<> Builder(Context);
313 Triple TargetTriple(TargetTripleStr);
314
315 // Create a new module.
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000316 std::unique_ptr<Module> M = make_unique<Module>("CygMingHelper", Context);
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000317 M->setTargetTriple(TargetTripleStr);
318
319 // Create an empty function named "__main".
320 Function *Result;
321 if (TargetTriple.isArch64Bit()) {
322 Result = Function::Create(
323 TypeBuilder<int64_t(void), false>::get(Context),
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000324 GlobalValue::ExternalLinkage, "__main", M.get());
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000325 } else {
326 Result = Function::Create(
327 TypeBuilder<int32_t(void), false>::get(Context),
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000328 GlobalValue::ExternalLinkage, "__main", M.get());
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000329 }
330 BasicBlock *BB = BasicBlock::Create(Context, "__main", Result);
331 Builder.SetInsertPoint(BB);
332 Value *ReturnVal;
333 if (TargetTriple.isArch64Bit())
334 ReturnVal = ConstantInt::get(Context, APInt(64, 0));
335 else
336 ReturnVal = ConstantInt::get(Context, APInt(32, 0));
337 Builder.CreateRet(ReturnVal);
338
339 // Add this new module to the ExecutionEngine.
Mehdi Aminia7de8202016-04-18 18:52:39 +0000340 EE.addModule(std::move(M));
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000341}
342
Lang Hames1899d0c2015-06-09 02:43:27 +0000343CodeGenOpt::Level getOptLevel() {
344 switch (OptLevel) {
345 default:
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000346 WithColor::error(errs(), "lli") << "invalid optimization level.\n";
Lang Hames1899d0c2015-06-09 02:43:27 +0000347 exit(1);
348 case '0': return CodeGenOpt::None;
349 case '1': return CodeGenOpt::Less;
350 case ' ':
351 case '2': return CodeGenOpt::Default;
352 case '3': return CodeGenOpt::Aggressive;
353 }
354 llvm_unreachable("Unrecognized opt level.");
355}
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000356
Davide Italianoda8e6b22016-11-17 22:58:13 +0000357LLVM_ATTRIBUTE_NORETURN
358static void reportError(SMDiagnostic Err, const char *ProgName) {
359 Err.print(ProgName, errs());
360 exit(1);
361}
362
Lang Hames37a66412018-08-28 20:20:31 +0000363int runOrcLazyJIT(const char *ProgName);
Lang Hames98440292018-09-29 23:49:57 +0000364void disallowOrcOptions();
Lang Hames6a941342018-06-26 21:35:48 +0000365
Chris Lattnerd7ff5782001-08-23 17:05:04 +0000366//===----------------------------------------------------------------------===//
Chris Lattnerd7ff5782001-08-23 17:05:04 +0000367// main Driver function
368//
Misha Brukman5b255e52003-10-14 21:39:53 +0000369int main(int argc, char **argv, char * const *envp) {
Rui Ueyama197194b2018-04-13 18:26:06 +0000370 InitLLVM X(argc, argv);
Daniel Dunbar3d92d932009-07-16 02:04:54 +0000371
Lang Hamesef5a0ee2016-04-25 19:56:45 +0000372 if (argc > 1)
373 ExitOnErr.setBanner(std::string(argv[0]) + ": ");
374
Daniel Dunbar3d92d932009-07-16 02:04:54 +0000375 // If we have a native target, initialize it to ensure it is linked in and
376 // usable by the JIT.
377 InitializeNativeTarget();
Jim Grosbach7b162492011-03-18 22:48:41 +0000378 InitializeNativeTargetAsmPrinter();
Jim Grosbach2cce3f92012-11-05 19:06:05 +0000379 InitializeNativeTargetAsmParser();
Daniel Dunbar3d92d932009-07-16 02:04:54 +0000380
Chris Lattner2785bdb2007-05-06 04:58:26 +0000381 cl::ParseCommandLineOptions(argc, argv,
Dan Gohman2c6a8212007-10-08 15:45:12 +0000382 "llvm interpreter & dynamic compiler\n");
Reid Spencer996ec722004-12-30 05:36:08 +0000383
Chris Lattner2785bdb2007-05-06 04:58:26 +0000384 // If the user doesn't want core files, disable them.
385 if (DisableCoreFiles)
386 sys::Process::PreventCoreFiles();
Eli Bendersky4c647582012-01-16 08:56:09 +0000387
Lang Hames37a66412018-08-28 20:20:31 +0000388 if (UseJITKind == JITKind::OrcLazy)
389 return runOrcLazyJIT(argv[0]);
Lang Hames98440292018-09-29 23:49:57 +0000390 else
391 disallowOrcOptions();
Lang Hames37a66412018-08-28 20:20:31 +0000392
Mehdi Aminia7de8202016-04-18 18:52:39 +0000393 LLVMContext Context;
394
Gabor Greife16561c2007-07-05 17:07:56 +0000395 // Load the bitcode...
Daniel Dunbar9589bf82010-11-13 00:28:01 +0000396 SMDiagnostic Err;
Rafael Espindolad233b062014-08-26 17:29:46 +0000397 std::unique_ptr<Module> Owner = parseIRFile(InputFile, Err, Context);
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000398 Module *Mod = Owner.get();
Davide Italianoda8e6b22016-11-17 22:58:13 +0000399 if (!Mod)
400 reportError(Err, argv[0]);
Chris Lattner2785bdb2007-05-06 04:58:26 +0000401
Lang Hames173c69f2014-01-08 04:09:09 +0000402 if (EnableCacheManager) {
Eric Christopher79cc1e32014-09-02 22:28:02 +0000403 std::string CacheName("file:");
404 CacheName.append(InputFile);
405 Mod->setModuleIdentifier(CacheName);
Lang Hames173c69f2014-01-08 04:09:09 +0000406 }
407
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000408 // If not jitting lazily, load the whole bitcode file eagerly too.
409 if (NoLazyCompilation) {
Davide Italianob0e067b2016-11-09 21:30:33 +0000410 // Use *argv instead of argv[0] to work around a wrong GCC warning.
411 ExitOnError ExitOnErr(std::string(*argv) +
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000412 ": bitcode didn't read correctly: ");
413 ExitOnErr(Mod->materializeAll());
Evan Cheng0422bef2008-04-22 06:51:41 +0000414 }
Chris Lattner2785bdb2007-05-06 04:58:26 +0000415
Rafael Espindolae9fab9b2014-01-14 23:51:27 +0000416 std::string ErrorMsg;
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000417 EngineBuilder builder(std::move(Owner));
Jeffrey Yasskin31faeff2010-02-05 16:19:36 +0000418 builder.setMArch(MArch);
Craig Topper243f20f2018-01-09 18:14:18 +0000419 builder.setMCPU(getCPUStr());
420 builder.setMAttrs(getFeatureList());
Rafael Espindola8c34dd82016-05-18 22:04:49 +0000421 if (RelocModel.getNumOccurrences())
422 builder.setRelocationModel(RelocModel);
Rafael Espindola79e238a2017-08-03 02:16:21 +0000423 if (CMModel.getNumOccurrences())
424 builder.setCodeModel(CMModel);
Daniel Dunbara78d8092009-07-18 08:07:13 +0000425 builder.setErrorStr(&ErrorMsg);
426 builder.setEngineKind(ForceInterpreter
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000427 ? EngineKind::Interpreter
428 : EngineKind::JIT);
Lang Hames9528bba2015-03-25 12:11:48 +0000429 builder.setUseOrcMCJITReplacement(UseJITKind == JITKind::OrcMCJITReplacement);
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000430
Chris Lattner2785bdb2007-05-06 04:58:26 +0000431 // If we are supposed to override the target triple, do so now.
432 if (!TargetTriple.empty())
Duncan Sands3bd97fe2010-08-28 01:30:02 +0000433 Mod->setTargetTriple(Triple::normalize(TargetTriple));
Evan Cheng0422bef2008-04-22 06:51:41 +0000434
Eli Bendersky4c647582012-01-16 08:56:09 +0000435 // Enable MCJIT if desired.
Craig Toppere6cb63e2014-04-25 04:24:47 +0000436 RTDyldMemoryManager *RTDyldMM = nullptr;
Eric Christopher79cc1e32014-09-02 22:28:02 +0000437 if (!ForceInterpreter) {
Jim Grosbach0f435d02012-09-05 16:50:34 +0000438 if (RemoteMCJIT)
Lang Hames9d7a2692016-01-11 16:35:55 +0000439 RTDyldMM = new ForwardingMemoryManager();
Jim Grosbach0f435d02012-09-05 16:50:34 +0000440 else
Filip Pizlo9bc53e82013-05-14 19:29:00 +0000441 RTDyldMM = new SectionMemoryManager();
Lang Hames4a5697e2014-12-03 00:51:19 +0000442
443 // Deliberately construct a temp std::unique_ptr to pass in. Do not null out
444 // RTDyldMM: We still use it below, even though we don't own it.
445 builder.setMCJITMemoryManager(
446 std::unique_ptr<RTDyldMemoryManager>(RTDyldMM));
Lang Hames0f154902014-09-23 16:56:02 +0000447 } else if (RemoteMCJIT) {
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000448 WithColor::error(errs(), argv[0])
449 << "remote process execution does not work with the interpreter.\n";
Lang Hames0f154902014-09-23 16:56:02 +0000450 exit(1);
Eli Bendersky4c647582012-01-16 08:56:09 +0000451 }
Daniel Dunbar70ff8b02010-11-17 16:06:37 +0000452
Lang Hames1899d0c2015-06-09 02:43:27 +0000453 builder.setOptLevel(getOptLevel());
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000454
David Blaikiec14bfec2017-11-27 19:43:58 +0000455 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000456 if (FloatABIForCalls != FloatABI::Default)
457 Options.FloatABIType = FloatABIForCalls;
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000458
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000459 builder.setTargetOptions(Options);
460
Mehdi Aminia7de8202016-04-18 18:52:39 +0000461 std::unique_ptr<ExecutionEngine> EE(builder.create());
Chris Lattnerf840ed72009-07-07 18:31:09 +0000462 if (!EE) {
463 if (!ErrorMsg.empty())
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000464 WithColor::error(errs(), argv[0])
465 << "error creating EE: " << ErrorMsg << "\n";
Chris Lattnerf840ed72009-07-07 18:31:09 +0000466 else
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000467 WithColor::error(errs(), argv[0]) << "unknown error creating EE!\n";
Chris Lattner2785bdb2007-05-06 04:58:26 +0000468 exit(1);
469 }
470
Mehdi Aminia7de8202016-04-18 18:52:39 +0000471 std::unique_ptr<LLIObjectCache> CacheManager;
Lang Hames173c69f2014-01-08 04:09:09 +0000472 if (EnableCacheManager) {
Mehdi Aminia7de8202016-04-18 18:52:39 +0000473 CacheManager.reset(new LLIObjectCache(ObjectCacheDir));
474 EE->setObjectCache(CacheManager.get());
Lang Hames173c69f2014-01-08 04:09:09 +0000475 }
476
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000477 // Load any additional modules specified on the command line.
478 for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) {
Rafael Espindolad233b062014-08-26 17:29:46 +0000479 std::unique_ptr<Module> XMod = parseIRFile(ExtraModules[i], Err, Context);
Davide Italianoda8e6b22016-11-17 22:58:13 +0000480 if (!XMod)
481 reportError(Err, argv[0]);
Lang Hames173c69f2014-01-08 04:09:09 +0000482 if (EnableCacheManager) {
Eric Christopher79cc1e32014-09-02 22:28:02 +0000483 std::string CacheName("file:");
484 CacheName.append(ExtraModules[i]);
485 XMod->setModuleIdentifier(CacheName);
Lang Hames173c69f2014-01-08 04:09:09 +0000486 }
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000487 EE->addModule(std::move(XMod));
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000488 }
489
Lang Hames173c69f2014-01-08 04:09:09 +0000490 for (unsigned i = 0, e = ExtraObjects.size(); i != e; ++i) {
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000491 Expected<object::OwningBinary<object::ObjectFile>> Obj =
Rafael Espindola51cc3602014-01-22 00:14:49 +0000492 object::ObjectFile::createObjectFile(ExtraObjects[i]);
Lang Hames173c69f2014-01-08 04:09:09 +0000493 if (!Obj) {
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000494 // TODO: Actually report errors helpfully.
495 consumeError(Obj.takeError());
Davide Italianoda8e6b22016-11-17 22:58:13 +0000496 reportError(Err, argv[0]);
Lang Hames173c69f2014-01-08 04:09:09 +0000497 }
Rafael Espindola061beab2014-08-20 15:19:37 +0000498 object::OwningBinary<object::ObjectFile> &O = Obj.get();
Rafael Espindola7271c192014-08-26 21:04:04 +0000499 EE->addObjectFile(std::move(O));
Lang Hames173c69f2014-01-08 04:09:09 +0000500 }
501
502 for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) {
Rafael Espindola48af1c22014-08-19 18:44:46 +0000503 ErrorOr<std::unique_ptr<MemoryBuffer>> ArBufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000504 MemoryBuffer::getFileOrSTDIN(ExtraArchives[i]);
Davide Italianoda8e6b22016-11-17 22:58:13 +0000505 if (!ArBufOrErr)
506 reportError(Err, argv[0]);
Rafael Espindola48af1c22014-08-19 18:44:46 +0000507 std::unique_ptr<MemoryBuffer> &ArBuf = ArBufOrErr.get();
Rafael Espindolae1923412014-08-01 18:31:17 +0000508
Kevin Enderbyc60a3212016-06-29 20:35:44 +0000509 Expected<std::unique_ptr<object::Archive>> ArOrErr =
Rafael Espindola48af1c22014-08-19 18:44:46 +0000510 object::Archive::create(ArBuf->getMemBufferRef());
Kevin Enderbyc60a3212016-06-29 20:35:44 +0000511 if (!ArOrErr) {
512 std::string Buf;
513 raw_string_ostream OS(Buf);
Jonas Devlieghere45eb84f2018-11-11 01:46:03 +0000514 logAllUnhandledErrors(ArOrErr.takeError(), OS);
Kevin Enderbyc60a3212016-06-29 20:35:44 +0000515 OS.flush();
516 errs() << Buf;
Davide Italiano86511442016-11-17 22:59:13 +0000517 exit(1);
Lang Hames173c69f2014-01-08 04:09:09 +0000518 }
Rafael Espindola48af1c22014-08-19 18:44:46 +0000519 std::unique_ptr<object::Archive> &Ar = ArOrErr.get();
520
521 object::OwningBinary<object::Archive> OB(std::move(Ar), std::move(ArBuf));
522
523 EE->addArchive(std::move(OB));
Lang Hames173c69f2014-01-08 04:09:09 +0000524 }
525
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000526 // If the target is Cygwin/MingW and we are generating remote code, we
527 // need an extra module to help out with linking.
528 if (RemoteMCJIT && Triple(Mod->getTargetTriple()).isOSCygMing()) {
Mehdi Aminia7de8202016-04-18 18:52:39 +0000529 addCygMingExtraModule(*EE, Context, Mod->getTargetTriple());
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000530 }
531
Eli Bendersky5262ad22012-03-13 08:33:15 +0000532 // The following functions have no effect if their respective profiling
533 // support wasn't enabled in the build configuration.
534 EE->RegisterJITEventListener(
535 JITEventListener::createOProfileJITEventListener());
536 EE->RegisterJITEventListener(
537 JITEventListener::createIntelJITEventListener());
Andres Freund376a3d32018-07-24 00:54:06 +0000538 if (!RemoteMCJIT)
539 EE->RegisterJITEventListener(
540 JITEventListener::createPerfJITEventListener());
Jeffrey Yasskin0b08f3d2009-06-25 02:04:04 +0000541
Jim Grosbach0f435d02012-09-05 16:50:34 +0000542 if (!NoLazyCompilation && RemoteMCJIT) {
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000543 WithColor::warning(errs(), argv[0])
544 << "remote mcjit does not support lazy compilation\n";
Jim Grosbach0f435d02012-09-05 16:50:34 +0000545 NoLazyCompilation = true;
546 }
Jeffrey Yasskinaa8814a2009-10-27 22:39:42 +0000547 EE->DisableLazyCompilation(NoLazyCompilation);
Evan Cheng0422bef2008-04-22 06:51:41 +0000548
Chris Lattner2785bdb2007-05-06 04:58:26 +0000549 // If the user specifically requested an argv[0] to pass into the program,
550 // do it now.
551 if (!FakeArgv0.empty()) {
Chris Bienemane71fb5c2015-01-22 01:49:59 +0000552 InputFile = static_cast<std::string>(FakeArgv0);
Chris Lattner2785bdb2007-05-06 04:58:26 +0000553 } else {
554 // Otherwise, if there is a .bc suffix on the executable strip it off, it
555 // might confuse the program.
Benjamin Kramera944a9a2010-04-15 11:33:14 +0000556 if (StringRef(InputFile).endswith(".bc"))
Chris Lattner2785bdb2007-05-06 04:58:26 +0000557 InputFile.erase(InputFile.length() - 3);
558 }
559
560 // Add the module's name to the start of the vector of arguments to main().
561 InputArgv.insert(InputArgv.begin(), InputFile);
562
563 // Call the main function from M as if its signature were:
564 // int main (int argc, char **argv, const char **envp)
565 // using the contents of Args to determine argc & argv, and the contents of
566 // EnvVars to determine envp.
567 //
Evan Cheng61582542008-11-05 23:21:52 +0000568 Function *EntryFn = Mod->getFunction(EntryFunc);
569 if (!EntryFn) {
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000570 WithColor::error(errs(), argv[0])
571 << '\'' << EntryFunc << "\' function not found in module.\n";
Chris Lattner2785bdb2007-05-06 04:58:26 +0000572 return -1;
573 }
574
Chris Lattner2785bdb2007-05-06 04:58:26 +0000575 // Reset errno to zero on entry to main.
576 errno = 0;
Eli Bendersky4c647582012-01-16 08:56:09 +0000577
Lang Hames3fde6522016-04-18 19:55:43 +0000578 int Result = -1;
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000579
Lang Hames9d7a2692016-01-11 16:35:55 +0000580 // Sanity check use of remote-jit: LLI currently only supports use of the
581 // remote JIT on Unix platforms.
Lang Hames9d7a2692016-01-11 16:35:55 +0000582 if (RemoteMCJIT) {
583#ifndef LLVM_ON_UNIX
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000584 WithColor::warning(errs(), argv[0])
Jonas Devlieghere7b5fa242018-04-22 08:35:00 +0000585 << "host does not support external remote targets.\n";
586 WithColor::note() << "defaulting to local execution\n";
Lang Hames4b6e0212016-01-11 21:41:34 +0000587 return -1;
Lang Hames9d7a2692016-01-11 16:35:55 +0000588#else
589 if (ChildExecPath.empty()) {
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000590 WithColor::error(errs(), argv[0])
591 << "-remote-mcjit requires -mcjit-remote-process.\n";
Lang Hames9d7a2692016-01-11 16:35:55 +0000592 exit(1);
593 } else if (!sys::fs::can_execute(ChildExecPath)) {
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000594 WithColor::error(errs(), argv[0])
595 << "unable to find usable child executable: '" << ChildExecPath
596 << "'\n";
Lang Hames9d7a2692016-01-11 16:35:55 +0000597 return -1;
598 }
599#endif
600 }
601
Andrew Kaylor58365b92012-11-27 19:49:00 +0000602 if (!RemoteMCJIT) {
Andrew Kaylor6587bcf2013-10-11 22:47:10 +0000603 // If the program doesn't explicitly call exit, we will need the Exit
604 // function later on to make an explicit call, so get the function now.
605 Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000606 Type::getInt32Ty(Context));
Andrew Kaylor6587bcf2013-10-11 22:47:10 +0000607
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000608 // Run static constructors.
Eric Christopher79cc1e32014-09-02 22:28:02 +0000609 if (!ForceInterpreter) {
Andrew Kaylorea395922013-10-01 01:47:35 +0000610 // Give MCJIT a chance to apply relocations and set page permissions.
611 EE->finalizeObject();
612 }
613 EE->runStaticConstructorsDestructors(false);
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);
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000636 WithColor::error(errs(), argv[0]) << "exit(" << Result << ") returned!\n";
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000637 abort();
638 } else {
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000639 WithColor::error(errs(), argv[0])
640 << "exit defined with wrong prototype!\n";
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000641 abort();
642 }
643 } else {
644 // else == "if (RemoteMCJIT)"
645
646 // Remote target MCJIT doesn't (yet) support static constructors. No reason
Hiroshi Inoue0ca79dc2017-07-11 06:04:59 +0000647 // it couldn't. This is a limitation of the LLI implementation, not the
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000648 // MCJIT itself. FIXME.
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000649
Lang Hames9d7a2692016-01-11 16:35:55 +0000650 // Lanch the remote process and get a channel to it.
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000651 std::unique_ptr<FDRawChannel> C = launchRemote();
Lang Hames9d7a2692016-01-11 16:35:55 +0000652 if (!C) {
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000653 WithColor::error(errs(), argv[0]) << "failed to launch remote JIT.\n";
Lang Hames9d7a2692016-01-11 16:35:55 +0000654 exit(1);
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000655 }
656
Lang Hames9d7a2692016-01-11 16:35:55 +0000657 // Create a remote target client running over the channel.
Lang Hamesbd0cb782018-05-30 01:57:45 +0000658 llvm::orc::ExecutionSession ES;
659 ES.setErrorReporter([&](Error Err) { ExitOnErr(std::move(Err)); });
Lang Hames9e68b7342017-09-04 20:54:46 +0000660 typedef orc::remote::OrcRemoteTargetClient MyRemote;
Lang Hamesbd0cb782018-05-30 01:57:45 +0000661 auto R = ExitOnErr(MyRemote::Create(*C, ES));
Jim Grosbach748b9472012-08-28 23:22:30 +0000662
Lang Hames9d7a2692016-01-11 16:35:55 +0000663 // Create a remote memory manager.
Lang Hames9e68b7342017-09-04 20:54:46 +0000664 auto RemoteMM = ExitOnErr(R->createRemoteMemoryManager());
Lang Hames9d7a2692016-01-11 16:35:55 +0000665
666 // Forward MCJIT's memory manager calls to the remote memory manager.
667 static_cast<ForwardingMemoryManager*>(RTDyldMM)->setMemMgr(
668 std::move(RemoteMM));
669
670 // Forward MCJIT's symbol resolution calls to the remote.
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +0000671 static_cast<ForwardingMemoryManager *>(RTDyldMM)->setResolver(
672 orc::createLambdaResolver(
673 [](const std::string &Name) { return nullptr; },
674 [&](const std::string &Name) {
675 if (auto Addr = ExitOnErr(R->getSymbolAddress(Name)))
676 return JITSymbol(Addr, JITSymbolFlags::Exported);
677 return JITSymbol(nullptr);
678 }));
Lang Hames9d7a2692016-01-11 16:35:55 +0000679
680 // Grab the target address of the JIT'd main function on the remote and call
681 // it.
Jim Grosbach0f435d02012-09-05 16:50:34 +0000682 // FIXME: argv and envp handling.
Lang Hamesad4a9112016-08-01 20:49:11 +0000683 JITTargetAddress Entry = EE->getFunctionAddress(EntryFn->getName().str());
Lang Hames9d7a2692016-01-11 16:35:55 +0000684 EE->finalizeObject();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000685 LLVM_DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"
686 << format("%llx", Entry) << "\n");
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000687 Result = ExitOnErr(R->callIntVoid(Entry));
Jim Grosbach0f435d02012-09-05 16:50:34 +0000688
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000689 // Like static constructors, the remote target MCJIT support doesn't handle
690 // this yet. It could. FIXME.
691
Lang Hames9d7a2692016-01-11 16:35:55 +0000692 // Delete the EE - we need to tear it down *before* we terminate the session
693 // with the remote, otherwise it'll crash when it tries to release resources
694 // on a remote that has already been disconnected.
Mehdi Aminia7de8202016-04-18 18:52:39 +0000695 EE.reset();
Lang Hames9d7a2692016-01-11 16:35:55 +0000696
697 // Signal the remote target that we're done JITing.
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000698 ExitOnErr(R->terminateSession());
Chris Lattner2785bdb2007-05-06 04:58:26 +0000699 }
Jim Grosbach0f435d02012-09-05 16:50:34 +0000700
Jim Grosbach0f435d02012-09-05 16:50:34 +0000701 return Result;
Chris Lattnerd7ff5782001-08-23 17:05:04 +0000702}
Lang Hames9d7a2692016-01-11 16:35:55 +0000703
Lang Hames079df9a2018-10-15 22:56:10 +0000704static orc::IRTransformLayer::TransformFunction createDebugDumper() {
Lang Hames6a941342018-06-26 21:35:48 +0000705 switch (OrcDumpKind) {
706 case DumpKind::NoDump:
Lang Hames3e709d52018-09-28 21:49:53 +0000707 return [](orc::ThreadSafeModule TSM,
708 const orc::MaterializationResponsibility &R) { return TSM; };
Lang Hames6a941342018-06-26 21:35:48 +0000709
710 case DumpKind::DumpFuncsToStdOut:
Lang Hames3e709d52018-09-28 21:49:53 +0000711 return [](orc::ThreadSafeModule TSM,
712 const orc::MaterializationResponsibility &R) {
Lang Hames6a941342018-06-26 21:35:48 +0000713 printf("[ ");
714
Lang Hames8d76c712018-09-26 01:24:12 +0000715 for (const auto &F : *TSM.getModule()) {
Lang Hames6a941342018-06-26 21:35:48 +0000716 if (F.isDeclaration())
717 continue;
718
719 if (F.hasName()) {
720 std::string Name(F.getName());
721 printf("%s ", Name.c_str());
722 } else
723 printf("<anon> ");
724 }
725
726 printf("]\n");
Lang Hames8d76c712018-09-26 01:24:12 +0000727 return TSM;
Lang Hames6a941342018-06-26 21:35:48 +0000728 };
729
730 case DumpKind::DumpModsToStdOut:
Lang Hames3e709d52018-09-28 21:49:53 +0000731 return [](orc::ThreadSafeModule TSM,
732 const orc::MaterializationResponsibility &R) {
Lang Hames6a941342018-06-26 21:35:48 +0000733 outs() << "----- Module Start -----\n"
Lang Hames8d76c712018-09-26 01:24:12 +0000734 << *TSM.getModule() << "----- Module End -----\n";
Lang Hames6a941342018-06-26 21:35:48 +0000735
Lang Hames8d76c712018-09-26 01:24:12 +0000736 return TSM;
Lang Hames6a941342018-06-26 21:35:48 +0000737 };
738
739 case DumpKind::DumpModsToDisk:
Lang Hames3e709d52018-09-28 21:49:53 +0000740 return [](orc::ThreadSafeModule TSM,
741 const orc::MaterializationResponsibility &R) {
Lang Hames6a941342018-06-26 21:35:48 +0000742 std::error_code EC;
Lang Hames8d76c712018-09-26 01:24:12 +0000743 raw_fd_ostream Out(TSM.getModule()->getModuleIdentifier() + ".ll", EC,
744 sys::fs::F_Text);
Lang Hames6a941342018-06-26 21:35:48 +0000745 if (EC) {
Lang Hames8d76c712018-09-26 01:24:12 +0000746 errs() << "Couldn't open " << TSM.getModule()->getModuleIdentifier()
Lang Hames6a941342018-06-26 21:35:48 +0000747 << " for dumping.\nError:" << EC.message() << "\n";
748 exit(1);
749 }
Lang Hames8d76c712018-09-26 01:24:12 +0000750 Out << *TSM.getModule();
751 return TSM;
Lang Hames6a941342018-06-26 21:35:48 +0000752 };
753 }
754 llvm_unreachable("Unknown DumpKind");
755}
756
Lang Hames23cb2e72018-10-23 23:01:39 +0000757static void exitOnLazyCallThroughFailure() { exit(1); }
758
Lang Hames37a66412018-08-28 20:20:31 +0000759int runOrcLazyJIT(const char *ProgName) {
760 // Start setting up the JIT environment.
Lang Hames6a941342018-06-26 21:35:48 +0000761
Lang Hames37a66412018-08-28 20:20:31 +0000762 // Parse the main module.
Lang Hames8d76c712018-09-26 01:24:12 +0000763 orc::ThreadSafeContext TSCtx(llvm::make_unique<LLVMContext>());
Lang Hames37a66412018-08-28 20:20:31 +0000764 SMDiagnostic Err;
Lang Hames8d76c712018-09-26 01:24:12 +0000765 auto MainModule = orc::ThreadSafeModule(
766 parseIRFile(InputFile, Err, *TSCtx.getContext()), TSCtx);
Lang Hames37a66412018-08-28 20:20:31 +0000767 if (!MainModule)
768 reportError(Err, ProgName);
769
Lang Hames8d76c712018-09-26 01:24:12 +0000770 const auto &TT = MainModule.getModule()->getTargetTriple();
Lang Hamesf0a3fd882018-09-26 16:26:59 +0000771 orc::JITTargetMachineBuilder JTMB =
Lang Hames6a941342018-06-26 21:35:48 +0000772 TT.empty() ? ExitOnErr(orc::JITTargetMachineBuilder::detectHost())
773 : orc::JITTargetMachineBuilder(Triple(TT));
774
Lang Hamesd435ce42018-09-30 19:12:23 +0000775 if (!MArch.empty())
776 JTMB.getTargetTriple().setArchName(MArch);
777
778 JTMB.setCPU(getCPUStr())
Lang Hames6a941342018-06-26 21:35:48 +0000779 .addFeatures(getFeatureList())
780 .setRelocationModel(RelocModel.getNumOccurrences()
781 ? Optional<Reloc::Model>(RelocModel)
782 : None)
783 .setCodeModel(CMModel.getNumOccurrences()
784 ? Optional<CodeModel::Model>(CMModel)
785 : None);
Lang Hamesd435ce42018-09-30 19:12:23 +0000786
Lang Hamesd89c2732018-10-01 00:59:26 +0000787 DataLayout DL = ExitOnErr(JTMB.getDefaultDataLayoutForTarget());
Lang Hames23cb2e72018-10-23 23:01:39 +0000788
789 auto J = ExitOnErr(orc::LLLazyJIT::Create(
790 std::move(JTMB), DL,
791 pointerToJITTargetAddress(exitOnLazyCallThroughFailure),
792 LazyJITCompileThreads));
Lang Hames6a941342018-06-26 21:35:48 +0000793
Lang Hames98440292018-09-29 23:49:57 +0000794 if (PerModuleLazy)
Lang Hames079df9a2018-10-15 22:56:10 +0000795 J->setPartitionFunction(orc::CompileOnDemandLayer::compileWholeModule);
Lang Hames98440292018-09-29 23:49:57 +0000796
Lang Hamesadae9bf2018-07-02 22:30:18 +0000797 auto Dump = createDebugDumper();
798
Lang Hames3e709d52018-09-28 21:49:53 +0000799 J->setLazyCompileTransform([&](orc::ThreadSafeModule TSM,
800 const orc::MaterializationResponsibility &R) {
Lang Hames8d76c712018-09-26 01:24:12 +0000801 if (verifyModule(*TSM.getModule(), &dbgs())) {
802 dbgs() << "Bad module: " << *TSM.getModule() << "\n";
803 exit(1);
804 }
Lang Hames3e709d52018-09-28 21:49:53 +0000805 return Dump(std::move(TSM), R);
Lang Hames8d76c712018-09-26 01:24:12 +0000806 });
Lang Hamesa5157d62018-10-15 05:07:54 +0000807 J->getMainJITDylib().setGenerator(
808 ExitOnErr(orc::DynamicLibrarySearchGenerator::GetForCurrentProcess(DL)));
Lang Hames6a941342018-06-26 21:35:48 +0000809
810 orc::MangleAndInterner Mangle(J->getExecutionSession(), DL);
Lang Hames079df9a2018-10-15 22:56:10 +0000811 orc::LocalCXXRuntimeOverrides CXXRuntimeOverrides;
Lang Hamesd5f56c52018-08-17 21:18:18 +0000812 ExitOnErr(CXXRuntimeOverrides.enable(J->getMainJITDylib(), Mangle));
Lang Hames6a941342018-06-26 21:35:48 +0000813
Lang Hames37a66412018-08-28 20:20:31 +0000814 // Add the main module.
815 ExitOnErr(J->addLazyIRModule(std::move(MainModule)));
816
Lang Hames23cb2e72018-10-23 23:01:39 +0000817 // Create JITDylibs and add any extra modules.
818 {
819 // Create JITDylibs, keep a map from argument index to dylib. We will use
820 // -extra-module argument indexes to determine what dylib to use for each
821 // -extra-module.
822 std::map<unsigned, orc::JITDylib *> IdxToDylib;
823 IdxToDylib[0] = &J->getMainJITDylib();
824 for (auto JDItr = JITDylibs.begin(), JDEnd = JITDylibs.end();
825 JDItr != JDEnd; ++JDItr) {
826 IdxToDylib[JITDylibs.getPosition(JDItr - JITDylibs.begin())] =
827 &J->createJITDylib(*JDItr);
828 }
Lang Hames37a66412018-08-28 20:20:31 +0000829
Lang Hames23cb2e72018-10-23 23:01:39 +0000830 for (auto EMItr = ExtraModules.begin(), EMEnd = ExtraModules.end();
831 EMItr != EMEnd; ++EMItr) {
832 auto M = parseIRFile(*EMItr, Err, *TSCtx.getContext());
833 if (!M)
834 reportError(Err, ProgName);
835
836 auto EMIdx = ExtraModules.getPosition(EMItr - ExtraModules.begin());
837 assert(EMIdx != 0 && "ExtraModule should have index > 0");
838 auto JDItr = std::prev(IdxToDylib.lower_bound(EMIdx));
839 auto &JD = *JDItr->second;
840 ExitOnErr(
841 J->addLazyIRModule(JD, orc::ThreadSafeModule(std::move(M), TSCtx)));
842 }
Lang Hamesadae9bf2018-07-02 22:30:18 +0000843 }
Lang Hames6a941342018-06-26 21:35:48 +0000844
Lang Hames37a66412018-08-28 20:20:31 +0000845 // Add the objects.
846 for (auto &ObjPath : ExtraObjects) {
847 auto Obj = ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(ObjPath)));
848 ExitOnErr(J->addObjectFile(std::move(Obj)));
849 }
850
851 // Generate a argument string.
852 std::vector<std::string> Args;
853 Args.push_back(InputFile);
854 for (auto &Arg : InputArgv)
855 Args.push_back(Arg);
856
857 // Run any static constructors.
Lang Hames6a941342018-06-26 21:35:48 +0000858 ExitOnErr(J->runConstructors());
859
Lang Hamesf0a3fd882018-09-26 16:26:59 +0000860 // Run any -thread-entry points.
861 std::vector<std::thread> AltEntryThreads;
862 for (auto &ThreadEntryPoint : ThreadEntryPoints) {
863 auto EntryPointSym = ExitOnErr(J->lookup(ThreadEntryPoint));
864 typedef void (*EntryPointPtr)();
865 auto EntryPoint =
866 reinterpret_cast<EntryPointPtr>(static_cast<uintptr_t>(EntryPointSym.getAddress()));
867 AltEntryThreads.push_back(std::thread([EntryPoint]() { EntryPoint(); }));
868 }
869
Lang Hames23cb2e72018-10-23 23:01:39 +0000870 J->getExecutionSession().dump(llvm::dbgs());
871
Lang Hames37a66412018-08-28 20:20:31 +0000872 // Run main.
Lang Hames6a941342018-06-26 21:35:48 +0000873 auto MainSym = ExitOnErr(J->lookup("main"));
874 typedef int (*MainFnPtr)(int, const char *[]);
875 std::vector<const char *> ArgV;
876 for (auto &Arg : Args)
877 ArgV.push_back(Arg.c_str());
Lang Hames94fe9d42018-09-27 19:27:19 +0000878 ArgV.push_back(nullptr);
879
880 int ArgC = ArgV.size() - 1;
Lang Hames6a941342018-06-26 21:35:48 +0000881 auto Main =
882 reinterpret_cast<MainFnPtr>(static_cast<uintptr_t>(MainSym.getAddress()));
Lang Hames94fe9d42018-09-27 19:27:19 +0000883 auto Result = Main(ArgC, (const char **)ArgV.data());
Lang Hames6a941342018-06-26 21:35:48 +0000884
Lang Hamesf0a3fd882018-09-26 16:26:59 +0000885 // Wait for -entry-point threads.
886 for (auto &AltEntryThread : AltEntryThreads)
887 AltEntryThread.join();
Hans Wennborg20b5abe2018-09-26 12:15:23 +0000888
Lang Hamesf0a3fd882018-09-26 16:26:59 +0000889 // Run destructors.
890 ExitOnErr(J->runDestructors());
Lang Hames6a941342018-06-26 21:35:48 +0000891 CXXRuntimeOverrides.runDestructors();
892
893 return Result;
894}
895
Lang Hames98440292018-09-29 23:49:57 +0000896void disallowOrcOptions() {
897 // Make sure nobody used an orc-lazy specific option accidentally.
898
899 if (LazyJITCompileThreads != 0) {
900 errs() << "-compile-threads requires -jit-kind=orc-lazy\n";
901 exit(1);
902 }
903
904 if (!ThreadEntryPoints.empty()) {
905 errs() << "-thread-entry requires -jit-kind=orc-lazy\n";
906 exit(1);
907 }
908
909 if (PerModuleLazy) {
910 errs() << "-per-module-lazy requires -jit-kind=orc-lazy\n";
911 exit(1);
912 }
913}
914
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000915std::unique_ptr<FDRawChannel> launchRemote() {
Lang Hames9d7a2692016-01-11 16:35:55 +0000916#ifndef LLVM_ON_UNIX
917 llvm_unreachable("launchRemote not supported on non-Unix platforms");
918#else
919 int PipeFD[2][2];
920 pid_t ChildPID;
921
922 // Create two pipes.
923 if (pipe(PipeFD[0]) != 0 || pipe(PipeFD[1]) != 0)
924 perror("Error creating pipe: ");
925
926 ChildPID = fork();
927
928 if (ChildPID == 0) {
929 // In the child...
930
931 // Close the parent ends of the pipes
932 close(PipeFD[0][1]);
933 close(PipeFD[1][0]);
934
935
936 // Execute the child process.
937 std::unique_ptr<char[]> ChildPath, ChildIn, ChildOut;
938 {
939 ChildPath.reset(new char[ChildExecPath.size() + 1]);
940 std::copy(ChildExecPath.begin(), ChildExecPath.end(), &ChildPath[0]);
941 ChildPath[ChildExecPath.size()] = '\0';
NAKAMURA Takumicef0a8212016-01-15 02:14:46 +0000942 std::string ChildInStr = utostr(PipeFD[0][0]);
Lang Hames9d7a2692016-01-11 16:35:55 +0000943 ChildIn.reset(new char[ChildInStr.size() + 1]);
944 std::copy(ChildInStr.begin(), ChildInStr.end(), &ChildIn[0]);
945 ChildIn[ChildInStr.size()] = '\0';
NAKAMURA Takumicef0a8212016-01-15 02:14:46 +0000946 std::string ChildOutStr = utostr(PipeFD[1][1]);
Lang Hames9d7a2692016-01-11 16:35:55 +0000947 ChildOut.reset(new char[ChildOutStr.size() + 1]);
948 std::copy(ChildOutStr.begin(), ChildOutStr.end(), &ChildOut[0]);
949 ChildOut[ChildOutStr.size()] = '\0';
950 }
951
952 char * const args[] = { &ChildPath[0], &ChildIn[0], &ChildOut[0], nullptr };
953 int rc = execv(ChildExecPath.c_str(), args);
954 if (rc != 0)
955 perror("Error executing child process: ");
956 llvm_unreachable("Error executing child process");
957 }
958 // else we're the parent...
959
960 // Close the child ends of the pipes
961 close(PipeFD[0][0]);
962 close(PipeFD[1][1]);
963
964 // Return an RPC channel connected to our end of the pipes.
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000965 return llvm::make_unique<FDRawChannel>(PipeFD[1][0], PipeFD[0][1]);
Lang Hames9d7a2692016-01-11 16:35:55 +0000966#endif
967}