1//===- lli.cpp - LLVM Interpreter / Dynamic compiler ----------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This utility provides a simple wrapper around the LLVM Execution Engines,
10// which allow the direct execution of LLVM programs through a Just-In-Time
11// compiler, or through an interpreter if no JIT is available for this platform.
12//
13//===----------------------------------------------------------------------===//
14
15#include "ForwardingMemoryManager.h"
16#include "llvm/ADT/StringExtras.h"
17#include "llvm/Bitcode/BitcodeReader.h"
18#include "llvm/CodeGen/CommandFlags.h"
19#include "llvm/CodeGen/LinkAllCodegenComponents.h"
20#include "llvm/Config/llvm-config.h"
21#include "llvm/ExecutionEngine/GenericValue.h"
22#include "llvm/ExecutionEngine/Interpreter.h"
23#include "llvm/ExecutionEngine/JITEventListener.h"
24#include "llvm/ExecutionEngine/JITSymbol.h"
25#include "llvm/ExecutionEngine/MCJIT.h"
26#include "llvm/ExecutionEngine/ObjectCache.h"
27#include "llvm/ExecutionEngine/Orc/AbsoluteSymbols.h"
28#include "llvm/ExecutionEngine/Orc/DebugUtils.h"
29#include "llvm/ExecutionEngine/Orc/Debugging/DebuggerSupport.h"
30#include "llvm/ExecutionEngine/Orc/EPCDynamicLibrarySearchGenerator.h"
31#include "llvm/ExecutionEngine/Orc/EPCGenericRTDyldMemoryManager.h"
32#include "llvm/ExecutionEngine/Orc/ExecutionUtils.h"
33#include "llvm/ExecutionEngine/Orc/IRPartitionLayer.h"
34#include "llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h"
35#include "llvm/ExecutionEngine/Orc/LLJIT.h"
36#include "llvm/ExecutionEngine/Orc/ObjectTransformLayer.h"
37#include "llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h"
38#include "llvm/ExecutionEngine/Orc/SelfExecutorProcessControl.h"
39#include "llvm/ExecutionEngine/Orc/SimpleRemoteEPC.h"
40#include "llvm/ExecutionEngine/Orc/SymbolStringPool.h"
41#include "llvm/ExecutionEngine/Orc/TargetProcess/JITLoaderGDB.h"
42#include "llvm/ExecutionEngine/Orc/TargetProcess/RegisterEHFrames.h"
43#include "llvm/ExecutionEngine/Orc/TargetProcess/TargetExecutionUtils.h"
44#include "llvm/ExecutionEngine/SectionMemoryManager.h"
45#include "llvm/IR/IRBuilder.h"
46#include "llvm/IR/LLVMContext.h"
47#include "llvm/IR/Module.h"
48#include "llvm/IR/Type.h"
49#include "llvm/IR/Verifier.h"
50#include "llvm/IRReader/IRReader.h"
51#include "llvm/Object/Archive.h"
52#include "llvm/Object/ObjectFile.h"
53#include "llvm/Support/CommandLine.h"
54#include "llvm/Support/Compiler.h"
55#include "llvm/Support/Debug.h"
56#include "llvm/Support/DynamicLibrary.h"
57#include "llvm/Support/Format.h"
58#include "llvm/Support/InitLLVM.h"
59#include "llvm/Support/MathExtras.h"
60#include "llvm/Support/Memory.h"
61#include "llvm/Support/MemoryBuffer.h"
62#include "llvm/Support/Path.h"
63#include "llvm/Support/PluginLoader.h"
64#include "llvm/Support/Process.h"
65#include "llvm/Support/Program.h"
66#include "llvm/Support/SourceMgr.h"
67#include "llvm/Support/TargetSelect.h"
68#include "llvm/Support/ToolOutputFile.h"
69#include "llvm/Support/WithColor.h"
70#include "llvm/Support/raw_ostream.h"
71#include "llvm/TargetParser/Triple.h"
72#include <cerrno>
73#include <optional>
74
75#if !defined(_MSC_VER) && !defined(__MINGW32__)
76#include <unistd.h>
77#else
78#include <io.h>
79#endif
80
81#ifdef __CYGWIN__
82#include <cygwin/version.h>
83#if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
84#define DO_NOTHING_ATEXIT 1
85#endif
86#endif
87
88using namespace llvm;
89
90static codegen::RegisterCodeGenFlags CGF;
91
92#define DEBUG_TYPE "lli"
93
94namespace {
95enum class JITKind { MCJIT, Orc, OrcLazy };
96enum class JITLinkerKind { Default, RuntimeDyld, JITLink };
97} // namespace
98
99static cl::opt<std::string> InputFile(cl::desc("<input bitcode>"),
100 cl::Positional, cl::init(Val: "-"));
101
102static cl::list<std::string> InputArgv(cl::ConsumeAfter,
103 cl::desc("<program arguments>..."));
104
105static cl::opt<bool>
106 ForceInterpreter("force-interpreter",
107 cl::desc("Force interpretation: disable JIT"),
108 cl::init(Val: false));
109
110static cl::opt<JITKind>
111 UseJITKind("jit-kind", cl::desc("Choose underlying JIT kind."),
112 cl::init(Val: JITKind::Orc),
113 cl::values(clEnumValN(JITKind::MCJIT, "mcjit", "MCJIT"),
114 clEnumValN(JITKind::Orc, "orc", "Orc JIT"),
115 clEnumValN(JITKind::OrcLazy, "orc-lazy",
116 "Orc-based lazy JIT.")));
117
118static cl::opt<JITLinkerKind> JITLinker(
119 "jit-linker", cl::desc("Choose the dynamic linker/loader."),
120 cl::init(Val: JITLinkerKind::Default),
121 cl::values(clEnumValN(JITLinkerKind::Default, "default",
122 "Default for platform and JIT-kind"),
123 clEnumValN(JITLinkerKind::RuntimeDyld, "rtdyld", "RuntimeDyld"),
124 clEnumValN(JITLinkerKind::JITLink, "jitlink",
125 "Orc-specific linker")));
126static cl::opt<std::string>
127 OrcRuntime("orc-runtime", cl::desc("Use ORC runtime from given path"),
128 cl::init(Val: ""));
129
130static cl::opt<unsigned>
131 LazyJITCompileThreads("compile-threads",
132 cl::desc("Choose the number of compile threads "
133 "(jit-kind=orc-lazy only)"),
134 cl::init(Val: 0));
135
136static cl::list<std::string>
137 ThreadEntryPoints("thread-entry",
138 cl::desc("calls the given entry-point on a new thread "
139 "(jit-kind=orc-lazy only)"));
140
141static cl::opt<bool> PerModuleLazy(
142 "per-module-lazy",
143 cl::desc("Performs lazy compilation on whole module boundaries "
144 "rather than individual functions"),
145 cl::init(Val: false));
146
147static cl::list<std::string>
148 JITDylibs("jd",
149 cl::desc("Specifies the JITDylib to be used for any subsequent "
150 "-extra-module arguments."));
151
152static cl::list<std::string>
153 Dylibs("dlopen", cl::desc("Dynamic libraries to load before linking"));
154
155// The MCJIT supports building for a target address space separate from
156// the JIT compilation process. Use a forked process and a copying
157// memory manager with IPC to execute using this functionality.
158static cl::opt<bool>
159 RemoteMCJIT("remote-mcjit",
160 cl::desc("Execute MCJIT'ed code in a separate process."),
161 cl::init(Val: false));
162
163// Manually specify the child process for remote execution. This overrides
164// the simulated remote execution that allocates address space for child
165// execution. The child process will be executed and will communicate with
166// lli via stdin/stdout pipes.
167static cl::opt<std::string> ChildExecPath(
168 "mcjit-remote-process",
169 cl::desc("Specify the filename of the process to launch "
170 "for remote MCJIT execution. If none is specified,"
171 "\n\tremote execution will be simulated in-process."),
172 cl::value_desc("filename"), cl::init(Val: ""));
173
174// Determine optimization level.
175static cl::opt<char>
176 OptLevel("O",
177 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
178 "(default = '-O2')"),
179 cl::Prefix, cl::init(Val: '2'));
180
181static cl::opt<std::string>
182 TargetTriple("mtriple", cl::desc("Override target triple for module"));
183
184static cl::opt<std::string>
185 EntryFunc("entry-function",
186 cl::desc("Specify the entry function (default = 'main') "
187 "of the executable"),
188 cl::value_desc("function"), cl::init(Val: "main"));
189
190static cl::list<std::string>
191 ExtraModules("extra-module", cl::desc("Extra modules to be loaded"),
192 cl::value_desc("input bitcode"));
193
194static cl::list<std::string>
195 ExtraObjects("extra-object", cl::desc("Extra object files to be loaded"),
196 cl::value_desc("input object"));
197
198static cl::list<std::string>
199 ExtraArchives("extra-archive", cl::desc("Extra archive files to be loaded"),
200 cl::value_desc("input archive"));
201
202static cl::opt<bool>
203 EnableCacheManager("enable-cache-manager",
204 cl::desc("Use cache manager to save/load modules"),
205 cl::init(Val: false));
206
207static cl::opt<std::string>
208 ObjectCacheDir("object-cache-dir",
209 cl::desc("Directory to store cached object files "
210 "(must be user writable)"),
211 cl::init(Val: ""));
212
213static cl::opt<std::string>
214 FakeArgv0("fake-argv0",
215 cl::desc("Override the 'argv[0]' value passed into the executing"
216 " program"),
217 cl::value_desc("executable"));
218
219static cl::opt<bool>
220 DisableCoreFiles("disable-core-files", cl::Hidden,
221 cl::desc("Disable emission of core files if possible"));
222
223static cl::opt<bool> NoLazyCompilation("disable-lazy-compilation",
224 cl::desc("Disable JIT lazy compilation"),
225 cl::init(Val: false));
226
227static cl::opt<bool> GenerateSoftFloatCalls(
228 "soft-float", cl::desc("Generate software floating point library calls"),
229 cl::init(Val: false));
230
231static cl::opt<bool> NoProcessSymbols(
232 "no-process-syms",
233 cl::desc("Do not resolve lli process symbols in JIT'd code"),
234 cl::init(Val: false));
235
236enum class LLJITPlatform { Inactive, Auto, ExecutorNative, GenericIR };
237
238static cl::opt<LLJITPlatform> Platform(
239 "lljit-platform", cl::desc("Platform to use with LLJIT"),
240 cl::init(Val: LLJITPlatform::Auto),
241 cl::values(clEnumValN(LLJITPlatform::Auto, "Auto",
242 "Like 'ExecutorNative' if ORC runtime "
243 "provided, otherwise like 'GenericIR'"),
244 clEnumValN(LLJITPlatform::ExecutorNative, "ExecutorNative",
245 "Use the native platform for the executor."
246 "Requires -orc-runtime"),
247 clEnumValN(LLJITPlatform::GenericIR, "GenericIR",
248 "Use LLJITGenericIRPlatform"),
249 clEnumValN(LLJITPlatform::Inactive, "Inactive",
250 "Disable platform support explicitly")),
251 cl::Hidden);
252
253enum class DumpKind {
254 NoDump,
255 DumpFuncsToStdOut,
256 DumpModsToStdOut,
257 DumpModsToDisk,
258 DumpDebugDescriptor,
259 DumpDebugObjects,
260};
261
262static cl::opt<DumpKind> OrcDumpKind(
263 "orc-lazy-debug", cl::desc("Debug dumping for the orc-lazy JIT."),
264 cl::init(Val: DumpKind::NoDump),
265 cl::values(clEnumValN(DumpKind::NoDump, "no-dump", "Don't dump anything."),
266 clEnumValN(DumpKind::DumpFuncsToStdOut, "funcs-to-stdout",
267 "Dump function names to stdout."),
268 clEnumValN(DumpKind::DumpModsToStdOut, "mods-to-stdout",
269 "Dump modules to stdout."),
270 clEnumValN(DumpKind::DumpModsToDisk, "mods-to-disk",
271 "Dump modules to the current "
272 "working directory. (WARNING: "
273 "will overwrite existing files)."),
274 clEnumValN(DumpKind::DumpDebugDescriptor, "jit-debug-descriptor",
275 "Dump __jit_debug_descriptor contents to stdout"),
276 clEnumValN(DumpKind::DumpDebugObjects, "jit-debug-objects",
277 "Dump __jit_debug_descriptor in-memory debug "
278 "objects as tool output")),
279 cl::Hidden);
280
281static ExitOnError ExitOnErr;
282
283LLVM_ATTRIBUTE_USED static void linkComponents() {
284 errs() << (void *)&llvm_orc_registerEHFrameSectionAllocAction
285 << (void *)&llvm_orc_deregisterEHFrameSectionAllocAction
286 << (void *)&llvm_orc_registerJITLoaderGDBAllocAction;
287}
288
289namespace {
290//===----------------------------------------------------------------------===//
291// Object cache
292//
293// This object cache implementation writes cached objects to disk to the
294// directory specified by CacheDir, using a filename provided in the module
295// descriptor. The cache tries to load a saved object using that path if the
296// file exists. CacheDir defaults to "", in which case objects are cached
297// alongside their originating bitcodes.
298//
299class LLIObjectCache : public ObjectCache {
300public:
301 LLIObjectCache(const std::string& CacheDir) : CacheDir(CacheDir) {
302 // Add trailing '/' to cache dir if necessary.
303 if (!this->CacheDir.empty() &&
304 this->CacheDir[this->CacheDir.size() - 1] != '/')
305 this->CacheDir += '/';
306 }
307 ~LLIObjectCache() override = default;
308
309 void notifyObjectCompiled(const Module *M, MemoryBufferRef Obj) override {
310 const std::string &ModuleID = M->getModuleIdentifier();
311 std::string CacheName;
312 if (!getCacheFilename(ModID: ModuleID, CacheName))
313 return;
314 if (!CacheDir.empty()) { // Create user-defined cache dir.
315 SmallString<128> dir(sys::path::parent_path(path: CacheName));
316 sys::fs::create_directories(path: Twine(dir));
317 }
318
319 std::error_code EC;
320 raw_fd_ostream outfile(CacheName, EC, sys::fs::OF_None);
321 outfile.write(Ptr: Obj.getBufferStart(), Size: Obj.getBufferSize());
322 outfile.close();
323 }
324
325 std::unique_ptr<MemoryBuffer> getObject(const Module* M) override {
326 const std::string &ModuleID = M->getModuleIdentifier();
327 std::string CacheName;
328 if (!getCacheFilename(ModID: ModuleID, CacheName))
329 return nullptr;
330 // Load the object from the cache filename
331 ErrorOr<std::unique_ptr<MemoryBuffer>> IRObjectBuffer =
332 MemoryBuffer::getFile(Filename: CacheName, /*IsText=*/false,
333 /*RequiresNullTerminator=*/false);
334 // If the file isn't there, that's OK.
335 if (!IRObjectBuffer)
336 return nullptr;
337 // MCJIT will want to write into this buffer, and we don't want that
338 // because the file has probably just been mmapped. Instead we make
339 // a copy. The filed-based buffer will be released when it goes
340 // out of scope.
341 return MemoryBuffer::getMemBufferCopy(InputData: IRObjectBuffer.get()->getBuffer());
342 }
343
344private:
345 std::string CacheDir;
346
347 bool getCacheFilename(StringRef ModID, std::string &CacheName) {
348 if (!ModID.consume_front(Prefix: "file:"))
349 return false;
350
351 std::string CacheSubdir = std::string(ModID);
352 // Transform "X:\foo" => "/X\foo" for convenience on Windows.
353 if (is_style_windows(S: llvm::sys::path::Style::native) &&
354 isalpha(CacheSubdir[0]) && CacheSubdir[1] == ':') {
355 CacheSubdir[1] = CacheSubdir[0];
356 CacheSubdir[0] = '/';
357 }
358
359 CacheName = CacheDir + CacheSubdir;
360 size_t pos = CacheName.rfind(c: '.');
361 CacheName.replace(pos: pos, n1: CacheName.length() - pos, s: ".o");
362 return true;
363 }
364};
365} // namespace
366
367// On Mingw and Cygwin, an external symbol named '__main' is called from the
368// generated 'main' function to allow static initialization. To avoid linking
369// problems with remote targets (because lli's remote target support does not
370// currently handle external linking) we add a secondary module which defines
371// an empty '__main' function.
372static void addCygMingExtraModule(ExecutionEngine &EE, LLVMContext &Context,
373 const Triple &TargetTriple) {
374 IRBuilder<> Builder(Context);
375
376 // Create a new module.
377 std::unique_ptr<Module> M = std::make_unique<Module>(args: "CygMingHelper", args&: Context);
378 M->setTargetTriple(TargetTriple);
379
380 // Create an empty function named "__main".
381 Type *ReturnTy;
382 if (TargetTriple.isArch64Bit())
383 ReturnTy = Type::getInt64Ty(C&: Context);
384 else
385 ReturnTy = Type::getInt32Ty(C&: Context);
386 Function *Result =
387 Function::Create(Ty: FunctionType::get(Result: ReturnTy, Params: {}, isVarArg: false),
388 Linkage: GlobalValue::ExternalLinkage, N: "__main", M: M.get());
389
390 BasicBlock *BB = BasicBlock::Create(Context, Name: "__main", Parent: Result);
391 Builder.SetInsertPoint(BB);
392 Value *ReturnVal = ConstantInt::get(Ty: ReturnTy, V: 0);
393 Builder.CreateRet(V: ReturnVal);
394
395 // Add this new module to the ExecutionEngine.
396 EE.addModule(M: std::move(M));
397}
398
399static CodeGenOptLevel getOptLevel() {
400 if (auto Level = CodeGenOpt::parseLevel(C: OptLevel))
401 return *Level;
402 WithColor::error(OS&: errs(), Prefix: "lli") << "invalid optimization level.\n";
403 exit(status: 1);
404}
405
406[[noreturn]] static void reportError(SMDiagnostic Err, const char *ProgName) {
407 Err.print(ProgName, S&: errs());
408 exit(status: 1);
409}
410
411static Error loadDylibs();
412static int runOrcJIT(const char *ProgName);
413static void disallowOrcOptions();
414static Expected<std::unique_ptr<orc::ExecutorProcessControl>> launchRemote();
415
416//===----------------------------------------------------------------------===//
417// main Driver function
418//
419int main(int argc, char **argv, char * const *envp) {
420 InitLLVM X(argc, argv);
421
422 if (argc > 1)
423 ExitOnErr.setBanner(std::string(argv[0]) + ": ");
424
425 // If we have a native target, initialize it to ensure it is linked in and
426 // usable by the JIT.
427 InitializeNativeTarget();
428 InitializeNativeTargetAsmPrinter();
429 InitializeNativeTargetAsmParser();
430
431 cl::ParseCommandLineOptions(argc, argv,
432 Overview: "llvm interpreter & dynamic compiler\n");
433
434 // If the user doesn't want core files, disable them.
435 if (DisableCoreFiles)
436 sys::Process::PreventCoreFiles();
437
438 ExitOnErr(loadDylibs());
439
440 if (EntryFunc.empty()) {
441 WithColor::error(OS&: errs(), Prefix: argv[0])
442 << "--entry-function name cannot be empty\n";
443 exit(status: 1);
444 }
445
446 if (UseJITKind == JITKind::MCJIT || ForceInterpreter)
447 disallowOrcOptions();
448 else
449 return runOrcJIT(ProgName: argv[0]);
450
451 // Old lli implementation based on ExecutionEngine and MCJIT.
452 LLVMContext Context;
453
454 // Load the bitcode...
455 SMDiagnostic Err;
456 std::unique_ptr<Module> Owner = parseIRFile(Filename: InputFile, Err, Context);
457 Module *Mod = Owner.get();
458 if (!Mod)
459 reportError(Err, ProgName: argv[0]);
460
461 if (EnableCacheManager) {
462 std::string CacheName("file:");
463 CacheName.append(str: InputFile);
464 Mod->setModuleIdentifier(CacheName);
465 }
466
467 // If not jitting lazily, load the whole bitcode file eagerly too.
468 if (NoLazyCompilation) {
469 // Use *argv instead of argv[0] to work around a wrong GCC warning.
470 ExitOnError ExitOnErr(std::string(*argv) +
471 ": bitcode didn't read correctly: ");
472 ExitOnErr(Mod->materializeAll());
473 }
474
475 std::string ErrorMsg;
476 EngineBuilder builder(std::move(Owner));
477 builder.setMArch(codegen::getMArch());
478 builder.setMCPU(codegen::getCPUStr());
479 builder.setMAttrs(codegen::getFeatureList());
480 if (auto RM = codegen::getExplicitRelocModel())
481 builder.setRelocationModel(*RM);
482 if (auto CM = codegen::getExplicitCodeModel())
483 builder.setCodeModel(*CM);
484 builder.setErrorStr(&ErrorMsg);
485 builder.setEngineKind(ForceInterpreter
486 ? EngineKind::Interpreter
487 : EngineKind::JIT);
488
489 // If we are supposed to override the target triple, do so now.
490 if (!TargetTriple.empty())
491 Mod->setTargetTriple(Triple(Triple::normalize(Str: TargetTriple)));
492
493 // Enable MCJIT if desired.
494 RTDyldMemoryManager *RTDyldMM = nullptr;
495 if (!ForceInterpreter) {
496 if (RemoteMCJIT)
497 RTDyldMM = new ForwardingMemoryManager();
498 else
499 RTDyldMM = new SectionMemoryManager();
500
501 // Deliberately construct a temp std::unique_ptr to pass in. Do not null out
502 // RTDyldMM: We still use it below, even though we don't own it.
503 builder.setMCJITMemoryManager(
504 std::unique_ptr<RTDyldMemoryManager>(RTDyldMM));
505 } else if (RemoteMCJIT) {
506 WithColor::error(OS&: errs(), Prefix: argv[0])
507 << "remote process execution does not work with the interpreter.\n";
508 exit(status: 1);
509 }
510
511 builder.setOptLevel(getOptLevel());
512
513 TargetOptions Options =
514 codegen::InitTargetOptionsFromCodeGenFlags(TheTriple: Triple(TargetTriple));
515 if (codegen::getFloatABIForCalls() != FloatABI::Default)
516 Options.FloatABIType = codegen::getFloatABIForCalls();
517
518 builder.setTargetOptions(Options);
519
520 std::unique_ptr<ExecutionEngine> EE(builder.create());
521 if (!EE) {
522 if (!ErrorMsg.empty())
523 WithColor::error(OS&: errs(), Prefix: argv[0])
524 << "error creating EE: " << ErrorMsg << "\n";
525 else
526 WithColor::error(OS&: errs(), Prefix: argv[0]) << "unknown error creating EE!\n";
527 exit(status: 1);
528 }
529
530 std::unique_ptr<LLIObjectCache> CacheManager;
531 if (EnableCacheManager) {
532 CacheManager.reset(p: new LLIObjectCache(ObjectCacheDir));
533 EE->setObjectCache(CacheManager.get());
534 }
535
536 // Load any additional modules specified on the command line.
537 for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) {
538 std::unique_ptr<Module> XMod = parseIRFile(Filename: ExtraModules[i], Err, Context);
539 if (!XMod)
540 reportError(Err, ProgName: argv[0]);
541 if (EnableCacheManager) {
542 std::string CacheName("file:");
543 CacheName.append(str: ExtraModules[i]);
544 XMod->setModuleIdentifier(CacheName);
545 }
546 EE->addModule(M: std::move(XMod));
547 }
548
549 for (unsigned i = 0, e = ExtraObjects.size(); i != e; ++i) {
550 Expected<object::OwningBinary<object::ObjectFile>> Obj =
551 object::ObjectFile::createObjectFile(ObjectPath: ExtraObjects[i]);
552 if (!Obj) {
553 // TODO: Actually report errors helpfully.
554 consumeError(Err: Obj.takeError());
555 reportError(Err, ProgName: argv[0]);
556 }
557 object::OwningBinary<object::ObjectFile> &O = Obj.get();
558 EE->addObjectFile(O: std::move(O));
559 }
560
561 for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) {
562 ErrorOr<std::unique_ptr<MemoryBuffer>> ArBufOrErr =
563 MemoryBuffer::getFileOrSTDIN(Filename: ExtraArchives[i]);
564 if (!ArBufOrErr)
565 reportError(Err, ProgName: argv[0]);
566 std::unique_ptr<MemoryBuffer> &ArBuf = ArBufOrErr.get();
567
568 Expected<std::unique_ptr<object::Archive>> ArOrErr =
569 object::Archive::create(Source: ArBuf->getMemBufferRef());
570 if (!ArOrErr) {
571 std::string Buf;
572 raw_string_ostream OS(Buf);
573 logAllUnhandledErrors(E: ArOrErr.takeError(), OS);
574 errs() << Buf;
575 exit(status: 1);
576 }
577 std::unique_ptr<object::Archive> &Ar = ArOrErr.get();
578
579 object::OwningBinary<object::Archive> OB(std::move(Ar), std::move(ArBuf));
580
581 EE->addArchive(A: std::move(OB));
582 }
583
584 // If the target is Cygwin/MingW and we are generating remote code, we
585 // need an extra module to help out with linking.
586 if (RemoteMCJIT && Mod->getTargetTriple().isOSCygMing()) {
587 addCygMingExtraModule(EE&: *EE, Context, TargetTriple: Mod->getTargetTriple());
588 }
589
590 // The following functions have no effect if their respective profiling
591 // support wasn't enabled in the build configuration.
592 EE->RegisterJITEventListener(
593 JITEventListener::createOProfileJITEventListener());
594 EE->RegisterJITEventListener(
595 JITEventListener::createIntelJITEventListener());
596 if (!RemoteMCJIT)
597 EE->RegisterJITEventListener(
598 JITEventListener::createPerfJITEventListener());
599
600 if (!NoLazyCompilation && RemoteMCJIT) {
601 WithColor::warning(OS&: errs(), Prefix: argv[0])
602 << "remote mcjit does not support lazy compilation\n";
603 NoLazyCompilation = true;
604 }
605 EE->DisableLazyCompilation(Disabled: NoLazyCompilation);
606
607 // If the user specifically requested an argv[0] to pass into the program,
608 // do it now.
609 if (!FakeArgv0.empty()) {
610 InputFile = static_cast<std::string>(FakeArgv0);
611 } else {
612 // Otherwise, if there is a .bc suffix on the executable strip it off, it
613 // might confuse the program.
614 if (StringRef(InputFile).ends_with(Suffix: ".bc"))
615 InputFile.erase(pos: InputFile.length() - 3);
616 }
617
618 // Add the module's name to the start of the vector of arguments to main().
619 InputArgv.insert(pos: InputArgv.begin(), value: InputFile);
620
621 // Call the main function from M as if its signature were:
622 // int main (int argc, char **argv, const char **envp)
623 // using the contents of Args to determine argc & argv, and the contents of
624 // EnvVars to determine envp.
625 //
626 Function *EntryFn = Mod->getFunction(Name: EntryFunc);
627 if (!EntryFn) {
628 WithColor::error(OS&: errs(), Prefix: argv[0])
629 << '\'' << EntryFunc << "\' function not found in module.\n";
630 return -1;
631 }
632
633 // Reset errno to zero on entry to main.
634 errno = 0;
635
636 int Result = -1;
637
638 // Sanity check use of remote-jit: LLI currently only supports use of the
639 // remote JIT on Unix platforms.
640 if (RemoteMCJIT) {
641#ifndef LLVM_ON_UNIX
642 WithColor::warning(errs(), argv[0])
643 << "host does not support external remote targets.\n";
644 WithColor::note() << "defaulting to local execution\n";
645 return -1;
646#else
647 if (ChildExecPath.empty()) {
648 WithColor::error(OS&: errs(), Prefix: argv[0])
649 << "-remote-mcjit requires -mcjit-remote-process.\n";
650 exit(status: 1);
651 } else if (!sys::fs::can_execute(Path: ChildExecPath)) {
652 WithColor::error(OS&: errs(), Prefix: argv[0])
653 << "unable to find usable child executable: '" << ChildExecPath
654 << "'\n";
655 return -1;
656 }
657#endif
658 }
659
660 if (!RemoteMCJIT) {
661 // If the program doesn't explicitly call exit, we will need the Exit
662 // function later on to make an explicit call, so get the function now.
663 FunctionCallee Exit = Mod->getOrInsertFunction(
664 Name: "exit", RetTy: Type::getVoidTy(C&: Context), Args: Type::getInt32Ty(C&: Context));
665
666 // Run static constructors.
667 if (!ForceInterpreter) {
668 // Give MCJIT a chance to apply relocations and set page permissions.
669 EE->finalizeObject();
670 }
671 EE->runStaticConstructorsDestructors(isDtors: false);
672
673 // Trigger compilation separately so code regions that need to be
674 // invalidated will be known.
675 (void)EE->getPointerToFunction(F: EntryFn);
676 // Clear instruction cache before code will be executed.
677 if (RTDyldMM)
678 static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
679
680 // Run main.
681 Result = EE->runFunctionAsMain(Fn: EntryFn, argv: InputArgv, envp);
682
683 // Run static destructors.
684 EE->runStaticConstructorsDestructors(isDtors: true);
685
686 // If the program didn't call exit explicitly, we should call it now.
687 // This ensures that any atexit handlers get called correctly.
688 if (Function *ExitF =
689 dyn_cast<Function>(Val: Exit.getCallee()->stripPointerCasts())) {
690 if (ExitF->getFunctionType() == Exit.getFunctionType()) {
691 std::vector<GenericValue> Args;
692 GenericValue ResultGV;
693 ResultGV.IntVal = APInt(32, Result);
694 Args.push_back(x: ResultGV);
695 EE->runFunction(F: ExitF, ArgValues: Args);
696 WithColor::error(OS&: errs(), Prefix: argv[0])
697 << "exit(" << Result << ") returned!\n";
698 abort();
699 }
700 }
701 WithColor::error(OS&: errs(), Prefix: argv[0]) << "exit defined with wrong prototype!\n";
702 abort();
703 } else {
704 // else == "if (RemoteMCJIT)"
705 std::unique_ptr<orc::ExecutorProcessControl> EPC = ExitOnErr(launchRemote());
706
707 // Remote target MCJIT doesn't (yet) support static constructors. No reason
708 // it couldn't. This is a limitation of the LLI implementation, not the
709 // MCJIT itself. FIXME.
710
711 // Create a remote memory manager.
712 auto RemoteMM = ExitOnErr(
713 orc::EPCGenericRTDyldMemoryManager::CreateWithDefaultBootstrapSymbols(
714 EPC&: *EPC));
715
716 // Forward MCJIT's memory manager calls to the remote memory manager.
717 static_cast<ForwardingMemoryManager*>(RTDyldMM)->setMemMgr(
718 std::move(RemoteMM));
719
720 // Forward MCJIT's symbol resolution calls to the remote.
721 static_cast<ForwardingMemoryManager *>(RTDyldMM)->setResolver(
722 ExitOnErr(RemoteResolver::Create(EPC&: *EPC)));
723 // Grab the target address of the JIT'd main function on the remote and call
724 // it.
725 // FIXME: argv and envp handling.
726 auto Entry =
727 orc::ExecutorAddr(EE->getFunctionAddress(Name: EntryFn->getName().str()));
728 EE->finalizeObject();
729 LLVM_DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"
730 << format("%llx", Entry.getValue()) << "\n");
731 Result = ExitOnErr(EPC->runAsMain(MainFnAddr: Entry, Args: {}));
732
733 // Like static constructors, the remote target MCJIT support doesn't handle
734 // this yet. It could. FIXME.
735
736 // Delete the EE - we need to tear it down *before* we terminate the session
737 // with the remote, otherwise it'll crash when it tries to release resources
738 // on a remote that has already been disconnected.
739 EE.reset();
740
741 // Signal the remote target that we're done JITing.
742 ExitOnErr(EPC->disconnect());
743 }
744
745 return Result;
746}
747
748// JITLink debug support plugins put information about JITed code in this GDB
749// JIT Interface global from OrcTargetProcess.
750extern "C" LLVM_ABI struct jit_descriptor __jit_debug_descriptor;
751
752static struct jit_code_entry *
753findNextDebugDescriptorEntry(struct jit_code_entry *Latest) {
754 if (Latest == nullptr)
755 return __jit_debug_descriptor.first_entry;
756 if (Latest->next_entry)
757 return Latest->next_entry;
758 return nullptr;
759}
760
761static ToolOutputFile &claimToolOutput() {
762 static std::unique_ptr<ToolOutputFile> ToolOutput = nullptr;
763 if (ToolOutput) {
764 WithColor::error(OS&: errs(), Prefix: "lli")
765 << "Can not claim stdout for tool output twice\n";
766 exit(status: 1);
767 }
768 std::error_code EC;
769 ToolOutput = std::make_unique<ToolOutputFile>(args: "-", args&: EC, args: sys::fs::OF_None);
770 if (EC) {
771 WithColor::error(OS&: errs(), Prefix: "lli")
772 << "Failed to create tool output file: " << EC.message() << "\n";
773 exit(status: 1);
774 }
775 return *ToolOutput;
776}
777
778static std::function<void(Module &)> createIRDebugDumper() {
779 switch (OrcDumpKind) {
780 case DumpKind::NoDump:
781 case DumpKind::DumpDebugDescriptor:
782 case DumpKind::DumpDebugObjects:
783 return [](Module &M) {};
784
785 case DumpKind::DumpFuncsToStdOut:
786 return [](Module &M) {
787 printf(format: "[ ");
788
789 for (const auto &F : M) {
790 if (F.isDeclaration())
791 continue;
792
793 if (F.hasName()) {
794 std::string Name(std::string(F.getName()));
795 printf(format: "%s ", Name.c_str());
796 } else
797 printf(format: "<anon> ");
798 }
799
800 printf(format: "]\n");
801 };
802
803 case DumpKind::DumpModsToStdOut:
804 return [](Module &M) {
805 outs() << "----- Module Start -----\n" << M << "----- Module End -----\n";
806 };
807
808 case DumpKind::DumpModsToDisk:
809 return [](Module &M) {
810 std::error_code EC;
811 raw_fd_ostream Out(M.getModuleIdentifier() + ".ll", EC,
812 sys::fs::OF_TextWithCRLF);
813 if (EC) {
814 errs() << "Couldn't open " << M.getModuleIdentifier()
815 << " for dumping.\nError:" << EC.message() << "\n";
816 exit(status: 1);
817 }
818 Out << M;
819 };
820 }
821 llvm_unreachable("Unknown DumpKind");
822}
823
824static std::function<void(MemoryBuffer &)> createObjDebugDumper() {
825 switch (OrcDumpKind) {
826 case DumpKind::NoDump:
827 case DumpKind::DumpFuncsToStdOut:
828 case DumpKind::DumpModsToStdOut:
829 case DumpKind::DumpModsToDisk:
830 return [](MemoryBuffer &) {};
831
832 case DumpKind::DumpDebugDescriptor: {
833 // Dump the empty descriptor at startup once
834 fprintf(stderr, format: "jit_debug_descriptor 0x%016" PRIx64 "\n",
835 pointerToJITTargetAddress(Ptr: __jit_debug_descriptor.first_entry));
836 return [](MemoryBuffer &) {
837 // Dump new entries as they appear
838 static struct jit_code_entry *Latest = nullptr;
839 while (auto *NewEntry = findNextDebugDescriptorEntry(Latest)) {
840 fprintf(stderr, format: "jit_debug_descriptor 0x%016" PRIx64 "\n",
841 pointerToJITTargetAddress(Ptr: NewEntry));
842 Latest = NewEntry;
843 }
844 };
845 }
846
847 case DumpKind::DumpDebugObjects: {
848 return [](MemoryBuffer &Obj) {
849 static struct jit_code_entry *Latest = nullptr;
850 static ToolOutputFile &ToolOutput = claimToolOutput();
851 while (auto *NewEntry = findNextDebugDescriptorEntry(Latest)) {
852 ToolOutput.os().write(Ptr: NewEntry->symfile_addr, Size: NewEntry->symfile_size);
853 Latest = NewEntry;
854 }
855 };
856 }
857 }
858 llvm_unreachable("Unknown DumpKind");
859}
860
861static Error loadDylibs() {
862 for (const auto &Dylib : Dylibs) {
863 std::string ErrMsg;
864 if (sys::DynamicLibrary::LoadLibraryPermanently(Filename: Dylib.c_str(), ErrMsg: &ErrMsg))
865 return make_error<StringError>(Args&: ErrMsg, Args: inconvertibleErrorCode());
866 }
867
868 return Error::success();
869}
870
871static void exitOnLazyCallThroughFailure() { exit(status: 1); }
872
873static Expected<orc::ThreadSafeModule>
874loadModule(StringRef Path, orc::ThreadSafeContext TSCtx) {
875 SMDiagnostic Err;
876 auto M = TSCtx.withContextDo(
877 F: [&](LLVMContext *Ctx) { return parseIRFile(Filename: Path, Err, Context&: *Ctx); });
878 if (!M) {
879 std::string ErrMsg;
880 {
881 raw_string_ostream ErrMsgStream(ErrMsg);
882 Err.print(ProgName: "lli", S&: ErrMsgStream);
883 }
884 return make_error<StringError>(Args: std::move(ErrMsg), Args: inconvertibleErrorCode());
885 }
886
887 if (EnableCacheManager)
888 M->setModuleIdentifier("file:" + M->getModuleIdentifier());
889
890 return orc::ThreadSafeModule(std::move(M), std::move(TSCtx));
891}
892
893static int mingw_noop_main(void) {
894 // Cygwin and MinGW insert calls from the main function to the runtime
895 // function __main. The __main function is responsible for setting up main's
896 // environment (e.g. running static constructors), however this is not needed
897 // when running under lli: the executor process will have run non-JIT ctors,
898 // and ORC will take care of running JIT'd ctors. To avoid a missing symbol
899 // error we just implement __main as a no-op.
900 //
901 // FIXME: Move this to ORC-RT (and the ORC-RT substitution library once it
902 // exists). That will allow it to work out-of-process, and for all
903 // ORC tools (the problem isn't lli specific).
904 return 0;
905}
906
907// Try to enable debugger support for the given instance.
908// This alway returns success, but prints a warning if it's not able to enable
909// debugger support.
910static Error tryEnableDebugSupport(orc::LLJIT &J) {
911 if (auto Err = enableDebuggerSupport(J)) {
912 [[maybe_unused]] std::string ErrMsg = toString(E: std::move(Err));
913 LLVM_DEBUG(dbgs() << "lli: " << ErrMsg << "\n");
914 }
915 return Error::success();
916}
917
918static int runOrcJIT(const char *ProgName) {
919 // Start setting up the JIT environment.
920
921 // Parse the main module.
922 orc::ThreadSafeContext TSCtx(std::make_unique<LLVMContext>());
923 auto MainModule = ExitOnErr(loadModule(Path: InputFile, TSCtx));
924
925 // Get TargetTriple and DataLayout from the main module if they're explicitly
926 // set.
927 std::optional<Triple> TT;
928 std::optional<DataLayout> DL;
929 MainModule.withModuleDo(F: [&](Module &M) {
930 if (!M.getTargetTriple().empty())
931 TT = M.getTargetTriple();
932 if (!M.getDataLayout().isDefault())
933 DL = M.getDataLayout();
934 });
935
936 orc::LLLazyJITBuilder Builder;
937
938 Builder.setJITTargetMachineBuilder(
939 TT ? orc::JITTargetMachineBuilder(*TT)
940 : ExitOnErr(orc::JITTargetMachineBuilder::detectHost()));
941
942 TT = Builder.getJITTargetMachineBuilder()->getTargetTriple();
943 if (DL)
944 Builder.setDataLayout(DL);
945
946 if (!codegen::getMArch().empty())
947 Builder.getJITTargetMachineBuilder()->getTargetTriple().setArchName(
948 codegen::getMArch());
949
950 Builder.getJITTargetMachineBuilder()
951 ->setCPU(codegen::getCPUStr())
952 .addFeatures(FeatureVec: codegen::getFeatureList())
953 .setRelocationModel(codegen::getExplicitRelocModel())
954 .setCodeModel(codegen::getExplicitCodeModel());
955
956 // Link process symbols unless NoProcessSymbols is set.
957 Builder.setLinkProcessSymbolsByDefault(!NoProcessSymbols);
958
959 // FIXME: Setting a dummy call-through manager in non-lazy mode prevents the
960 // JIT builder to instantiate a default (which would fail with an error for
961 // unsupported architectures).
962 if (UseJITKind != JITKind::OrcLazy) {
963 auto ES = std::make_unique<orc::ExecutionSession>(
964 args: ExitOnErr(orc::SelfExecutorProcessControl::Create()));
965 Builder.setLazyCallthroughManager(
966 std::make_unique<orc::LazyCallThroughManager>(args&: *ES, args: orc::ExecutorAddr(),
967 args: nullptr));
968 Builder.setExecutionSession(std::move(ES));
969 }
970
971 Builder.setLazyCompileFailureAddr(
972 orc::ExecutorAddr::fromPtr(Ptr: exitOnLazyCallThroughFailure));
973 Builder.setNumCompileThreads(LazyJITCompileThreads);
974
975 // If the object cache is enabled then set a custom compile function
976 // creator to use the cache.
977 std::unique_ptr<LLIObjectCache> CacheManager;
978 if (EnableCacheManager) {
979
980 CacheManager = std::make_unique<LLIObjectCache>(args&: ObjectCacheDir);
981
982 Builder.setCompileFunctionCreator(
983 [&](orc::JITTargetMachineBuilder JTMB)
984 -> Expected<std::unique_ptr<orc::IRCompileLayer::IRCompiler>> {
985 if (LazyJITCompileThreads > 0)
986 return std::make_unique<orc::ConcurrentIRCompiler>(args: std::move(JTMB),
987 args: CacheManager.get());
988
989 auto TM = JTMB.createTargetMachine();
990 if (!TM)
991 return TM.takeError();
992
993 return std::make_unique<orc::TMOwningSimpleCompiler>(args: std::move(*TM),
994 args: CacheManager.get());
995 });
996 }
997
998 // Enable debugging of JIT'd code (only works on JITLink for ELF and MachO).
999 Builder.setPrePlatformSetup(tryEnableDebugSupport);
1000
1001 // Set up LLJIT platform.
1002 LLJITPlatform P = Platform;
1003 if (P == LLJITPlatform::Auto)
1004 P = OrcRuntime.empty() ? LLJITPlatform::GenericIR
1005 : LLJITPlatform::ExecutorNative;
1006
1007 switch (P) {
1008 case LLJITPlatform::ExecutorNative: {
1009 Builder.setPlatformSetUp(orc::ExecutorNativePlatform(OrcRuntime));
1010 break;
1011 }
1012 case LLJITPlatform::GenericIR:
1013 // Nothing to do: LLJITBuilder will use this by default.
1014 break;
1015 case LLJITPlatform::Inactive:
1016 Builder.setPlatformSetUp(orc::setUpInactivePlatform);
1017 break;
1018 default:
1019 llvm_unreachable("Unrecognized platform value");
1020 }
1021
1022 switch (JITLinker) {
1023 case JITLinkerKind::JITLink:
1024 Builder.getJITTargetMachineBuilder()
1025 ->setRelocationModel(Reloc::PIC_)
1026 .setCodeModel(CodeModel::Small);
1027 Builder.setObjectLinkingLayerCreator([&](orc::ExecutionSession &ES) {
1028 return std::make_unique<orc::ObjectLinkingLayer>(args&: ES);
1029 });
1030 break;
1031 case JITLinkerKind::RuntimeDyld:
1032 Builder.setObjectLinkingLayerCreator([&](orc::ExecutionSession &ES) {
1033 return std::make_unique<orc::RTDyldObjectLinkingLayer>(
1034 args&: ES, args: [](const MemoryBuffer &) {
1035 return std::make_unique<SectionMemoryManager>();
1036 });
1037 });
1038 break;
1039 case JITLinkerKind::Default:
1040 // Let LLJITBuilder decide
1041 break;
1042 }
1043
1044 auto J = ExitOnErr(Builder.create());
1045
1046 auto *ObjLayer = &J->getObjLinkingLayer();
1047 if (auto *RTDyldObjLayer = dyn_cast<orc::RTDyldObjectLinkingLayer>(Val: ObjLayer)) {
1048 RTDyldObjLayer->registerJITEventListener(
1049 L&: *JITEventListener::createGDBRegistrationListener());
1050#if LLVM_USE_OPROFILE
1051 RTDyldObjLayer->registerJITEventListener(
1052 *JITEventListener::createOProfileJITEventListener());
1053#endif
1054#if LLVM_USE_INTEL_JITEVENTS
1055 RTDyldObjLayer->registerJITEventListener(
1056 *JITEventListener::createIntelJITEventListener());
1057#endif
1058#if LLVM_USE_PERF
1059 RTDyldObjLayer->registerJITEventListener(
1060 *JITEventListener::createPerfJITEventListener());
1061#endif
1062 }
1063
1064 if (PerModuleLazy)
1065 J->setPartitionFunction(orc::IRPartitionLayer::compileWholeModule);
1066
1067 auto IRDump = createIRDebugDumper();
1068 J->getIRTransformLayer().setTransform(
1069 [&](orc::ThreadSafeModule TSM,
1070 const orc::MaterializationResponsibility &R) {
1071 TSM.withModuleDo(F: [&](Module &M) {
1072 if (verifyModule(M, OS: &dbgs())) {
1073 dbgs() << "Bad module: " << &M << "\n";
1074 exit(status: 1);
1075 }
1076 IRDump(M);
1077 });
1078 return TSM;
1079 });
1080
1081 auto ObjDump = createObjDebugDumper();
1082 J->getObjTransformLayer().setTransform(
1083 [&](std::unique_ptr<MemoryBuffer> Obj)
1084 -> Expected<std::unique_ptr<MemoryBuffer>> {
1085 ObjDump(*Obj);
1086 return std::move(Obj);
1087 });
1088
1089 // If this is a Mingw or Cygwin executor then we need to alias __main to
1090 // orc_rt_int_void_return_0.
1091 if (J->getTargetTriple().isOSCygMing()) {
1092 auto &WorkaroundJD = J->getProcessSymbolsJITDylib()
1093 ? *J->getProcessSymbolsJITDylib()
1094 : J->getMainJITDylib();
1095 ExitOnErr(WorkaroundJD.define(
1096 MU: orc::absoluteSymbols(Symbols: {{J->mangleAndIntern(UnmangledName: "__main"),
1097 {orc::ExecutorAddr::fromPtr(Ptr: mingw_noop_main),
1098 JITSymbolFlags::Exported}}})));
1099 }
1100
1101 // Regular modules are greedy: They materialize as a whole and trigger
1102 // materialization for all required symbols recursively. Lazy modules go
1103 // through partitioning and they replace outgoing calls with reexport stubs
1104 // that resolve on call-through.
1105 auto AddModule = [&](orc::JITDylib &JD, orc::ThreadSafeModule M) {
1106 return UseJITKind == JITKind::OrcLazy ? J->addLazyIRModule(JD, M: std::move(M))
1107 : J->addIRModule(JD, TSM: std::move(M));
1108 };
1109
1110 // Add the main module.
1111 ExitOnErr(AddModule(J->getMainJITDylib(), std::move(MainModule)));
1112
1113 // Create JITDylibs and add any extra modules.
1114 {
1115 // Create JITDylibs, keep a map from argument index to dylib. We will use
1116 // -extra-module argument indexes to determine what dylib to use for each
1117 // -extra-module.
1118 std::map<unsigned, orc::JITDylib *> IdxToDylib;
1119 IdxToDylib[0] = &J->getMainJITDylib();
1120 for (auto JDItr = JITDylibs.begin(), JDEnd = JITDylibs.end();
1121 JDItr != JDEnd; ++JDItr) {
1122 orc::JITDylib *JD = J->getJITDylibByName(Name: *JDItr);
1123 if (!JD) {
1124 JD = &ExitOnErr(J->createJITDylib(Name: *JDItr));
1125 J->getMainJITDylib().addToLinkOrder(JD&: *JD);
1126 JD->addToLinkOrder(JD&: J->getMainJITDylib());
1127 }
1128 IdxToDylib[JITDylibs.getPosition(optnum: JDItr - JITDylibs.begin())] = JD;
1129 }
1130
1131 for (auto EMItr = ExtraModules.begin(), EMEnd = ExtraModules.end();
1132 EMItr != EMEnd; ++EMItr) {
1133 auto M = ExitOnErr(loadModule(Path: *EMItr, TSCtx));
1134
1135 auto EMIdx = ExtraModules.getPosition(optnum: EMItr - ExtraModules.begin());
1136 assert(EMIdx != 0 && "ExtraModule should have index > 0");
1137 auto JDItr = std::prev(x: IdxToDylib.lower_bound(x: EMIdx));
1138 auto &JD = *JDItr->second;
1139 ExitOnErr(AddModule(JD, std::move(M)));
1140 }
1141
1142 for (auto EAItr = ExtraArchives.begin(), EAEnd = ExtraArchives.end();
1143 EAItr != EAEnd; ++EAItr) {
1144 auto EAIdx = ExtraArchives.getPosition(optnum: EAItr - ExtraArchives.begin());
1145 assert(EAIdx != 0 && "ExtraArchive should have index > 0");
1146 auto JDItr = std::prev(x: IdxToDylib.lower_bound(x: EAIdx));
1147 auto &JD = *JDItr->second;
1148 ExitOnErr(J->linkStaticLibraryInto(JD, Path: EAItr->c_str()));
1149 }
1150 }
1151
1152 // Add the objects.
1153 for (auto &ObjPath : ExtraObjects) {
1154 auto Obj = ExitOnErr(errorOrToExpected(EO: MemoryBuffer::getFile(Filename: ObjPath)));
1155 ExitOnErr(J->addObjectFile(Obj: std::move(Obj)));
1156 }
1157
1158 // Run any static constructors.
1159 ExitOnErr(J->initialize(JD&: J->getMainJITDylib()));
1160
1161 // Run any -thread-entry points.
1162 std::vector<std::thread> AltEntryThreads;
1163 for (auto &ThreadEntryPoint : ThreadEntryPoints) {
1164 auto EntryPointSym = ExitOnErr(J->lookup(UnmangledName: ThreadEntryPoint));
1165 typedef void (*EntryPointPtr)();
1166 auto EntryPoint = EntryPointSym.toPtr<EntryPointPtr>();
1167 AltEntryThreads.push_back(x: std::thread([EntryPoint]() { EntryPoint(); }));
1168 }
1169
1170 // Resolve and run the main function.
1171 using MainFnTy = int(int, char *[]);
1172 auto MainAddr = ExitOnErr(J->lookup(UnmangledName: EntryFunc));
1173 auto MainFn = MainAddr.toPtr<MainFnTy *>();
1174 int Result = orc::runAsMain(Main: MainFn, Args: InputArgv, ProgramName: StringRef(InputFile));
1175
1176 // Wait for -entry-point threads.
1177 for (auto &AltEntryThread : AltEntryThreads)
1178 AltEntryThread.join();
1179
1180 // Run destructors.
1181 ExitOnErr(J->deinitialize(JD&: J->getMainJITDylib()));
1182
1183 return Result;
1184}
1185
1186static void disallowOrcOptions() {
1187 // Make sure nobody used an orc-lazy specific option accidentally.
1188
1189 if (LazyJITCompileThreads != 0) {
1190 errs() << "-compile-threads requires -jit-kind=orc-lazy\n";
1191 exit(status: 1);
1192 }
1193
1194 if (!ThreadEntryPoints.empty()) {
1195 errs() << "-thread-entry requires -jit-kind=orc-lazy\n";
1196 exit(status: 1);
1197 }
1198
1199 if (PerModuleLazy) {
1200 errs() << "-per-module-lazy requires -jit-kind=orc-lazy\n";
1201 exit(status: 1);
1202 }
1203}
1204
1205static Expected<std::unique_ptr<orc::ExecutorProcessControl>> launchRemote() {
1206#ifndef LLVM_ON_UNIX
1207 llvm_unreachable("launchRemote not supported on non-Unix platforms");
1208#else
1209 int PipeFD[2][2];
1210 pid_t ChildPID;
1211
1212 // Create two pipes.
1213 if (pipe(pipedes: PipeFD[0]) != 0 || pipe(pipedes: PipeFD[1]) != 0)
1214 perror(s: "Error creating pipe: ");
1215
1216 ChildPID = fork();
1217
1218 if (ChildPID == 0) {
1219 // In the child...
1220
1221 // Close the parent ends of the pipes
1222 close(fd: PipeFD[0][1]);
1223 close(fd: PipeFD[1][0]);
1224
1225
1226 // Execute the child process.
1227 std::unique_ptr<char[]> ChildPath, ChildIn, ChildOut;
1228 {
1229 ChildPath.reset(p: new char[ChildExecPath.size() + 1]);
1230 llvm::copy(Range&: ChildExecPath, Out: &ChildPath[0]);
1231 ChildPath[ChildExecPath.size()] = '\0';
1232 std::string ChildInStr = utostr(X: PipeFD[0][0]);
1233 ChildIn.reset(p: new char[ChildInStr.size() + 1]);
1234 llvm::copy(Range&: ChildInStr, Out: &ChildIn[0]);
1235 ChildIn[ChildInStr.size()] = '\0';
1236 std::string ChildOutStr = utostr(X: PipeFD[1][1]);
1237 ChildOut.reset(p: new char[ChildOutStr.size() + 1]);
1238 llvm::copy(Range&: ChildOutStr, Out: &ChildOut[0]);
1239 ChildOut[ChildOutStr.size()] = '\0';
1240 }
1241
1242 char * const args[] = { &ChildPath[0], &ChildIn[0], &ChildOut[0], nullptr };
1243 int rc = execv(path: ChildExecPath.c_str(), argv: args);
1244 if (rc != 0)
1245 perror(s: "Error executing child process: ");
1246 llvm_unreachable("Error executing child process");
1247 }
1248 // else we're the parent...
1249
1250 // Close the child ends of the pipes
1251 close(fd: PipeFD[0][0]);
1252 close(fd: PipeFD[1][1]);
1253
1254 // Return a SimpleRemoteEPC instance connected to our end of the pipes.
1255 return orc::SimpleRemoteEPC::Create<orc::FDSimpleRemoteEPCTransport>(
1256 D: std::make_unique<llvm::orc::InPlaceTaskDispatcher>(),
1257 S: llvm::orc::SimpleRemoteEPC::Setup(), TransportTCtorArgs&: PipeFD[1][0], TransportTCtorArgs&: PipeFD[0][1]);
1258#endif
1259}
1260
1261// For MinGW environments, manually export the __chkstk function from the lli
1262// executable.
1263//
1264// Normally, this function is provided by compiler-rt builtins or libgcc.
1265// It is named "_alloca" on i386, "___chkstk_ms" on x86_64, and "__chkstk" on
1266// arm/aarch64. In MSVC configurations, it's named "__chkstk" in all
1267// configurations.
1268//
1269// When Orc tries to resolve symbols at runtime, this succeeds in MSVC
1270// configurations, somewhat by accident/luck; kernelbase.dll does export a
1271// symbol named "__chkstk" which gets found by Orc, even if regular applications
1272// never link against that function from that DLL (it's linked in statically
1273// from a compiler support library).
1274//
1275// The MinGW specific symbol names aren't available in that DLL though.
1276// Therefore, manually export the relevant symbol from lli, to let it be
1277// found at runtime during tests.
1278//
1279// For real JIT uses, the real compiler support libraries should be linked
1280// in, somehow; this is a workaround to let tests pass.
1281//
1282// We need to make sure that this symbol actually is linked in when we
1283// try to export it; if no functions allocate a large enough stack area,
1284// nothing would reference it. Therefore, manually declare it and add a
1285// reference to it. (Note, the declarations of _alloca/___chkstk_ms/__chkstk
1286// are somewhat bogus, these functions use a different custom calling
1287// convention.)
1288//
1289// TODO: Move this into libORC at some point, see
1290// https://github.com/llvm/llvm-project/issues/56603.
1291#ifdef __MINGW32__
1292// This is a MinGW version of #pragma comment(linker, "...") that doesn't
1293// require compiling with -fms-extensions.
1294#if defined(__i386__)
1295#undef _alloca
1296extern "C" void _alloca(void);
1297static __attribute__((used)) void (*const ref_func)(void) = _alloca;
1298static __attribute__((section(".drectve"), used)) const char export_chkstk[] =
1299 "-export:_alloca";
1300#elif defined(__x86_64__)
1301extern "C" void ___chkstk_ms(void);
1302static __attribute__((used)) void (*const ref_func)(void) = ___chkstk_ms;
1303static __attribute__((section(".drectve"), used)) const char export_chkstk[] =
1304 "-export:___chkstk_ms";
1305#else
1306extern "C" void __chkstk(void);
1307static __attribute__((used)) void (*const ref_func)(void) = __chkstk;
1308static __attribute__((section(".drectve"), used)) const char export_chkstk[] =
1309 "-export:__chkstk";
1310#endif
1311#endif
1312