blob: 091ca22b4e82c52a5505ab93c870747ec5557e57 [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 Hames9528bba2015-03-25 12:11:48 +000016#include "OrcLazyJIT.h"
Lang Hames9d7a2692016-01-11 16:35:55 +000017#include "RemoteJITUtils.h"
18#include "llvm/IR/LLVMContext.h"
NAKAMURA Takumicef0a8212016-01-15 02:14:46 +000019#include "llvm/ADT/StringExtras.h"
Duncan Sands3bd97fe2010-08-28 01:30:02 +000020#include "llvm/ADT/Triple.h"
Teresa Johnsonad176792016-11-11 05:34:58 +000021#include "llvm/Bitcode/BitcodeReader.h"
Chris Lattner5af6a3f2006-08-01 22:34:35 +000022#include "llvm/CodeGen/LinkAllCodegenComponents.h"
Brian Gaekee99ca442003-09-05 19:42:34 +000023#include "llvm/ExecutionEngine/GenericValue.h"
Jeffrey Yasskin0b08f3d2009-06-25 02:04:04 +000024#include "llvm/ExecutionEngine/Interpreter.h"
Jeffrey Yasskin0b08f3d2009-06-25 02:04:04 +000025#include "llvm/ExecutionEngine/JITEventListener.h"
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000026#include "llvm/ExecutionEngine/MCJIT.h"
Lang Hames173c69f2014-01-08 04:09:09 +000027#include "llvm/ExecutionEngine/ObjectCache.h"
Lang Hames93de2a12015-01-23 21:25:00 +000028#include "llvm/ExecutionEngine/OrcMCJITReplacement.h"
Andrew Kaylor58365b92012-11-27 19:49:00 +000029#include "llvm/ExecutionEngine/SectionMemoryManager.h"
Lang Hames9d7a2692016-01-11 16:35:55 +000030#include "llvm/ExecutionEngine/Orc/OrcRemoteTargetClient.h"
Andrew Kaylor1ca510e2013-10-29 01:29:56 +000031#include "llvm/IR/IRBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/Module.h"
33#include "llvm/IR/Type.h"
Andrew Kaylor1ca510e2013-10-29 01:29:56 +000034#include "llvm/IR/TypeBuilder.h"
Chandler Carruthe60e57b2013-03-26 02:25:37 +000035#include "llvm/IRReader/IRReader.h"
Lang Hames173c69f2014-01-08 04:09:09 +000036#include "llvm/Object/Archive.h"
37#include "llvm/Object/ObjectFile.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000038#include "llvm/Support/CommandLine.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000039#include "llvm/Support/Debug.h"
40#include "llvm/Support/DynamicLibrary.h"
41#include "llvm/Support/Format.h"
Chris Lattner76d46322006-12-06 01:18:01 +000042#include "llvm/Support/ManagedStatic.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000043#include "llvm/Support/MathExtras.h"
44#include "llvm/Support/Memory.h"
Chris Lattner2785bdb2007-05-06 04:58:26 +000045#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer16132e62015-03-23 18:07:13 +000046#include "llvm/Support/Path.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000047#include "llvm/Support/PluginLoader.h"
Chris Lattnere3fc2d12009-03-06 05:34:10 +000048#include "llvm/Support/PrettyStackTrace.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000049#include "llvm/Support/Process.h"
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +000050#include "llvm/Support/Program.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000051#include "llvm/Support/Signals.h"
Chandler Carruthe60e57b2013-03-26 02:25:37 +000052#include "llvm/Support/SourceMgr.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000053#include "llvm/Support/TargetSelect.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000054#include "llvm/Support/raw_ostream.h"
Daniel Maleaa960c542013-06-28 19:11:40 +000055#include "llvm/Transforms/Instrumentation.h"
Chris Lattner4c522b92007-04-27 17:02:33 +000056#include <cerrno>
NAKAMURA Takumi15304872010-10-22 14:53:59 +000057
58#ifdef __CYGWIN__
59#include <cygwin/version.h>
60#if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
61#define DO_NOTHING_ATEXIT 1
62#endif
63#endif
64
Brian Gaeke960707c2003-11-11 22:41:34 +000065using namespace llvm;
66
Chandler Carruthf98597a2014-04-22 03:10:36 +000067#define DEBUG_TYPE "lli"
68
Chris Lattnera0d7b082002-12-23 23:59:41 +000069namespace {
Lang Hames9528bba2015-03-25 12:11:48 +000070
71 enum class JITKind { MCJIT, OrcMCJITReplacement, OrcLazy };
72
Chris Lattnera0d7b082002-12-23 23:59:41 +000073 cl::opt<std::string>
Gabor Greife16561c2007-07-05 17:07:56 +000074 InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
Chris Lattnerf5cad152002-07-22 02:10:13 +000075
Chris Lattnera0d7b082002-12-23 23:59:41 +000076 cl::list<std::string>
77 InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
Chris Lattnerf5cad152002-07-22 02:10:13 +000078
Chris Lattnera0d7b082002-12-23 23:59:41 +000079 cl::opt<bool> ForceInterpreter("force-interpreter",
Misha Brukmanc2186e32003-09-25 18:10:34 +000080 cl::desc("Force interpretation: disable JIT"),
81 cl::init(false));
Evan Cheng06d988e2008-08-08 08:12:06 +000082
Lang Hames9528bba2015-03-25 12:11:48 +000083 cl::opt<JITKind> UseJITKind("jit-kind",
84 cl::desc("Choose underlying JIT kind."),
85 cl::init(JITKind::MCJIT),
86 cl::values(
87 clEnumValN(JITKind::MCJIT, "mcjit",
88 "MCJIT"),
89 clEnumValN(JITKind::OrcMCJITReplacement,
90 "orc-mcjit",
91 "Orc-based MCJIT replacement"),
92 clEnumValN(JITKind::OrcLazy,
93 "orc-lazy",
Mehdi Amini732afdd2016-10-08 19:41:06 +000094 "Orc-based lazy JIT.")));
Lang Hames93de2a12015-01-23 21:25:00 +000095
Jim Grosbach0f435d02012-09-05 16:50:34 +000096 // The MCJIT supports building for a target address space separate from
97 // the JIT compilation process. Use a forked process and a copying
98 // memory manager with IPC to execute using this functionality.
99 cl::opt<bool> RemoteMCJIT("remote-mcjit",
100 cl::desc("Execute MCJIT'ed code in a separate process."),
101 cl::init(false));
102
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000103 // Manually specify the child process for remote execution. This overrides
104 // the simulated remote execution that allocates address space for child
Andrew Kaylor89352582013-10-29 01:33:14 +0000105 // execution. The child process will be executed and will communicate with
106 // lli via stdin/stdout pipes.
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000107 cl::opt<std::string>
Alp Tokera1186382014-01-22 21:52:35 +0000108 ChildExecPath("mcjit-remote-process",
109 cl::desc("Specify the filename of the process to launch "
110 "for remote MCJIT execution. If none is specified,"
111 "\n\tremote execution will be simulated in-process."),
112 cl::value_desc("filename"), cl::init(""));
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000113
Evan Cheng09bd0b12009-05-04 23:05:19 +0000114 // Determine optimization level.
115 cl::opt<char>
116 OptLevel("O",
117 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
118 "(default = '-O2')"),
119 cl::Prefix,
120 cl::ZeroOrMore,
121 cl::init(' '));
Evan Cheng06d988e2008-08-08 08:12:06 +0000122
Chris Lattner76766cb2005-12-16 05:00:21 +0000123 cl::opt<std::string>
Chris Lattner78e9e102005-12-16 05:19:18 +0000124 TargetTriple("mtriple", cl::desc("Override target triple for module"));
Evan Cheng61582542008-11-05 23:21:52 +0000125
126 cl::opt<std::string>
Jeffrey Yasskin31faeff2010-02-05 16:19:36 +0000127 MArch("march",
128 cl::desc("Architecture to generate assembly for (see --version)"));
129
130 cl::opt<std::string>
131 MCPU("mcpu",
132 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
133 cl::value_desc("cpu-name"),
134 cl::init(""));
135
136 cl::list<std::string>
137 MAttrs("mattr",
138 cl::CommaSeparated,
139 cl::desc("Target specific attributes (-mattr=help for details)"),
140 cl::value_desc("a1,+a2,-a3,..."));
141
142 cl::opt<std::string>
Evan Cheng61582542008-11-05 23:21:52 +0000143 EntryFunc("entry-function",
144 cl::desc("Specify the entry function (default = 'main') "
145 "of the executable"),
146 cl::value_desc("function"),
147 cl::init("main"));
Eli Bendersky4c647582012-01-16 08:56:09 +0000148
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000149 cl::list<std::string>
Andrew Kaylor4404eb42013-10-28 21:58:15 +0000150 ExtraModules("extra-module",
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000151 cl::desc("Extra modules to be loaded"),
Alp Toker0a09ebf2013-10-28 22:51:25 +0000152 cl::value_desc("input bitcode"));
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000153
Lang Hames173c69f2014-01-08 04:09:09 +0000154 cl::list<std::string>
155 ExtraObjects("extra-object",
156 cl::desc("Extra object files to be loaded"),
157 cl::value_desc("input object"));
158
159 cl::list<std::string>
160 ExtraArchives("extra-archive",
161 cl::desc("Extra archive files to be loaded"),
162 cl::value_desc("input archive"));
163
164 cl::opt<bool>
165 EnableCacheManager("enable-cache-manager",
Lang Hames1ddecc02014-01-09 05:24:05 +0000166 cl::desc("Use cache manager to save/load mdoules"),
Lang Hames173c69f2014-01-08 04:09:09 +0000167 cl::init(false));
168
Chris Lattner55644062003-10-28 22:51:44 +0000169 cl::opt<std::string>
Lang Hames1ddecc02014-01-09 05:24:05 +0000170 ObjectCacheDir("object-cache-dir",
171 cl::desc("Directory to store cached object files "
172 "(must be user writable)"),
173 cl::init(""));
174
175 cl::opt<std::string>
Chris Lattner55644062003-10-28 22:51:44 +0000176 FakeArgv0("fake-argv0",
177 cl::desc("Override the 'argv[0]' value passed into the executing"
178 " program"), cl::value_desc("executable"));
Eli Bendersky4c647582012-01-16 08:56:09 +0000179
Chris Lattner3f0ffd32006-09-14 06:17:09 +0000180 cl::opt<bool>
181 DisableCoreFiles("disable-core-files", cl::Hidden,
182 cl::desc("Disable emission of core files if possible"));
Evan Cheng0422bef2008-04-22 06:51:41 +0000183
184 cl::opt<bool>
Evan Cheng16f036c2008-05-21 18:20:21 +0000185 NoLazyCompilation("disable-lazy-compilation",
Evan Cheng0422bef2008-04-22 06:51:41 +0000186 cl::desc("Disable JIT lazy compilation"),
187 cl::init(false));
Evan Cheng2129f592011-07-19 06:37:02 +0000188
Rafael Espindola8c34dd82016-05-18 22:04:49 +0000189 cl::opt<Reloc::Model> RelocModel(
190 "relocation-model", cl::desc("Choose relocation model"),
191 cl::values(
192 clEnumValN(Reloc::Static, "static", "Non-relocatable code"),
193 clEnumValN(Reloc::PIC_, "pic",
194 "Fully relocatable, position independent code"),
195 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
Mehdi Amini732afdd2016-10-08 19:41:06 +0000196 "Relocatable external references, non-relocatable code")));
Evan Chengefd9b422011-07-20 07:51:56 +0000197
198 cl::opt<llvm::CodeModel::Model>
199 CMModel("code-model",
200 cl::desc("Choose code model"),
201 cl::init(CodeModel::JITDefault),
202 cl::values(clEnumValN(CodeModel::JITDefault, "default",
203 "Target default JIT code model"),
204 clEnumValN(CodeModel::Small, "small",
205 "Small code model"),
206 clEnumValN(CodeModel::Kernel, "kernel",
207 "Kernel code model"),
208 clEnumValN(CodeModel::Medium, "medium",
209 "Medium code model"),
210 clEnumValN(CodeModel::Large, "large",
Mehdi Amini732afdd2016-10-08 19:41:06 +0000211 "Large code model")));
Evan Chengefd9b422011-07-20 07:51:56 +0000212
Nick Lewyckyb0e97892012-04-18 08:34:12 +0000213 cl::opt<bool>
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000214 GenerateSoftFloatCalls("soft-float",
215 cl::desc("Generate software floating point library calls"),
216 cl::init(false));
217
218 cl::opt<llvm::FloatABI::ABIType>
219 FloatABIForCalls("float-abi",
220 cl::desc("Choose float ABI type"),
221 cl::init(FloatABI::Default),
222 cl::values(
223 clEnumValN(FloatABI::Default, "default",
224 "Target default float ABI type"),
225 clEnumValN(FloatABI::Soft, "soft",
226 "Soft float ABI (implied by -soft-float)"),
227 clEnumValN(FloatABI::Hard, "hard",
Mehdi Amini732afdd2016-10-08 19:41:06 +0000228 "Hard float ABI (uses FP registers)")));
Lang Hamesef5a0ee2016-04-25 19:56:45 +0000229
230 ExitOnError ExitOnErr;
Chris Lattnera0d7b082002-12-23 23:59:41 +0000231}
Chris Lattner009f8102001-10-27 08:43:52 +0000232
Lang Hames173c69f2014-01-08 04:09:09 +0000233//===----------------------------------------------------------------------===//
234// Object cache
235//
Lang Hames1ddecc02014-01-09 05:24:05 +0000236// This object cache implementation writes cached objects to disk to the
237// directory specified by CacheDir, using a filename provided in the module
238// descriptor. The cache tries to load a saved object using that path if the
239// file exists. CacheDir defaults to "", in which case objects are cached
NAKAMURA Takumif462f9c2014-01-10 10:38:28 +0000240// alongside their originating bitcodes.
Lang Hames173c69f2014-01-08 04:09:09 +0000241//
242class LLIObjectCache : public ObjectCache {
243public:
Lang Hames1ddecc02014-01-09 05:24:05 +0000244 LLIObjectCache(const std::string& CacheDir) : CacheDir(CacheDir) {
245 // Add trailing '/' to cache dir if necessary.
Lang Hamesf9dd8fd2014-01-09 05:29:59 +0000246 if (!this->CacheDir.empty() &&
247 this->CacheDir[this->CacheDir.size() - 1] != '/')
NAKAMURA Takumif462f9c2014-01-10 10:38:28 +0000248 this->CacheDir += '/';
Lang Hames1ddecc02014-01-09 05:24:05 +0000249 }
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000250 ~LLIObjectCache() override {}
Lang Hames173c69f2014-01-08 04:09:09 +0000251
Rafael Espindola48af1c22014-08-19 18:44:46 +0000252 void notifyObjectCompiled(const Module *M, MemoryBufferRef Obj) override {
Benjamin Kramer46e38f32016-06-08 10:01:20 +0000253 const std::string &ModuleID = M->getModuleIdentifier();
Lang Hames173c69f2014-01-08 04:09:09 +0000254 std::string CacheName;
255 if (!getCacheFilename(ModuleID, CacheName))
256 return;
NAKAMURA Takumi390e0602014-01-10 10:38:34 +0000257 if (!CacheDir.empty()) { // Create user-defined cache dir.
Rafael Espindolaf662e002015-07-15 21:24:07 +0000258 SmallString<128> dir(sys::path::parent_path(CacheName));
NAKAMURA Takumi390e0602014-01-10 10:38:34 +0000259 sys::fs::create_directories(Twine(dir));
260 }
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000261 std::error_code EC;
262 raw_fd_ostream outfile(CacheName, EC, sys::fs::F_None);
Rafael Espindola48af1c22014-08-19 18:44:46 +0000263 outfile.write(Obj.getBufferStart(), Obj.getBufferSize());
Lang Hames173c69f2014-01-08 04:09:09 +0000264 outfile.close();
265 }
266
Rafael Espindola5f2bb7d2014-08-13 18:49:01 +0000267 std::unique_ptr<MemoryBuffer> getObject(const Module* M) override {
Benjamin Kramer46e38f32016-06-08 10:01:20 +0000268 const std::string &ModuleID = M->getModuleIdentifier();
Lang Hames173c69f2014-01-08 04:09:09 +0000269 std::string CacheName;
270 if (!getCacheFilename(ModuleID, CacheName))
Craig Toppere6cb63e2014-04-25 04:24:47 +0000271 return nullptr;
Lang Hames173c69f2014-01-08 04:09:09 +0000272 // Load the object from the cache filename
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000273 ErrorOr<std::unique_ptr<MemoryBuffer>> IRObjectBuffer =
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000274 MemoryBuffer::getFile(CacheName, -1, false);
Lang Hames173c69f2014-01-08 04:09:09 +0000275 // If the file isn't there, that's OK.
276 if (!IRObjectBuffer)
Craig Toppere6cb63e2014-04-25 04:24:47 +0000277 return nullptr;
Lang Hames173c69f2014-01-08 04:09:09 +0000278 // MCJIT will want to write into this buffer, and we don't want that
279 // because the file has probably just been mmapped. Instead we make
280 // a copy. The filed-based buffer will be released when it goes
281 // out of scope.
Rafael Espindola3560ff22014-08-27 20:03:13 +0000282 return MemoryBuffer::getMemBufferCopy(IRObjectBuffer.get()->getBuffer());
Lang Hames173c69f2014-01-08 04:09:09 +0000283 }
284
285private:
Lang Hames1ddecc02014-01-09 05:24:05 +0000286 std::string CacheDir;
287
Lang Hames173c69f2014-01-08 04:09:09 +0000288 bool getCacheFilename(const std::string &ModID, std::string &CacheName) {
289 std::string Prefix("file:");
290 size_t PrefixLength = Prefix.length();
291 if (ModID.substr(0, PrefixLength) != Prefix)
292 return false;
NAKAMURA Takumid7fd6d92014-01-10 10:38:40 +0000293 std::string CacheSubdir = ModID.substr(PrefixLength);
294#if defined(_WIN32)
295 // Transform "X:\foo" => "/X\foo" for convenience.
296 if (isalpha(CacheSubdir[0]) && CacheSubdir[1] == ':') {
297 CacheSubdir[1] = CacheSubdir[0];
298 CacheSubdir[0] = '/';
299 }
300#endif
301 CacheName = CacheDir + CacheSubdir;
Lang Hames173c69f2014-01-08 04:09:09 +0000302 size_t pos = CacheName.rfind('.');
303 CacheName.replace(pos, CacheName.length() - pos, ".o");
304 return true;
305 }
306};
307
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000308// On Mingw and Cygwin, an external symbol named '__main' is called from the
Simon Pilgrimdae11f72016-11-20 13:31:13 +0000309// generated 'main' function to allow static initialization. To avoid linking
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000310// problems with remote targets (because lli's remote target support does not
311// currently handle external linking) we add a secondary module which defines
312// an empty '__main' function.
Mehdi Aminia7de8202016-04-18 18:52:39 +0000313static void addCygMingExtraModule(ExecutionEngine &EE, LLVMContext &Context,
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000314 StringRef TargetTripleStr) {
315 IRBuilder<> Builder(Context);
316 Triple TargetTriple(TargetTripleStr);
317
318 // Create a new module.
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000319 std::unique_ptr<Module> M = make_unique<Module>("CygMingHelper", Context);
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000320 M->setTargetTriple(TargetTripleStr);
321
322 // Create an empty function named "__main".
323 Function *Result;
324 if (TargetTriple.isArch64Bit()) {
325 Result = Function::Create(
326 TypeBuilder<int64_t(void), false>::get(Context),
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000327 GlobalValue::ExternalLinkage, "__main", M.get());
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000328 } else {
329 Result = Function::Create(
330 TypeBuilder<int32_t(void), false>::get(Context),
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000331 GlobalValue::ExternalLinkage, "__main", M.get());
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000332 }
333 BasicBlock *BB = BasicBlock::Create(Context, "__main", Result);
334 Builder.SetInsertPoint(BB);
335 Value *ReturnVal;
336 if (TargetTriple.isArch64Bit())
337 ReturnVal = ConstantInt::get(Context, APInt(64, 0));
338 else
339 ReturnVal = ConstantInt::get(Context, APInt(32, 0));
340 Builder.CreateRet(ReturnVal);
341
342 // Add this new module to the ExecutionEngine.
Mehdi Aminia7de8202016-04-18 18:52:39 +0000343 EE.addModule(std::move(M));
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000344}
345
Lang Hames1899d0c2015-06-09 02:43:27 +0000346CodeGenOpt::Level getOptLevel() {
347 switch (OptLevel) {
348 default:
349 errs() << "lli: Invalid optimization level.\n";
350 exit(1);
351 case '0': return CodeGenOpt::None;
352 case '1': return CodeGenOpt::Less;
353 case ' ':
354 case '2': return CodeGenOpt::Default;
355 case '3': return CodeGenOpt::Aggressive;
356 }
357 llvm_unreachable("Unrecognized opt level.");
358}
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000359
Davide Italianoda8e6b22016-11-17 22:58:13 +0000360LLVM_ATTRIBUTE_NORETURN
361static void reportError(SMDiagnostic Err, const char *ProgName) {
362 Err.print(ProgName, errs());
363 exit(1);
364}
365
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) {
Richard Smith2ad6d482016-06-09 00:53:21 +0000370 sys::PrintStackTraceOnErrorSignal(argv[0]);
Chris Lattnere3fc2d12009-03-06 05:34:10 +0000371 PrettyStackTraceProgram X(argc, argv);
Eli Bendersky4c647582012-01-16 08:56:09 +0000372
Mehdi Aminia7de8202016-04-18 18:52:39 +0000373 atexit(llvm_shutdown); // Call llvm_shutdown() on exit.
Daniel Dunbar3d92d932009-07-16 02:04:54 +0000374
Lang Hamesef5a0ee2016-04-25 19:56:45 +0000375 if (argc > 1)
376 ExitOnErr.setBanner(std::string(argv[0]) + ": ");
377
Daniel Dunbar3d92d932009-07-16 02:04:54 +0000378 // If we have a native target, initialize it to ensure it is linked in and
379 // usable by the JIT.
380 InitializeNativeTarget();
Jim Grosbach7b162492011-03-18 22:48:41 +0000381 InitializeNativeTargetAsmPrinter();
Jim Grosbach2cce3f92012-11-05 19:06:05 +0000382 InitializeNativeTargetAsmParser();
Daniel Dunbar3d92d932009-07-16 02:04:54 +0000383
Chris Lattner2785bdb2007-05-06 04:58:26 +0000384 cl::ParseCommandLineOptions(argc, argv,
Dan Gohman2c6a8212007-10-08 15:45:12 +0000385 "llvm interpreter & dynamic compiler\n");
Reid Spencer996ec722004-12-30 05:36:08 +0000386
Chris Lattner2785bdb2007-05-06 04:58:26 +0000387 // If the user doesn't want core files, disable them.
388 if (DisableCoreFiles)
389 sys::Process::PreventCoreFiles();
Eli Bendersky4c647582012-01-16 08:56:09 +0000390
Mehdi Aminia7de8202016-04-18 18:52:39 +0000391 LLVMContext Context;
392
Gabor Greife16561c2007-07-05 17:07:56 +0000393 // Load the bitcode...
Daniel Dunbar9589bf82010-11-13 00:28:01 +0000394 SMDiagnostic Err;
Rafael Espindolad233b062014-08-26 17:29:46 +0000395 std::unique_ptr<Module> Owner = parseIRFile(InputFile, Err, Context);
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000396 Module *Mod = Owner.get();
Davide Italianoda8e6b22016-11-17 22:58:13 +0000397 if (!Mod)
398 reportError(Err, argv[0]);
Chris Lattner2785bdb2007-05-06 04:58:26 +0000399
Lang Hames368c4222016-08-02 21:00:40 +0000400 if (UseJITKind == JITKind::OrcLazy) {
401 std::vector<std::unique_ptr<Module>> Ms;
402 Ms.push_back(std::move(Owner));
403 for (auto &ExtraMod : ExtraModules) {
404 Ms.push_back(parseIRFile(ExtraMod, Err, Context));
Davide Italianoda8e6b22016-11-17 22:58:13 +0000405 if (!Ms.back())
406 reportError(Err, argv[0]);
Lang Hames368c4222016-08-02 21:00:40 +0000407 }
Lang Hames1a2e6562016-10-28 16:52:34 +0000408 std::vector<std::string> Args;
409 Args.push_back(InputFile);
410 for (auto &Arg : InputArgv)
411 Args.push_back(Arg);
412 return runOrcLazyJIT(std::move(Ms), Args);
Lang Hames368c4222016-08-02 21:00:40 +0000413 }
Lang Hames9528bba2015-03-25 12:11:48 +0000414
Lang Hames173c69f2014-01-08 04:09:09 +0000415 if (EnableCacheManager) {
Eric Christopher79cc1e32014-09-02 22:28:02 +0000416 std::string CacheName("file:");
417 CacheName.append(InputFile);
418 Mod->setModuleIdentifier(CacheName);
Lang Hames173c69f2014-01-08 04:09:09 +0000419 }
420
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000421 // If not jitting lazily, load the whole bitcode file eagerly too.
422 if (NoLazyCompilation) {
Davide Italianob0e067b2016-11-09 21:30:33 +0000423 // Use *argv instead of argv[0] to work around a wrong GCC warning.
424 ExitOnError ExitOnErr(std::string(*argv) +
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000425 ": bitcode didn't read correctly: ");
426 ExitOnErr(Mod->materializeAll());
Evan Cheng0422bef2008-04-22 06:51:41 +0000427 }
Chris Lattner2785bdb2007-05-06 04:58:26 +0000428
Rafael Espindolae9fab9b2014-01-14 23:51:27 +0000429 std::string ErrorMsg;
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000430 EngineBuilder builder(std::move(Owner));
Jeffrey Yasskin31faeff2010-02-05 16:19:36 +0000431 builder.setMArch(MArch);
432 builder.setMCPU(MCPU);
433 builder.setMAttrs(MAttrs);
Rafael Espindola8c34dd82016-05-18 22:04:49 +0000434 if (RelocModel.getNumOccurrences())
435 builder.setRelocationModel(RelocModel);
Evan Chengefd9b422011-07-20 07:51:56 +0000436 builder.setCodeModel(CMModel);
Daniel Dunbara78d8092009-07-18 08:07:13 +0000437 builder.setErrorStr(&ErrorMsg);
438 builder.setEngineKind(ForceInterpreter
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000439 ? EngineKind::Interpreter
440 : EngineKind::JIT);
Lang Hames9528bba2015-03-25 12:11:48 +0000441 builder.setUseOrcMCJITReplacement(UseJITKind == JITKind::OrcMCJITReplacement);
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000442
Chris Lattner2785bdb2007-05-06 04:58:26 +0000443 // If we are supposed to override the target triple, do so now.
444 if (!TargetTriple.empty())
Duncan Sands3bd97fe2010-08-28 01:30:02 +0000445 Mod->setTargetTriple(Triple::normalize(TargetTriple));
Evan Cheng0422bef2008-04-22 06:51:41 +0000446
Eli Bendersky4c647582012-01-16 08:56:09 +0000447 // Enable MCJIT if desired.
Craig Toppere6cb63e2014-04-25 04:24:47 +0000448 RTDyldMemoryManager *RTDyldMM = nullptr;
Eric Christopher79cc1e32014-09-02 22:28:02 +0000449 if (!ForceInterpreter) {
Jim Grosbach0f435d02012-09-05 16:50:34 +0000450 if (RemoteMCJIT)
Lang Hames9d7a2692016-01-11 16:35:55 +0000451 RTDyldMM = new ForwardingMemoryManager();
Jim Grosbach0f435d02012-09-05 16:50:34 +0000452 else
Filip Pizlo9bc53e82013-05-14 19:29:00 +0000453 RTDyldMM = new SectionMemoryManager();
Lang Hames4a5697e2014-12-03 00:51:19 +0000454
455 // Deliberately construct a temp std::unique_ptr to pass in. Do not null out
456 // RTDyldMM: We still use it below, even though we don't own it.
457 builder.setMCJITMemoryManager(
458 std::unique_ptr<RTDyldMemoryManager>(RTDyldMM));
Lang Hames0f154902014-09-23 16:56:02 +0000459 } else if (RemoteMCJIT) {
460 errs() << "error: Remote process execution does not work with the "
461 "interpreter.\n";
462 exit(1);
Eli Bendersky4c647582012-01-16 08:56:09 +0000463 }
Daniel Dunbar70ff8b02010-11-17 16:06:37 +0000464
Lang Hames1899d0c2015-06-09 02:43:27 +0000465 builder.setOptLevel(getOptLevel());
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000466
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000467 TargetOptions Options;
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000468 if (FloatABIForCalls != FloatABI::Default)
469 Options.FloatABIType = FloatABIForCalls;
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000470
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000471 builder.setTargetOptions(Options);
472
Mehdi Aminia7de8202016-04-18 18:52:39 +0000473 std::unique_ptr<ExecutionEngine> EE(builder.create());
Chris Lattnerf840ed72009-07-07 18:31:09 +0000474 if (!EE) {
475 if (!ErrorMsg.empty())
Dan Gohmand8db3762009-07-15 16:35:29 +0000476 errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n";
Chris Lattnerf840ed72009-07-07 18:31:09 +0000477 else
Dan Gohmand8db3762009-07-15 16:35:29 +0000478 errs() << argv[0] << ": unknown error creating EE!\n";
Chris Lattner2785bdb2007-05-06 04:58:26 +0000479 exit(1);
480 }
481
Mehdi Aminia7de8202016-04-18 18:52:39 +0000482 std::unique_ptr<LLIObjectCache> CacheManager;
Lang Hames173c69f2014-01-08 04:09:09 +0000483 if (EnableCacheManager) {
Mehdi Aminia7de8202016-04-18 18:52:39 +0000484 CacheManager.reset(new LLIObjectCache(ObjectCacheDir));
485 EE->setObjectCache(CacheManager.get());
Lang Hames173c69f2014-01-08 04:09:09 +0000486 }
487
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000488 // Load any additional modules specified on the command line.
489 for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) {
Rafael Espindolad233b062014-08-26 17:29:46 +0000490 std::unique_ptr<Module> XMod = parseIRFile(ExtraModules[i], Err, Context);
Davide Italianoda8e6b22016-11-17 22:58:13 +0000491 if (!XMod)
492 reportError(Err, argv[0]);
Lang Hames173c69f2014-01-08 04:09:09 +0000493 if (EnableCacheManager) {
Eric Christopher79cc1e32014-09-02 22:28:02 +0000494 std::string CacheName("file:");
495 CacheName.append(ExtraModules[i]);
496 XMod->setModuleIdentifier(CacheName);
Lang Hames173c69f2014-01-08 04:09:09 +0000497 }
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000498 EE->addModule(std::move(XMod));
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000499 }
500
Lang Hames173c69f2014-01-08 04:09:09 +0000501 for (unsigned i = 0, e = ExtraObjects.size(); i != e; ++i) {
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000502 Expected<object::OwningBinary<object::ObjectFile>> Obj =
Rafael Espindola51cc3602014-01-22 00:14:49 +0000503 object::ObjectFile::createObjectFile(ExtraObjects[i]);
Lang Hames173c69f2014-01-08 04:09:09 +0000504 if (!Obj) {
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000505 // TODO: Actually report errors helpfully.
506 consumeError(Obj.takeError());
Davide Italianoda8e6b22016-11-17 22:58:13 +0000507 reportError(Err, argv[0]);
Lang Hames173c69f2014-01-08 04:09:09 +0000508 }
Rafael Espindola061beab2014-08-20 15:19:37 +0000509 object::OwningBinary<object::ObjectFile> &O = Obj.get();
Rafael Espindola7271c192014-08-26 21:04:04 +0000510 EE->addObjectFile(std::move(O));
Lang Hames173c69f2014-01-08 04:09:09 +0000511 }
512
513 for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) {
Rafael Espindola48af1c22014-08-19 18:44:46 +0000514 ErrorOr<std::unique_ptr<MemoryBuffer>> ArBufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000515 MemoryBuffer::getFileOrSTDIN(ExtraArchives[i]);
Davide Italianoda8e6b22016-11-17 22:58:13 +0000516 if (!ArBufOrErr)
517 reportError(Err, argv[0]);
Rafael Espindola48af1c22014-08-19 18:44:46 +0000518 std::unique_ptr<MemoryBuffer> &ArBuf = ArBufOrErr.get();
Rafael Espindolae1923412014-08-01 18:31:17 +0000519
Kevin Enderbyc60a3212016-06-29 20:35:44 +0000520 Expected<std::unique_ptr<object::Archive>> ArOrErr =
Rafael Espindola48af1c22014-08-19 18:44:46 +0000521 object::Archive::create(ArBuf->getMemBufferRef());
Kevin Enderbyc60a3212016-06-29 20:35:44 +0000522 if (!ArOrErr) {
523 std::string Buf;
524 raw_string_ostream OS(Buf);
525 logAllUnhandledErrors(ArOrErr.takeError(), OS, "");
526 OS.flush();
527 errs() << Buf;
Davide Italiano86511442016-11-17 22:59:13 +0000528 exit(1);
Lang Hames173c69f2014-01-08 04:09:09 +0000529 }
Rafael Espindola48af1c22014-08-19 18:44:46 +0000530 std::unique_ptr<object::Archive> &Ar = ArOrErr.get();
531
532 object::OwningBinary<object::Archive> OB(std::move(Ar), std::move(ArBuf));
533
534 EE->addArchive(std::move(OB));
Lang Hames173c69f2014-01-08 04:09:09 +0000535 }
536
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000537 // If the target is Cygwin/MingW and we are generating remote code, we
538 // need an extra module to help out with linking.
539 if (RemoteMCJIT && Triple(Mod->getTargetTriple()).isOSCygMing()) {
Mehdi Aminia7de8202016-04-18 18:52:39 +0000540 addCygMingExtraModule(*EE, Context, Mod->getTargetTriple());
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000541 }
542
Eli Bendersky5262ad22012-03-13 08:33:15 +0000543 // The following functions have no effect if their respective profiling
544 // support wasn't enabled in the build configuration.
545 EE->RegisterJITEventListener(
546 JITEventListener::createOProfileJITEventListener());
547 EE->RegisterJITEventListener(
548 JITEventListener::createIntelJITEventListener());
Jeffrey Yasskin0b08f3d2009-06-25 02:04:04 +0000549
Jim Grosbach0f435d02012-09-05 16:50:34 +0000550 if (!NoLazyCompilation && RemoteMCJIT) {
551 errs() << "warning: remote mcjit does not support lazy compilation\n";
552 NoLazyCompilation = true;
553 }
Jeffrey Yasskinaa8814a2009-10-27 22:39:42 +0000554 EE->DisableLazyCompilation(NoLazyCompilation);
Evan Cheng0422bef2008-04-22 06:51:41 +0000555
Chris Lattner2785bdb2007-05-06 04:58:26 +0000556 // If the user specifically requested an argv[0] to pass into the program,
557 // do it now.
558 if (!FakeArgv0.empty()) {
Chris Bienemane71fb5c2015-01-22 01:49:59 +0000559 InputFile = static_cast<std::string>(FakeArgv0);
Chris Lattner2785bdb2007-05-06 04:58:26 +0000560 } else {
561 // Otherwise, if there is a .bc suffix on the executable strip it off, it
562 // might confuse the program.
Benjamin Kramera944a9a2010-04-15 11:33:14 +0000563 if (StringRef(InputFile).endswith(".bc"))
Chris Lattner2785bdb2007-05-06 04:58:26 +0000564 InputFile.erase(InputFile.length() - 3);
565 }
566
567 // Add the module's name to the start of the vector of arguments to main().
568 InputArgv.insert(InputArgv.begin(), InputFile);
569
570 // Call the main function from M as if its signature were:
571 // int main (int argc, char **argv, const char **envp)
572 // using the contents of Args to determine argc & argv, and the contents of
573 // EnvVars to determine envp.
574 //
Evan Cheng61582542008-11-05 23:21:52 +0000575 Function *EntryFn = Mod->getFunction(EntryFunc);
576 if (!EntryFn) {
Dan Gohmand8db3762009-07-15 16:35:29 +0000577 errs() << '\'' << EntryFunc << "\' function not found in module.\n";
Chris Lattner2785bdb2007-05-06 04:58:26 +0000578 return -1;
579 }
580
Chris Lattner2785bdb2007-05-06 04:58:26 +0000581 // Reset errno to zero on entry to main.
582 errno = 0;
Eli Bendersky4c647582012-01-16 08:56:09 +0000583
Lang Hames3fde6522016-04-18 19:55:43 +0000584 int Result = -1;
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000585
Lang Hames9d7a2692016-01-11 16:35:55 +0000586 // Sanity check use of remote-jit: LLI currently only supports use of the
587 // remote JIT on Unix platforms.
Lang Hames9d7a2692016-01-11 16:35:55 +0000588 if (RemoteMCJIT) {
589#ifndef LLVM_ON_UNIX
590 errs() << "Warning: host does not support external remote targets.\n"
Lang Hames4ce7cc02016-01-17 01:49:46 +0000591 << " Defaulting to local execution\n";
Lang Hames4b6e0212016-01-11 21:41:34 +0000592 return -1;
Lang Hames9d7a2692016-01-11 16:35:55 +0000593#else
594 if (ChildExecPath.empty()) {
595 errs() << "-remote-mcjit requires -mcjit-remote-process.\n";
596 exit(1);
597 } else if (!sys::fs::can_execute(ChildExecPath)) {
598 errs() << "Unable to find usable child executable: '" << ChildExecPath
599 << "'\n";
600 return -1;
601 }
602#endif
603 }
604
Andrew Kaylor58365b92012-11-27 19:49:00 +0000605 if (!RemoteMCJIT) {
Andrew Kaylor6587bcf2013-10-11 22:47:10 +0000606 // If the program doesn't explicitly call exit, we will need the Exit
607 // function later on to make an explicit call, so get the function now.
608 Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000609 Type::getInt32Ty(Context));
Andrew Kaylor6587bcf2013-10-11 22:47:10 +0000610
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000611 // Run static constructors.
Eric Christopher79cc1e32014-09-02 22:28:02 +0000612 if (!ForceInterpreter) {
Andrew Kaylorea395922013-10-01 01:47:35 +0000613 // Give MCJIT a chance to apply relocations and set page permissions.
614 EE->finalizeObject();
615 }
616 EE->runStaticConstructorsDestructors(false);
Evan Cheng0422bef2008-04-22 06:51:41 +0000617
NAKAMURA Takumi87e08802013-12-07 11:21:42 +0000618 // Trigger compilation separately so code regions that need to be
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000619 // invalidated will be known.
620 (void)EE->getPointerToFunction(EntryFn);
621 // Clear instruction cache before code will be executed.
622 if (RTDyldMM)
623 static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
624
625 // Run main.
626 Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
627
628 // Run static destructors.
629 EE->runStaticConstructorsDestructors(true);
630
631 // If the program didn't call exit explicitly, we should call it now.
632 // This ensures that any atexit handlers get called correctly.
633 if (Function *ExitF = dyn_cast<Function>(Exit)) {
634 std::vector<GenericValue> Args;
635 GenericValue ResultGV;
636 ResultGV.IntVal = APInt(32, Result);
637 Args.push_back(ResultGV);
638 EE->runFunction(ExitF, Args);
639 errs() << "ERROR: exit(" << Result << ") returned!\n";
640 abort();
641 } else {
642 errs() << "ERROR: exit defined with wrong prototype!\n";
643 abort();
644 }
645 } else {
646 // else == "if (RemoteMCJIT)"
647
648 // Remote target MCJIT doesn't (yet) support static constructors. No reason
Hiroshi Inoue0ca79dc2017-07-11 06:04:59 +0000649 // it couldn't. This is a limitation of the LLI implementation, not the
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000650 // MCJIT itself. FIXME.
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000651
Lang Hames9d7a2692016-01-11 16:35:55 +0000652 // Lanch the remote process and get a channel to it.
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000653 std::unique_ptr<FDRawChannel> C = launchRemote();
Lang Hames9d7a2692016-01-11 16:35:55 +0000654 if (!C) {
655 errs() << "Failed to launch remote JIT.\n";
656 exit(1);
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000657 }
658
Lang Hames9d7a2692016-01-11 16:35:55 +0000659 // Create a remote target client running over the channel.
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000660 typedef orc::remote::OrcRemoteTargetClient<orc::rpc::RawByteChannel>
Lang Hamese98bc7af2016-09-11 18:41:05 +0000661 MyRemote;
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000662 auto R = ExitOnErr(MyRemote::Create(*C));
Jim Grosbach748b9472012-08-28 23:22:30 +0000663
Lang Hames9d7a2692016-01-11 16:35:55 +0000664 // Create a remote memory manager.
665 std::unique_ptr<MyRemote::RCMemoryManager> RemoteMM;
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000666 ExitOnErr(R->createRemoteMemoryManager(RemoteMM));
Lang Hames9d7a2692016-01-11 16:35:55 +0000667
668 // Forward MCJIT's memory manager calls to the remote memory manager.
669 static_cast<ForwardingMemoryManager*>(RTDyldMM)->setMemMgr(
670 std::move(RemoteMM));
671
672 // Forward MCJIT's symbol resolution calls to the remote.
673 static_cast<ForwardingMemoryManager*>(RTDyldMM)->setResolver(
674 orc::createLambdaResolver(
Lang Hamesbf9d1aa2016-05-25 16:23:59 +0000675 [](const std::string &Name) { return nullptr; },
Lang Hames9d7a2692016-01-11 16:35:55 +0000676 [&](const std::string &Name) {
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000677 if (auto Addr = ExitOnErr(R->getSymbolAddress(Name)))
Lang Hamesad4a9112016-08-01 20:49:11 +0000678 return JITSymbol(Addr, JITSymbolFlags::Exported);
679 return JITSymbol(nullptr);
Lang Hamesbf9d1aa2016-05-25 16:23:59 +0000680 }
Lang Hames9d7a2692016-01-11 16:35:55 +0000681 ));
682
683 // Grab the target address of the JIT'd main function on the remote and call
684 // it.
Jim Grosbach0f435d02012-09-05 16:50:34 +0000685 // FIXME: argv and envp handling.
Lang Hamesad4a9112016-08-01 20:49:11 +0000686 JITTargetAddress Entry = EE->getFunctionAddress(EntryFn->getName().str());
Lang Hames9d7a2692016-01-11 16:35:55 +0000687 EE->finalizeObject();
Tim Northover79ab7f72013-05-19 09:55:06 +0000688 DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"
689 << format("%llx", Entry) << "\n");
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000690 Result = ExitOnErr(R->callIntVoid(Entry));
Jim Grosbach0f435d02012-09-05 16:50:34 +0000691
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000692 // Like static constructors, the remote target MCJIT support doesn't handle
693 // this yet. It could. FIXME.
694
Lang Hames9d7a2692016-01-11 16:35:55 +0000695 // Delete the EE - we need to tear it down *before* we terminate the session
696 // with the remote, otherwise it'll crash when it tries to release resources
697 // on a remote that has already been disconnected.
Mehdi Aminia7de8202016-04-18 18:52:39 +0000698 EE.reset();
Lang Hames9d7a2692016-01-11 16:35:55 +0000699
700 // Signal the remote target that we're done JITing.
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000701 ExitOnErr(R->terminateSession());
Chris Lattner2785bdb2007-05-06 04:58:26 +0000702 }
Jim Grosbach0f435d02012-09-05 16:50:34 +0000703
Jim Grosbach0f435d02012-09-05 16:50:34 +0000704 return Result;
Chris Lattnerd7ff5782001-08-23 17:05:04 +0000705}
Lang Hames9d7a2692016-01-11 16:35:55 +0000706
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000707std::unique_ptr<FDRawChannel> launchRemote() {
Lang Hames9d7a2692016-01-11 16:35:55 +0000708#ifndef LLVM_ON_UNIX
709 llvm_unreachable("launchRemote not supported on non-Unix platforms");
710#else
711 int PipeFD[2][2];
712 pid_t ChildPID;
713
714 // Create two pipes.
715 if (pipe(PipeFD[0]) != 0 || pipe(PipeFD[1]) != 0)
716 perror("Error creating pipe: ");
717
718 ChildPID = fork();
719
720 if (ChildPID == 0) {
721 // In the child...
722
723 // Close the parent ends of the pipes
724 close(PipeFD[0][1]);
725 close(PipeFD[1][0]);
726
727
728 // Execute the child process.
729 std::unique_ptr<char[]> ChildPath, ChildIn, ChildOut;
730 {
731 ChildPath.reset(new char[ChildExecPath.size() + 1]);
732 std::copy(ChildExecPath.begin(), ChildExecPath.end(), &ChildPath[0]);
733 ChildPath[ChildExecPath.size()] = '\0';
NAKAMURA Takumicef0a8212016-01-15 02:14:46 +0000734 std::string ChildInStr = utostr(PipeFD[0][0]);
Lang Hames9d7a2692016-01-11 16:35:55 +0000735 ChildIn.reset(new char[ChildInStr.size() + 1]);
736 std::copy(ChildInStr.begin(), ChildInStr.end(), &ChildIn[0]);
737 ChildIn[ChildInStr.size()] = '\0';
NAKAMURA Takumicef0a8212016-01-15 02:14:46 +0000738 std::string ChildOutStr = utostr(PipeFD[1][1]);
Lang Hames9d7a2692016-01-11 16:35:55 +0000739 ChildOut.reset(new char[ChildOutStr.size() + 1]);
740 std::copy(ChildOutStr.begin(), ChildOutStr.end(), &ChildOut[0]);
741 ChildOut[ChildOutStr.size()] = '\0';
742 }
743
744 char * const args[] = { &ChildPath[0], &ChildIn[0], &ChildOut[0], nullptr };
745 int rc = execv(ChildExecPath.c_str(), args);
746 if (rc != 0)
747 perror("Error executing child process: ");
748 llvm_unreachable("Error executing child process");
749 }
750 // else we're the parent...
751
752 // Close the child ends of the pipes
753 close(PipeFD[0][0]);
754 close(PipeFD[1][1]);
755
756 // Return an RPC channel connected to our end of the pipes.
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000757 return llvm::make_unique<FDRawChannel>(PipeFD[1][0], PipeFD[0][1]);
Lang Hames9d7a2692016-01-11 16:35:55 +0000758#endif
759}