blob: 07075c2496db3c8953e516556c51fc6c4374f5e1 [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"
NAKAMURA Takumicef0a8212016-01-15 02:14:46 +000018#include "llvm/ADT/StringExtras.h"
Duncan Sands3bd97fe2010-08-28 01:30:02 +000019#include "llvm/ADT/Triple.h"
Teresa Johnsonad176792016-11-11 05:34:58 +000020#include "llvm/Bitcode/BitcodeReader.h"
David Blaikie4333f972018-04-11 18:49:37 +000021#include "llvm/CodeGen/CommandFlags.inc"
Chris Lattner5af6a3f2006-08-01 22:34:35 +000022#include "llvm/CodeGen/LinkAllCodegenComponents.h"
Nico Weber432a3882018-04-30 14:59:11 +000023#include "llvm/Config/llvm-config.h"
Brian Gaekee99ca442003-09-05 19:42:34 +000024#include "llvm/ExecutionEngine/GenericValue.h"
Jeffrey Yasskin0b08f3d2009-06-25 02:04:04 +000025#include "llvm/ExecutionEngine/Interpreter.h"
Jeffrey Yasskin0b08f3d2009-06-25 02:04:04 +000026#include "llvm/ExecutionEngine/JITEventListener.h"
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000027#include "llvm/ExecutionEngine/MCJIT.h"
Lang Hames173c69f2014-01-08 04:09:09 +000028#include "llvm/ExecutionEngine/ObjectCache.h"
Rafael Espindola79e238a2017-08-03 02:16:21 +000029#include "llvm/ExecutionEngine/Orc/OrcRemoteTargetClient.h"
Lang Hames93de2a12015-01-23 21:25:00 +000030#include "llvm/ExecutionEngine/OrcMCJITReplacement.h"
Andrew Kaylor58365b92012-11-27 19:49:00 +000031#include "llvm/ExecutionEngine/SectionMemoryManager.h"
Andrew Kaylor1ca510e2013-10-29 01:29:56 +000032#include "llvm/IR/IRBuilder.h"
Rafael Espindola79e238a2017-08-03 02:16:21 +000033#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/Module.h"
35#include "llvm/IR/Type.h"
Andrew Kaylor1ca510e2013-10-29 01:29:56 +000036#include "llvm/IR/TypeBuilder.h"
Chandler Carruthe60e57b2013-03-26 02:25:37 +000037#include "llvm/IRReader/IRReader.h"
Lang Hames173c69f2014-01-08 04:09:09 +000038#include "llvm/Object/Archive.h"
39#include "llvm/Object/ObjectFile.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000040#include "llvm/Support/CommandLine.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000041#include "llvm/Support/Debug.h"
42#include "llvm/Support/DynamicLibrary.h"
43#include "llvm/Support/Format.h"
Rui Ueyama197194b2018-04-13 18:26:06 +000044#include "llvm/Support/InitLLVM.h"
Chris Lattner76d46322006-12-06 01:18:01 +000045#include "llvm/Support/ManagedStatic.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000046#include "llvm/Support/MathExtras.h"
47#include "llvm/Support/Memory.h"
Chris Lattner2785bdb2007-05-06 04:58:26 +000048#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer16132e62015-03-23 18:07:13 +000049#include "llvm/Support/Path.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000050#include "llvm/Support/PluginLoader.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000051#include "llvm/Support/Process.h"
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +000052#include "llvm/Support/Program.h"
Chandler Carruthe60e57b2013-03-26 02:25:37 +000053#include "llvm/Support/SourceMgr.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000054#include "llvm/Support/TargetSelect.h"
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +000055#include "llvm/Support/WithColor.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000056#include "llvm/Support/raw_ostream.h"
Daniel Maleaa960c542013-06-28 19:11:40 +000057#include "llvm/Transforms/Instrumentation.h"
Chris Lattner4c522b92007-04-27 17:02:33 +000058#include <cerrno>
NAKAMURA Takumi15304872010-10-22 14:53:59 +000059
60#ifdef __CYGWIN__
61#include <cygwin/version.h>
62#if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
63#define DO_NOTHING_ATEXIT 1
64#endif
65#endif
66
Brian Gaeke960707c2003-11-11 22:41:34 +000067using namespace llvm;
68
Chandler Carruthf98597a2014-04-22 03:10:36 +000069#define DEBUG_TYPE "lli"
70
Chris Lattnera0d7b082002-12-23 23:59:41 +000071namespace {
Lang Hames9528bba2015-03-25 12:11:48 +000072
73 enum class JITKind { MCJIT, OrcMCJITReplacement, OrcLazy };
74
Chris Lattnera0d7b082002-12-23 23:59:41 +000075 cl::opt<std::string>
Gabor Greife16561c2007-07-05 17:07:56 +000076 InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
Chris Lattnerf5cad152002-07-22 02:10:13 +000077
Chris Lattnera0d7b082002-12-23 23:59:41 +000078 cl::list<std::string>
79 InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
Chris Lattnerf5cad152002-07-22 02:10:13 +000080
Chris Lattnera0d7b082002-12-23 23:59:41 +000081 cl::opt<bool> ForceInterpreter("force-interpreter",
Misha Brukmanc2186e32003-09-25 18:10:34 +000082 cl::desc("Force interpretation: disable JIT"),
83 cl::init(false));
Evan Cheng06d988e2008-08-08 08:12:06 +000084
Lang Hames9528bba2015-03-25 12:11:48 +000085 cl::opt<JITKind> UseJITKind("jit-kind",
86 cl::desc("Choose underlying JIT kind."),
87 cl::init(JITKind::MCJIT),
88 cl::values(
89 clEnumValN(JITKind::MCJIT, "mcjit",
90 "MCJIT"),
91 clEnumValN(JITKind::OrcMCJITReplacement,
92 "orc-mcjit",
93 "Orc-based MCJIT replacement"),
94 clEnumValN(JITKind::OrcLazy,
95 "orc-lazy",
Mehdi Amini732afdd2016-10-08 19:41:06 +000096 "Orc-based lazy JIT.")));
Lang Hames93de2a12015-01-23 21:25:00 +000097
Jim Grosbach0f435d02012-09-05 16:50:34 +000098 // The MCJIT supports building for a target address space separate from
99 // the JIT compilation process. Use a forked process and a copying
100 // memory manager with IPC to execute using this functionality.
101 cl::opt<bool> RemoteMCJIT("remote-mcjit",
102 cl::desc("Execute MCJIT'ed code in a separate process."),
103 cl::init(false));
104
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000105 // Manually specify the child process for remote execution. This overrides
106 // the simulated remote execution that allocates address space for child
Andrew Kaylor89352582013-10-29 01:33:14 +0000107 // execution. The child process will be executed and will communicate with
108 // lli via stdin/stdout pipes.
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000109 cl::opt<std::string>
Alp Tokera1186382014-01-22 21:52:35 +0000110 ChildExecPath("mcjit-remote-process",
111 cl::desc("Specify the filename of the process to launch "
112 "for remote MCJIT execution. If none is specified,"
113 "\n\tremote execution will be simulated in-process."),
114 cl::value_desc("filename"), cl::init(""));
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000115
Evan Cheng09bd0b12009-05-04 23:05:19 +0000116 // Determine optimization level.
117 cl::opt<char>
118 OptLevel("O",
119 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
120 "(default = '-O2')"),
121 cl::Prefix,
122 cl::ZeroOrMore,
123 cl::init(' '));
Evan Cheng06d988e2008-08-08 08:12:06 +0000124
Chris Lattner76766cb2005-12-16 05:00:21 +0000125 cl::opt<std::string>
Chris Lattner78e9e102005-12-16 05:19:18 +0000126 TargetTriple("mtriple", cl::desc("Override target triple for module"));
Evan Cheng61582542008-11-05 23:21:52 +0000127
128 cl::opt<std::string>
129 EntryFunc("entry-function",
130 cl::desc("Specify the entry function (default = 'main') "
131 "of the executable"),
132 cl::value_desc("function"),
133 cl::init("main"));
Eli Bendersky4c647582012-01-16 08:56:09 +0000134
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000135 cl::list<std::string>
Andrew Kaylor4404eb42013-10-28 21:58:15 +0000136 ExtraModules("extra-module",
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000137 cl::desc("Extra modules to be loaded"),
Alp Toker0a09ebf2013-10-28 22:51:25 +0000138 cl::value_desc("input bitcode"));
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000139
Lang Hames173c69f2014-01-08 04:09:09 +0000140 cl::list<std::string>
141 ExtraObjects("extra-object",
142 cl::desc("Extra object files to be loaded"),
143 cl::value_desc("input object"));
144
145 cl::list<std::string>
146 ExtraArchives("extra-archive",
147 cl::desc("Extra archive files to be loaded"),
148 cl::value_desc("input archive"));
149
150 cl::opt<bool>
151 EnableCacheManager("enable-cache-manager",
Lang Hames1ddecc02014-01-09 05:24:05 +0000152 cl::desc("Use cache manager to save/load mdoules"),
Lang Hames173c69f2014-01-08 04:09:09 +0000153 cl::init(false));
154
Chris Lattner55644062003-10-28 22:51:44 +0000155 cl::opt<std::string>
Lang Hames1ddecc02014-01-09 05:24:05 +0000156 ObjectCacheDir("object-cache-dir",
157 cl::desc("Directory to store cached object files "
158 "(must be user writable)"),
159 cl::init(""));
160
161 cl::opt<std::string>
Chris Lattner55644062003-10-28 22:51:44 +0000162 FakeArgv0("fake-argv0",
163 cl::desc("Override the 'argv[0]' value passed into the executing"
164 " program"), cl::value_desc("executable"));
Eli Bendersky4c647582012-01-16 08:56:09 +0000165
Chris Lattner3f0ffd32006-09-14 06:17:09 +0000166 cl::opt<bool>
167 DisableCoreFiles("disable-core-files", cl::Hidden,
168 cl::desc("Disable emission of core files if possible"));
Evan Cheng0422bef2008-04-22 06:51:41 +0000169
170 cl::opt<bool>
Evan Cheng16f036c2008-05-21 18:20:21 +0000171 NoLazyCompilation("disable-lazy-compilation",
Evan Cheng0422bef2008-04-22 06:51:41 +0000172 cl::desc("Disable JIT lazy compilation"),
173 cl::init(false));
Evan Cheng2129f592011-07-19 06:37:02 +0000174
Nick Lewyckyb0e97892012-04-18 08:34:12 +0000175 cl::opt<bool>
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000176 GenerateSoftFloatCalls("soft-float",
177 cl::desc("Generate software floating point library calls"),
178 cl::init(false));
179
Lang Hamesef5a0ee2016-04-25 19:56:45 +0000180 ExitOnError ExitOnErr;
Chris Lattnera0d7b082002-12-23 23:59:41 +0000181}
Chris Lattner009f8102001-10-27 08:43:52 +0000182
Lang Hames173c69f2014-01-08 04:09:09 +0000183//===----------------------------------------------------------------------===//
184// Object cache
185//
Lang Hames1ddecc02014-01-09 05:24:05 +0000186// This object cache implementation writes cached objects to disk to the
187// directory specified by CacheDir, using a filename provided in the module
188// descriptor. The cache tries to load a saved object using that path if the
189// file exists. CacheDir defaults to "", in which case objects are cached
NAKAMURA Takumif462f9c2014-01-10 10:38:28 +0000190// alongside their originating bitcodes.
Lang Hames173c69f2014-01-08 04:09:09 +0000191//
192class LLIObjectCache : public ObjectCache {
193public:
Lang Hames1ddecc02014-01-09 05:24:05 +0000194 LLIObjectCache(const std::string& CacheDir) : CacheDir(CacheDir) {
195 // Add trailing '/' to cache dir if necessary.
Lang Hamesf9dd8fd2014-01-09 05:29:59 +0000196 if (!this->CacheDir.empty() &&
197 this->CacheDir[this->CacheDir.size() - 1] != '/')
NAKAMURA Takumif462f9c2014-01-10 10:38:28 +0000198 this->CacheDir += '/';
Lang Hames1ddecc02014-01-09 05:24:05 +0000199 }
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000200 ~LLIObjectCache() override {}
Lang Hames173c69f2014-01-08 04:09:09 +0000201
Rafael Espindola48af1c22014-08-19 18:44:46 +0000202 void notifyObjectCompiled(const Module *M, MemoryBufferRef Obj) override {
Benjamin Kramer46e38f32016-06-08 10:01:20 +0000203 const std::string &ModuleID = M->getModuleIdentifier();
Lang Hames173c69f2014-01-08 04:09:09 +0000204 std::string CacheName;
205 if (!getCacheFilename(ModuleID, CacheName))
206 return;
NAKAMURA Takumi390e0602014-01-10 10:38:34 +0000207 if (!CacheDir.empty()) { // Create user-defined cache dir.
Rafael Espindolaf662e002015-07-15 21:24:07 +0000208 SmallString<128> dir(sys::path::parent_path(CacheName));
NAKAMURA Takumi390e0602014-01-10 10:38:34 +0000209 sys::fs::create_directories(Twine(dir));
210 }
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000211 std::error_code EC;
212 raw_fd_ostream outfile(CacheName, EC, sys::fs::F_None);
Rafael Espindola48af1c22014-08-19 18:44:46 +0000213 outfile.write(Obj.getBufferStart(), Obj.getBufferSize());
Lang Hames173c69f2014-01-08 04:09:09 +0000214 outfile.close();
215 }
216
Rafael Espindola5f2bb7d2014-08-13 18:49:01 +0000217 std::unique_ptr<MemoryBuffer> getObject(const Module* M) override {
Benjamin Kramer46e38f32016-06-08 10:01:20 +0000218 const std::string &ModuleID = M->getModuleIdentifier();
Lang Hames173c69f2014-01-08 04:09:09 +0000219 std::string CacheName;
220 if (!getCacheFilename(ModuleID, CacheName))
Craig Toppere6cb63e2014-04-25 04:24:47 +0000221 return nullptr;
Lang Hames173c69f2014-01-08 04:09:09 +0000222 // Load the object from the cache filename
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000223 ErrorOr<std::unique_ptr<MemoryBuffer>> IRObjectBuffer =
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000224 MemoryBuffer::getFile(CacheName, -1, false);
Lang Hames173c69f2014-01-08 04:09:09 +0000225 // If the file isn't there, that's OK.
226 if (!IRObjectBuffer)
Craig Toppere6cb63e2014-04-25 04:24:47 +0000227 return nullptr;
Lang Hames173c69f2014-01-08 04:09:09 +0000228 // MCJIT will want to write into this buffer, and we don't want that
229 // because the file has probably just been mmapped. Instead we make
230 // a copy. The filed-based buffer will be released when it goes
231 // out of scope.
Rafael Espindola3560ff22014-08-27 20:03:13 +0000232 return MemoryBuffer::getMemBufferCopy(IRObjectBuffer.get()->getBuffer());
Lang Hames173c69f2014-01-08 04:09:09 +0000233 }
234
235private:
Lang Hames1ddecc02014-01-09 05:24:05 +0000236 std::string CacheDir;
237
Lang Hames173c69f2014-01-08 04:09:09 +0000238 bool getCacheFilename(const std::string &ModID, std::string &CacheName) {
239 std::string Prefix("file:");
240 size_t PrefixLength = Prefix.length();
241 if (ModID.substr(0, PrefixLength) != Prefix)
242 return false;
NAKAMURA Takumid7fd6d92014-01-10 10:38:40 +0000243 std::string CacheSubdir = ModID.substr(PrefixLength);
244#if defined(_WIN32)
245 // Transform "X:\foo" => "/X\foo" for convenience.
246 if (isalpha(CacheSubdir[0]) && CacheSubdir[1] == ':') {
247 CacheSubdir[1] = CacheSubdir[0];
248 CacheSubdir[0] = '/';
249 }
250#endif
251 CacheName = CacheDir + CacheSubdir;
Lang Hames173c69f2014-01-08 04:09:09 +0000252 size_t pos = CacheName.rfind('.');
253 CacheName.replace(pos, CacheName.length() - pos, ".o");
254 return true;
255 }
256};
257
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000258// On Mingw and Cygwin, an external symbol named '__main' is called from the
Simon Pilgrimdae11f72016-11-20 13:31:13 +0000259// generated 'main' function to allow static initialization. To avoid linking
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000260// problems with remote targets (because lli's remote target support does not
261// currently handle external linking) we add a secondary module which defines
262// an empty '__main' function.
Mehdi Aminia7de8202016-04-18 18:52:39 +0000263static void addCygMingExtraModule(ExecutionEngine &EE, LLVMContext &Context,
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000264 StringRef TargetTripleStr) {
265 IRBuilder<> Builder(Context);
266 Triple TargetTriple(TargetTripleStr);
267
268 // Create a new module.
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000269 std::unique_ptr<Module> M = make_unique<Module>("CygMingHelper", Context);
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000270 M->setTargetTriple(TargetTripleStr);
271
272 // Create an empty function named "__main".
273 Function *Result;
274 if (TargetTriple.isArch64Bit()) {
275 Result = Function::Create(
276 TypeBuilder<int64_t(void), false>::get(Context),
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000277 GlobalValue::ExternalLinkage, "__main", M.get());
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000278 } else {
279 Result = Function::Create(
280 TypeBuilder<int32_t(void), false>::get(Context),
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000281 GlobalValue::ExternalLinkage, "__main", M.get());
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000282 }
283 BasicBlock *BB = BasicBlock::Create(Context, "__main", Result);
284 Builder.SetInsertPoint(BB);
285 Value *ReturnVal;
286 if (TargetTriple.isArch64Bit())
287 ReturnVal = ConstantInt::get(Context, APInt(64, 0));
288 else
289 ReturnVal = ConstantInt::get(Context, APInt(32, 0));
290 Builder.CreateRet(ReturnVal);
291
292 // Add this new module to the ExecutionEngine.
Mehdi Aminia7de8202016-04-18 18:52:39 +0000293 EE.addModule(std::move(M));
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000294}
295
Lang Hames1899d0c2015-06-09 02:43:27 +0000296CodeGenOpt::Level getOptLevel() {
297 switch (OptLevel) {
298 default:
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000299 WithColor::error(errs(), "lli") << "invalid optimization level.\n";
Lang Hames1899d0c2015-06-09 02:43:27 +0000300 exit(1);
301 case '0': return CodeGenOpt::None;
302 case '1': return CodeGenOpt::Less;
303 case ' ':
304 case '2': return CodeGenOpt::Default;
305 case '3': return CodeGenOpt::Aggressive;
306 }
307 llvm_unreachable("Unrecognized opt level.");
308}
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000309
Davide Italianoda8e6b22016-11-17 22:58:13 +0000310LLVM_ATTRIBUTE_NORETURN
311static void reportError(SMDiagnostic Err, const char *ProgName) {
312 Err.print(ProgName, errs());
313 exit(1);
314}
315
Chris Lattnerd7ff5782001-08-23 17:05:04 +0000316//===----------------------------------------------------------------------===//
Chris Lattnerd7ff5782001-08-23 17:05:04 +0000317// main Driver function
318//
Misha Brukman5b255e52003-10-14 21:39:53 +0000319int main(int argc, char **argv, char * const *envp) {
Rui Ueyama197194b2018-04-13 18:26:06 +0000320 InitLLVM X(argc, argv);
Daniel Dunbar3d92d932009-07-16 02:04:54 +0000321
Lang Hamesef5a0ee2016-04-25 19:56:45 +0000322 if (argc > 1)
323 ExitOnErr.setBanner(std::string(argv[0]) + ": ");
324
Daniel Dunbar3d92d932009-07-16 02:04:54 +0000325 // If we have a native target, initialize it to ensure it is linked in and
326 // usable by the JIT.
327 InitializeNativeTarget();
Jim Grosbach7b162492011-03-18 22:48:41 +0000328 InitializeNativeTargetAsmPrinter();
Jim Grosbach2cce3f92012-11-05 19:06:05 +0000329 InitializeNativeTargetAsmParser();
Daniel Dunbar3d92d932009-07-16 02:04:54 +0000330
Chris Lattner2785bdb2007-05-06 04:58:26 +0000331 cl::ParseCommandLineOptions(argc, argv,
Dan Gohman2c6a8212007-10-08 15:45:12 +0000332 "llvm interpreter & dynamic compiler\n");
Reid Spencer996ec722004-12-30 05:36:08 +0000333
Chris Lattner2785bdb2007-05-06 04:58:26 +0000334 // If the user doesn't want core files, disable them.
335 if (DisableCoreFiles)
336 sys::Process::PreventCoreFiles();
Eli Bendersky4c647582012-01-16 08:56:09 +0000337
Mehdi Aminia7de8202016-04-18 18:52:39 +0000338 LLVMContext Context;
339
Gabor Greife16561c2007-07-05 17:07:56 +0000340 // Load the bitcode...
Daniel Dunbar9589bf82010-11-13 00:28:01 +0000341 SMDiagnostic Err;
Rafael Espindolad233b062014-08-26 17:29:46 +0000342 std::unique_ptr<Module> Owner = parseIRFile(InputFile, Err, Context);
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000343 Module *Mod = Owner.get();
Davide Italianoda8e6b22016-11-17 22:58:13 +0000344 if (!Mod)
345 reportError(Err, argv[0]);
Chris Lattner2785bdb2007-05-06 04:58:26 +0000346
Lang Hames368c4222016-08-02 21:00:40 +0000347 if (UseJITKind == JITKind::OrcLazy) {
348 std::vector<std::unique_ptr<Module>> Ms;
349 Ms.push_back(std::move(Owner));
350 for (auto &ExtraMod : ExtraModules) {
351 Ms.push_back(parseIRFile(ExtraMod, Err, Context));
Davide Italianoda8e6b22016-11-17 22:58:13 +0000352 if (!Ms.back())
353 reportError(Err, argv[0]);
Lang Hames368c4222016-08-02 21:00:40 +0000354 }
Lang Hames1a2e6562016-10-28 16:52:34 +0000355 std::vector<std::string> Args;
356 Args.push_back(InputFile);
357 for (auto &Arg : InputArgv)
358 Args.push_back(Arg);
359 return runOrcLazyJIT(std::move(Ms), Args);
Lang Hames368c4222016-08-02 21:00:40 +0000360 }
Lang Hames9528bba2015-03-25 12:11:48 +0000361
Lang Hames173c69f2014-01-08 04:09:09 +0000362 if (EnableCacheManager) {
Eric Christopher79cc1e32014-09-02 22:28:02 +0000363 std::string CacheName("file:");
364 CacheName.append(InputFile);
365 Mod->setModuleIdentifier(CacheName);
Lang Hames173c69f2014-01-08 04:09:09 +0000366 }
367
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000368 // If not jitting lazily, load the whole bitcode file eagerly too.
369 if (NoLazyCompilation) {
Davide Italianob0e067b2016-11-09 21:30:33 +0000370 // Use *argv instead of argv[0] to work around a wrong GCC warning.
371 ExitOnError ExitOnErr(std::string(*argv) +
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000372 ": bitcode didn't read correctly: ");
373 ExitOnErr(Mod->materializeAll());
Evan Cheng0422bef2008-04-22 06:51:41 +0000374 }
Chris Lattner2785bdb2007-05-06 04:58:26 +0000375
Rafael Espindolae9fab9b2014-01-14 23:51:27 +0000376 std::string ErrorMsg;
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000377 EngineBuilder builder(std::move(Owner));
Jeffrey Yasskin31faeff2010-02-05 16:19:36 +0000378 builder.setMArch(MArch);
Craig Topper243f20f2018-01-09 18:14:18 +0000379 builder.setMCPU(getCPUStr());
380 builder.setMAttrs(getFeatureList());
Rafael Espindola8c34dd82016-05-18 22:04:49 +0000381 if (RelocModel.getNumOccurrences())
382 builder.setRelocationModel(RelocModel);
Rafael Espindola79e238a2017-08-03 02:16:21 +0000383 if (CMModel.getNumOccurrences())
384 builder.setCodeModel(CMModel);
Daniel Dunbara78d8092009-07-18 08:07:13 +0000385 builder.setErrorStr(&ErrorMsg);
386 builder.setEngineKind(ForceInterpreter
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000387 ? EngineKind::Interpreter
388 : EngineKind::JIT);
Lang Hames9528bba2015-03-25 12:11:48 +0000389 builder.setUseOrcMCJITReplacement(UseJITKind == JITKind::OrcMCJITReplacement);
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000390
Chris Lattner2785bdb2007-05-06 04:58:26 +0000391 // If we are supposed to override the target triple, do so now.
392 if (!TargetTriple.empty())
Duncan Sands3bd97fe2010-08-28 01:30:02 +0000393 Mod->setTargetTriple(Triple::normalize(TargetTriple));
Evan Cheng0422bef2008-04-22 06:51:41 +0000394
Eli Bendersky4c647582012-01-16 08:56:09 +0000395 // Enable MCJIT if desired.
Craig Toppere6cb63e2014-04-25 04:24:47 +0000396 RTDyldMemoryManager *RTDyldMM = nullptr;
Eric Christopher79cc1e32014-09-02 22:28:02 +0000397 if (!ForceInterpreter) {
Jim Grosbach0f435d02012-09-05 16:50:34 +0000398 if (RemoteMCJIT)
Lang Hames9d7a2692016-01-11 16:35:55 +0000399 RTDyldMM = new ForwardingMemoryManager();
Jim Grosbach0f435d02012-09-05 16:50:34 +0000400 else
Filip Pizlo9bc53e82013-05-14 19:29:00 +0000401 RTDyldMM = new SectionMemoryManager();
Lang Hames4a5697e2014-12-03 00:51:19 +0000402
403 // Deliberately construct a temp std::unique_ptr to pass in. Do not null out
404 // RTDyldMM: We still use it below, even though we don't own it.
405 builder.setMCJITMemoryManager(
406 std::unique_ptr<RTDyldMemoryManager>(RTDyldMM));
Lang Hames0f154902014-09-23 16:56:02 +0000407 } else if (RemoteMCJIT) {
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000408 WithColor::error(errs(), argv[0])
409 << "remote process execution does not work with the interpreter.\n";
Lang Hames0f154902014-09-23 16:56:02 +0000410 exit(1);
Eli Bendersky4c647582012-01-16 08:56:09 +0000411 }
Daniel Dunbar70ff8b02010-11-17 16:06:37 +0000412
Lang Hames1899d0c2015-06-09 02:43:27 +0000413 builder.setOptLevel(getOptLevel());
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000414
David Blaikiec14bfec2017-11-27 19:43:58 +0000415 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000416 if (FloatABIForCalls != FloatABI::Default)
417 Options.FloatABIType = FloatABIForCalls;
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000418
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000419 builder.setTargetOptions(Options);
420
Mehdi Aminia7de8202016-04-18 18:52:39 +0000421 std::unique_ptr<ExecutionEngine> EE(builder.create());
Chris Lattnerf840ed72009-07-07 18:31:09 +0000422 if (!EE) {
423 if (!ErrorMsg.empty())
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000424 WithColor::error(errs(), argv[0])
425 << "error creating EE: " << ErrorMsg << "\n";
Chris Lattnerf840ed72009-07-07 18:31:09 +0000426 else
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000427 WithColor::error(errs(), argv[0]) << "unknown error creating EE!\n";
Chris Lattner2785bdb2007-05-06 04:58:26 +0000428 exit(1);
429 }
430
Mehdi Aminia7de8202016-04-18 18:52:39 +0000431 std::unique_ptr<LLIObjectCache> CacheManager;
Lang Hames173c69f2014-01-08 04:09:09 +0000432 if (EnableCacheManager) {
Mehdi Aminia7de8202016-04-18 18:52:39 +0000433 CacheManager.reset(new LLIObjectCache(ObjectCacheDir));
434 EE->setObjectCache(CacheManager.get());
Lang Hames173c69f2014-01-08 04:09:09 +0000435 }
436
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000437 // Load any additional modules specified on the command line.
438 for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) {
Rafael Espindolad233b062014-08-26 17:29:46 +0000439 std::unique_ptr<Module> XMod = parseIRFile(ExtraModules[i], Err, Context);
Davide Italianoda8e6b22016-11-17 22:58:13 +0000440 if (!XMod)
441 reportError(Err, argv[0]);
Lang Hames173c69f2014-01-08 04:09:09 +0000442 if (EnableCacheManager) {
Eric Christopher79cc1e32014-09-02 22:28:02 +0000443 std::string CacheName("file:");
444 CacheName.append(ExtraModules[i]);
445 XMod->setModuleIdentifier(CacheName);
Lang Hames173c69f2014-01-08 04:09:09 +0000446 }
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000447 EE->addModule(std::move(XMod));
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000448 }
449
Lang Hames173c69f2014-01-08 04:09:09 +0000450 for (unsigned i = 0, e = ExtraObjects.size(); i != e; ++i) {
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000451 Expected<object::OwningBinary<object::ObjectFile>> Obj =
Rafael Espindola51cc3602014-01-22 00:14:49 +0000452 object::ObjectFile::createObjectFile(ExtraObjects[i]);
Lang Hames173c69f2014-01-08 04:09:09 +0000453 if (!Obj) {
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000454 // TODO: Actually report errors helpfully.
455 consumeError(Obj.takeError());
Davide Italianoda8e6b22016-11-17 22:58:13 +0000456 reportError(Err, argv[0]);
Lang Hames173c69f2014-01-08 04:09:09 +0000457 }
Rafael Espindola061beab2014-08-20 15:19:37 +0000458 object::OwningBinary<object::ObjectFile> &O = Obj.get();
Rafael Espindola7271c192014-08-26 21:04:04 +0000459 EE->addObjectFile(std::move(O));
Lang Hames173c69f2014-01-08 04:09:09 +0000460 }
461
462 for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) {
Rafael Espindola48af1c22014-08-19 18:44:46 +0000463 ErrorOr<std::unique_ptr<MemoryBuffer>> ArBufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000464 MemoryBuffer::getFileOrSTDIN(ExtraArchives[i]);
Davide Italianoda8e6b22016-11-17 22:58:13 +0000465 if (!ArBufOrErr)
466 reportError(Err, argv[0]);
Rafael Espindola48af1c22014-08-19 18:44:46 +0000467 std::unique_ptr<MemoryBuffer> &ArBuf = ArBufOrErr.get();
Rafael Espindolae1923412014-08-01 18:31:17 +0000468
Kevin Enderbyc60a3212016-06-29 20:35:44 +0000469 Expected<std::unique_ptr<object::Archive>> ArOrErr =
Rafael Espindola48af1c22014-08-19 18:44:46 +0000470 object::Archive::create(ArBuf->getMemBufferRef());
Kevin Enderbyc60a3212016-06-29 20:35:44 +0000471 if (!ArOrErr) {
472 std::string Buf;
473 raw_string_ostream OS(Buf);
474 logAllUnhandledErrors(ArOrErr.takeError(), OS, "");
475 OS.flush();
476 errs() << Buf;
Davide Italiano86511442016-11-17 22:59:13 +0000477 exit(1);
Lang Hames173c69f2014-01-08 04:09:09 +0000478 }
Rafael Espindola48af1c22014-08-19 18:44:46 +0000479 std::unique_ptr<object::Archive> &Ar = ArOrErr.get();
480
481 object::OwningBinary<object::Archive> OB(std::move(Ar), std::move(ArBuf));
482
483 EE->addArchive(std::move(OB));
Lang Hames173c69f2014-01-08 04:09:09 +0000484 }
485
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000486 // If the target is Cygwin/MingW and we are generating remote code, we
487 // need an extra module to help out with linking.
488 if (RemoteMCJIT && Triple(Mod->getTargetTriple()).isOSCygMing()) {
Mehdi Aminia7de8202016-04-18 18:52:39 +0000489 addCygMingExtraModule(*EE, Context, Mod->getTargetTriple());
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000490 }
491
Eli Bendersky5262ad22012-03-13 08:33:15 +0000492 // The following functions have no effect if their respective profiling
493 // support wasn't enabled in the build configuration.
494 EE->RegisterJITEventListener(
495 JITEventListener::createOProfileJITEventListener());
496 EE->RegisterJITEventListener(
497 JITEventListener::createIntelJITEventListener());
Jeffrey Yasskin0b08f3d2009-06-25 02:04:04 +0000498
Jim Grosbach0f435d02012-09-05 16:50:34 +0000499 if (!NoLazyCompilation && RemoteMCJIT) {
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000500 WithColor::warning(errs(), argv[0])
501 << "remote mcjit does not support lazy compilation\n";
Jim Grosbach0f435d02012-09-05 16:50:34 +0000502 NoLazyCompilation = true;
503 }
Jeffrey Yasskinaa8814a2009-10-27 22:39:42 +0000504 EE->DisableLazyCompilation(NoLazyCompilation);
Evan Cheng0422bef2008-04-22 06:51:41 +0000505
Chris Lattner2785bdb2007-05-06 04:58:26 +0000506 // If the user specifically requested an argv[0] to pass into the program,
507 // do it now.
508 if (!FakeArgv0.empty()) {
Chris Bienemane71fb5c2015-01-22 01:49:59 +0000509 InputFile = static_cast<std::string>(FakeArgv0);
Chris Lattner2785bdb2007-05-06 04:58:26 +0000510 } else {
511 // Otherwise, if there is a .bc suffix on the executable strip it off, it
512 // might confuse the program.
Benjamin Kramera944a9a2010-04-15 11:33:14 +0000513 if (StringRef(InputFile).endswith(".bc"))
Chris Lattner2785bdb2007-05-06 04:58:26 +0000514 InputFile.erase(InputFile.length() - 3);
515 }
516
517 // Add the module's name to the start of the vector of arguments to main().
518 InputArgv.insert(InputArgv.begin(), InputFile);
519
520 // Call the main function from M as if its signature were:
521 // int main (int argc, char **argv, const char **envp)
522 // using the contents of Args to determine argc & argv, and the contents of
523 // EnvVars to determine envp.
524 //
Evan Cheng61582542008-11-05 23:21:52 +0000525 Function *EntryFn = Mod->getFunction(EntryFunc);
526 if (!EntryFn) {
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000527 WithColor::error(errs(), argv[0])
528 << '\'' << EntryFunc << "\' function not found in module.\n";
Chris Lattner2785bdb2007-05-06 04:58:26 +0000529 return -1;
530 }
531
Chris Lattner2785bdb2007-05-06 04:58:26 +0000532 // Reset errno to zero on entry to main.
533 errno = 0;
Eli Bendersky4c647582012-01-16 08:56:09 +0000534
Lang Hames3fde6522016-04-18 19:55:43 +0000535 int Result = -1;
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000536
Lang Hames9d7a2692016-01-11 16:35:55 +0000537 // Sanity check use of remote-jit: LLI currently only supports use of the
538 // remote JIT on Unix platforms.
Lang Hames9d7a2692016-01-11 16:35:55 +0000539 if (RemoteMCJIT) {
540#ifndef LLVM_ON_UNIX
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000541 WithColor::warning(errs(), argv[0])
Jonas Devlieghere7b5fa242018-04-22 08:35:00 +0000542 << "host does not support external remote targets.\n";
543 WithColor::note() << "defaulting to local execution\n";
Lang Hames4b6e0212016-01-11 21:41:34 +0000544 return -1;
Lang Hames9d7a2692016-01-11 16:35:55 +0000545#else
546 if (ChildExecPath.empty()) {
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000547 WithColor::error(errs(), argv[0])
548 << "-remote-mcjit requires -mcjit-remote-process.\n";
Lang Hames9d7a2692016-01-11 16:35:55 +0000549 exit(1);
550 } else if (!sys::fs::can_execute(ChildExecPath)) {
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000551 WithColor::error(errs(), argv[0])
552 << "unable to find usable child executable: '" << ChildExecPath
553 << "'\n";
Lang Hames9d7a2692016-01-11 16:35:55 +0000554 return -1;
555 }
556#endif
557 }
558
Andrew Kaylor58365b92012-11-27 19:49:00 +0000559 if (!RemoteMCJIT) {
Andrew Kaylor6587bcf2013-10-11 22:47:10 +0000560 // If the program doesn't explicitly call exit, we will need the Exit
561 // function later on to make an explicit call, so get the function now.
562 Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000563 Type::getInt32Ty(Context));
Andrew Kaylor6587bcf2013-10-11 22:47:10 +0000564
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000565 // Run static constructors.
Eric Christopher79cc1e32014-09-02 22:28:02 +0000566 if (!ForceInterpreter) {
Andrew Kaylorea395922013-10-01 01:47:35 +0000567 // Give MCJIT a chance to apply relocations and set page permissions.
568 EE->finalizeObject();
569 }
570 EE->runStaticConstructorsDestructors(false);
Evan Cheng0422bef2008-04-22 06:51:41 +0000571
NAKAMURA Takumi87e08802013-12-07 11:21:42 +0000572 // Trigger compilation separately so code regions that need to be
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000573 // invalidated will be known.
574 (void)EE->getPointerToFunction(EntryFn);
575 // Clear instruction cache before code will be executed.
576 if (RTDyldMM)
577 static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
578
579 // Run main.
580 Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
581
582 // Run static destructors.
583 EE->runStaticConstructorsDestructors(true);
584
585 // If the program didn't call exit explicitly, we should call it now.
586 // This ensures that any atexit handlers get called correctly.
587 if (Function *ExitF = dyn_cast<Function>(Exit)) {
588 std::vector<GenericValue> Args;
589 GenericValue ResultGV;
590 ResultGV.IntVal = APInt(32, Result);
591 Args.push_back(ResultGV);
592 EE->runFunction(ExitF, Args);
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000593 WithColor::error(errs(), argv[0]) << "exit(" << Result << ") returned!\n";
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000594 abort();
595 } else {
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000596 WithColor::error(errs(), argv[0])
597 << "exit defined with wrong prototype!\n";
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000598 abort();
599 }
600 } else {
601 // else == "if (RemoteMCJIT)"
602
603 // Remote target MCJIT doesn't (yet) support static constructors. No reason
Hiroshi Inoue0ca79dc2017-07-11 06:04:59 +0000604 // it couldn't. This is a limitation of the LLI implementation, not the
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000605 // MCJIT itself. FIXME.
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000606
Lang Hames9d7a2692016-01-11 16:35:55 +0000607 // Lanch the remote process and get a channel to it.
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000608 std::unique_ptr<FDRawChannel> C = launchRemote();
Lang Hames9d7a2692016-01-11 16:35:55 +0000609 if (!C) {
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000610 WithColor::error(errs(), argv[0]) << "failed to launch remote JIT.\n";
Lang Hames9d7a2692016-01-11 16:35:55 +0000611 exit(1);
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000612 }
613
Lang Hames9d7a2692016-01-11 16:35:55 +0000614 // Create a remote target client running over the channel.
Lang Hamesbd0cb782018-05-30 01:57:45 +0000615 llvm::orc::ExecutionSession ES;
616 ES.setErrorReporter([&](Error Err) { ExitOnErr(std::move(Err)); });
Lang Hames9e68b7342017-09-04 20:54:46 +0000617 typedef orc::remote::OrcRemoteTargetClient MyRemote;
Lang Hamesbd0cb782018-05-30 01:57:45 +0000618 auto R = ExitOnErr(MyRemote::Create(*C, ES));
Jim Grosbach748b9472012-08-28 23:22:30 +0000619
Lang Hames9d7a2692016-01-11 16:35:55 +0000620 // Create a remote memory manager.
Lang Hames9e68b7342017-09-04 20:54:46 +0000621 auto RemoteMM = ExitOnErr(R->createRemoteMemoryManager());
Lang Hames9d7a2692016-01-11 16:35:55 +0000622
623 // Forward MCJIT's memory manager calls to the remote memory manager.
624 static_cast<ForwardingMemoryManager*>(RTDyldMM)->setMemMgr(
625 std::move(RemoteMM));
626
627 // Forward MCJIT's symbol resolution calls to the remote.
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +0000628 static_cast<ForwardingMemoryManager *>(RTDyldMM)->setResolver(
629 orc::createLambdaResolver(
630 [](const std::string &Name) { return nullptr; },
631 [&](const std::string &Name) {
632 if (auto Addr = ExitOnErr(R->getSymbolAddress(Name)))
633 return JITSymbol(Addr, JITSymbolFlags::Exported);
634 return JITSymbol(nullptr);
635 }));
Lang Hames9d7a2692016-01-11 16:35:55 +0000636
637 // Grab the target address of the JIT'd main function on the remote and call
638 // it.
Jim Grosbach0f435d02012-09-05 16:50:34 +0000639 // FIXME: argv and envp handling.
Lang Hamesad4a9112016-08-01 20:49:11 +0000640 JITTargetAddress Entry = EE->getFunctionAddress(EntryFn->getName().str());
Lang Hames9d7a2692016-01-11 16:35:55 +0000641 EE->finalizeObject();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000642 LLVM_DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"
643 << format("%llx", Entry) << "\n");
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000644 Result = ExitOnErr(R->callIntVoid(Entry));
Jim Grosbach0f435d02012-09-05 16:50:34 +0000645
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000646 // Like static constructors, the remote target MCJIT support doesn't handle
647 // this yet. It could. FIXME.
648
Lang Hames9d7a2692016-01-11 16:35:55 +0000649 // Delete the EE - we need to tear it down *before* we terminate the session
650 // with the remote, otherwise it'll crash when it tries to release resources
651 // on a remote that has already been disconnected.
Mehdi Aminia7de8202016-04-18 18:52:39 +0000652 EE.reset();
Lang Hames9d7a2692016-01-11 16:35:55 +0000653
654 // Signal the remote target that we're done JITing.
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000655 ExitOnErr(R->terminateSession());
Chris Lattner2785bdb2007-05-06 04:58:26 +0000656 }
Jim Grosbach0f435d02012-09-05 16:50:34 +0000657
Jim Grosbach0f435d02012-09-05 16:50:34 +0000658 return Result;
Chris Lattnerd7ff5782001-08-23 17:05:04 +0000659}
Lang Hames9d7a2692016-01-11 16:35:55 +0000660
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000661std::unique_ptr<FDRawChannel> launchRemote() {
Lang Hames9d7a2692016-01-11 16:35:55 +0000662#ifndef LLVM_ON_UNIX
663 llvm_unreachable("launchRemote not supported on non-Unix platforms");
664#else
665 int PipeFD[2][2];
666 pid_t ChildPID;
667
668 // Create two pipes.
669 if (pipe(PipeFD[0]) != 0 || pipe(PipeFD[1]) != 0)
670 perror("Error creating pipe: ");
671
672 ChildPID = fork();
673
674 if (ChildPID == 0) {
675 // In the child...
676
677 // Close the parent ends of the pipes
678 close(PipeFD[0][1]);
679 close(PipeFD[1][0]);
680
681
682 // Execute the child process.
683 std::unique_ptr<char[]> ChildPath, ChildIn, ChildOut;
684 {
685 ChildPath.reset(new char[ChildExecPath.size() + 1]);
686 std::copy(ChildExecPath.begin(), ChildExecPath.end(), &ChildPath[0]);
687 ChildPath[ChildExecPath.size()] = '\0';
NAKAMURA Takumicef0a8212016-01-15 02:14:46 +0000688 std::string ChildInStr = utostr(PipeFD[0][0]);
Lang Hames9d7a2692016-01-11 16:35:55 +0000689 ChildIn.reset(new char[ChildInStr.size() + 1]);
690 std::copy(ChildInStr.begin(), ChildInStr.end(), &ChildIn[0]);
691 ChildIn[ChildInStr.size()] = '\0';
NAKAMURA Takumicef0a8212016-01-15 02:14:46 +0000692 std::string ChildOutStr = utostr(PipeFD[1][1]);
Lang Hames9d7a2692016-01-11 16:35:55 +0000693 ChildOut.reset(new char[ChildOutStr.size() + 1]);
694 std::copy(ChildOutStr.begin(), ChildOutStr.end(), &ChildOut[0]);
695 ChildOut[ChildOutStr.size()] = '\0';
696 }
697
698 char * const args[] = { &ChildPath[0], &ChildIn[0], &ChildOut[0], nullptr };
699 int rc = execv(ChildExecPath.c_str(), args);
700 if (rc != 0)
701 perror("Error executing child process: ");
702 llvm_unreachable("Error executing child process");
703 }
704 // else we're the parent...
705
706 // Close the child ends of the pipes
707 close(PipeFD[0][0]);
708 close(PipeFD[1][1]);
709
710 // Return an RPC channel connected to our end of the pipes.
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000711 return llvm::make_unique<FDRawChannel>(PipeFD[1][0], PipeFD[0][1]);
Lang Hames9d7a2692016-01-11 16:35:55 +0000712#endif
713}