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