blob: 55b9557bddfe4da572952ad095ff28ba9477b1f7 [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Misha Brukman650ba8e2005-04-22 00:00:37 +00006//
John Criswell09344dc2003-10-20 17:47:21 +00007//===----------------------------------------------------------------------===//
Chris Lattnerd7ff5782001-08-23 17:05:04 +00008//
Chris Lattner141ea3a2003-12-26 05:07:35 +00009// This utility provides a simple wrapper around the LLVM Execution Engines,
10// which allow the direct execution of LLVM programs through a Just-In-Time
Torok Edwinf011f282009-07-03 12:11:32 +000011// compiler, or through an interpreter if no JIT is available for this platform.
Chris Lattnerd7ff5782001-08-23 17:05:04 +000012//
13//===----------------------------------------------------------------------===//
14
Lang Hames9d7a2692016-01-11 16:35:55 +000015#include "RemoteJITUtils.h"
NAKAMURA Takumicef0a8212016-01-15 02:14:46 +000016#include "llvm/ADT/StringExtras.h"
Duncan Sands3bd97fe2010-08-28 01:30:02 +000017#include "llvm/ADT/Triple.h"
Teresa Johnsonad176792016-11-11 05:34:58 +000018#include "llvm/Bitcode/BitcodeReader.h"
David Blaikie4333f972018-04-11 18:49:37 +000019#include "llvm/CodeGen/CommandFlags.inc"
Chris Lattner5af6a3f2006-08-01 22:34:35 +000020#include "llvm/CodeGen/LinkAllCodegenComponents.h"
Nico Weber432a3882018-04-30 14:59:11 +000021#include "llvm/Config/llvm-config.h"
Brian Gaekee99ca442003-09-05 19:42:34 +000022#include "llvm/ExecutionEngine/GenericValue.h"
Jeffrey Yasskin0b08f3d2009-06-25 02:04:04 +000023#include "llvm/ExecutionEngine/Interpreter.h"
Jeffrey Yasskin0b08f3d2009-06-25 02:04:04 +000024#include "llvm/ExecutionEngine/JITEventListener.h"
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000025#include "llvm/ExecutionEngine/MCJIT.h"
Lang Hames173c69f2014-01-08 04:09:09 +000026#include "llvm/ExecutionEngine/ObjectCache.h"
Lang Hames85fb9972019-12-16 02:50:40 -080027#include "llvm/ExecutionEngine/Orc/DebugUtils.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"
Lang Hames85fb9972019-12-16 02:50:40 -080031#include "llvm/ExecutionEngine/Orc/MachOPlatform.h"
Rafael Espindola79e238a2017-08-03 02:16:21 +000032#include "llvm/ExecutionEngine/Orc/OrcRemoteTargetClient.h"
Lang Hames93de2a12015-01-23 21:25:00 +000033#include "llvm/ExecutionEngine/OrcMCJITReplacement.h"
Andrew Kaylor58365b92012-11-27 19:49:00 +000034#include "llvm/ExecutionEngine/SectionMemoryManager.h"
Andrew Kaylor1ca510e2013-10-29 01:29:56 +000035#include "llvm/IR/IRBuilder.h"
Rafael Espindola79e238a2017-08-03 02:16:21 +000036#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000037#include "llvm/IR/Module.h"
38#include "llvm/IR/Type.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 Hames17164542019-07-17 16:40:52 +000088 cl::opt<JITKind> UseJITKind(
89 "jit-kind", cl::desc("Choose underlying JIT kind."),
90 cl::init(JITKind::MCJIT),
91 cl::values(clEnumValN(JITKind::MCJIT, "mcjit", "MCJIT"),
92 clEnumValN(JITKind::OrcMCJITReplacement, "orc-mcjit",
93 "Orc-based MCJIT replacement "
94 "(deprecated)"),
95 clEnumValN(JITKind::OrcLazy, "orc-lazy",
96 "Orc-based lazy JIT.")));
Lang Hames93de2a12015-01-23 21:25:00 +000097
Lang Hamesf0a3fd882018-09-26 16:26:59 +000098 cl::opt<unsigned>
99 LazyJITCompileThreads("compile-threads",
100 cl::desc("Choose the number of compile threads "
101 "(jit-kind=orc-lazy only)"),
102 cl::init(0));
103
104 cl::list<std::string>
105 ThreadEntryPoints("thread-entry",
106 cl::desc("calls the given entry-point on a new thread "
107 "(jit-kind=orc-lazy only)"));
108
Lang Hames98440292018-09-29 23:49:57 +0000109 cl::opt<bool> PerModuleLazy(
110 "per-module-lazy",
111 cl::desc("Performs lazy compilation on whole module boundaries "
112 "rather than individual functions"),
113 cl::init(false));
114
Lang Hames23cb2e72018-10-23 23:01:39 +0000115 cl::list<std::string>
116 JITDylibs("jd",
117 cl::desc("Specifies the JITDylib to be used for any subsequent "
118 "-extra-module arguments."));
119
Lang Hamesb7be6b42020-02-14 14:22:59 -0800120 cl::list<std::string>
121 Dylibs("dlopen", cl::desc("Dynamic libraries to load before linking"),
122 cl::ZeroOrMore);
123
Jim Grosbach0f435d02012-09-05 16:50:34 +0000124 // The MCJIT supports building for a target address space separate from
125 // the JIT compilation process. Use a forked process and a copying
126 // memory manager with IPC to execute using this functionality.
127 cl::opt<bool> RemoteMCJIT("remote-mcjit",
128 cl::desc("Execute MCJIT'ed code in a separate process."),
129 cl::init(false));
130
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000131 // Manually specify the child process for remote execution. This overrides
132 // the simulated remote execution that allocates address space for child
Andrew Kaylor89352582013-10-29 01:33:14 +0000133 // execution. The child process will be executed and will communicate with
134 // lli via stdin/stdout pipes.
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000135 cl::opt<std::string>
Alp Tokera1186382014-01-22 21:52:35 +0000136 ChildExecPath("mcjit-remote-process",
137 cl::desc("Specify the filename of the process to launch "
138 "for remote MCJIT execution. If none is specified,"
139 "\n\tremote execution will be simulated in-process."),
140 cl::value_desc("filename"), cl::init(""));
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000141
Evan Cheng09bd0b12009-05-04 23:05:19 +0000142 // Determine optimization level.
143 cl::opt<char>
144 OptLevel("O",
145 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
146 "(default = '-O2')"),
147 cl::Prefix,
148 cl::ZeroOrMore,
149 cl::init(' '));
Evan Cheng06d988e2008-08-08 08:12:06 +0000150
Chris Lattner76766cb2005-12-16 05:00:21 +0000151 cl::opt<std::string>
Chris Lattner78e9e102005-12-16 05:19:18 +0000152 TargetTriple("mtriple", cl::desc("Override target triple for module"));
Evan Cheng61582542008-11-05 23:21:52 +0000153
154 cl::opt<std::string>
155 EntryFunc("entry-function",
156 cl::desc("Specify the entry function (default = 'main') "
157 "of the executable"),
158 cl::value_desc("function"),
159 cl::init("main"));
Eli Bendersky4c647582012-01-16 08:56:09 +0000160
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000161 cl::list<std::string>
Andrew Kaylor4404eb42013-10-28 21:58:15 +0000162 ExtraModules("extra-module",
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000163 cl::desc("Extra modules to be loaded"),
Alp Toker0a09ebf2013-10-28 22:51:25 +0000164 cl::value_desc("input bitcode"));
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000165
Lang Hames173c69f2014-01-08 04:09:09 +0000166 cl::list<std::string>
167 ExtraObjects("extra-object",
168 cl::desc("Extra object files to be loaded"),
169 cl::value_desc("input object"));
170
171 cl::list<std::string>
172 ExtraArchives("extra-archive",
173 cl::desc("Extra archive files to be loaded"),
174 cl::value_desc("input archive"));
175
176 cl::opt<bool>
177 EnableCacheManager("enable-cache-manager",
Lang Hames15c072a2019-04-27 16:13:53 +0000178 cl::desc("Use cache manager to save/load modules"),
Lang Hames173c69f2014-01-08 04:09:09 +0000179 cl::init(false));
180
Chris Lattner55644062003-10-28 22:51:44 +0000181 cl::opt<std::string>
Lang Hames1ddecc02014-01-09 05:24:05 +0000182 ObjectCacheDir("object-cache-dir",
183 cl::desc("Directory to store cached object files "
184 "(must be user writable)"),
185 cl::init(""));
186
187 cl::opt<std::string>
Chris Lattner55644062003-10-28 22:51:44 +0000188 FakeArgv0("fake-argv0",
189 cl::desc("Override the 'argv[0]' value passed into the executing"
190 " program"), cl::value_desc("executable"));
Eli Bendersky4c647582012-01-16 08:56:09 +0000191
Chris Lattner3f0ffd32006-09-14 06:17:09 +0000192 cl::opt<bool>
193 DisableCoreFiles("disable-core-files", cl::Hidden,
194 cl::desc("Disable emission of core files if possible"));
Evan Cheng0422bef2008-04-22 06:51:41 +0000195
196 cl::opt<bool>
Evan Cheng16f036c2008-05-21 18:20:21 +0000197 NoLazyCompilation("disable-lazy-compilation",
Evan Cheng0422bef2008-04-22 06:51:41 +0000198 cl::desc("Disable JIT lazy compilation"),
199 cl::init(false));
Evan Cheng2129f592011-07-19 06:37:02 +0000200
Nick Lewyckyb0e97892012-04-18 08:34:12 +0000201 cl::opt<bool>
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000202 GenerateSoftFloatCalls("soft-float",
203 cl::desc("Generate software floating point library calls"),
204 cl::init(false));
205
Lang Hamesce2207a2020-01-21 16:28:30 -0800206 cl::opt<bool> NoProcessSymbols(
207 "no-process-syms",
208 cl::desc("Do not resolve lli process symbols in JIT'd code"),
209 cl::init(false));
210
Lang Hames85fb9972019-12-16 02:50:40 -0800211 enum class LLJITPlatform { DetectHost, GenericIR, MachO };
212
213 cl::opt<LLJITPlatform>
214 Platform("lljit-platform", cl::desc("Platform to use with LLJIT"),
215 cl::init(LLJITPlatform::DetectHost),
216 cl::values(clEnumValN(LLJITPlatform::DetectHost, "DetectHost",
217 "Select based on JIT target triple"),
218 clEnumValN(LLJITPlatform::GenericIR, "GenericIR",
219 "Use LLJITGenericIRPlatform"),
220 clEnumValN(LLJITPlatform::MachO, "MachO",
221 "Use LLJITMachOPlatform")),
222 cl::Hidden);
223
Lang Hames6a941342018-06-26 21:35:48 +0000224 enum class DumpKind {
225 NoDump,
226 DumpFuncsToStdOut,
227 DumpModsToStdOut,
228 DumpModsToDisk
229 };
230
231 cl::opt<DumpKind> OrcDumpKind(
232 "orc-lazy-debug", cl::desc("Debug dumping for the orc-lazy JIT."),
233 cl::init(DumpKind::NoDump),
234 cl::values(clEnumValN(DumpKind::NoDump, "no-dump",
235 "Don't dump anything."),
236 clEnumValN(DumpKind::DumpFuncsToStdOut, "funcs-to-stdout",
237 "Dump function names to stdout."),
238 clEnumValN(DumpKind::DumpModsToStdOut, "mods-to-stdout",
239 "Dump modules to stdout."),
240 clEnumValN(DumpKind::DumpModsToDisk, "mods-to-disk",
241 "Dump modules to the current "
242 "working directory. (WARNING: "
243 "will overwrite existing files).")),
244 cl::Hidden);
245
Lang Hamesef5a0ee2016-04-25 19:56:45 +0000246 ExitOnError ExitOnErr;
Chris Lattnera0d7b082002-12-23 23:59:41 +0000247}
Chris Lattner009f8102001-10-27 08:43:52 +0000248
Lang Hames173c69f2014-01-08 04:09:09 +0000249//===----------------------------------------------------------------------===//
250// Object cache
251//
Lang Hames1ddecc02014-01-09 05:24:05 +0000252// This object cache implementation writes cached objects to disk to the
253// directory specified by CacheDir, using a filename provided in the module
254// descriptor. The cache tries to load a saved object using that path if the
255// file exists. CacheDir defaults to "", in which case objects are cached
NAKAMURA Takumif462f9c2014-01-10 10:38:28 +0000256// alongside their originating bitcodes.
Lang Hames173c69f2014-01-08 04:09:09 +0000257//
258class LLIObjectCache : public ObjectCache {
259public:
Lang Hames1ddecc02014-01-09 05:24:05 +0000260 LLIObjectCache(const std::string& CacheDir) : CacheDir(CacheDir) {
261 // Add trailing '/' to cache dir if necessary.
Lang Hamesf9dd8fd2014-01-09 05:29:59 +0000262 if (!this->CacheDir.empty() &&
263 this->CacheDir[this->CacheDir.size() - 1] != '/')
NAKAMURA Takumif462f9c2014-01-10 10:38:28 +0000264 this->CacheDir += '/';
Lang Hames1ddecc02014-01-09 05:24:05 +0000265 }
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000266 ~LLIObjectCache() override {}
Lang Hames173c69f2014-01-08 04:09:09 +0000267
Rafael Espindola48af1c22014-08-19 18:44:46 +0000268 void notifyObjectCompiled(const Module *M, MemoryBufferRef Obj) override {
Benjamin Kramer46e38f32016-06-08 10:01:20 +0000269 const std::string &ModuleID = M->getModuleIdentifier();
Lang Hames173c69f2014-01-08 04:09:09 +0000270 std::string CacheName;
271 if (!getCacheFilename(ModuleID, CacheName))
272 return;
NAKAMURA Takumi390e0602014-01-10 10:38:34 +0000273 if (!CacheDir.empty()) { // Create user-defined cache dir.
Rafael Espindolaf662e002015-07-15 21:24:07 +0000274 SmallString<128> dir(sys::path::parent_path(CacheName));
NAKAMURA Takumi390e0602014-01-10 10:38:34 +0000275 sys::fs::create_directories(Twine(dir));
276 }
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000277 std::error_code EC;
Fangrui Songd9b948b2019-08-05 05:43:48 +0000278 raw_fd_ostream outfile(CacheName, EC, sys::fs::OF_None);
Rafael Espindola48af1c22014-08-19 18:44:46 +0000279 outfile.write(Obj.getBufferStart(), Obj.getBufferSize());
Lang Hames173c69f2014-01-08 04:09:09 +0000280 outfile.close();
281 }
282
Rafael Espindola5f2bb7d2014-08-13 18:49:01 +0000283 std::unique_ptr<MemoryBuffer> getObject(const Module* M) override {
Benjamin Kramer46e38f32016-06-08 10:01:20 +0000284 const std::string &ModuleID = M->getModuleIdentifier();
Lang Hames173c69f2014-01-08 04:09:09 +0000285 std::string CacheName;
286 if (!getCacheFilename(ModuleID, CacheName))
Craig Toppere6cb63e2014-04-25 04:24:47 +0000287 return nullptr;
Lang Hames173c69f2014-01-08 04:09:09 +0000288 // Load the object from the cache filename
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000289 ErrorOr<std::unique_ptr<MemoryBuffer>> IRObjectBuffer =
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000290 MemoryBuffer::getFile(CacheName, -1, false);
Lang Hames173c69f2014-01-08 04:09:09 +0000291 // If the file isn't there, that's OK.
292 if (!IRObjectBuffer)
Craig Toppere6cb63e2014-04-25 04:24:47 +0000293 return nullptr;
Lang Hames173c69f2014-01-08 04:09:09 +0000294 // MCJIT will want to write into this buffer, and we don't want that
295 // because the file has probably just been mmapped. Instead we make
296 // a copy. The filed-based buffer will be released when it goes
297 // out of scope.
Rafael Espindola3560ff22014-08-27 20:03:13 +0000298 return MemoryBuffer::getMemBufferCopy(IRObjectBuffer.get()->getBuffer());
Lang Hames173c69f2014-01-08 04:09:09 +0000299 }
300
301private:
Lang Hames1ddecc02014-01-09 05:24:05 +0000302 std::string CacheDir;
303
Lang Hames173c69f2014-01-08 04:09:09 +0000304 bool getCacheFilename(const std::string &ModID, std::string &CacheName) {
305 std::string Prefix("file:");
306 size_t PrefixLength = Prefix.length();
307 if (ModID.substr(0, PrefixLength) != Prefix)
308 return false;
NAKAMURA Takumid7fd6d92014-01-10 10:38:40 +0000309 std::string CacheSubdir = ModID.substr(PrefixLength);
310#if defined(_WIN32)
311 // Transform "X:\foo" => "/X\foo" for convenience.
312 if (isalpha(CacheSubdir[0]) && CacheSubdir[1] == ':') {
313 CacheSubdir[1] = CacheSubdir[0];
314 CacheSubdir[0] = '/';
315 }
316#endif
317 CacheName = CacheDir + CacheSubdir;
Lang Hames173c69f2014-01-08 04:09:09 +0000318 size_t pos = CacheName.rfind('.');
319 CacheName.replace(pos, CacheName.length() - pos, ".o");
320 return true;
321 }
322};
323
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000324// On Mingw and Cygwin, an external symbol named '__main' is called from the
Simon Pilgrimdae11f72016-11-20 13:31:13 +0000325// generated 'main' function to allow static initialization. To avoid linking
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000326// problems with remote targets (because lli's remote target support does not
327// currently handle external linking) we add a secondary module which defines
328// an empty '__main' function.
Mehdi Aminia7de8202016-04-18 18:52:39 +0000329static void addCygMingExtraModule(ExecutionEngine &EE, LLVMContext &Context,
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000330 StringRef TargetTripleStr) {
331 IRBuilder<> Builder(Context);
332 Triple TargetTriple(TargetTripleStr);
333
334 // Create a new module.
Jonas Devlieghere0eaee542019-08-15 15:54:37 +0000335 std::unique_ptr<Module> M = std::make_unique<Module>("CygMingHelper", Context);
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000336 M->setTargetTriple(TargetTripleStr);
337
338 // Create an empty function named "__main".
James Y Knightc0044112019-01-13 16:09:28 +0000339 Type *ReturnTy;
340 if (TargetTriple.isArch64Bit())
341 ReturnTy = Type::getInt64Ty(Context);
342 else
343 ReturnTy = Type::getInt32Ty(Context);
344 Function *Result =
345 Function::Create(FunctionType::get(ReturnTy, {}, false),
346 GlobalValue::ExternalLinkage, "__main", M.get());
347
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000348 BasicBlock *BB = BasicBlock::Create(Context, "__main", Result);
349 Builder.SetInsertPoint(BB);
James Y Knightc0044112019-01-13 16:09:28 +0000350 Value *ReturnVal = ConstantInt::get(ReturnTy, 0);
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000351 Builder.CreateRet(ReturnVal);
352
353 // Add this new module to the ExecutionEngine.
Mehdi Aminia7de8202016-04-18 18:52:39 +0000354 EE.addModule(std::move(M));
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000355}
356
Lang Hames1899d0c2015-06-09 02:43:27 +0000357CodeGenOpt::Level getOptLevel() {
358 switch (OptLevel) {
359 default:
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000360 WithColor::error(errs(), "lli") << "invalid optimization level.\n";
Lang Hames1899d0c2015-06-09 02:43:27 +0000361 exit(1);
362 case '0': return CodeGenOpt::None;
363 case '1': return CodeGenOpt::Less;
364 case ' ':
365 case '2': return CodeGenOpt::Default;
366 case '3': return CodeGenOpt::Aggressive;
367 }
368 llvm_unreachable("Unrecognized opt level.");
369}
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000370
Davide Italianoda8e6b22016-11-17 22:58:13 +0000371LLVM_ATTRIBUTE_NORETURN
372static void reportError(SMDiagnostic Err, const char *ProgName) {
373 Err.print(ProgName, errs());
374 exit(1);
375}
376
Lang Hamesb7be6b42020-02-14 14:22:59 -0800377Error loadDylibs();
Lang Hames37a66412018-08-28 20:20:31 +0000378int runOrcLazyJIT(const char *ProgName);
Lang Hames98440292018-09-29 23:49:57 +0000379void disallowOrcOptions();
Lang Hames6a941342018-06-26 21:35:48 +0000380
Chris Lattnerd7ff5782001-08-23 17:05:04 +0000381//===----------------------------------------------------------------------===//
Chris Lattnerd7ff5782001-08-23 17:05:04 +0000382// main Driver function
383//
Misha Brukman5b255e52003-10-14 21:39:53 +0000384int main(int argc, char **argv, char * const *envp) {
Rui Ueyama197194b2018-04-13 18:26:06 +0000385 InitLLVM X(argc, argv);
Daniel Dunbar3d92d932009-07-16 02:04:54 +0000386
Lang Hamesef5a0ee2016-04-25 19:56:45 +0000387 if (argc > 1)
388 ExitOnErr.setBanner(std::string(argv[0]) + ": ");
389
Daniel Dunbar3d92d932009-07-16 02:04:54 +0000390 // If we have a native target, initialize it to ensure it is linked in and
391 // usable by the JIT.
392 InitializeNativeTarget();
Jim Grosbach7b162492011-03-18 22:48:41 +0000393 InitializeNativeTargetAsmPrinter();
Jim Grosbach2cce3f92012-11-05 19:06:05 +0000394 InitializeNativeTargetAsmParser();
Daniel Dunbar3d92d932009-07-16 02:04:54 +0000395
Chris Lattner2785bdb2007-05-06 04:58:26 +0000396 cl::ParseCommandLineOptions(argc, argv,
Dan Gohman2c6a8212007-10-08 15:45:12 +0000397 "llvm interpreter & dynamic compiler\n");
Reid Spencer996ec722004-12-30 05:36:08 +0000398
Chris Lattner2785bdb2007-05-06 04:58:26 +0000399 // If the user doesn't want core files, disable them.
400 if (DisableCoreFiles)
401 sys::Process::PreventCoreFiles();
Eli Bendersky4c647582012-01-16 08:56:09 +0000402
Lang Hamesb7be6b42020-02-14 14:22:59 -0800403 ExitOnErr(loadDylibs());
404
Lang Hames37a66412018-08-28 20:20:31 +0000405 if (UseJITKind == JITKind::OrcLazy)
406 return runOrcLazyJIT(argv[0]);
Lang Hames98440292018-09-29 23:49:57 +0000407 else
408 disallowOrcOptions();
Lang Hames37a66412018-08-28 20:20:31 +0000409
Mehdi Aminia7de8202016-04-18 18:52:39 +0000410 LLVMContext Context;
411
Gabor Greife16561c2007-07-05 17:07:56 +0000412 // Load the bitcode...
Daniel Dunbar9589bf82010-11-13 00:28:01 +0000413 SMDiagnostic Err;
Rafael Espindolad233b062014-08-26 17:29:46 +0000414 std::unique_ptr<Module> Owner = parseIRFile(InputFile, Err, Context);
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000415 Module *Mod = Owner.get();
Davide Italianoda8e6b22016-11-17 22:58:13 +0000416 if (!Mod)
417 reportError(Err, argv[0]);
Chris Lattner2785bdb2007-05-06 04:58:26 +0000418
Lang Hames173c69f2014-01-08 04:09:09 +0000419 if (EnableCacheManager) {
Eric Christopher79cc1e32014-09-02 22:28:02 +0000420 std::string CacheName("file:");
421 CacheName.append(InputFile);
422 Mod->setModuleIdentifier(CacheName);
Lang Hames173c69f2014-01-08 04:09:09 +0000423 }
424
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000425 // If not jitting lazily, load the whole bitcode file eagerly too.
426 if (NoLazyCompilation) {
Davide Italianob0e067b2016-11-09 21:30:33 +0000427 // Use *argv instead of argv[0] to work around a wrong GCC warning.
428 ExitOnError ExitOnErr(std::string(*argv) +
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000429 ": bitcode didn't read correctly: ");
430 ExitOnErr(Mod->materializeAll());
Evan Cheng0422bef2008-04-22 06:51:41 +0000431 }
Chris Lattner2785bdb2007-05-06 04:58:26 +0000432
Rafael Espindolae9fab9b2014-01-14 23:51:27 +0000433 std::string ErrorMsg;
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000434 EngineBuilder builder(std::move(Owner));
Jeffrey Yasskin31faeff2010-02-05 16:19:36 +0000435 builder.setMArch(MArch);
Craig Topper243f20f2018-01-09 18:14:18 +0000436 builder.setMCPU(getCPUStr());
437 builder.setMAttrs(getFeatureList());
Rafael Espindola8c34dd82016-05-18 22:04:49 +0000438 if (RelocModel.getNumOccurrences())
439 builder.setRelocationModel(RelocModel);
Rafael Espindola79e238a2017-08-03 02:16:21 +0000440 if (CMModel.getNumOccurrences())
441 builder.setCodeModel(CMModel);
Daniel Dunbara78d8092009-07-18 08:07:13 +0000442 builder.setErrorStr(&ErrorMsg);
443 builder.setEngineKind(ForceInterpreter
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000444 ? EngineKind::Interpreter
445 : EngineKind::JIT);
Lang Hames17164542019-07-17 16:40:52 +0000446 builder.setUseOrcMCJITReplacement(AcknowledgeORCv1Deprecation,
447 UseJITKind == JITKind::OrcMCJITReplacement);
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000448
Chris Lattner2785bdb2007-05-06 04:58:26 +0000449 // If we are supposed to override the target triple, do so now.
450 if (!TargetTriple.empty())
Duncan Sands3bd97fe2010-08-28 01:30:02 +0000451 Mod->setTargetTriple(Triple::normalize(TargetTriple));
Evan Cheng0422bef2008-04-22 06:51:41 +0000452
Eli Bendersky4c647582012-01-16 08:56:09 +0000453 // Enable MCJIT if desired.
Craig Toppere6cb63e2014-04-25 04:24:47 +0000454 RTDyldMemoryManager *RTDyldMM = nullptr;
Eric Christopher79cc1e32014-09-02 22:28:02 +0000455 if (!ForceInterpreter) {
Jim Grosbach0f435d02012-09-05 16:50:34 +0000456 if (RemoteMCJIT)
Lang Hames9d7a2692016-01-11 16:35:55 +0000457 RTDyldMM = new ForwardingMemoryManager();
Jim Grosbach0f435d02012-09-05 16:50:34 +0000458 else
Filip Pizlo9bc53e82013-05-14 19:29:00 +0000459 RTDyldMM = new SectionMemoryManager();
Lang Hames4a5697e2014-12-03 00:51:19 +0000460
461 // Deliberately construct a temp std::unique_ptr to pass in. Do not null out
462 // RTDyldMM: We still use it below, even though we don't own it.
463 builder.setMCJITMemoryManager(
464 std::unique_ptr<RTDyldMemoryManager>(RTDyldMM));
Lang Hames0f154902014-09-23 16:56:02 +0000465 } else if (RemoteMCJIT) {
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000466 WithColor::error(errs(), argv[0])
467 << "remote process execution does not work with the interpreter.\n";
Lang Hames0f154902014-09-23 16:56:02 +0000468 exit(1);
Eli Bendersky4c647582012-01-16 08:56:09 +0000469 }
Daniel Dunbar70ff8b02010-11-17 16:06:37 +0000470
Lang Hames1899d0c2015-06-09 02:43:27 +0000471 builder.setOptLevel(getOptLevel());
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000472
David Blaikiec14bfec2017-11-27 19:43:58 +0000473 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000474 if (FloatABIForCalls != FloatABI::Default)
475 Options.FloatABIType = FloatABIForCalls;
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000476
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000477 builder.setTargetOptions(Options);
478
Mehdi Aminia7de8202016-04-18 18:52:39 +0000479 std::unique_ptr<ExecutionEngine> EE(builder.create());
Chris Lattnerf840ed72009-07-07 18:31:09 +0000480 if (!EE) {
481 if (!ErrorMsg.empty())
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000482 WithColor::error(errs(), argv[0])
483 << "error creating EE: " << ErrorMsg << "\n";
Chris Lattnerf840ed72009-07-07 18:31:09 +0000484 else
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000485 WithColor::error(errs(), argv[0]) << "unknown error creating EE!\n";
Chris Lattner2785bdb2007-05-06 04:58:26 +0000486 exit(1);
487 }
488
Mehdi Aminia7de8202016-04-18 18:52:39 +0000489 std::unique_ptr<LLIObjectCache> CacheManager;
Lang Hames173c69f2014-01-08 04:09:09 +0000490 if (EnableCacheManager) {
Mehdi Aminia7de8202016-04-18 18:52:39 +0000491 CacheManager.reset(new LLIObjectCache(ObjectCacheDir));
492 EE->setObjectCache(CacheManager.get());
Lang Hames173c69f2014-01-08 04:09:09 +0000493 }
494
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000495 // Load any additional modules specified on the command line.
496 for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) {
Rafael Espindolad233b062014-08-26 17:29:46 +0000497 std::unique_ptr<Module> XMod = parseIRFile(ExtraModules[i], Err, Context);
Davide Italianoda8e6b22016-11-17 22:58:13 +0000498 if (!XMod)
499 reportError(Err, argv[0]);
Lang Hames173c69f2014-01-08 04:09:09 +0000500 if (EnableCacheManager) {
Eric Christopher79cc1e32014-09-02 22:28:02 +0000501 std::string CacheName("file:");
502 CacheName.append(ExtraModules[i]);
503 XMod->setModuleIdentifier(CacheName);
Lang Hames173c69f2014-01-08 04:09:09 +0000504 }
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000505 EE->addModule(std::move(XMod));
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000506 }
507
Lang Hames173c69f2014-01-08 04:09:09 +0000508 for (unsigned i = 0, e = ExtraObjects.size(); i != e; ++i) {
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000509 Expected<object::OwningBinary<object::ObjectFile>> Obj =
Rafael Espindola51cc3602014-01-22 00:14:49 +0000510 object::ObjectFile::createObjectFile(ExtraObjects[i]);
Lang Hames173c69f2014-01-08 04:09:09 +0000511 if (!Obj) {
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000512 // TODO: Actually report errors helpfully.
513 consumeError(Obj.takeError());
Davide Italianoda8e6b22016-11-17 22:58:13 +0000514 reportError(Err, argv[0]);
Lang Hames173c69f2014-01-08 04:09:09 +0000515 }
Rafael Espindola061beab2014-08-20 15:19:37 +0000516 object::OwningBinary<object::ObjectFile> &O = Obj.get();
Rafael Espindola7271c192014-08-26 21:04:04 +0000517 EE->addObjectFile(std::move(O));
Lang Hames173c69f2014-01-08 04:09:09 +0000518 }
519
520 for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) {
Rafael Espindola48af1c22014-08-19 18:44:46 +0000521 ErrorOr<std::unique_ptr<MemoryBuffer>> ArBufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000522 MemoryBuffer::getFileOrSTDIN(ExtraArchives[i]);
Davide Italianoda8e6b22016-11-17 22:58:13 +0000523 if (!ArBufOrErr)
524 reportError(Err, argv[0]);
Rafael Espindola48af1c22014-08-19 18:44:46 +0000525 std::unique_ptr<MemoryBuffer> &ArBuf = ArBufOrErr.get();
Rafael Espindolae1923412014-08-01 18:31:17 +0000526
Kevin Enderbyc60a3212016-06-29 20:35:44 +0000527 Expected<std::unique_ptr<object::Archive>> ArOrErr =
Rafael Espindola48af1c22014-08-19 18:44:46 +0000528 object::Archive::create(ArBuf->getMemBufferRef());
Kevin Enderbyc60a3212016-06-29 20:35:44 +0000529 if (!ArOrErr) {
530 std::string Buf;
531 raw_string_ostream OS(Buf);
Jonas Devlieghere45eb84f2018-11-11 01:46:03 +0000532 logAllUnhandledErrors(ArOrErr.takeError(), OS);
Kevin Enderbyc60a3212016-06-29 20:35:44 +0000533 OS.flush();
534 errs() << Buf;
Davide Italiano86511442016-11-17 22:59:13 +0000535 exit(1);
Lang Hames173c69f2014-01-08 04:09:09 +0000536 }
Rafael Espindola48af1c22014-08-19 18:44:46 +0000537 std::unique_ptr<object::Archive> &Ar = ArOrErr.get();
538
539 object::OwningBinary<object::Archive> OB(std::move(Ar), std::move(ArBuf));
540
541 EE->addArchive(std::move(OB));
Lang Hames173c69f2014-01-08 04:09:09 +0000542 }
543
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000544 // If the target is Cygwin/MingW and we are generating remote code, we
545 // need an extra module to help out with linking.
546 if (RemoteMCJIT && Triple(Mod->getTargetTriple()).isOSCygMing()) {
Mehdi Aminia7de8202016-04-18 18:52:39 +0000547 addCygMingExtraModule(*EE, Context, Mod->getTargetTriple());
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000548 }
549
Eli Bendersky5262ad22012-03-13 08:33:15 +0000550 // The following functions have no effect if their respective profiling
551 // support wasn't enabled in the build configuration.
552 EE->RegisterJITEventListener(
553 JITEventListener::createOProfileJITEventListener());
554 EE->RegisterJITEventListener(
555 JITEventListener::createIntelJITEventListener());
Andres Freund376a3d32018-07-24 00:54:06 +0000556 if (!RemoteMCJIT)
557 EE->RegisterJITEventListener(
558 JITEventListener::createPerfJITEventListener());
Jeffrey Yasskin0b08f3d2009-06-25 02:04:04 +0000559
Jim Grosbach0f435d02012-09-05 16:50:34 +0000560 if (!NoLazyCompilation && RemoteMCJIT) {
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000561 WithColor::warning(errs(), argv[0])
562 << "remote mcjit does not support lazy compilation\n";
Jim Grosbach0f435d02012-09-05 16:50:34 +0000563 NoLazyCompilation = true;
564 }
Jeffrey Yasskinaa8814a2009-10-27 22:39:42 +0000565 EE->DisableLazyCompilation(NoLazyCompilation);
Evan Cheng0422bef2008-04-22 06:51:41 +0000566
Chris Lattner2785bdb2007-05-06 04:58:26 +0000567 // If the user specifically requested an argv[0] to pass into the program,
568 // do it now.
569 if (!FakeArgv0.empty()) {
Chris Bienemane71fb5c2015-01-22 01:49:59 +0000570 InputFile = static_cast<std::string>(FakeArgv0);
Chris Lattner2785bdb2007-05-06 04:58:26 +0000571 } else {
572 // Otherwise, if there is a .bc suffix on the executable strip it off, it
573 // might confuse the program.
Benjamin Kramera944a9a2010-04-15 11:33:14 +0000574 if (StringRef(InputFile).endswith(".bc"))
Chris Lattner2785bdb2007-05-06 04:58:26 +0000575 InputFile.erase(InputFile.length() - 3);
576 }
577
578 // Add the module's name to the start of the vector of arguments to main().
579 InputArgv.insert(InputArgv.begin(), InputFile);
580
581 // Call the main function from M as if its signature were:
582 // int main (int argc, char **argv, const char **envp)
583 // using the contents of Args to determine argc & argv, and the contents of
584 // EnvVars to determine envp.
585 //
Evan Cheng61582542008-11-05 23:21:52 +0000586 Function *EntryFn = Mod->getFunction(EntryFunc);
587 if (!EntryFn) {
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000588 WithColor::error(errs(), argv[0])
589 << '\'' << EntryFunc << "\' function not found in module.\n";
Chris Lattner2785bdb2007-05-06 04:58:26 +0000590 return -1;
591 }
592
Chris Lattner2785bdb2007-05-06 04:58:26 +0000593 // Reset errno to zero on entry to main.
594 errno = 0;
Eli Bendersky4c647582012-01-16 08:56:09 +0000595
Lang Hames3fde6522016-04-18 19:55:43 +0000596 int Result = -1;
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000597
Lang Hames9d7a2692016-01-11 16:35:55 +0000598 // Sanity check use of remote-jit: LLI currently only supports use of the
599 // remote JIT on Unix platforms.
Lang Hames9d7a2692016-01-11 16:35:55 +0000600 if (RemoteMCJIT) {
601#ifndef LLVM_ON_UNIX
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000602 WithColor::warning(errs(), argv[0])
Jonas Devlieghere7b5fa242018-04-22 08:35:00 +0000603 << "host does not support external remote targets.\n";
604 WithColor::note() << "defaulting to local execution\n";
Lang Hames4b6e0212016-01-11 21:41:34 +0000605 return -1;
Lang Hames9d7a2692016-01-11 16:35:55 +0000606#else
607 if (ChildExecPath.empty()) {
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000608 WithColor::error(errs(), argv[0])
609 << "-remote-mcjit requires -mcjit-remote-process.\n";
Lang Hames9d7a2692016-01-11 16:35:55 +0000610 exit(1);
611 } else if (!sys::fs::can_execute(ChildExecPath)) {
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000612 WithColor::error(errs(), argv[0])
613 << "unable to find usable child executable: '" << ChildExecPath
614 << "'\n";
Lang Hames9d7a2692016-01-11 16:35:55 +0000615 return -1;
616 }
617#endif
618 }
619
Andrew Kaylor58365b92012-11-27 19:49:00 +0000620 if (!RemoteMCJIT) {
Andrew Kaylor6587bcf2013-10-11 22:47:10 +0000621 // If the program doesn't explicitly call exit, we will need the Exit
622 // function later on to make an explicit call, so get the function now.
James Y Knight13680222019-02-01 02:28:03 +0000623 FunctionCallee Exit = Mod->getOrInsertFunction(
624 "exit", Type::getVoidTy(Context), Type::getInt32Ty(Context));
Andrew Kaylor6587bcf2013-10-11 22:47:10 +0000625
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000626 // Run static constructors.
Eric Christopher79cc1e32014-09-02 22:28:02 +0000627 if (!ForceInterpreter) {
Andrew Kaylorea395922013-10-01 01:47:35 +0000628 // Give MCJIT a chance to apply relocations and set page permissions.
629 EE->finalizeObject();
630 }
631 EE->runStaticConstructorsDestructors(false);
Evan Cheng0422bef2008-04-22 06:51:41 +0000632
NAKAMURA Takumi87e08802013-12-07 11:21:42 +0000633 // Trigger compilation separately so code regions that need to be
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000634 // invalidated will be known.
635 (void)EE->getPointerToFunction(EntryFn);
636 // Clear instruction cache before code will be executed.
637 if (RTDyldMM)
638 static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
639
640 // Run main.
641 Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
642
643 // Run static destructors.
644 EE->runStaticConstructorsDestructors(true);
645
646 // If the program didn't call exit explicitly, we should call it now.
647 // This ensures that any atexit handlers get called correctly.
James Y Knight13680222019-02-01 02:28:03 +0000648 if (Function *ExitF =
649 dyn_cast<Function>(Exit.getCallee()->stripPointerCasts())) {
650 if (ExitF->getFunctionType() == Exit.getFunctionType()) {
651 std::vector<GenericValue> Args;
652 GenericValue ResultGV;
653 ResultGV.IntVal = APInt(32, Result);
654 Args.push_back(ResultGV);
655 EE->runFunction(ExitF, Args);
656 WithColor::error(errs(), argv[0])
657 << "exit(" << Result << ") returned!\n";
658 abort();
659 }
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000660 }
James Y Knight13680222019-02-01 02:28:03 +0000661 WithColor::error(errs(), argv[0]) << "exit defined with wrong prototype!\n";
662 abort();
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000663 } else {
664 // else == "if (RemoteMCJIT)"
665
666 // Remote target MCJIT doesn't (yet) support static constructors. No reason
Hiroshi Inoue0ca79dc2017-07-11 06:04:59 +0000667 // it couldn't. This is a limitation of the LLI implementation, not the
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000668 // MCJIT itself. FIXME.
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000669
Lang Hames9d7a2692016-01-11 16:35:55 +0000670 // Lanch the remote process and get a channel to it.
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000671 std::unique_ptr<FDRawChannel> C = launchRemote();
Lang Hames9d7a2692016-01-11 16:35:55 +0000672 if (!C) {
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000673 WithColor::error(errs(), argv[0]) << "failed to launch remote JIT.\n";
Lang Hames9d7a2692016-01-11 16:35:55 +0000674 exit(1);
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000675 }
676
Lang Hames9d7a2692016-01-11 16:35:55 +0000677 // Create a remote target client running over the channel.
Lang Hamesbd0cb782018-05-30 01:57:45 +0000678 llvm::orc::ExecutionSession ES;
679 ES.setErrorReporter([&](Error Err) { ExitOnErr(std::move(Err)); });
Lang Hames9e68b7342017-09-04 20:54:46 +0000680 typedef orc::remote::OrcRemoteTargetClient MyRemote;
Lang Hamesbd0cb782018-05-30 01:57:45 +0000681 auto R = ExitOnErr(MyRemote::Create(*C, ES));
Jim Grosbach748b9472012-08-28 23:22:30 +0000682
Lang Hames9d7a2692016-01-11 16:35:55 +0000683 // Create a remote memory manager.
Lang Hames9e68b7342017-09-04 20:54:46 +0000684 auto RemoteMM = ExitOnErr(R->createRemoteMemoryManager());
Lang Hames9d7a2692016-01-11 16:35:55 +0000685
686 // Forward MCJIT's memory manager calls to the remote memory manager.
687 static_cast<ForwardingMemoryManager*>(RTDyldMM)->setMemMgr(
688 std::move(RemoteMM));
689
690 // Forward MCJIT's symbol resolution calls to the remote.
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +0000691 static_cast<ForwardingMemoryManager *>(RTDyldMM)->setResolver(
692 orc::createLambdaResolver(
Lang Hames17164542019-07-17 16:40:52 +0000693 AcknowledgeORCv1Deprecation,
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +0000694 [](const std::string &Name) { return nullptr; },
695 [&](const std::string &Name) {
696 if (auto Addr = ExitOnErr(R->getSymbolAddress(Name)))
697 return JITSymbol(Addr, JITSymbolFlags::Exported);
698 return JITSymbol(nullptr);
699 }));
Lang Hames9d7a2692016-01-11 16:35:55 +0000700
701 // Grab the target address of the JIT'd main function on the remote and call
702 // it.
Jim Grosbach0f435d02012-09-05 16:50:34 +0000703 // FIXME: argv and envp handling.
Lang Hamesad4a9112016-08-01 20:49:11 +0000704 JITTargetAddress Entry = EE->getFunctionAddress(EntryFn->getName().str());
Lang Hames9d7a2692016-01-11 16:35:55 +0000705 EE->finalizeObject();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000706 LLVM_DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"
707 << format("%llx", Entry) << "\n");
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000708 Result = ExitOnErr(R->callIntVoid(Entry));
Jim Grosbach0f435d02012-09-05 16:50:34 +0000709
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000710 // Like static constructors, the remote target MCJIT support doesn't handle
711 // this yet. It could. FIXME.
712
Lang Hames9d7a2692016-01-11 16:35:55 +0000713 // Delete the EE - we need to tear it down *before* we terminate the session
714 // with the remote, otherwise it'll crash when it tries to release resources
715 // on a remote that has already been disconnected.
Mehdi Aminia7de8202016-04-18 18:52:39 +0000716 EE.reset();
Lang Hames9d7a2692016-01-11 16:35:55 +0000717
718 // Signal the remote target that we're done JITing.
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000719 ExitOnErr(R->terminateSession());
Chris Lattner2785bdb2007-05-06 04:58:26 +0000720 }
Jim Grosbach0f435d02012-09-05 16:50:34 +0000721
Jim Grosbach0f435d02012-09-05 16:50:34 +0000722 return Result;
Chris Lattnerd7ff5782001-08-23 17:05:04 +0000723}
Lang Hames9d7a2692016-01-11 16:35:55 +0000724
Lang Hames809e9d12019-08-02 15:21:37 +0000725static std::function<void(Module &)> createDebugDumper() {
Lang Hames6a941342018-06-26 21:35:48 +0000726 switch (OrcDumpKind) {
727 case DumpKind::NoDump:
Lang Hames809e9d12019-08-02 15:21:37 +0000728 return [](Module &M) {};
Lang Hames6a941342018-06-26 21:35:48 +0000729
730 case DumpKind::DumpFuncsToStdOut:
Lang Hames809e9d12019-08-02 15:21:37 +0000731 return [](Module &M) {
Lang Hames6a941342018-06-26 21:35:48 +0000732 printf("[ ");
733
Lang Hames809e9d12019-08-02 15:21:37 +0000734 for (const auto &F : M) {
Lang Hames6a941342018-06-26 21:35:48 +0000735 if (F.isDeclaration())
736 continue;
737
738 if (F.hasName()) {
Benjamin Krameradcd0262020-01-28 20:23:46 +0100739 std::string Name(std::string(F.getName()));
Lang Hames6a941342018-06-26 21:35:48 +0000740 printf("%s ", Name.c_str());
741 } else
742 printf("<anon> ");
743 }
744
745 printf("]\n");
Lang Hames6a941342018-06-26 21:35:48 +0000746 };
747
748 case DumpKind::DumpModsToStdOut:
Lang Hames809e9d12019-08-02 15:21:37 +0000749 return [](Module &M) {
750 outs() << "----- Module Start -----\n" << M << "----- Module End -----\n";
Lang Hames6a941342018-06-26 21:35:48 +0000751 };
752
753 case DumpKind::DumpModsToDisk:
Lang Hames809e9d12019-08-02 15:21:37 +0000754 return [](Module &M) {
Lang Hames6a941342018-06-26 21:35:48 +0000755 std::error_code EC;
Fangrui Songd9b948b2019-08-05 05:43:48 +0000756 raw_fd_ostream Out(M.getModuleIdentifier() + ".ll", EC, sys::fs::OF_Text);
Lang Hames6a941342018-06-26 21:35:48 +0000757 if (EC) {
Lang Hames809e9d12019-08-02 15:21:37 +0000758 errs() << "Couldn't open " << M.getModuleIdentifier()
Lang Hames6a941342018-06-26 21:35:48 +0000759 << " for dumping.\nError:" << EC.message() << "\n";
760 exit(1);
761 }
Lang Hames809e9d12019-08-02 15:21:37 +0000762 Out << M;
Lang Hames6a941342018-06-26 21:35:48 +0000763 };
764 }
765 llvm_unreachable("Unknown DumpKind");
766}
767
Lang Hamesb7be6b42020-02-14 14:22:59 -0800768Error loadDylibs() {
769 for (const auto &Dylib : Dylibs) {
770 std::string ErrMsg;
771 if (sys::DynamicLibrary::LoadLibraryPermanently(Dylib.c_str(), &ErrMsg))
772 return make_error<StringError>(ErrMsg, inconvertibleErrorCode());
773 }
774
775 return Error::success();
776}
777
Lang Hames23cb2e72018-10-23 23:01:39 +0000778static void exitOnLazyCallThroughFailure() { exit(1); }
779
Lang Hames37a66412018-08-28 20:20:31 +0000780int runOrcLazyJIT(const char *ProgName) {
781 // Start setting up the JIT environment.
Lang Hames6a941342018-06-26 21:35:48 +0000782
Lang Hames37a66412018-08-28 20:20:31 +0000783 // Parse the main module.
Jonas Devlieghere0eaee542019-08-15 15:54:37 +0000784 orc::ThreadSafeContext TSCtx(std::make_unique<LLVMContext>());
Lang Hames37a66412018-08-28 20:20:31 +0000785 SMDiagnostic Err;
Lang Hames809e9d12019-08-02 15:21:37 +0000786 auto MainModule = parseIRFile(InputFile, Err, *TSCtx.getContext());
Lang Hames37a66412018-08-28 20:20:31 +0000787 if (!MainModule)
788 reportError(Err, ProgName);
789
Lang Hames85fb9972019-12-16 02:50:40 -0800790 Triple TT(MainModule->getTargetTriple());
Lang Hameseb14dc72019-04-29 22:37:27 +0000791 orc::LLLazyJITBuilder Builder;
792
793 Builder.setJITTargetMachineBuilder(
Lang Hames85fb9972019-12-16 02:50:40 -0800794 MainModule->getTargetTriple().empty()
795 ? ExitOnErr(orc::JITTargetMachineBuilder::detectHost())
796 : orc::JITTargetMachineBuilder(TT));
Lang Hames6a941342018-06-26 21:35:48 +0000797
Lang Hamesd435ce42018-09-30 19:12:23 +0000798 if (!MArch.empty())
Lang Hameseb14dc72019-04-29 22:37:27 +0000799 Builder.getJITTargetMachineBuilder()->getTargetTriple().setArchName(MArch);
Lang Hamesd435ce42018-09-30 19:12:23 +0000800
Lang Hames85fb9972019-12-16 02:50:40 -0800801 if (!MainModule->getDataLayout().isDefault())
802 Builder.setDataLayout(MainModule->getDataLayout());
803
Lang Hameseb14dc72019-04-29 22:37:27 +0000804 Builder.getJITTargetMachineBuilder()
805 ->setCPU(getCPUStr())
Lang Hames6a941342018-06-26 21:35:48 +0000806 .addFeatures(getFeatureList())
807 .setRelocationModel(RelocModel.getNumOccurrences()
808 ? Optional<Reloc::Model>(RelocModel)
809 : None)
810 .setCodeModel(CMModel.getNumOccurrences()
811 ? Optional<CodeModel::Model>(CMModel)
812 : None);
Lang Hamesd435ce42018-09-30 19:12:23 +0000813
Lang Hameseb14dc72019-04-29 22:37:27 +0000814 Builder.setLazyCompileFailureAddr(
815 pointerToJITTargetAddress(exitOnLazyCallThroughFailure));
816 Builder.setNumCompileThreads(LazyJITCompileThreads);
Lang Hames23cb2e72018-10-23 23:01:39 +0000817
Lang Hames85fb9972019-12-16 02:50:40 -0800818 // Set up LLJIT platform.
819 {
820 LLJITPlatform P = Platform;
821 if (P == LLJITPlatform::DetectHost) {
822 if (TT.isOSBinFormatMachO())
823 P = LLJITPlatform::MachO;
824 else
825 P = LLJITPlatform::GenericIR;
826 }
827
828 switch (P) {
829 case LLJITPlatform::GenericIR:
830 // Nothing to do: LLJITBuilder will use this by default.
831 break;
832 case LLJITPlatform::MachO:
833 Builder.setPlatformSetUp(orc::setUpMachOPlatform);
834 ExitOnErr(orc::enableObjCRegistration("libobjc.dylib"));
835 break;
836 default:
837 llvm_unreachable("Unrecognized platform value");
838 }
839 }
840
Lang Hameseb14dc72019-04-29 22:37:27 +0000841 auto J = ExitOnErr(Builder.create());
Lang Hames6a941342018-06-26 21:35:48 +0000842
Lang Hames98440292018-09-29 23:49:57 +0000843 if (PerModuleLazy)
Lang Hames079df9a2018-10-15 22:56:10 +0000844 J->setPartitionFunction(orc::CompileOnDemandLayer::compileWholeModule);
Lang Hames98440292018-09-29 23:49:57 +0000845
Lang Hamesadae9bf2018-07-02 22:30:18 +0000846 auto Dump = createDebugDumper();
847
Lang Hamese9e26c02020-01-14 18:14:00 -0800848 J->getIRTransformLayer().setTransform(
849 [&](orc::ThreadSafeModule TSM,
850 const orc::MaterializationResponsibility &R) {
851 TSM.withModuleDo([&](Module &M) {
852 if (verifyModule(M, &dbgs())) {
853 dbgs() << "Bad module: " << &M << "\n";
854 exit(1);
855 }
856 Dump(M);
857 });
858 return TSM;
859 });
Lang Hames6a941342018-06-26 21:35:48 +0000860
Lang Hameseb14dc72019-04-29 22:37:27 +0000861 orc::MangleAndInterner Mangle(J->getExecutionSession(), J->getDataLayout());
Lang Hamesce2207a2020-01-21 16:28:30 -0800862
863 // Unless they've been explicitly disabled, make process symbols available to
864 // JIT'd code.
865 if (!NoProcessSymbols)
866 J->getMainJITDylib().addGenerator(
867 ExitOnErr(orc::DynamicLibrarySearchGenerator::GetForCurrentProcess(
868 J->getDataLayout().getGlobalPrefix(),
869 [MainName = Mangle("main")](const orc::SymbolStringPtr &Name) {
870 return Name != MainName;
871 })));
Lang Hames35598312020-01-02 15:47:47 -0800872
Lang Hames37a66412018-08-28 20:20:31 +0000873 // Add the main module.
Lang Hames809e9d12019-08-02 15:21:37 +0000874 ExitOnErr(
875 J->addLazyIRModule(orc::ThreadSafeModule(std::move(MainModule), TSCtx)));
Lang Hames37a66412018-08-28 20:20:31 +0000876
Lang Hames23cb2e72018-10-23 23:01:39 +0000877 // Create JITDylibs and add any extra modules.
878 {
879 // Create JITDylibs, keep a map from argument index to dylib. We will use
880 // -extra-module argument indexes to determine what dylib to use for each
881 // -extra-module.
882 std::map<unsigned, orc::JITDylib *> IdxToDylib;
883 IdxToDylib[0] = &J->getMainJITDylib();
884 for (auto JDItr = JITDylibs.begin(), JDEnd = JITDylibs.end();
885 JDItr != JDEnd; ++JDItr) {
Lang Hamesa2ee80b2019-05-21 22:07:53 +0000886 orc::JITDylib *JD = J->getJITDylibByName(*JDItr);
Lang Hames85fb9972019-12-16 02:50:40 -0800887 if (!JD) {
888 JD = &ExitOnErr(J->createJITDylib(*JDItr));
889 J->getMainJITDylib().addToSearchOrder(*JD);
890 JD->addToSearchOrder(J->getMainJITDylib());
891 }
Lang Hamesa2ee80b2019-05-21 22:07:53 +0000892 IdxToDylib[JITDylibs.getPosition(JDItr - JITDylibs.begin())] = JD;
Lang Hames23cb2e72018-10-23 23:01:39 +0000893 }
Lang Hames37a66412018-08-28 20:20:31 +0000894
Lang Hames23cb2e72018-10-23 23:01:39 +0000895 for (auto EMItr = ExtraModules.begin(), EMEnd = ExtraModules.end();
896 EMItr != EMEnd; ++EMItr) {
897 auto M = parseIRFile(*EMItr, Err, *TSCtx.getContext());
898 if (!M)
899 reportError(Err, ProgName);
900
901 auto EMIdx = ExtraModules.getPosition(EMItr - ExtraModules.begin());
902 assert(EMIdx != 0 && "ExtraModule should have index > 0");
903 auto JDItr = std::prev(IdxToDylib.lower_bound(EMIdx));
904 auto &JD = *JDItr->second;
905 ExitOnErr(
906 J->addLazyIRModule(JD, orc::ThreadSafeModule(std::move(M), TSCtx)));
907 }
Lang Hames52a34a72019-08-13 16:05:18 +0000908
909 for (auto EAItr = ExtraArchives.begin(), EAEnd = ExtraArchives.end();
910 EAItr != EAEnd; ++EAItr) {
911 auto EAIdx = ExtraArchives.getPosition(EAItr - ExtraArchives.begin());
912 assert(EAIdx != 0 && "ExtraArchive should have index > 0");
913 auto JDItr = std::prev(IdxToDylib.lower_bound(EAIdx));
914 auto &JD = *JDItr->second;
915 JD.addGenerator(ExitOnErr(orc::StaticLibraryDefinitionGenerator::Load(
916 J->getObjLinkingLayer(), EAItr->c_str())));
917 }
Lang Hamesadae9bf2018-07-02 22:30:18 +0000918 }
Lang Hames6a941342018-06-26 21:35:48 +0000919
Lang Hames37a66412018-08-28 20:20:31 +0000920 // Add the objects.
921 for (auto &ObjPath : ExtraObjects) {
922 auto Obj = ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(ObjPath)));
923 ExitOnErr(J->addObjectFile(std::move(Obj)));
924 }
925
Lang Hames37a66412018-08-28 20:20:31 +0000926 // Run any static constructors.
Lang Hames85fb9972019-12-16 02:50:40 -0800927 ExitOnErr(J->initialize(J->getMainJITDylib()));
Lang Hames6a941342018-06-26 21:35:48 +0000928
Lang Hamesf0a3fd882018-09-26 16:26:59 +0000929 // Run any -thread-entry points.
930 std::vector<std::thread> AltEntryThreads;
931 for (auto &ThreadEntryPoint : ThreadEntryPoints) {
932 auto EntryPointSym = ExitOnErr(J->lookup(ThreadEntryPoint));
933 typedef void (*EntryPointPtr)();
934 auto EntryPoint =
935 reinterpret_cast<EntryPointPtr>(static_cast<uintptr_t>(EntryPointSym.getAddress()));
936 AltEntryThreads.push_back(std::thread([EntryPoint]() { EntryPoint(); }));
937 }
938
Lang Hames37a66412018-08-28 20:20:31 +0000939 // Run main.
Lang Hames6a941342018-06-26 21:35:48 +0000940 auto MainSym = ExitOnErr(J->lookup("main"));
Lang Hames94fe9d42018-09-27 19:27:19 +0000941
Lang Hamesece8fed2019-12-02 01:45:49 -0800942 typedef int (*MainFnPtr)(int, char *[]);
943 auto Result = orc::runAsMain(
Lang Hames2cdb18a2020-01-11 12:58:38 -0800944 jitTargetAddressToFunction<MainFnPtr>(MainSym.getAddress()), InputArgv,
945 StringRef(InputFile));
Lang Hames6a941342018-06-26 21:35:48 +0000946
Lang Hamesf0a3fd882018-09-26 16:26:59 +0000947 // Wait for -entry-point threads.
948 for (auto &AltEntryThread : AltEntryThreads)
949 AltEntryThread.join();
Hans Wennborg20b5abe2018-09-26 12:15:23 +0000950
Lang Hamesf0a3fd882018-09-26 16:26:59 +0000951 // Run destructors.
Lang Hames85fb9972019-12-16 02:50:40 -0800952 ExitOnErr(J->deinitialize(J->getMainJITDylib()));
Lang Hames6a941342018-06-26 21:35:48 +0000953
954 return Result;
955}
956
Lang Hames98440292018-09-29 23:49:57 +0000957void disallowOrcOptions() {
958 // Make sure nobody used an orc-lazy specific option accidentally.
959
960 if (LazyJITCompileThreads != 0) {
961 errs() << "-compile-threads requires -jit-kind=orc-lazy\n";
962 exit(1);
963 }
964
965 if (!ThreadEntryPoints.empty()) {
966 errs() << "-thread-entry requires -jit-kind=orc-lazy\n";
967 exit(1);
968 }
969
970 if (PerModuleLazy) {
971 errs() << "-per-module-lazy requires -jit-kind=orc-lazy\n";
972 exit(1);
973 }
974}
975
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000976std::unique_ptr<FDRawChannel> launchRemote() {
Lang Hames9d7a2692016-01-11 16:35:55 +0000977#ifndef LLVM_ON_UNIX
978 llvm_unreachable("launchRemote not supported on non-Unix platforms");
979#else
980 int PipeFD[2][2];
981 pid_t ChildPID;
982
983 // Create two pipes.
984 if (pipe(PipeFD[0]) != 0 || pipe(PipeFD[1]) != 0)
985 perror("Error creating pipe: ");
986
987 ChildPID = fork();
988
989 if (ChildPID == 0) {
990 // In the child...
991
992 // Close the parent ends of the pipes
993 close(PipeFD[0][1]);
994 close(PipeFD[1][0]);
995
996
997 // Execute the child process.
998 std::unique_ptr<char[]> ChildPath, ChildIn, ChildOut;
999 {
1000 ChildPath.reset(new char[ChildExecPath.size() + 1]);
1001 std::copy(ChildExecPath.begin(), ChildExecPath.end(), &ChildPath[0]);
1002 ChildPath[ChildExecPath.size()] = '\0';
NAKAMURA Takumicef0a8212016-01-15 02:14:46 +00001003 std::string ChildInStr = utostr(PipeFD[0][0]);
Lang Hames9d7a2692016-01-11 16:35:55 +00001004 ChildIn.reset(new char[ChildInStr.size() + 1]);
1005 std::copy(ChildInStr.begin(), ChildInStr.end(), &ChildIn[0]);
1006 ChildIn[ChildInStr.size()] = '\0';
NAKAMURA Takumicef0a8212016-01-15 02:14:46 +00001007 std::string ChildOutStr = utostr(PipeFD[1][1]);
Lang Hames9d7a2692016-01-11 16:35:55 +00001008 ChildOut.reset(new char[ChildOutStr.size() + 1]);
1009 std::copy(ChildOutStr.begin(), ChildOutStr.end(), &ChildOut[0]);
1010 ChildOut[ChildOutStr.size()] = '\0';
1011 }
1012
1013 char * const args[] = { &ChildPath[0], &ChildIn[0], &ChildOut[0], nullptr };
1014 int rc = execv(ChildExecPath.c_str(), args);
1015 if (rc != 0)
1016 perror("Error executing child process: ");
1017 llvm_unreachable("Error executing child process");
1018 }
1019 // else we're the parent...
1020
1021 // Close the child ends of the pipes
1022 close(PipeFD[0][0]);
1023 close(PipeFD[1][1]);
1024
1025 // Return an RPC channel connected to our end of the pipes.
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00001026 return std::make_unique<FDRawChannel>(PipeFD[1][0], PipeFD[0][1]);
Lang Hames9d7a2692016-01-11 16:35:55 +00001027#endif
1028}