blob: 48aa1d83a48aa59e143f32e37d1dbe3769620e1d [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"
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"
Rafael Espindola79e238a2017-08-03 02:16:21 +000028#include "llvm/ExecutionEngine/Orc/OrcRemoteTargetClient.h"
Lang Hames93de2a12015-01-23 21:25:00 +000029#include "llvm/ExecutionEngine/OrcMCJITReplacement.h"
Andrew Kaylor58365b92012-11-27 19:49:00 +000030#include "llvm/ExecutionEngine/SectionMemoryManager.h"
Andrew Kaylor1ca510e2013-10-29 01:29:56 +000031#include "llvm/IR/IRBuilder.h"
Rafael Espindola79e238a2017-08-03 02:16:21 +000032#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000033#include "llvm/IR/Module.h"
34#include "llvm/IR/Type.h"
Andrew Kaylor1ca510e2013-10-29 01:29:56 +000035#include "llvm/IR/TypeBuilder.h"
Chandler Carruthe60e57b2013-03-26 02:25:37 +000036#include "llvm/IRReader/IRReader.h"
Lang Hames173c69f2014-01-08 04:09:09 +000037#include "llvm/Object/Archive.h"
38#include "llvm/Object/ObjectFile.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000039#include "llvm/Support/CommandLine.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000040#include "llvm/Support/Debug.h"
41#include "llvm/Support/DynamicLibrary.h"
42#include "llvm/Support/Format.h"
Rui Ueyama197194b2018-04-13 18:26:06 +000043#include "llvm/Support/InitLLVM.h"
Chris Lattner76d46322006-12-06 01:18:01 +000044#include "llvm/Support/ManagedStatic.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000045#include "llvm/Support/MathExtras.h"
46#include "llvm/Support/Memory.h"
Chris Lattner2785bdb2007-05-06 04:58:26 +000047#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer16132e62015-03-23 18:07:13 +000048#include "llvm/Support/Path.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000049#include "llvm/Support/PluginLoader.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000050#include "llvm/Support/Process.h"
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +000051#include "llvm/Support/Program.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"
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +000054#include "llvm/Support/WithColor.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000055#include "llvm/Support/raw_ostream.h"
Daniel Maleaa960c542013-06-28 19:11:40 +000056#include "llvm/Transforms/Instrumentation.h"
Chris Lattner4c522b92007-04-27 17:02:33 +000057#include <cerrno>
NAKAMURA Takumi15304872010-10-22 14:53:59 +000058
59#ifdef __CYGWIN__
60#include <cygwin/version.h>
61#if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
62#define DO_NOTHING_ATEXIT 1
63#endif
64#endif
65
Brian Gaeke960707c2003-11-11 22:41:34 +000066using namespace llvm;
67
Chandler Carruthf98597a2014-04-22 03:10:36 +000068#define DEBUG_TYPE "lli"
69
Chris Lattnera0d7b082002-12-23 23:59:41 +000070namespace {
Lang Hames9528bba2015-03-25 12:11:48 +000071
72 enum class JITKind { MCJIT, OrcMCJITReplacement, OrcLazy };
73
Chris Lattnera0d7b082002-12-23 23:59:41 +000074 cl::opt<std::string>
Gabor Greife16561c2007-07-05 17:07:56 +000075 InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
Chris Lattnerf5cad152002-07-22 02:10:13 +000076
Chris Lattnera0d7b082002-12-23 23:59:41 +000077 cl::list<std::string>
78 InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
Chris Lattnerf5cad152002-07-22 02:10:13 +000079
Chris Lattnera0d7b082002-12-23 23:59:41 +000080 cl::opt<bool> ForceInterpreter("force-interpreter",
Misha Brukmanc2186e32003-09-25 18:10:34 +000081 cl::desc("Force interpretation: disable JIT"),
82 cl::init(false));
Evan Cheng06d988e2008-08-08 08:12:06 +000083
Lang Hames9528bba2015-03-25 12:11:48 +000084 cl::opt<JITKind> UseJITKind("jit-kind",
85 cl::desc("Choose underlying JIT kind."),
86 cl::init(JITKind::MCJIT),
87 cl::values(
88 clEnumValN(JITKind::MCJIT, "mcjit",
89 "MCJIT"),
90 clEnumValN(JITKind::OrcMCJITReplacement,
91 "orc-mcjit",
92 "Orc-based MCJIT replacement"),
93 clEnumValN(JITKind::OrcLazy,
94 "orc-lazy",
Mehdi Amini732afdd2016-10-08 19:41:06 +000095 "Orc-based lazy JIT.")));
Lang Hames93de2a12015-01-23 21:25:00 +000096
Jim Grosbach0f435d02012-09-05 16:50:34 +000097 // The MCJIT supports building for a target address space separate from
98 // the JIT compilation process. Use a forked process and a copying
99 // memory manager with IPC to execute using this functionality.
100 cl::opt<bool> RemoteMCJIT("remote-mcjit",
101 cl::desc("Execute MCJIT'ed code in a separate process."),
102 cl::init(false));
103
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000104 // Manually specify the child process for remote execution. This overrides
105 // the simulated remote execution that allocates address space for child
Andrew Kaylor89352582013-10-29 01:33:14 +0000106 // execution. The child process will be executed and will communicate with
107 // lli via stdin/stdout pipes.
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000108 cl::opt<std::string>
Alp Tokera1186382014-01-22 21:52:35 +0000109 ChildExecPath("mcjit-remote-process",
110 cl::desc("Specify the filename of the process to launch "
111 "for remote MCJIT execution. If none is specified,"
112 "\n\tremote execution will be simulated in-process."),
113 cl::value_desc("filename"), cl::init(""));
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000114
Evan Cheng09bd0b12009-05-04 23:05:19 +0000115 // Determine optimization level.
116 cl::opt<char>
117 OptLevel("O",
118 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
119 "(default = '-O2')"),
120 cl::Prefix,
121 cl::ZeroOrMore,
122 cl::init(' '));
Evan Cheng06d988e2008-08-08 08:12:06 +0000123
Chris Lattner76766cb2005-12-16 05:00:21 +0000124 cl::opt<std::string>
Chris Lattner78e9e102005-12-16 05:19:18 +0000125 TargetTriple("mtriple", cl::desc("Override target triple for module"));
Evan Cheng61582542008-11-05 23:21:52 +0000126
127 cl::opt<std::string>
128 EntryFunc("entry-function",
129 cl::desc("Specify the entry function (default = 'main') "
130 "of the executable"),
131 cl::value_desc("function"),
132 cl::init("main"));
Eli Bendersky4c647582012-01-16 08:56:09 +0000133
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000134 cl::list<std::string>
Andrew Kaylor4404eb42013-10-28 21:58:15 +0000135 ExtraModules("extra-module",
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000136 cl::desc("Extra modules to be loaded"),
Alp Toker0a09ebf2013-10-28 22:51:25 +0000137 cl::value_desc("input bitcode"));
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000138
Lang Hames173c69f2014-01-08 04:09:09 +0000139 cl::list<std::string>
140 ExtraObjects("extra-object",
141 cl::desc("Extra object files to be loaded"),
142 cl::value_desc("input object"));
143
144 cl::list<std::string>
145 ExtraArchives("extra-archive",
146 cl::desc("Extra archive files to be loaded"),
147 cl::value_desc("input archive"));
148
149 cl::opt<bool>
150 EnableCacheManager("enable-cache-manager",
Lang Hames1ddecc02014-01-09 05:24:05 +0000151 cl::desc("Use cache manager to save/load mdoules"),
Lang Hames173c69f2014-01-08 04:09:09 +0000152 cl::init(false));
153
Chris Lattner55644062003-10-28 22:51:44 +0000154 cl::opt<std::string>
Lang Hames1ddecc02014-01-09 05:24:05 +0000155 ObjectCacheDir("object-cache-dir",
156 cl::desc("Directory to store cached object files "
157 "(must be user writable)"),
158 cl::init(""));
159
160 cl::opt<std::string>
Chris Lattner55644062003-10-28 22:51:44 +0000161 FakeArgv0("fake-argv0",
162 cl::desc("Override the 'argv[0]' value passed into the executing"
163 " program"), cl::value_desc("executable"));
Eli Bendersky4c647582012-01-16 08:56:09 +0000164
Chris Lattner3f0ffd32006-09-14 06:17:09 +0000165 cl::opt<bool>
166 DisableCoreFiles("disable-core-files", cl::Hidden,
167 cl::desc("Disable emission of core files if possible"));
Evan Cheng0422bef2008-04-22 06:51:41 +0000168
169 cl::opt<bool>
Evan Cheng16f036c2008-05-21 18:20:21 +0000170 NoLazyCompilation("disable-lazy-compilation",
Evan Cheng0422bef2008-04-22 06:51:41 +0000171 cl::desc("Disable JIT lazy compilation"),
172 cl::init(false));
Evan Cheng2129f592011-07-19 06:37:02 +0000173
Nick Lewyckyb0e97892012-04-18 08:34:12 +0000174 cl::opt<bool>
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000175 GenerateSoftFloatCalls("soft-float",
176 cl::desc("Generate software floating point library calls"),
177 cl::init(false));
178
Lang Hamesef5a0ee2016-04-25 19:56:45 +0000179 ExitOnError ExitOnErr;
Chris Lattnera0d7b082002-12-23 23:59:41 +0000180}
Chris Lattner009f8102001-10-27 08:43:52 +0000181
Lang Hames173c69f2014-01-08 04:09:09 +0000182//===----------------------------------------------------------------------===//
183// Object cache
184//
Lang Hames1ddecc02014-01-09 05:24:05 +0000185// This object cache implementation writes cached objects to disk to the
186// directory specified by CacheDir, using a filename provided in the module
187// descriptor. The cache tries to load a saved object using that path if the
188// file exists. CacheDir defaults to "", in which case objects are cached
NAKAMURA Takumif462f9c2014-01-10 10:38:28 +0000189// alongside their originating bitcodes.
Lang Hames173c69f2014-01-08 04:09:09 +0000190//
191class LLIObjectCache : public ObjectCache {
192public:
Lang Hames1ddecc02014-01-09 05:24:05 +0000193 LLIObjectCache(const std::string& CacheDir) : CacheDir(CacheDir) {
194 // Add trailing '/' to cache dir if necessary.
Lang Hamesf9dd8fd2014-01-09 05:29:59 +0000195 if (!this->CacheDir.empty() &&
196 this->CacheDir[this->CacheDir.size() - 1] != '/')
NAKAMURA Takumif462f9c2014-01-10 10:38:28 +0000197 this->CacheDir += '/';
Lang Hames1ddecc02014-01-09 05:24:05 +0000198 }
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000199 ~LLIObjectCache() override {}
Lang Hames173c69f2014-01-08 04:09:09 +0000200
Rafael Espindola48af1c22014-08-19 18:44:46 +0000201 void notifyObjectCompiled(const Module *M, MemoryBufferRef Obj) override {
Benjamin Kramer46e38f32016-06-08 10:01:20 +0000202 const std::string &ModuleID = M->getModuleIdentifier();
Lang Hames173c69f2014-01-08 04:09:09 +0000203 std::string CacheName;
204 if (!getCacheFilename(ModuleID, CacheName))
205 return;
NAKAMURA Takumi390e0602014-01-10 10:38:34 +0000206 if (!CacheDir.empty()) { // Create user-defined cache dir.
Rafael Espindolaf662e002015-07-15 21:24:07 +0000207 SmallString<128> dir(sys::path::parent_path(CacheName));
NAKAMURA Takumi390e0602014-01-10 10:38:34 +0000208 sys::fs::create_directories(Twine(dir));
209 }
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000210 std::error_code EC;
211 raw_fd_ostream outfile(CacheName, EC, sys::fs::F_None);
Rafael Espindola48af1c22014-08-19 18:44:46 +0000212 outfile.write(Obj.getBufferStart(), Obj.getBufferSize());
Lang Hames173c69f2014-01-08 04:09:09 +0000213 outfile.close();
214 }
215
Rafael Espindola5f2bb7d2014-08-13 18:49:01 +0000216 std::unique_ptr<MemoryBuffer> getObject(const Module* M) override {
Benjamin Kramer46e38f32016-06-08 10:01:20 +0000217 const std::string &ModuleID = M->getModuleIdentifier();
Lang Hames173c69f2014-01-08 04:09:09 +0000218 std::string CacheName;
219 if (!getCacheFilename(ModuleID, CacheName))
Craig Toppere6cb63e2014-04-25 04:24:47 +0000220 return nullptr;
Lang Hames173c69f2014-01-08 04:09:09 +0000221 // Load the object from the cache filename
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000222 ErrorOr<std::unique_ptr<MemoryBuffer>> IRObjectBuffer =
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000223 MemoryBuffer::getFile(CacheName, -1, false);
Lang Hames173c69f2014-01-08 04:09:09 +0000224 // If the file isn't there, that's OK.
225 if (!IRObjectBuffer)
Craig Toppere6cb63e2014-04-25 04:24:47 +0000226 return nullptr;
Lang Hames173c69f2014-01-08 04:09:09 +0000227 // MCJIT will want to write into this buffer, and we don't want that
228 // because the file has probably just been mmapped. Instead we make
229 // a copy. The filed-based buffer will be released when it goes
230 // out of scope.
Rafael Espindola3560ff22014-08-27 20:03:13 +0000231 return MemoryBuffer::getMemBufferCopy(IRObjectBuffer.get()->getBuffer());
Lang Hames173c69f2014-01-08 04:09:09 +0000232 }
233
234private:
Lang Hames1ddecc02014-01-09 05:24:05 +0000235 std::string CacheDir;
236
Lang Hames173c69f2014-01-08 04:09:09 +0000237 bool getCacheFilename(const std::string &ModID, std::string &CacheName) {
238 std::string Prefix("file:");
239 size_t PrefixLength = Prefix.length();
240 if (ModID.substr(0, PrefixLength) != Prefix)
241 return false;
NAKAMURA Takumid7fd6d92014-01-10 10:38:40 +0000242 std::string CacheSubdir = ModID.substr(PrefixLength);
243#if defined(_WIN32)
244 // Transform "X:\foo" => "/X\foo" for convenience.
245 if (isalpha(CacheSubdir[0]) && CacheSubdir[1] == ':') {
246 CacheSubdir[1] = CacheSubdir[0];
247 CacheSubdir[0] = '/';
248 }
249#endif
250 CacheName = CacheDir + CacheSubdir;
Lang Hames173c69f2014-01-08 04:09:09 +0000251 size_t pos = CacheName.rfind('.');
252 CacheName.replace(pos, CacheName.length() - pos, ".o");
253 return true;
254 }
255};
256
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000257// On Mingw and Cygwin, an external symbol named '__main' is called from the
Simon Pilgrimdae11f72016-11-20 13:31:13 +0000258// generated 'main' function to allow static initialization. To avoid linking
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000259// problems with remote targets (because lli's remote target support does not
260// currently handle external linking) we add a secondary module which defines
261// an empty '__main' function.
Mehdi Aminia7de8202016-04-18 18:52:39 +0000262static void addCygMingExtraModule(ExecutionEngine &EE, LLVMContext &Context,
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000263 StringRef TargetTripleStr) {
264 IRBuilder<> Builder(Context);
265 Triple TargetTriple(TargetTripleStr);
266
267 // Create a new module.
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000268 std::unique_ptr<Module> M = make_unique<Module>("CygMingHelper", Context);
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000269 M->setTargetTriple(TargetTripleStr);
270
271 // Create an empty function named "__main".
272 Function *Result;
273 if (TargetTriple.isArch64Bit()) {
274 Result = Function::Create(
275 TypeBuilder<int64_t(void), false>::get(Context),
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000276 GlobalValue::ExternalLinkage, "__main", M.get());
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000277 } else {
278 Result = Function::Create(
279 TypeBuilder<int32_t(void), false>::get(Context),
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000280 GlobalValue::ExternalLinkage, "__main", M.get());
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000281 }
282 BasicBlock *BB = BasicBlock::Create(Context, "__main", Result);
283 Builder.SetInsertPoint(BB);
284 Value *ReturnVal;
285 if (TargetTriple.isArch64Bit())
286 ReturnVal = ConstantInt::get(Context, APInt(64, 0));
287 else
288 ReturnVal = ConstantInt::get(Context, APInt(32, 0));
289 Builder.CreateRet(ReturnVal);
290
291 // Add this new module to the ExecutionEngine.
Mehdi Aminia7de8202016-04-18 18:52:39 +0000292 EE.addModule(std::move(M));
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000293}
294
Lang Hames1899d0c2015-06-09 02:43:27 +0000295CodeGenOpt::Level getOptLevel() {
296 switch (OptLevel) {
297 default:
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000298 WithColor::error(errs(), "lli") << "invalid optimization level.\n";
Lang Hames1899d0c2015-06-09 02:43:27 +0000299 exit(1);
300 case '0': return CodeGenOpt::None;
301 case '1': return CodeGenOpt::Less;
302 case ' ':
303 case '2': return CodeGenOpt::Default;
304 case '3': return CodeGenOpt::Aggressive;
305 }
306 llvm_unreachable("Unrecognized opt level.");
307}
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000308
Davide Italianoda8e6b22016-11-17 22:58:13 +0000309LLVM_ATTRIBUTE_NORETURN
310static void reportError(SMDiagnostic Err, const char *ProgName) {
311 Err.print(ProgName, errs());
312 exit(1);
313}
314
Chris Lattnerd7ff5782001-08-23 17:05:04 +0000315//===----------------------------------------------------------------------===//
Chris Lattnerd7ff5782001-08-23 17:05:04 +0000316// main Driver function
317//
Misha Brukman5b255e52003-10-14 21:39:53 +0000318int main(int argc, char **argv, char * const *envp) {
Rui Ueyama197194b2018-04-13 18:26:06 +0000319 InitLLVM X(argc, argv);
Daniel Dunbar3d92d932009-07-16 02:04:54 +0000320
Lang Hamesef5a0ee2016-04-25 19:56:45 +0000321 if (argc > 1)
322 ExitOnErr.setBanner(std::string(argv[0]) + ": ");
323
Daniel Dunbar3d92d932009-07-16 02:04:54 +0000324 // If we have a native target, initialize it to ensure it is linked in and
325 // usable by the JIT.
326 InitializeNativeTarget();
Jim Grosbach7b162492011-03-18 22:48:41 +0000327 InitializeNativeTargetAsmPrinter();
Jim Grosbach2cce3f92012-11-05 19:06:05 +0000328 InitializeNativeTargetAsmParser();
Daniel Dunbar3d92d932009-07-16 02:04:54 +0000329
Chris Lattner2785bdb2007-05-06 04:58:26 +0000330 cl::ParseCommandLineOptions(argc, argv,
Dan Gohman2c6a8212007-10-08 15:45:12 +0000331 "llvm interpreter & dynamic compiler\n");
Reid Spencer996ec722004-12-30 05:36:08 +0000332
Chris Lattner2785bdb2007-05-06 04:58:26 +0000333 // If the user doesn't want core files, disable them.
334 if (DisableCoreFiles)
335 sys::Process::PreventCoreFiles();
Eli Bendersky4c647582012-01-16 08:56:09 +0000336
Mehdi Aminia7de8202016-04-18 18:52:39 +0000337 LLVMContext Context;
338
Gabor Greife16561c2007-07-05 17:07:56 +0000339 // Load the bitcode...
Daniel Dunbar9589bf82010-11-13 00:28:01 +0000340 SMDiagnostic Err;
Rafael Espindolad233b062014-08-26 17:29:46 +0000341 std::unique_ptr<Module> Owner = parseIRFile(InputFile, Err, Context);
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000342 Module *Mod = Owner.get();
Davide Italianoda8e6b22016-11-17 22:58:13 +0000343 if (!Mod)
344 reportError(Err, argv[0]);
Chris Lattner2785bdb2007-05-06 04:58:26 +0000345
Lang Hames368c4222016-08-02 21:00:40 +0000346 if (UseJITKind == JITKind::OrcLazy) {
347 std::vector<std::unique_ptr<Module>> Ms;
348 Ms.push_back(std::move(Owner));
349 for (auto &ExtraMod : ExtraModules) {
350 Ms.push_back(parseIRFile(ExtraMod, Err, Context));
Davide Italianoda8e6b22016-11-17 22:58:13 +0000351 if (!Ms.back())
352 reportError(Err, argv[0]);
Lang Hames368c4222016-08-02 21:00:40 +0000353 }
Lang Hames1a2e6562016-10-28 16:52:34 +0000354 std::vector<std::string> Args;
355 Args.push_back(InputFile);
356 for (auto &Arg : InputArgv)
357 Args.push_back(Arg);
358 return runOrcLazyJIT(std::move(Ms), Args);
Lang Hames368c4222016-08-02 21:00:40 +0000359 }
Lang Hames9528bba2015-03-25 12:11:48 +0000360
Lang Hames173c69f2014-01-08 04:09:09 +0000361 if (EnableCacheManager) {
Eric Christopher79cc1e32014-09-02 22:28:02 +0000362 std::string CacheName("file:");
363 CacheName.append(InputFile);
364 Mod->setModuleIdentifier(CacheName);
Lang Hames173c69f2014-01-08 04:09:09 +0000365 }
366
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000367 // If not jitting lazily, load the whole bitcode file eagerly too.
368 if (NoLazyCompilation) {
Davide Italianob0e067b2016-11-09 21:30:33 +0000369 // Use *argv instead of argv[0] to work around a wrong GCC warning.
370 ExitOnError ExitOnErr(std::string(*argv) +
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000371 ": bitcode didn't read correctly: ");
372 ExitOnErr(Mod->materializeAll());
Evan Cheng0422bef2008-04-22 06:51:41 +0000373 }
Chris Lattner2785bdb2007-05-06 04:58:26 +0000374
Rafael Espindolae9fab9b2014-01-14 23:51:27 +0000375 std::string ErrorMsg;
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000376 EngineBuilder builder(std::move(Owner));
Jeffrey Yasskin31faeff2010-02-05 16:19:36 +0000377 builder.setMArch(MArch);
Craig Topper243f20f2018-01-09 18:14:18 +0000378 builder.setMCPU(getCPUStr());
379 builder.setMAttrs(getFeatureList());
Rafael Espindola8c34dd82016-05-18 22:04:49 +0000380 if (RelocModel.getNumOccurrences())
381 builder.setRelocationModel(RelocModel);
Rafael Espindola79e238a2017-08-03 02:16:21 +0000382 if (CMModel.getNumOccurrences())
383 builder.setCodeModel(CMModel);
Daniel Dunbara78d8092009-07-18 08:07:13 +0000384 builder.setErrorStr(&ErrorMsg);
385 builder.setEngineKind(ForceInterpreter
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000386 ? EngineKind::Interpreter
387 : EngineKind::JIT);
Lang Hames9528bba2015-03-25 12:11:48 +0000388 builder.setUseOrcMCJITReplacement(UseJITKind == JITKind::OrcMCJITReplacement);
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000389
Chris Lattner2785bdb2007-05-06 04:58:26 +0000390 // If we are supposed to override the target triple, do so now.
391 if (!TargetTriple.empty())
Duncan Sands3bd97fe2010-08-28 01:30:02 +0000392 Mod->setTargetTriple(Triple::normalize(TargetTriple));
Evan Cheng0422bef2008-04-22 06:51:41 +0000393
Eli Bendersky4c647582012-01-16 08:56:09 +0000394 // Enable MCJIT if desired.
Craig Toppere6cb63e2014-04-25 04:24:47 +0000395 RTDyldMemoryManager *RTDyldMM = nullptr;
Eric Christopher79cc1e32014-09-02 22:28:02 +0000396 if (!ForceInterpreter) {
Jim Grosbach0f435d02012-09-05 16:50:34 +0000397 if (RemoteMCJIT)
Lang Hames9d7a2692016-01-11 16:35:55 +0000398 RTDyldMM = new ForwardingMemoryManager();
Jim Grosbach0f435d02012-09-05 16:50:34 +0000399 else
Filip Pizlo9bc53e82013-05-14 19:29:00 +0000400 RTDyldMM = new SectionMemoryManager();
Lang Hames4a5697e2014-12-03 00:51:19 +0000401
402 // Deliberately construct a temp std::unique_ptr to pass in. Do not null out
403 // RTDyldMM: We still use it below, even though we don't own it.
404 builder.setMCJITMemoryManager(
405 std::unique_ptr<RTDyldMemoryManager>(RTDyldMM));
Lang Hames0f154902014-09-23 16:56:02 +0000406 } else if (RemoteMCJIT) {
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000407 WithColor::error(errs(), argv[0])
408 << "remote process execution does not work with the interpreter.\n";
Lang Hames0f154902014-09-23 16:56:02 +0000409 exit(1);
Eli Bendersky4c647582012-01-16 08:56:09 +0000410 }
Daniel Dunbar70ff8b02010-11-17 16:06:37 +0000411
Lang Hames1899d0c2015-06-09 02:43:27 +0000412 builder.setOptLevel(getOptLevel());
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000413
David Blaikiec14bfec2017-11-27 19:43:58 +0000414 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000415 if (FloatABIForCalls != FloatABI::Default)
416 Options.FloatABIType = FloatABIForCalls;
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000417
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000418 builder.setTargetOptions(Options);
419
Mehdi Aminia7de8202016-04-18 18:52:39 +0000420 std::unique_ptr<ExecutionEngine> EE(builder.create());
Chris Lattnerf840ed72009-07-07 18:31:09 +0000421 if (!EE) {
422 if (!ErrorMsg.empty())
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000423 WithColor::error(errs(), argv[0])
424 << "error creating EE: " << ErrorMsg << "\n";
Chris Lattnerf840ed72009-07-07 18:31:09 +0000425 else
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000426 WithColor::error(errs(), argv[0]) << "unknown error creating EE!\n";
Chris Lattner2785bdb2007-05-06 04:58:26 +0000427 exit(1);
428 }
429
Mehdi Aminia7de8202016-04-18 18:52:39 +0000430 std::unique_ptr<LLIObjectCache> CacheManager;
Lang Hames173c69f2014-01-08 04:09:09 +0000431 if (EnableCacheManager) {
Mehdi Aminia7de8202016-04-18 18:52:39 +0000432 CacheManager.reset(new LLIObjectCache(ObjectCacheDir));
433 EE->setObjectCache(CacheManager.get());
Lang Hames173c69f2014-01-08 04:09:09 +0000434 }
435
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000436 // Load any additional modules specified on the command line.
437 for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) {
Rafael Espindolad233b062014-08-26 17:29:46 +0000438 std::unique_ptr<Module> XMod = parseIRFile(ExtraModules[i], Err, Context);
Davide Italianoda8e6b22016-11-17 22:58:13 +0000439 if (!XMod)
440 reportError(Err, argv[0]);
Lang Hames173c69f2014-01-08 04:09:09 +0000441 if (EnableCacheManager) {
Eric Christopher79cc1e32014-09-02 22:28:02 +0000442 std::string CacheName("file:");
443 CacheName.append(ExtraModules[i]);
444 XMod->setModuleIdentifier(CacheName);
Lang Hames173c69f2014-01-08 04:09:09 +0000445 }
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000446 EE->addModule(std::move(XMod));
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000447 }
448
Lang Hames173c69f2014-01-08 04:09:09 +0000449 for (unsigned i = 0, e = ExtraObjects.size(); i != e; ++i) {
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000450 Expected<object::OwningBinary<object::ObjectFile>> Obj =
Rafael Espindola51cc3602014-01-22 00:14:49 +0000451 object::ObjectFile::createObjectFile(ExtraObjects[i]);
Lang Hames173c69f2014-01-08 04:09:09 +0000452 if (!Obj) {
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000453 // TODO: Actually report errors helpfully.
454 consumeError(Obj.takeError());
Davide Italianoda8e6b22016-11-17 22:58:13 +0000455 reportError(Err, argv[0]);
Lang Hames173c69f2014-01-08 04:09:09 +0000456 }
Rafael Espindola061beab2014-08-20 15:19:37 +0000457 object::OwningBinary<object::ObjectFile> &O = Obj.get();
Rafael Espindola7271c192014-08-26 21:04:04 +0000458 EE->addObjectFile(std::move(O));
Lang Hames173c69f2014-01-08 04:09:09 +0000459 }
460
461 for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) {
Rafael Espindola48af1c22014-08-19 18:44:46 +0000462 ErrorOr<std::unique_ptr<MemoryBuffer>> ArBufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000463 MemoryBuffer::getFileOrSTDIN(ExtraArchives[i]);
Davide Italianoda8e6b22016-11-17 22:58:13 +0000464 if (!ArBufOrErr)
465 reportError(Err, argv[0]);
Rafael Espindola48af1c22014-08-19 18:44:46 +0000466 std::unique_ptr<MemoryBuffer> &ArBuf = ArBufOrErr.get();
Rafael Espindolae1923412014-08-01 18:31:17 +0000467
Kevin Enderbyc60a3212016-06-29 20:35:44 +0000468 Expected<std::unique_ptr<object::Archive>> ArOrErr =
Rafael Espindola48af1c22014-08-19 18:44:46 +0000469 object::Archive::create(ArBuf->getMemBufferRef());
Kevin Enderbyc60a3212016-06-29 20:35:44 +0000470 if (!ArOrErr) {
471 std::string Buf;
472 raw_string_ostream OS(Buf);
473 logAllUnhandledErrors(ArOrErr.takeError(), OS, "");
474 OS.flush();
475 errs() << Buf;
Davide Italiano86511442016-11-17 22:59:13 +0000476 exit(1);
Lang Hames173c69f2014-01-08 04:09:09 +0000477 }
Rafael Espindola48af1c22014-08-19 18:44:46 +0000478 std::unique_ptr<object::Archive> &Ar = ArOrErr.get();
479
480 object::OwningBinary<object::Archive> OB(std::move(Ar), std::move(ArBuf));
481
482 EE->addArchive(std::move(OB));
Lang Hames173c69f2014-01-08 04:09:09 +0000483 }
484
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000485 // If the target is Cygwin/MingW and we are generating remote code, we
486 // need an extra module to help out with linking.
487 if (RemoteMCJIT && Triple(Mod->getTargetTriple()).isOSCygMing()) {
Mehdi Aminia7de8202016-04-18 18:52:39 +0000488 addCygMingExtraModule(*EE, Context, Mod->getTargetTriple());
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000489 }
490
Eli Bendersky5262ad22012-03-13 08:33:15 +0000491 // The following functions have no effect if their respective profiling
492 // support wasn't enabled in the build configuration.
493 EE->RegisterJITEventListener(
494 JITEventListener::createOProfileJITEventListener());
495 EE->RegisterJITEventListener(
496 JITEventListener::createIntelJITEventListener());
Jeffrey Yasskin0b08f3d2009-06-25 02:04:04 +0000497
Jim Grosbach0f435d02012-09-05 16:50:34 +0000498 if (!NoLazyCompilation && RemoteMCJIT) {
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000499 WithColor::warning(errs(), argv[0])
500 << "remote mcjit does not support lazy compilation\n";
Jim Grosbach0f435d02012-09-05 16:50:34 +0000501 NoLazyCompilation = true;
502 }
Jeffrey Yasskinaa8814a2009-10-27 22:39:42 +0000503 EE->DisableLazyCompilation(NoLazyCompilation);
Evan Cheng0422bef2008-04-22 06:51:41 +0000504
Chris Lattner2785bdb2007-05-06 04:58:26 +0000505 // If the user specifically requested an argv[0] to pass into the program,
506 // do it now.
507 if (!FakeArgv0.empty()) {
Chris Bienemane71fb5c2015-01-22 01:49:59 +0000508 InputFile = static_cast<std::string>(FakeArgv0);
Chris Lattner2785bdb2007-05-06 04:58:26 +0000509 } else {
510 // Otherwise, if there is a .bc suffix on the executable strip it off, it
511 // might confuse the program.
Benjamin Kramera944a9a2010-04-15 11:33:14 +0000512 if (StringRef(InputFile).endswith(".bc"))
Chris Lattner2785bdb2007-05-06 04:58:26 +0000513 InputFile.erase(InputFile.length() - 3);
514 }
515
516 // Add the module's name to the start of the vector of arguments to main().
517 InputArgv.insert(InputArgv.begin(), InputFile);
518
519 // Call the main function from M as if its signature were:
520 // int main (int argc, char **argv, const char **envp)
521 // using the contents of Args to determine argc & argv, and the contents of
522 // EnvVars to determine envp.
523 //
Evan Cheng61582542008-11-05 23:21:52 +0000524 Function *EntryFn = Mod->getFunction(EntryFunc);
525 if (!EntryFn) {
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000526 WithColor::error(errs(), argv[0])
527 << '\'' << EntryFunc << "\' function not found in module.\n";
Chris Lattner2785bdb2007-05-06 04:58:26 +0000528 return -1;
529 }
530
Chris Lattner2785bdb2007-05-06 04:58:26 +0000531 // Reset errno to zero on entry to main.
532 errno = 0;
Eli Bendersky4c647582012-01-16 08:56:09 +0000533
Lang Hames3fde6522016-04-18 19:55:43 +0000534 int Result = -1;
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000535
Lang Hames9d7a2692016-01-11 16:35:55 +0000536 // Sanity check use of remote-jit: LLI currently only supports use of the
537 // remote JIT on Unix platforms.
Lang Hames9d7a2692016-01-11 16:35:55 +0000538 if (RemoteMCJIT) {
539#ifndef LLVM_ON_UNIX
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000540 WithColor::warning(errs(), argv[0])
Jonas Devlieghere7b5fa242018-04-22 08:35:00 +0000541 << "host does not support external remote targets.\n";
542 WithColor::note() << "defaulting to local execution\n";
Lang Hames4b6e0212016-01-11 21:41:34 +0000543 return -1;
Lang Hames9d7a2692016-01-11 16:35:55 +0000544#else
545 if (ChildExecPath.empty()) {
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000546 WithColor::error(errs(), argv[0])
547 << "-remote-mcjit requires -mcjit-remote-process.\n";
Lang Hames9d7a2692016-01-11 16:35:55 +0000548 exit(1);
549 } else if (!sys::fs::can_execute(ChildExecPath)) {
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000550 WithColor::error(errs(), argv[0])
551 << "unable to find usable child executable: '" << ChildExecPath
552 << "'\n";
Lang Hames9d7a2692016-01-11 16:35:55 +0000553 return -1;
554 }
555#endif
556 }
557
Andrew Kaylor58365b92012-11-27 19:49:00 +0000558 if (!RemoteMCJIT) {
Andrew Kaylor6587bcf2013-10-11 22:47:10 +0000559 // If the program doesn't explicitly call exit, we will need the Exit
560 // function later on to make an explicit call, so get the function now.
561 Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000562 Type::getInt32Ty(Context));
Andrew Kaylor6587bcf2013-10-11 22:47:10 +0000563
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000564 // Run static constructors.
Eric Christopher79cc1e32014-09-02 22:28:02 +0000565 if (!ForceInterpreter) {
Andrew Kaylorea395922013-10-01 01:47:35 +0000566 // Give MCJIT a chance to apply relocations and set page permissions.
567 EE->finalizeObject();
568 }
569 EE->runStaticConstructorsDestructors(false);
Evan Cheng0422bef2008-04-22 06:51:41 +0000570
NAKAMURA Takumi87e08802013-12-07 11:21:42 +0000571 // Trigger compilation separately so code regions that need to be
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000572 // invalidated will be known.
573 (void)EE->getPointerToFunction(EntryFn);
574 // Clear instruction cache before code will be executed.
575 if (RTDyldMM)
576 static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
577
578 // Run main.
579 Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
580
581 // Run static destructors.
582 EE->runStaticConstructorsDestructors(true);
583
584 // If the program didn't call exit explicitly, we should call it now.
585 // This ensures that any atexit handlers get called correctly.
586 if (Function *ExitF = dyn_cast<Function>(Exit)) {
587 std::vector<GenericValue> Args;
588 GenericValue ResultGV;
589 ResultGV.IntVal = APInt(32, Result);
590 Args.push_back(ResultGV);
591 EE->runFunction(ExitF, Args);
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000592 WithColor::error(errs(), argv[0]) << "exit(" << Result << ") returned!\n";
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000593 abort();
594 } else {
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000595 WithColor::error(errs(), argv[0])
596 << "exit defined with wrong prototype!\n";
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000597 abort();
598 }
599 } else {
600 // else == "if (RemoteMCJIT)"
601
602 // Remote target MCJIT doesn't (yet) support static constructors. No reason
Hiroshi Inoue0ca79dc2017-07-11 06:04:59 +0000603 // it couldn't. This is a limitation of the LLI implementation, not the
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000604 // MCJIT itself. FIXME.
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000605
Lang Hames9d7a2692016-01-11 16:35:55 +0000606 // Lanch the remote process and get a channel to it.
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000607 std::unique_ptr<FDRawChannel> C = launchRemote();
Lang Hames9d7a2692016-01-11 16:35:55 +0000608 if (!C) {
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000609 WithColor::error(errs(), argv[0]) << "failed to launch remote JIT.\n";
Lang Hames9d7a2692016-01-11 16:35:55 +0000610 exit(1);
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000611 }
612
Lang Hames9d7a2692016-01-11 16:35:55 +0000613 // Create a remote target client running over the channel.
Lang Hames9e68b7342017-09-04 20:54:46 +0000614 typedef orc::remote::OrcRemoteTargetClient MyRemote;
615 auto R = ExitOnErr(MyRemote::Create(*C, ExitOnErr));
Jim Grosbach748b9472012-08-28 23:22:30 +0000616
Lang Hames9d7a2692016-01-11 16:35:55 +0000617 // Create a remote memory manager.
Lang Hames9e68b7342017-09-04 20:54:46 +0000618 auto RemoteMM = ExitOnErr(R->createRemoteMemoryManager());
Lang Hames9d7a2692016-01-11 16:35:55 +0000619
620 // Forward MCJIT's memory manager calls to the remote memory manager.
621 static_cast<ForwardingMemoryManager*>(RTDyldMM)->setMemMgr(
622 std::move(RemoteMM));
623
624 // Forward MCJIT's symbol resolution calls to the remote.
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +0000625 static_cast<ForwardingMemoryManager *>(RTDyldMM)->setResolver(
626 orc::createLambdaResolver(
627 [](const std::string &Name) { return nullptr; },
628 [&](const std::string &Name) {
629 if (auto Addr = ExitOnErr(R->getSymbolAddress(Name)))
630 return JITSymbol(Addr, JITSymbolFlags::Exported);
631 return JITSymbol(nullptr);
632 }));
Lang Hames9d7a2692016-01-11 16:35:55 +0000633
634 // Grab the target address of the JIT'd main function on the remote and call
635 // it.
Jim Grosbach0f435d02012-09-05 16:50:34 +0000636 // FIXME: argv and envp handling.
Lang Hamesad4a9112016-08-01 20:49:11 +0000637 JITTargetAddress Entry = EE->getFunctionAddress(EntryFn->getName().str());
Lang Hames9d7a2692016-01-11 16:35:55 +0000638 EE->finalizeObject();
Tim Northover79ab7f72013-05-19 09:55:06 +0000639 DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"
640 << format("%llx", Entry) << "\n");
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000641 Result = ExitOnErr(R->callIntVoid(Entry));
Jim Grosbach0f435d02012-09-05 16:50:34 +0000642
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000643 // Like static constructors, the remote target MCJIT support doesn't handle
644 // this yet. It could. FIXME.
645
Lang Hames9d7a2692016-01-11 16:35:55 +0000646 // Delete the EE - we need to tear it down *before* we terminate the session
647 // with the remote, otherwise it'll crash when it tries to release resources
648 // on a remote that has already been disconnected.
Mehdi Aminia7de8202016-04-18 18:52:39 +0000649 EE.reset();
Lang Hames9d7a2692016-01-11 16:35:55 +0000650
651 // Signal the remote target that we're done JITing.
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000652 ExitOnErr(R->terminateSession());
Chris Lattner2785bdb2007-05-06 04:58:26 +0000653 }
Jim Grosbach0f435d02012-09-05 16:50:34 +0000654
Jim Grosbach0f435d02012-09-05 16:50:34 +0000655 return Result;
Chris Lattnerd7ff5782001-08-23 17:05:04 +0000656}
Lang Hames9d7a2692016-01-11 16:35:55 +0000657
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000658std::unique_ptr<FDRawChannel> launchRemote() {
Lang Hames9d7a2692016-01-11 16:35:55 +0000659#ifndef LLVM_ON_UNIX
660 llvm_unreachable("launchRemote not supported on non-Unix platforms");
661#else
662 int PipeFD[2][2];
663 pid_t ChildPID;
664
665 // Create two pipes.
666 if (pipe(PipeFD[0]) != 0 || pipe(PipeFD[1]) != 0)
667 perror("Error creating pipe: ");
668
669 ChildPID = fork();
670
671 if (ChildPID == 0) {
672 // In the child...
673
674 // Close the parent ends of the pipes
675 close(PipeFD[0][1]);
676 close(PipeFD[1][0]);
677
678
679 // Execute the child process.
680 std::unique_ptr<char[]> ChildPath, ChildIn, ChildOut;
681 {
682 ChildPath.reset(new char[ChildExecPath.size() + 1]);
683 std::copy(ChildExecPath.begin(), ChildExecPath.end(), &ChildPath[0]);
684 ChildPath[ChildExecPath.size()] = '\0';
NAKAMURA Takumicef0a8212016-01-15 02:14:46 +0000685 std::string ChildInStr = utostr(PipeFD[0][0]);
Lang Hames9d7a2692016-01-11 16:35:55 +0000686 ChildIn.reset(new char[ChildInStr.size() + 1]);
687 std::copy(ChildInStr.begin(), ChildInStr.end(), &ChildIn[0]);
688 ChildIn[ChildInStr.size()] = '\0';
NAKAMURA Takumicef0a8212016-01-15 02:14:46 +0000689 std::string ChildOutStr = utostr(PipeFD[1][1]);
Lang Hames9d7a2692016-01-11 16:35:55 +0000690 ChildOut.reset(new char[ChildOutStr.size() + 1]);
691 std::copy(ChildOutStr.begin(), ChildOutStr.end(), &ChildOut[0]);
692 ChildOut[ChildOutStr.size()] = '\0';
693 }
694
695 char * const args[] = { &ChildPath[0], &ChildIn[0], &ChildOut[0], nullptr };
696 int rc = execv(ChildExecPath.c_str(), args);
697 if (rc != 0)
698 perror("Error executing child process: ");
699 llvm_unreachable("Error executing child process");
700 }
701 // else we're the parent...
702
703 // Close the child ends of the pipes
704 close(PipeFD[0][0]);
705 close(PipeFD[1][1]);
706
707 // Return an RPC channel connected to our end of the pipes.
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000708 return llvm::make_unique<FDRawChannel>(PipeFD[1][0], PipeFD[0][1]);
Lang Hames9d7a2692016-01-11 16:35:55 +0000709#endif
710}