1 //===- lli.cpp - LLVM Interpreter / Dynamic compiler ----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // 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
12 // compiler, or through an interpreter if no JIT is available for this platform.
14 //===----------------------------------------------------------------------===//
16 #include "OrcLazyJIT.h"
17 #include "RemoteJITUtils.h"
18 #include "llvm/IR/LLVMContext.h"
19 #include "llvm/ADT/Triple.h"
20 #include "llvm/Bitcode/ReaderWriter.h"
21 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
22 #include "llvm/ExecutionEngine/GenericValue.h"
23 #include "llvm/ExecutionEngine/Interpreter.h"
24 #include "llvm/ExecutionEngine/JITEventListener.h"
25 #include "llvm/ExecutionEngine/MCJIT.h"
26 #include "llvm/ExecutionEngine/ObjectCache.h"
27 #include "llvm/ExecutionEngine/OrcMCJITReplacement.h"
28 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
29 #include "llvm/ExecutionEngine/Orc/OrcRemoteTargetClient.h"
30 #include "llvm/IR/IRBuilder.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/IR/Type.h"
33 #include "llvm/IR/TypeBuilder.h"
34 #include "llvm/IRReader/IRReader.h"
35 #include "llvm/Object/Archive.h"
36 #include "llvm/Object/ObjectFile.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/DynamicLibrary.h"
40 #include "llvm/Support/Format.h"
41 #include "llvm/Support/ManagedStatic.h"
42 #include "llvm/Support/MathExtras.h"
43 #include "llvm/Support/Memory.h"
44 #include "llvm/Support/MemoryBuffer.h"
45 #include "llvm/Support/Path.h"
46 #include "llvm/Support/PluginLoader.h"
47 #include "llvm/Support/PrettyStackTrace.h"
48 #include "llvm/Support/Process.h"
49 #include "llvm/Support/Program.h"
50 #include "llvm/Support/Signals.h"
51 #include "llvm/Support/SourceMgr.h"
52 #include "llvm/Support/TargetSelect.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include "llvm/Transforms/Instrumentation.h"
58 #include <cygwin/version.h>
59 #if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
60 #define DO_NOTHING_ATEXIT 1
66 #define DEBUG_TYPE "lli"
70 enum class JITKind { MCJIT, OrcMCJITReplacement, OrcLazy };
73 InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
76 InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
78 cl::opt<bool> ForceInterpreter("force-interpreter",
79 cl::desc("Force interpretation: disable JIT"),
82 cl::opt<JITKind> UseJITKind("jit-kind",
83 cl::desc("Choose underlying JIT kind."),
84 cl::init(JITKind::MCJIT),
86 clEnumValN(JITKind::MCJIT, "mcjit",
88 clEnumValN(JITKind::OrcMCJITReplacement,
90 "Orc-based MCJIT replacement"),
91 clEnumValN(JITKind::OrcLazy,
93 "Orc-based lazy JIT."),
96 // 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."),
103 // Manually specify the child process for remote execution. This overrides
104 // the simulated remote execution that allocates address space for child
105 // execution. The child process will be executed and will communicate with
106 // lli via stdin/stdout pipes.
108 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(""));
114 // Determine optimization level.
117 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
118 "(default = '-O2')"),
124 TargetTriple("mtriple", cl::desc("Override target triple for module"));
128 cl::desc("Architecture to generate assembly for (see --version)"));
132 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
133 cl::value_desc("cpu-name"),
136 cl::list<std::string>
139 cl::desc("Target specific attributes (-mattr=help for details)"),
140 cl::value_desc("a1,+a2,-a3,..."));
143 EntryFunc("entry-function",
144 cl::desc("Specify the entry function (default = 'main') "
145 "of the executable"),
146 cl::value_desc("function"),
149 cl::list<std::string>
150 ExtraModules("extra-module",
151 cl::desc("Extra modules to be loaded"),
152 cl::value_desc("input bitcode"));
154 cl::list<std::string>
155 ExtraObjects("extra-object",
156 cl::desc("Extra object files to be loaded"),
157 cl::value_desc("input object"));
159 cl::list<std::string>
160 ExtraArchives("extra-archive",
161 cl::desc("Extra archive files to be loaded"),
162 cl::value_desc("input archive"));
165 EnableCacheManager("enable-cache-manager",
166 cl::desc("Use cache manager to save/load mdoules"),
170 ObjectCacheDir("object-cache-dir",
171 cl::desc("Directory to store cached object files "
172 "(must be user writable)"),
176 FakeArgv0("fake-argv0",
177 cl::desc("Override the 'argv[0]' value passed into the executing"
178 " program"), cl::value_desc("executable"));
181 DisableCoreFiles("disable-core-files", cl::Hidden,
182 cl::desc("Disable emission of core files if possible"));
185 NoLazyCompilation("disable-lazy-compilation",
186 cl::desc("Disable JIT lazy compilation"),
189 cl::opt<Reloc::Model>
190 RelocModel("relocation-model",
191 cl::desc("Choose relocation model"),
192 cl::init(Reloc::Default),
194 clEnumValN(Reloc::Default, "default",
195 "Target default relocation model"),
196 clEnumValN(Reloc::Static, "static",
197 "Non-relocatable code"),
198 clEnumValN(Reloc::PIC_, "pic",
199 "Fully relocatable, position independent code"),
200 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
201 "Relocatable external references, non-relocatable code"),
204 cl::opt<llvm::CodeModel::Model>
205 CMModel("code-model",
206 cl::desc("Choose code model"),
207 cl::init(CodeModel::JITDefault),
208 cl::values(clEnumValN(CodeModel::JITDefault, "default",
209 "Target default JIT code model"),
210 clEnumValN(CodeModel::Small, "small",
212 clEnumValN(CodeModel::Kernel, "kernel",
213 "Kernel code model"),
214 clEnumValN(CodeModel::Medium, "medium",
215 "Medium code model"),
216 clEnumValN(CodeModel::Large, "large",
221 GenerateSoftFloatCalls("soft-float",
222 cl::desc("Generate software floating point library calls"),
225 cl::opt<llvm::FloatABI::ABIType>
226 FloatABIForCalls("float-abi",
227 cl::desc("Choose float ABI type"),
228 cl::init(FloatABI::Default),
230 clEnumValN(FloatABI::Default, "default",
231 "Target default float ABI type"),
232 clEnumValN(FloatABI::Soft, "soft",
233 "Soft float ABI (implied by -soft-float)"),
234 clEnumValN(FloatABI::Hard, "hard",
235 "Hard float ABI (uses FP registers)"),
239 //===----------------------------------------------------------------------===//
242 // This object cache implementation writes cached objects to disk to the
243 // directory specified by CacheDir, using a filename provided in the module
244 // descriptor. The cache tries to load a saved object using that path if the
245 // file exists. CacheDir defaults to "", in which case objects are cached
246 // alongside their originating bitcodes.
248 class LLIObjectCache : public ObjectCache {
250 LLIObjectCache(const std::string& CacheDir) : CacheDir(CacheDir) {
251 // Add trailing '/' to cache dir if necessary.
252 if (!this->CacheDir.empty() &&
253 this->CacheDir[this->CacheDir.size() - 1] != '/')
254 this->CacheDir += '/';
256 ~LLIObjectCache() override {}
258 void notifyObjectCompiled(const Module *M, MemoryBufferRef Obj) override {
259 const std::string ModuleID = M->getModuleIdentifier();
260 std::string CacheName;
261 if (!getCacheFilename(ModuleID, CacheName))
263 if (!CacheDir.empty()) { // Create user-defined cache dir.
264 SmallString<128> dir(sys::path::parent_path(CacheName));
265 sys::fs::create_directories(Twine(dir));
268 raw_fd_ostream outfile(CacheName, EC, sys::fs::F_None);
269 outfile.write(Obj.getBufferStart(), Obj.getBufferSize());
273 std::unique_ptr<MemoryBuffer> getObject(const Module* M) override {
274 const std::string ModuleID = M->getModuleIdentifier();
275 std::string CacheName;
276 if (!getCacheFilename(ModuleID, CacheName))
278 // Load the object from the cache filename
279 ErrorOr<std::unique_ptr<MemoryBuffer>> IRObjectBuffer =
280 MemoryBuffer::getFile(CacheName.c_str(), -1, false);
281 // If the file isn't there, that's OK.
284 // MCJIT will want to write into this buffer, and we don't want that
285 // because the file has probably just been mmapped. Instead we make
286 // a copy. The filed-based buffer will be released when it goes
288 return MemoryBuffer::getMemBufferCopy(IRObjectBuffer.get()->getBuffer());
292 std::string CacheDir;
294 bool getCacheFilename(const std::string &ModID, std::string &CacheName) {
295 std::string Prefix("file:");
296 size_t PrefixLength = Prefix.length();
297 if (ModID.substr(0, PrefixLength) != Prefix)
299 std::string CacheSubdir = ModID.substr(PrefixLength);
301 // Transform "X:\foo" => "/X\foo" for convenience.
302 if (isalpha(CacheSubdir[0]) && CacheSubdir[1] == ':') {
303 CacheSubdir[1] = CacheSubdir[0];
304 CacheSubdir[0] = '/';
307 CacheName = CacheDir + CacheSubdir;
308 size_t pos = CacheName.rfind('.');
309 CacheName.replace(pos, CacheName.length() - pos, ".o");
314 static ExecutionEngine *EE = nullptr;
315 static LLIObjectCache *CacheManager = nullptr;
317 static void do_shutdown() {
318 // Cygwin-1.5 invokes DLL's dtors before atexit handler.
319 #ifndef DO_NOTHING_ATEXIT
327 // On Mingw and Cygwin, an external symbol named '__main' is called from the
328 // generated 'main' function to allow static intialization. To avoid linking
329 // problems with remote targets (because lli's remote target support does not
330 // currently handle external linking) we add a secondary module which defines
331 // an empty '__main' function.
332 static void addCygMingExtraModule(ExecutionEngine *EE,
333 LLVMContext &Context,
334 StringRef TargetTripleStr) {
335 IRBuilder<> Builder(Context);
336 Triple TargetTriple(TargetTripleStr);
338 // Create a new module.
339 std::unique_ptr<Module> M = make_unique<Module>("CygMingHelper", Context);
340 M->setTargetTriple(TargetTripleStr);
342 // Create an empty function named "__main".
344 if (TargetTriple.isArch64Bit()) {
345 Result = Function::Create(
346 TypeBuilder<int64_t(void), false>::get(Context),
347 GlobalValue::ExternalLinkage, "__main", M.get());
349 Result = Function::Create(
350 TypeBuilder<int32_t(void), false>::get(Context),
351 GlobalValue::ExternalLinkage, "__main", M.get());
353 BasicBlock *BB = BasicBlock::Create(Context, "__main", Result);
354 Builder.SetInsertPoint(BB);
356 if (TargetTriple.isArch64Bit())
357 ReturnVal = ConstantInt::get(Context, APInt(64, 0));
359 ReturnVal = ConstantInt::get(Context, APInt(32, 0));
360 Builder.CreateRet(ReturnVal);
362 // Add this new module to the ExecutionEngine.
363 EE->addModule(std::move(M));
366 CodeGenOpt::Level getOptLevel() {
369 errs() << "lli: Invalid optimization level.\n";
371 case '0': return CodeGenOpt::None;
372 case '1': return CodeGenOpt::Less;
374 case '2': return CodeGenOpt::Default;
375 case '3': return CodeGenOpt::Aggressive;
377 llvm_unreachable("Unrecognized opt level.");
380 //===----------------------------------------------------------------------===//
381 // main Driver function
383 int main(int argc, char **argv, char * const *envp) {
384 sys::PrintStackTraceOnErrorSignal();
385 PrettyStackTraceProgram X(argc, argv);
387 LLVMContext &Context = getGlobalContext();
388 atexit(do_shutdown); // Call llvm_shutdown() on exit.
390 // If we have a native target, initialize it to ensure it is linked in and
391 // usable by the JIT.
392 InitializeNativeTarget();
393 InitializeNativeTargetAsmPrinter();
394 InitializeNativeTargetAsmParser();
396 cl::ParseCommandLineOptions(argc, argv,
397 "llvm interpreter & dynamic compiler\n");
399 // If the user doesn't want core files, disable them.
400 if (DisableCoreFiles)
401 sys::Process::PreventCoreFiles();
403 // Load the bitcode...
405 std::unique_ptr<Module> Owner = parseIRFile(InputFile, Err, Context);
406 Module *Mod = Owner.get();
408 Err.print(argv[0], errs());
412 if (UseJITKind == JITKind::OrcLazy)
413 return runOrcLazyJIT(std::move(Owner), argc, argv);
415 if (EnableCacheManager) {
416 std::string CacheName("file:");
417 CacheName.append(InputFile);
418 Mod->setModuleIdentifier(CacheName);
421 // If not jitting lazily, load the whole bitcode file eagerly too.
422 if (NoLazyCompilation) {
423 if (std::error_code EC = Mod->materializeAll()) {
424 errs() << argv[0] << ": bitcode didn't read correctly.\n";
425 errs() << "Reason: " << EC.message() << "\n";
430 std::string ErrorMsg;
431 EngineBuilder builder(std::move(Owner));
432 builder.setMArch(MArch);
433 builder.setMCPU(MCPU);
434 builder.setMAttrs(MAttrs);
435 builder.setRelocationModel(RelocModel);
436 builder.setCodeModel(CMModel);
437 builder.setErrorStr(&ErrorMsg);
438 builder.setEngineKind(ForceInterpreter
439 ? EngineKind::Interpreter
441 builder.setUseOrcMCJITReplacement(UseJITKind == JITKind::OrcMCJITReplacement);
443 // If we are supposed to override the target triple, do so now.
444 if (!TargetTriple.empty())
445 Mod->setTargetTriple(Triple::normalize(TargetTriple));
447 // Enable MCJIT if desired.
448 RTDyldMemoryManager *RTDyldMM = nullptr;
449 if (!ForceInterpreter) {
451 RTDyldMM = new ForwardingMemoryManager();
453 RTDyldMM = new SectionMemoryManager();
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));
459 } else if (RemoteMCJIT) {
460 errs() << "error: Remote process execution does not work with the "
465 builder.setOptLevel(getOptLevel());
467 TargetOptions Options;
468 if (FloatABIForCalls != FloatABI::Default)
469 Options.FloatABIType = FloatABIForCalls;
471 builder.setTargetOptions(Options);
473 EE = builder.create();
475 if (!ErrorMsg.empty())
476 errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n";
478 errs() << argv[0] << ": unknown error creating EE!\n";
482 if (EnableCacheManager) {
483 CacheManager = new LLIObjectCache(ObjectCacheDir);
484 EE->setObjectCache(CacheManager);
487 // Load any additional modules specified on the command line.
488 for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) {
489 std::unique_ptr<Module> XMod = parseIRFile(ExtraModules[i], Err, Context);
491 Err.print(argv[0], errs());
494 if (EnableCacheManager) {
495 std::string CacheName("file:");
496 CacheName.append(ExtraModules[i]);
497 XMod->setModuleIdentifier(CacheName);
499 EE->addModule(std::move(XMod));
502 for (unsigned i = 0, e = ExtraObjects.size(); i != e; ++i) {
503 ErrorOr<object::OwningBinary<object::ObjectFile>> Obj =
504 object::ObjectFile::createObjectFile(ExtraObjects[i]);
506 Err.print(argv[0], errs());
509 object::OwningBinary<object::ObjectFile> &O = Obj.get();
510 EE->addObjectFile(std::move(O));
513 for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) {
514 ErrorOr<std::unique_ptr<MemoryBuffer>> ArBufOrErr =
515 MemoryBuffer::getFileOrSTDIN(ExtraArchives[i]);
517 Err.print(argv[0], errs());
520 std::unique_ptr<MemoryBuffer> &ArBuf = ArBufOrErr.get();
522 ErrorOr<std::unique_ptr<object::Archive>> ArOrErr =
523 object::Archive::create(ArBuf->getMemBufferRef());
524 if (std::error_code EC = ArOrErr.getError()) {
525 errs() << EC.message();
528 std::unique_ptr<object::Archive> &Ar = ArOrErr.get();
530 object::OwningBinary<object::Archive> OB(std::move(Ar), std::move(ArBuf));
532 EE->addArchive(std::move(OB));
535 // If the target is Cygwin/MingW and we are generating remote code, we
536 // need an extra module to help out with linking.
537 if (RemoteMCJIT && Triple(Mod->getTargetTriple()).isOSCygMing()) {
538 addCygMingExtraModule(EE, Context, Mod->getTargetTriple());
541 // The following functions have no effect if their respective profiling
542 // support wasn't enabled in the build configuration.
543 EE->RegisterJITEventListener(
544 JITEventListener::createOProfileJITEventListener());
545 EE->RegisterJITEventListener(
546 JITEventListener::createIntelJITEventListener());
548 if (!NoLazyCompilation && RemoteMCJIT) {
549 errs() << "warning: remote mcjit does not support lazy compilation\n";
550 NoLazyCompilation = true;
552 EE->DisableLazyCompilation(NoLazyCompilation);
554 // If the user specifically requested an argv[0] to pass into the program,
556 if (!FakeArgv0.empty()) {
557 InputFile = static_cast<std::string>(FakeArgv0);
559 // Otherwise, if there is a .bc suffix on the executable strip it off, it
560 // might confuse the program.
561 if (StringRef(InputFile).endswith(".bc"))
562 InputFile.erase(InputFile.length() - 3);
565 // Add the module's name to the start of the vector of arguments to main().
566 InputArgv.insert(InputArgv.begin(), InputFile);
568 // Call the main function from M as if its signature were:
569 // int main (int argc, char **argv, const char **envp)
570 // using the contents of Args to determine argc & argv, and the contents of
571 // EnvVars to determine envp.
573 Function *EntryFn = Mod->getFunction(EntryFunc);
575 errs() << '\'' << EntryFunc << "\' function not found in module.\n";
579 // Reset errno to zero on entry to main.
584 // Sanity check use of remote-jit: LLI currently only supports use of the
585 // remote JIT on Unix platforms.
586 // FIXME: Remove this pointless fallback mode which causes tests to "pass"
587 // on platforms where they should XFAIL.
590 errs() << "Warning: host does not support external remote targets.\n"
591 << " Defaulting to local execution execution\n";
594 if (ChildExecPath.empty()) {
595 errs() << "-remote-mcjit requires -mcjit-remote-process.\n";
597 } else if (!sys::fs::can_execute(ChildExecPath)) {
598 errs() << "Unable to find usable child executable: '" << ChildExecPath
606 // 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),
609 Type::getInt32Ty(Context),
612 // Run static constructors.
613 if (!ForceInterpreter) {
614 // Give MCJIT a chance to apply relocations and set page permissions.
615 EE->finalizeObject();
617 EE->runStaticConstructorsDestructors(false);
619 // Trigger compilation separately so code regions that need to be
620 // invalidated will be known.
621 (void)EE->getPointerToFunction(EntryFn);
622 // Clear instruction cache before code will be executed.
624 static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
627 Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
629 // Run static destructors.
630 EE->runStaticConstructorsDestructors(true);
632 // If the program didn't call exit explicitly, we should call it now.
633 // This ensures that any atexit handlers get called correctly.
634 if (Function *ExitF = dyn_cast<Function>(Exit)) {
635 std::vector<GenericValue> Args;
636 GenericValue ResultGV;
637 ResultGV.IntVal = APInt(32, Result);
638 Args.push_back(ResultGV);
639 EE->runFunction(ExitF, Args);
640 errs() << "ERROR: exit(" << Result << ") returned!\n";
643 errs() << "ERROR: exit defined with wrong prototype!\n";
647 // else == "if (RemoteMCJIT)"
649 // Remote target MCJIT doesn't (yet) support static constructors. No reason
650 // it couldn't. This is a limitation of the LLI implemantation, not the
651 // MCJIT itself. FIXME.
653 // Lanch the remote process and get a channel to it.
654 std::unique_ptr<FDRPCChannel> C = launchRemote();
656 errs() << "Failed to launch remote JIT.\n";
660 // Create a remote target client running over the channel.
661 typedef orc::remote::OrcRemoteTargetClient<orc::remote::RPCChannel> MyRemote;
662 ErrorOr<MyRemote> R = MyRemote::Create(*C);
664 errs() << "Could not create remote: " << R.getError().message() << "\n";
668 // Create a remote memory manager.
669 std::unique_ptr<MyRemote::RCMemoryManager> RemoteMM;
670 if (auto EC = R->createRemoteMemoryManager(RemoteMM)) {
671 errs() << "Could not create remote memory manager: " << EC.message() << "\n";
675 // Forward MCJIT's memory manager calls to the remote memory manager.
676 static_cast<ForwardingMemoryManager*>(RTDyldMM)->setMemMgr(
677 std::move(RemoteMM));
679 // Forward MCJIT's symbol resolution calls to the remote.
680 static_cast<ForwardingMemoryManager*>(RTDyldMM)->setResolver(
681 orc::createLambdaResolver(
682 [&](const std::string &Name) {
683 orc::TargetAddress Addr = 0;
684 if (auto EC = R->getSymbolAddress(Addr, Name)) {
685 errs() << "Failure during symbol lookup: " << EC.message() << "\n";
688 return RuntimeDyld::SymbolInfo(Addr, JITSymbolFlags::Exported);
690 [](const std::string &Name) { return nullptr; }
693 // Grab the target address of the JIT'd main function on the remote and call
695 // FIXME: argv and envp handling.
696 orc::TargetAddress Entry = EE->getFunctionAddress(EntryFn->getName().str());
697 EE->finalizeObject();
698 DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"
699 << format("%llx", Entry) << "\n");
700 if (auto EC = R->callIntVoid(Result, Entry))
701 errs() << "ERROR: " << EC.message() << "\n";
703 // Like static constructors, the remote target MCJIT support doesn't handle
704 // this yet. It could. FIXME.
706 // Delete the EE - we need to tear it down *before* we terminate the session
707 // with the remote, otherwise it'll crash when it tries to release resources
708 // on a remote that has already been disconnected.
712 // Signal the remote target that we're done JITing.
713 R->terminateSession();
719 std::unique_ptr<FDRPCChannel> launchRemote() {
721 llvm_unreachable("launchRemote not supported on non-Unix platforms");
727 if (pipe(PipeFD[0]) != 0 || pipe(PipeFD[1]) != 0)
728 perror("Error creating pipe: ");
735 // Close the parent ends of the pipes
740 // Execute the child process.
741 std::unique_ptr<char[]> ChildPath, ChildIn, ChildOut;
743 ChildPath.reset(new char[ChildExecPath.size() + 1]);
744 std::copy(ChildExecPath.begin(), ChildExecPath.end(), &ChildPath[0]);
745 ChildPath[ChildExecPath.size()] = '\0';
746 std::string ChildInStr = std::to_string(PipeFD[0][0]);
747 ChildIn.reset(new char[ChildInStr.size() + 1]);
748 std::copy(ChildInStr.begin(), ChildInStr.end(), &ChildIn[0]);
749 ChildIn[ChildInStr.size()] = '\0';
750 std::string ChildOutStr = std::to_string(PipeFD[1][1]);
751 ChildOut.reset(new char[ChildOutStr.size() + 1]);
752 std::copy(ChildOutStr.begin(), ChildOutStr.end(), &ChildOut[0]);
753 ChildOut[ChildOutStr.size()] = '\0';
756 char * const args[] = { &ChildPath[0], &ChildIn[0], &ChildOut[0], nullptr };
757 int rc = execv(ChildExecPath.c_str(), args);
759 perror("Error executing child process: ");
760 llvm_unreachable("Error executing child process");
762 // else we're the parent...
764 // Close the child ends of the pipes
768 // Return an RPC channel connected to our end of the pipes.
769 return llvm::make_unique<FDRPCChannel>(PipeFD[1][0], PipeFD[0][1]);