lli.cpp 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155
  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. #include "ExecutionUtils.h"
  15. #include "ForwardingMemoryManager.h"
  16. #include "llvm/ADT/StringExtras.h"
  17. #include "llvm/ADT/Triple.h"
  18. #include "llvm/Bitcode/BitcodeReader.h"
  19. #include "llvm/CodeGen/CommandFlags.h"
  20. #include "llvm/CodeGen/LinkAllCodegenComponents.h"
  21. #include "llvm/Config/llvm-config.h"
  22. #include "llvm/ExecutionEngine/GenericValue.h"
  23. #include "llvm/ExecutionEngine/Interpreter.h"
  24. #include "llvm/ExecutionEngine/JITEventListener.h"
  25. #include "llvm/ExecutionEngine/JITSymbol.h"
  26. #include "llvm/ExecutionEngine/MCJIT.h"
  27. #include "llvm/ExecutionEngine/ObjectCache.h"
  28. #include "llvm/ExecutionEngine/Orc/DebugObjectManagerPlugin.h"
  29. #include "llvm/ExecutionEngine/Orc/DebugUtils.h"
  30. #include "llvm/ExecutionEngine/Orc/EPCDebugObjectRegistrar.h"
  31. #include "llvm/ExecutionEngine/Orc/EPCEHFrameRegistrar.h"
  32. #include "llvm/ExecutionEngine/Orc/EPCGenericRTDyldMemoryManager.h"
  33. #include "llvm/ExecutionEngine/Orc/ExecutionUtils.h"
  34. #include "llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h"
  35. #include "llvm/ExecutionEngine/Orc/LLJIT.h"
  36. #include "llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h"
  37. #include "llvm/ExecutionEngine/Orc/SimpleRemoteEPC.h"
  38. #include "llvm/ExecutionEngine/Orc/SymbolStringPool.h"
  39. #include "llvm/ExecutionEngine/Orc/TargetProcess/JITLoaderGDB.h"
  40. #include "llvm/ExecutionEngine/Orc/TargetProcess/RegisterEHFrames.h"
  41. #include "llvm/ExecutionEngine/Orc/TargetProcess/TargetExecutionUtils.h"
  42. #include "llvm/ExecutionEngine/SectionMemoryManager.h"
  43. #include "llvm/IR/IRBuilder.h"
  44. #include "llvm/IR/LLVMContext.h"
  45. #include "llvm/IR/Module.h"
  46. #include "llvm/IR/Type.h"
  47. #include "llvm/IR/Verifier.h"
  48. #include "llvm/IRReader/IRReader.h"
  49. #include "llvm/Object/Archive.h"
  50. #include "llvm/Object/ObjectFile.h"
  51. #include "llvm/Support/CommandLine.h"
  52. #include "llvm/Support/Debug.h"
  53. #include "llvm/Support/DynamicLibrary.h"
  54. #include "llvm/Support/Format.h"
  55. #include "llvm/Support/InitLLVM.h"
  56. #include "llvm/Support/ManagedStatic.h"
  57. #include "llvm/Support/MathExtras.h"
  58. #include "llvm/Support/Memory.h"
  59. #include "llvm/Support/MemoryBuffer.h"
  60. #include "llvm/Support/Path.h"
  61. #include "llvm/Support/PluginLoader.h"
  62. #include "llvm/Support/Process.h"
  63. #include "llvm/Support/Program.h"
  64. #include "llvm/Support/SourceMgr.h"
  65. #include "llvm/Support/TargetSelect.h"
  66. #include "llvm/Support/WithColor.h"
  67. #include "llvm/Support/raw_ostream.h"
  68. #include "llvm/Transforms/Instrumentation.h"
  69. #include <cerrno>
  70. #if !defined(_MSC_VER) && !defined(__MINGW32__)
  71. #include <unistd.h>
  72. #else
  73. #include <io.h>
  74. #endif
  75. #ifdef __CYGWIN__
  76. #include <cygwin/version.h>
  77. #if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
  78. #define DO_NOTHING_ATEXIT 1
  79. #endif
  80. #endif
  81. using namespace llvm;
  82. static codegen::RegisterCodeGenFlags CGF;
  83. #define DEBUG_TYPE "lli"
  84. namespace {
  85. enum class JITKind { MCJIT, Orc, OrcLazy };
  86. enum class JITLinkerKind { Default, RuntimeDyld, JITLink };
  87. cl::opt<std::string>
  88. InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
  89. cl::list<std::string>
  90. InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
  91. cl::opt<bool> ForceInterpreter("force-interpreter",
  92. cl::desc("Force interpretation: disable JIT"),
  93. cl::init(false));
  94. cl::opt<JITKind> UseJITKind(
  95. "jit-kind", cl::desc("Choose underlying JIT kind."),
  96. cl::init(JITKind::Orc),
  97. cl::values(clEnumValN(JITKind::MCJIT, "mcjit", "MCJIT"),
  98. clEnumValN(JITKind::Orc, "orc", "Orc JIT"),
  99. clEnumValN(JITKind::OrcLazy, "orc-lazy",
  100. "Orc-based lazy JIT.")));
  101. cl::opt<JITLinkerKind>
  102. JITLinker("jit-linker", cl::desc("Choose the dynamic linker/loader."),
  103. cl::init(JITLinkerKind::Default),
  104. cl::values(clEnumValN(JITLinkerKind::Default, "default",
  105. "Default for platform and JIT-kind"),
  106. clEnumValN(JITLinkerKind::RuntimeDyld, "rtdyld",
  107. "RuntimeDyld"),
  108. clEnumValN(JITLinkerKind::JITLink, "jitlink",
  109. "Orc-specific linker")));
  110. cl::opt<unsigned>
  111. LazyJITCompileThreads("compile-threads",
  112. cl::desc("Choose the number of compile threads "
  113. "(jit-kind=orc-lazy only)"),
  114. cl::init(0));
  115. cl::list<std::string>
  116. ThreadEntryPoints("thread-entry",
  117. cl::desc("calls the given entry-point on a new thread "
  118. "(jit-kind=orc-lazy only)"));
  119. cl::opt<bool> PerModuleLazy(
  120. "per-module-lazy",
  121. cl::desc("Performs lazy compilation on whole module boundaries "
  122. "rather than individual functions"),
  123. cl::init(false));
  124. cl::list<std::string>
  125. JITDylibs("jd",
  126. cl::desc("Specifies the JITDylib to be used for any subsequent "
  127. "-extra-module arguments."));
  128. cl::list<std::string>
  129. Dylibs("dlopen", cl::desc("Dynamic libraries to load before linking"),
  130. cl::ZeroOrMore);
  131. // The MCJIT supports building for a target address space separate from
  132. // the JIT compilation process. Use a forked process and a copying
  133. // memory manager with IPC to execute using this functionality.
  134. cl::opt<bool> RemoteMCJIT("remote-mcjit",
  135. cl::desc("Execute MCJIT'ed code in a separate process."),
  136. cl::init(false));
  137. // Manually specify the child process for remote execution. This overrides
  138. // the simulated remote execution that allocates address space for child
  139. // execution. The child process will be executed and will communicate with
  140. // lli via stdin/stdout pipes.
  141. cl::opt<std::string>
  142. ChildExecPath("mcjit-remote-process",
  143. cl::desc("Specify the filename of the process to launch "
  144. "for remote MCJIT execution. If none is specified,"
  145. "\n\tremote execution will be simulated in-process."),
  146. cl::value_desc("filename"), cl::init(""));
  147. // Determine optimization level.
  148. cl::opt<char>
  149. OptLevel("O",
  150. cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
  151. "(default = '-O2')"),
  152. cl::Prefix,
  153. cl::ZeroOrMore,
  154. cl::init(' '));
  155. cl::opt<std::string>
  156. TargetTriple("mtriple", cl::desc("Override target triple for module"));
  157. cl::opt<std::string>
  158. EntryFunc("entry-function",
  159. cl::desc("Specify the entry function (default = 'main') "
  160. "of the executable"),
  161. cl::value_desc("function"),
  162. cl::init("main"));
  163. cl::list<std::string>
  164. ExtraModules("extra-module",
  165. cl::desc("Extra modules to be loaded"),
  166. cl::value_desc("input bitcode"));
  167. cl::list<std::string>
  168. ExtraObjects("extra-object",
  169. cl::desc("Extra object files to be loaded"),
  170. cl::value_desc("input object"));
  171. cl::list<std::string>
  172. ExtraArchives("extra-archive",
  173. cl::desc("Extra archive files to be loaded"),
  174. cl::value_desc("input archive"));
  175. cl::opt<bool>
  176. EnableCacheManager("enable-cache-manager",
  177. cl::desc("Use cache manager to save/load modules"),
  178. cl::init(false));
  179. cl::opt<std::string>
  180. ObjectCacheDir("object-cache-dir",
  181. cl::desc("Directory to store cached object files "
  182. "(must be user writable)"),
  183. cl::init(""));
  184. cl::opt<std::string>
  185. FakeArgv0("fake-argv0",
  186. cl::desc("Override the 'argv[0]' value passed into the executing"
  187. " program"), cl::value_desc("executable"));
  188. cl::opt<bool>
  189. DisableCoreFiles("disable-core-files", cl::Hidden,
  190. cl::desc("Disable emission of core files if possible"));
  191. cl::opt<bool>
  192. NoLazyCompilation("disable-lazy-compilation",
  193. cl::desc("Disable JIT lazy compilation"),
  194. cl::init(false));
  195. cl::opt<bool>
  196. GenerateSoftFloatCalls("soft-float",
  197. cl::desc("Generate software floating point library calls"),
  198. cl::init(false));
  199. cl::opt<bool> NoProcessSymbols(
  200. "no-process-syms",
  201. cl::desc("Do not resolve lli process symbols in JIT'd code"),
  202. cl::init(false));
  203. enum class LLJITPlatform { Inactive, DetectHost, GenericIR };
  204. cl::opt<LLJITPlatform>
  205. Platform("lljit-platform", cl::desc("Platform to use with LLJIT"),
  206. cl::init(LLJITPlatform::DetectHost),
  207. cl::values(clEnumValN(LLJITPlatform::DetectHost, "DetectHost",
  208. "Select based on JIT target triple"),
  209. clEnumValN(LLJITPlatform::GenericIR, "GenericIR",
  210. "Use LLJITGenericIRPlatform"),
  211. clEnumValN(LLJITPlatform::Inactive, "Inactive",
  212. "Disable platform support explicitly")),
  213. cl::Hidden);
  214. enum class DumpKind {
  215. NoDump,
  216. DumpFuncsToStdOut,
  217. DumpModsToStdOut,
  218. DumpModsToDisk
  219. };
  220. cl::opt<DumpKind> OrcDumpKind(
  221. "orc-lazy-debug", cl::desc("Debug dumping for the orc-lazy JIT."),
  222. cl::init(DumpKind::NoDump),
  223. cl::values(clEnumValN(DumpKind::NoDump, "no-dump",
  224. "Don't dump anything."),
  225. clEnumValN(DumpKind::DumpFuncsToStdOut, "funcs-to-stdout",
  226. "Dump function names to stdout."),
  227. clEnumValN(DumpKind::DumpModsToStdOut, "mods-to-stdout",
  228. "Dump modules to stdout."),
  229. clEnumValN(DumpKind::DumpModsToDisk, "mods-to-disk",
  230. "Dump modules to the current "
  231. "working directory. (WARNING: "
  232. "will overwrite existing files).")),
  233. cl::Hidden);
  234. cl::list<BuiltinFunctionKind> GenerateBuiltinFunctions(
  235. "generate",
  236. cl::desc("Provide built-in functions for access by JITed code "
  237. "(jit-kind=orc-lazy only)"),
  238. cl::values(clEnumValN(BuiltinFunctionKind::DumpDebugDescriptor,
  239. "__dump_jit_debug_descriptor",
  240. "Dump __jit_debug_descriptor contents to stdout"),
  241. clEnumValN(BuiltinFunctionKind::DumpDebugObjects,
  242. "__dump_jit_debug_objects",
  243. "Dump __jit_debug_descriptor in-memory debug "
  244. "objects as tool output")),
  245. cl::Hidden);
  246. ExitOnError ExitOnErr;
  247. }
  248. LLVM_ATTRIBUTE_USED void linkComponents() {
  249. errs() << (void *)&llvm_orc_registerEHFrameSectionWrapper
  250. << (void *)&llvm_orc_deregisterEHFrameSectionWrapper
  251. << (void *)&llvm_orc_registerJITLoaderGDBWrapper;
  252. }
  253. //===----------------------------------------------------------------------===//
  254. // Object cache
  255. //
  256. // This object cache implementation writes cached objects to disk to the
  257. // directory specified by CacheDir, using a filename provided in the module
  258. // descriptor. The cache tries to load a saved object using that path if the
  259. // file exists. CacheDir defaults to "", in which case objects are cached
  260. // alongside their originating bitcodes.
  261. //
  262. class LLIObjectCache : public ObjectCache {
  263. public:
  264. LLIObjectCache(const std::string& CacheDir) : CacheDir(CacheDir) {
  265. // Add trailing '/' to cache dir if necessary.
  266. if (!this->CacheDir.empty() &&
  267. this->CacheDir[this->CacheDir.size() - 1] != '/')
  268. this->CacheDir += '/';
  269. }
  270. ~LLIObjectCache() override {}
  271. void notifyObjectCompiled(const Module *M, MemoryBufferRef Obj) override {
  272. const std::string &ModuleID = M->getModuleIdentifier();
  273. std::string CacheName;
  274. if (!getCacheFilename(ModuleID, CacheName))
  275. return;
  276. if (!CacheDir.empty()) { // Create user-defined cache dir.
  277. SmallString<128> dir(sys::path::parent_path(CacheName));
  278. sys::fs::create_directories(Twine(dir));
  279. }
  280. std::error_code EC;
  281. raw_fd_ostream outfile(CacheName, EC, sys::fs::OF_None);
  282. outfile.write(Obj.getBufferStart(), Obj.getBufferSize());
  283. outfile.close();
  284. }
  285. std::unique_ptr<MemoryBuffer> getObject(const Module* M) override {
  286. const std::string &ModuleID = M->getModuleIdentifier();
  287. std::string CacheName;
  288. if (!getCacheFilename(ModuleID, CacheName))
  289. return nullptr;
  290. // Load the object from the cache filename
  291. ErrorOr<std::unique_ptr<MemoryBuffer>> IRObjectBuffer =
  292. MemoryBuffer::getFile(CacheName, /*IsText=*/false,
  293. /*RequiresNullTerminator=*/false);
  294. // If the file isn't there, that's OK.
  295. if (!IRObjectBuffer)
  296. return nullptr;
  297. // MCJIT will want to write into this buffer, and we don't want that
  298. // because the file has probably just been mmapped. Instead we make
  299. // a copy. The filed-based buffer will be released when it goes
  300. // out of scope.
  301. return MemoryBuffer::getMemBufferCopy(IRObjectBuffer.get()->getBuffer());
  302. }
  303. private:
  304. std::string CacheDir;
  305. bool getCacheFilename(const std::string &ModID, std::string &CacheName) {
  306. std::string Prefix("file:");
  307. size_t PrefixLength = Prefix.length();
  308. if (ModID.substr(0, PrefixLength) != Prefix)
  309. return false;
  310. std::string CacheSubdir = ModID.substr(PrefixLength);
  311. // Transform "X:\foo" => "/X\foo" for convenience on Windows.
  312. if (is_style_windows(llvm::sys::path::Style::native) &&
  313. isalpha(CacheSubdir[0]) && CacheSubdir[1] == ':') {
  314. CacheSubdir[1] = CacheSubdir[0];
  315. CacheSubdir[0] = '/';
  316. }
  317. CacheName = CacheDir + CacheSubdir;
  318. size_t pos = CacheName.rfind('.');
  319. CacheName.replace(pos, CacheName.length() - pos, ".o");
  320. return true;
  321. }
  322. };
  323. // On Mingw and Cygwin, an external symbol named '__main' is called from the
  324. // generated 'main' function to allow static initialization. To avoid linking
  325. // problems with remote targets (because lli's remote target support does not
  326. // currently handle external linking) we add a secondary module which defines
  327. // an empty '__main' function.
  328. static void addCygMingExtraModule(ExecutionEngine &EE, LLVMContext &Context,
  329. StringRef TargetTripleStr) {
  330. IRBuilder<> Builder(Context);
  331. Triple TargetTriple(TargetTripleStr);
  332. // Create a new module.
  333. std::unique_ptr<Module> M = std::make_unique<Module>("CygMingHelper", Context);
  334. M->setTargetTriple(TargetTripleStr);
  335. // Create an empty function named "__main".
  336. Type *ReturnTy;
  337. if (TargetTriple.isArch64Bit())
  338. ReturnTy = Type::getInt64Ty(Context);
  339. else
  340. ReturnTy = Type::getInt32Ty(Context);
  341. Function *Result =
  342. Function::Create(FunctionType::get(ReturnTy, {}, false),
  343. GlobalValue::ExternalLinkage, "__main", M.get());
  344. BasicBlock *BB = BasicBlock::Create(Context, "__main", Result);
  345. Builder.SetInsertPoint(BB);
  346. Value *ReturnVal = ConstantInt::get(ReturnTy, 0);
  347. Builder.CreateRet(ReturnVal);
  348. // Add this new module to the ExecutionEngine.
  349. EE.addModule(std::move(M));
  350. }
  351. CodeGenOpt::Level getOptLevel() {
  352. switch (OptLevel) {
  353. default:
  354. WithColor::error(errs(), "lli") << "invalid optimization level.\n";
  355. exit(1);
  356. case '0': return CodeGenOpt::None;
  357. case '1': return CodeGenOpt::Less;
  358. case ' ':
  359. case '2': return CodeGenOpt::Default;
  360. case '3': return CodeGenOpt::Aggressive;
  361. }
  362. llvm_unreachable("Unrecognized opt level.");
  363. }
  364. [[noreturn]] static void reportError(SMDiagnostic Err, const char *ProgName) {
  365. Err.print(ProgName, errs());
  366. exit(1);
  367. }
  368. Error loadDylibs();
  369. int runOrcJIT(const char *ProgName);
  370. void disallowOrcOptions();
  371. Expected<std::unique_ptr<orc::ExecutorProcessControl>> launchRemote();
  372. //===----------------------------------------------------------------------===//
  373. // main Driver function
  374. //
  375. int main(int argc, char **argv, char * const *envp) {
  376. InitLLVM X(argc, argv);
  377. if (argc > 1)
  378. ExitOnErr.setBanner(std::string(argv[0]) + ": ");
  379. // If we have a native target, initialize it to ensure it is linked in and
  380. // usable by the JIT.
  381. InitializeNativeTarget();
  382. InitializeNativeTargetAsmPrinter();
  383. InitializeNativeTargetAsmParser();
  384. cl::ParseCommandLineOptions(argc, argv,
  385. "llvm interpreter & dynamic compiler\n");
  386. // If the user doesn't want core files, disable them.
  387. if (DisableCoreFiles)
  388. sys::Process::PreventCoreFiles();
  389. ExitOnErr(loadDylibs());
  390. if (UseJITKind == JITKind::MCJIT)
  391. disallowOrcOptions();
  392. else
  393. return runOrcJIT(argv[0]);
  394. // Old lli implementation based on ExecutionEngine and MCJIT.
  395. LLVMContext Context;
  396. // Load the bitcode...
  397. SMDiagnostic Err;
  398. std::unique_ptr<Module> Owner = parseIRFile(InputFile, Err, Context);
  399. Module *Mod = Owner.get();
  400. if (!Mod)
  401. reportError(Err, argv[0]);
  402. if (EnableCacheManager) {
  403. std::string CacheName("file:");
  404. CacheName.append(InputFile);
  405. Mod->setModuleIdentifier(CacheName);
  406. }
  407. // If not jitting lazily, load the whole bitcode file eagerly too.
  408. if (NoLazyCompilation) {
  409. // Use *argv instead of argv[0] to work around a wrong GCC warning.
  410. ExitOnError ExitOnErr(std::string(*argv) +
  411. ": bitcode didn't read correctly: ");
  412. ExitOnErr(Mod->materializeAll());
  413. }
  414. std::string ErrorMsg;
  415. EngineBuilder builder(std::move(Owner));
  416. builder.setMArch(codegen::getMArch());
  417. builder.setMCPU(codegen::getCPUStr());
  418. builder.setMAttrs(codegen::getFeatureList());
  419. if (auto RM = codegen::getExplicitRelocModel())
  420. builder.setRelocationModel(RM.getValue());
  421. if (auto CM = codegen::getExplicitCodeModel())
  422. builder.setCodeModel(CM.getValue());
  423. builder.setErrorStr(&ErrorMsg);
  424. builder.setEngineKind(ForceInterpreter
  425. ? EngineKind::Interpreter
  426. : EngineKind::JIT);
  427. // If we are supposed to override the target triple, do so now.
  428. if (!TargetTriple.empty())
  429. Mod->setTargetTriple(Triple::normalize(TargetTriple));
  430. // Enable MCJIT if desired.
  431. RTDyldMemoryManager *RTDyldMM = nullptr;
  432. if (!ForceInterpreter) {
  433. if (RemoteMCJIT)
  434. RTDyldMM = new ForwardingMemoryManager();
  435. else
  436. RTDyldMM = new SectionMemoryManager();
  437. // Deliberately construct a temp std::unique_ptr to pass in. Do not null out
  438. // RTDyldMM: We still use it below, even though we don't own it.
  439. builder.setMCJITMemoryManager(
  440. std::unique_ptr<RTDyldMemoryManager>(RTDyldMM));
  441. } else if (RemoteMCJIT) {
  442. WithColor::error(errs(), argv[0])
  443. << "remote process execution does not work with the interpreter.\n";
  444. exit(1);
  445. }
  446. builder.setOptLevel(getOptLevel());
  447. TargetOptions Options =
  448. codegen::InitTargetOptionsFromCodeGenFlags(Triple(TargetTriple));
  449. if (codegen::getFloatABIForCalls() != FloatABI::Default)
  450. Options.FloatABIType = codegen::getFloatABIForCalls();
  451. builder.setTargetOptions(Options);
  452. std::unique_ptr<ExecutionEngine> EE(builder.create());
  453. if (!EE) {
  454. if (!ErrorMsg.empty())
  455. WithColor::error(errs(), argv[0])
  456. << "error creating EE: " << ErrorMsg << "\n";
  457. else
  458. WithColor::error(errs(), argv[0]) << "unknown error creating EE!\n";
  459. exit(1);
  460. }
  461. std::unique_ptr<LLIObjectCache> CacheManager;
  462. if (EnableCacheManager) {
  463. CacheManager.reset(new LLIObjectCache(ObjectCacheDir));
  464. EE->setObjectCache(CacheManager.get());
  465. }
  466. // Load any additional modules specified on the command line.
  467. for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) {
  468. std::unique_ptr<Module> XMod = parseIRFile(ExtraModules[i], Err, Context);
  469. if (!XMod)
  470. reportError(Err, argv[0]);
  471. if (EnableCacheManager) {
  472. std::string CacheName("file:");
  473. CacheName.append(ExtraModules[i]);
  474. XMod->setModuleIdentifier(CacheName);
  475. }
  476. EE->addModule(std::move(XMod));
  477. }
  478. for (unsigned i = 0, e = ExtraObjects.size(); i != e; ++i) {
  479. Expected<object::OwningBinary<object::ObjectFile>> Obj =
  480. object::ObjectFile::createObjectFile(ExtraObjects[i]);
  481. if (!Obj) {
  482. // TODO: Actually report errors helpfully.
  483. consumeError(Obj.takeError());
  484. reportError(Err, argv[0]);
  485. }
  486. object::OwningBinary<object::ObjectFile> &O = Obj.get();
  487. EE->addObjectFile(std::move(O));
  488. }
  489. for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) {
  490. ErrorOr<std::unique_ptr<MemoryBuffer>> ArBufOrErr =
  491. MemoryBuffer::getFileOrSTDIN(ExtraArchives[i]);
  492. if (!ArBufOrErr)
  493. reportError(Err, argv[0]);
  494. std::unique_ptr<MemoryBuffer> &ArBuf = ArBufOrErr.get();
  495. Expected<std::unique_ptr<object::Archive>> ArOrErr =
  496. object::Archive::create(ArBuf->getMemBufferRef());
  497. if (!ArOrErr) {
  498. std::string Buf;
  499. raw_string_ostream OS(Buf);
  500. logAllUnhandledErrors(ArOrErr.takeError(), OS);
  501. OS.flush();
  502. errs() << Buf;
  503. exit(1);
  504. }
  505. std::unique_ptr<object::Archive> &Ar = ArOrErr.get();
  506. object::OwningBinary<object::Archive> OB(std::move(Ar), std::move(ArBuf));
  507. EE->addArchive(std::move(OB));
  508. }
  509. // If the target is Cygwin/MingW and we are generating remote code, we
  510. // need an extra module to help out with linking.
  511. if (RemoteMCJIT && Triple(Mod->getTargetTriple()).isOSCygMing()) {
  512. addCygMingExtraModule(*EE, Context, Mod->getTargetTriple());
  513. }
  514. // The following functions have no effect if their respective profiling
  515. // support wasn't enabled in the build configuration.
  516. EE->RegisterJITEventListener(
  517. JITEventListener::createOProfileJITEventListener());
  518. EE->RegisterJITEventListener(
  519. JITEventListener::createIntelJITEventListener());
  520. if (!RemoteMCJIT)
  521. EE->RegisterJITEventListener(
  522. JITEventListener::createPerfJITEventListener());
  523. if (!NoLazyCompilation && RemoteMCJIT) {
  524. WithColor::warning(errs(), argv[0])
  525. << "remote mcjit does not support lazy compilation\n";
  526. NoLazyCompilation = true;
  527. }
  528. EE->DisableLazyCompilation(NoLazyCompilation);
  529. // If the user specifically requested an argv[0] to pass into the program,
  530. // do it now.
  531. if (!FakeArgv0.empty()) {
  532. InputFile = static_cast<std::string>(FakeArgv0);
  533. } else {
  534. // Otherwise, if there is a .bc suffix on the executable strip it off, it
  535. // might confuse the program.
  536. if (StringRef(InputFile).endswith(".bc"))
  537. InputFile.erase(InputFile.length() - 3);
  538. }
  539. // Add the module's name to the start of the vector of arguments to main().
  540. InputArgv.insert(InputArgv.begin(), InputFile);
  541. // Call the main function from M as if its signature were:
  542. // int main (int argc, char **argv, const char **envp)
  543. // using the contents of Args to determine argc & argv, and the contents of
  544. // EnvVars to determine envp.
  545. //
  546. Function *EntryFn = Mod->getFunction(EntryFunc);
  547. if (!EntryFn) {
  548. WithColor::error(errs(), argv[0])
  549. << '\'' << EntryFunc << "\' function not found in module.\n";
  550. return -1;
  551. }
  552. // Reset errno to zero on entry to main.
  553. errno = 0;
  554. int Result = -1;
  555. // Sanity check use of remote-jit: LLI currently only supports use of the
  556. // remote JIT on Unix platforms.
  557. if (RemoteMCJIT) {
  558. #ifndef LLVM_ON_UNIX
  559. WithColor::warning(errs(), argv[0])
  560. << "host does not support external remote targets.\n";
  561. WithColor::note() << "defaulting to local execution\n";
  562. return -1;
  563. #else
  564. if (ChildExecPath.empty()) {
  565. WithColor::error(errs(), argv[0])
  566. << "-remote-mcjit requires -mcjit-remote-process.\n";
  567. exit(1);
  568. } else if (!sys::fs::can_execute(ChildExecPath)) {
  569. WithColor::error(errs(), argv[0])
  570. << "unable to find usable child executable: '" << ChildExecPath
  571. << "'\n";
  572. return -1;
  573. }
  574. #endif
  575. }
  576. std::unique_ptr<orc::ExecutorProcessControl> EPC =
  577. RemoteMCJIT ? ExitOnErr(launchRemote())
  578. : ExitOnErr(orc::SelfExecutorProcessControl::Create());
  579. if (!RemoteMCJIT) {
  580. // If the program doesn't explicitly call exit, we will need the Exit
  581. // function later on to make an explicit call, so get the function now.
  582. FunctionCallee Exit = Mod->getOrInsertFunction(
  583. "exit", Type::getVoidTy(Context), Type::getInt32Ty(Context));
  584. // Run static constructors.
  585. if (!ForceInterpreter) {
  586. // Give MCJIT a chance to apply relocations and set page permissions.
  587. EE->finalizeObject();
  588. }
  589. EE->runStaticConstructorsDestructors(false);
  590. // Trigger compilation separately so code regions that need to be
  591. // invalidated will be known.
  592. (void)EE->getPointerToFunction(EntryFn);
  593. // Clear instruction cache before code will be executed.
  594. if (RTDyldMM)
  595. static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
  596. // Run main.
  597. Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
  598. // Run static destructors.
  599. EE->runStaticConstructorsDestructors(true);
  600. // If the program didn't call exit explicitly, we should call it now.
  601. // This ensures that any atexit handlers get called correctly.
  602. if (Function *ExitF =
  603. dyn_cast<Function>(Exit.getCallee()->stripPointerCasts())) {
  604. if (ExitF->getFunctionType() == Exit.getFunctionType()) {
  605. std::vector<GenericValue> Args;
  606. GenericValue ResultGV;
  607. ResultGV.IntVal = APInt(32, Result);
  608. Args.push_back(ResultGV);
  609. EE->runFunction(ExitF, Args);
  610. WithColor::error(errs(), argv[0])
  611. << "exit(" << Result << ") returned!\n";
  612. abort();
  613. }
  614. }
  615. WithColor::error(errs(), argv[0]) << "exit defined with wrong prototype!\n";
  616. abort();
  617. } else {
  618. // else == "if (RemoteMCJIT)"
  619. // Remote target MCJIT doesn't (yet) support static constructors. No reason
  620. // it couldn't. This is a limitation of the LLI implementation, not the
  621. // MCJIT itself. FIXME.
  622. // Create a remote memory manager.
  623. auto RemoteMM = ExitOnErr(
  624. orc::EPCGenericRTDyldMemoryManager::CreateWithDefaultBootstrapSymbols(
  625. *EPC));
  626. // Forward MCJIT's memory manager calls to the remote memory manager.
  627. static_cast<ForwardingMemoryManager*>(RTDyldMM)->setMemMgr(
  628. std::move(RemoteMM));
  629. // Forward MCJIT's symbol resolution calls to the remote.
  630. static_cast<ForwardingMemoryManager *>(RTDyldMM)->setResolver(
  631. ExitOnErr(RemoteResolver::Create(*EPC)));
  632. // Grab the target address of the JIT'd main function on the remote and call
  633. // it.
  634. // FIXME: argv and envp handling.
  635. auto Entry =
  636. orc::ExecutorAddr(EE->getFunctionAddress(EntryFn->getName().str()));
  637. EE->finalizeObject();
  638. LLVM_DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"
  639. << format("%llx", Entry.getValue()) << "\n");
  640. Result = ExitOnErr(EPC->runAsMain(Entry, {}));
  641. // Like static constructors, the remote target MCJIT support doesn't handle
  642. // this yet. It could. FIXME.
  643. // Delete the EE - we need to tear it down *before* we terminate the session
  644. // with the remote, otherwise it'll crash when it tries to release resources
  645. // on a remote that has already been disconnected.
  646. EE.reset();
  647. // Signal the remote target that we're done JITing.
  648. ExitOnErr(EPC->disconnect());
  649. }
  650. return Result;
  651. }
  652. static std::function<void(Module &)> createDebugDumper() {
  653. switch (OrcDumpKind) {
  654. case DumpKind::NoDump:
  655. return [](Module &M) {};
  656. case DumpKind::DumpFuncsToStdOut:
  657. return [](Module &M) {
  658. printf("[ ");
  659. for (const auto &F : M) {
  660. if (F.isDeclaration())
  661. continue;
  662. if (F.hasName()) {
  663. std::string Name(std::string(F.getName()));
  664. printf("%s ", Name.c_str());
  665. } else
  666. printf("<anon> ");
  667. }
  668. printf("]\n");
  669. };
  670. case DumpKind::DumpModsToStdOut:
  671. return [](Module &M) {
  672. outs() << "----- Module Start -----\n" << M << "----- Module End -----\n";
  673. };
  674. case DumpKind::DumpModsToDisk:
  675. return [](Module &M) {
  676. std::error_code EC;
  677. raw_fd_ostream Out(M.getModuleIdentifier() + ".ll", EC,
  678. sys::fs::OF_TextWithCRLF);
  679. if (EC) {
  680. errs() << "Couldn't open " << M.getModuleIdentifier()
  681. << " for dumping.\nError:" << EC.message() << "\n";
  682. exit(1);
  683. }
  684. Out << M;
  685. };
  686. }
  687. llvm_unreachable("Unknown DumpKind");
  688. }
  689. Error loadDylibs() {
  690. for (const auto &Dylib : Dylibs) {
  691. std::string ErrMsg;
  692. if (sys::DynamicLibrary::LoadLibraryPermanently(Dylib.c_str(), &ErrMsg))
  693. return make_error<StringError>(ErrMsg, inconvertibleErrorCode());
  694. }
  695. return Error::success();
  696. }
  697. static void exitOnLazyCallThroughFailure() { exit(1); }
  698. Expected<orc::ThreadSafeModule>
  699. loadModule(StringRef Path, orc::ThreadSafeContext TSCtx) {
  700. SMDiagnostic Err;
  701. auto M = parseIRFile(Path, Err, *TSCtx.getContext());
  702. if (!M) {
  703. std::string ErrMsg;
  704. {
  705. raw_string_ostream ErrMsgStream(ErrMsg);
  706. Err.print("lli", ErrMsgStream);
  707. }
  708. return make_error<StringError>(std::move(ErrMsg), inconvertibleErrorCode());
  709. }
  710. if (EnableCacheManager)
  711. M->setModuleIdentifier("file:" + M->getModuleIdentifier());
  712. return orc::ThreadSafeModule(std::move(M), std::move(TSCtx));
  713. }
  714. int runOrcJIT(const char *ProgName) {
  715. // Start setting up the JIT environment.
  716. // Parse the main module.
  717. orc::ThreadSafeContext TSCtx(std::make_unique<LLVMContext>());
  718. auto MainModule = ExitOnErr(loadModule(InputFile, TSCtx));
  719. // Get TargetTriple and DataLayout from the main module if they're explicitly
  720. // set.
  721. Optional<Triple> TT;
  722. Optional<DataLayout> DL;
  723. MainModule.withModuleDo([&](Module &M) {
  724. if (!M.getTargetTriple().empty())
  725. TT = Triple(M.getTargetTriple());
  726. if (!M.getDataLayout().isDefault())
  727. DL = M.getDataLayout();
  728. });
  729. orc::LLLazyJITBuilder Builder;
  730. Builder.setJITTargetMachineBuilder(
  731. TT ? orc::JITTargetMachineBuilder(*TT)
  732. : ExitOnErr(orc::JITTargetMachineBuilder::detectHost()));
  733. TT = Builder.getJITTargetMachineBuilder()->getTargetTriple();
  734. if (DL)
  735. Builder.setDataLayout(DL);
  736. if (!codegen::getMArch().empty())
  737. Builder.getJITTargetMachineBuilder()->getTargetTriple().setArchName(
  738. codegen::getMArch());
  739. Builder.getJITTargetMachineBuilder()
  740. ->setCPU(codegen::getCPUStr())
  741. .addFeatures(codegen::getFeatureList())
  742. .setRelocationModel(codegen::getExplicitRelocModel())
  743. .setCodeModel(codegen::getExplicitCodeModel());
  744. // FIXME: Setting a dummy call-through manager in non-lazy mode prevents the
  745. // JIT builder to instantiate a default (which would fail with an error for
  746. // unsupported architectures).
  747. if (UseJITKind != JITKind::OrcLazy) {
  748. auto ES = std::make_unique<orc::ExecutionSession>(
  749. ExitOnErr(orc::SelfExecutorProcessControl::Create()));
  750. Builder.setLazyCallthroughManager(
  751. std::make_unique<orc::LazyCallThroughManager>(*ES, 0, nullptr));
  752. Builder.setExecutionSession(std::move(ES));
  753. }
  754. Builder.setLazyCompileFailureAddr(
  755. pointerToJITTargetAddress(exitOnLazyCallThroughFailure));
  756. Builder.setNumCompileThreads(LazyJITCompileThreads);
  757. // If the object cache is enabled then set a custom compile function
  758. // creator to use the cache.
  759. std::unique_ptr<LLIObjectCache> CacheManager;
  760. if (EnableCacheManager) {
  761. CacheManager = std::make_unique<LLIObjectCache>(ObjectCacheDir);
  762. Builder.setCompileFunctionCreator(
  763. [&](orc::JITTargetMachineBuilder JTMB)
  764. -> Expected<std::unique_ptr<orc::IRCompileLayer::IRCompiler>> {
  765. if (LazyJITCompileThreads > 0)
  766. return std::make_unique<orc::ConcurrentIRCompiler>(std::move(JTMB),
  767. CacheManager.get());
  768. auto TM = JTMB.createTargetMachine();
  769. if (!TM)
  770. return TM.takeError();
  771. return std::make_unique<orc::TMOwningSimpleCompiler>(std::move(*TM),
  772. CacheManager.get());
  773. });
  774. }
  775. // Set up LLJIT platform.
  776. {
  777. LLJITPlatform P = Platform;
  778. if (P == LLJITPlatform::DetectHost)
  779. P = LLJITPlatform::GenericIR;
  780. switch (P) {
  781. case LLJITPlatform::GenericIR:
  782. // Nothing to do: LLJITBuilder will use this by default.
  783. break;
  784. case LLJITPlatform::Inactive:
  785. Builder.setPlatformSetUp(orc::setUpInactivePlatform);
  786. break;
  787. default:
  788. llvm_unreachable("Unrecognized platform value");
  789. }
  790. }
  791. std::unique_ptr<orc::ExecutorProcessControl> EPC = nullptr;
  792. if (JITLinker == JITLinkerKind::JITLink) {
  793. EPC = ExitOnErr(orc::SelfExecutorProcessControl::Create(
  794. std::make_shared<orc::SymbolStringPool>()));
  795. Builder.setObjectLinkingLayerCreator([&EPC](orc::ExecutionSession &ES,
  796. const Triple &) {
  797. auto L = std::make_unique<orc::ObjectLinkingLayer>(ES, EPC->getMemMgr());
  798. L->addPlugin(std::make_unique<orc::EHFrameRegistrationPlugin>(
  799. ES, ExitOnErr(orc::EPCEHFrameRegistrar::Create(ES))));
  800. L->addPlugin(std::make_unique<orc::DebugObjectManagerPlugin>(
  801. ES, ExitOnErr(orc::createJITLoaderGDBRegistrar(ES))));
  802. return L;
  803. });
  804. }
  805. auto J = ExitOnErr(Builder.create());
  806. auto *ObjLayer = &J->getObjLinkingLayer();
  807. if (auto *RTDyldObjLayer = dyn_cast<orc::RTDyldObjectLinkingLayer>(ObjLayer))
  808. RTDyldObjLayer->registerJITEventListener(
  809. *JITEventListener::createGDBRegistrationListener());
  810. if (PerModuleLazy)
  811. J->setPartitionFunction(orc::CompileOnDemandLayer::compileWholeModule);
  812. auto Dump = createDebugDumper();
  813. J->getIRTransformLayer().setTransform(
  814. [&](orc::ThreadSafeModule TSM,
  815. const orc::MaterializationResponsibility &R) {
  816. TSM.withModuleDo([&](Module &M) {
  817. if (verifyModule(M, &dbgs())) {
  818. dbgs() << "Bad module: " << &M << "\n";
  819. exit(1);
  820. }
  821. Dump(M);
  822. });
  823. return TSM;
  824. });
  825. orc::MangleAndInterner Mangle(J->getExecutionSession(), J->getDataLayout());
  826. // Unless they've been explicitly disabled, make process symbols available to
  827. // JIT'd code.
  828. if (!NoProcessSymbols)
  829. J->getMainJITDylib().addGenerator(
  830. ExitOnErr(orc::DynamicLibrarySearchGenerator::GetForCurrentProcess(
  831. J->getDataLayout().getGlobalPrefix(),
  832. [MainName = Mangle("main")](const orc::SymbolStringPtr &Name) {
  833. return Name != MainName;
  834. })));
  835. if (GenerateBuiltinFunctions.size() > 0)
  836. J->getMainJITDylib().addGenerator(
  837. std::make_unique<LLIBuiltinFunctionGenerator>(GenerateBuiltinFunctions,
  838. Mangle));
  839. // Regular modules are greedy: They materialize as a whole and trigger
  840. // materialization for all required symbols recursively. Lazy modules go
  841. // through partitioning and they replace outgoing calls with reexport stubs
  842. // that resolve on call-through.
  843. auto AddModule = [&](orc::JITDylib &JD, orc::ThreadSafeModule M) {
  844. return UseJITKind == JITKind::OrcLazy ? J->addLazyIRModule(JD, std::move(M))
  845. : J->addIRModule(JD, std::move(M));
  846. };
  847. // Add the main module.
  848. ExitOnErr(AddModule(J->getMainJITDylib(), std::move(MainModule)));
  849. // Create JITDylibs and add any extra modules.
  850. {
  851. // Create JITDylibs, keep a map from argument index to dylib. We will use
  852. // -extra-module argument indexes to determine what dylib to use for each
  853. // -extra-module.
  854. std::map<unsigned, orc::JITDylib *> IdxToDylib;
  855. IdxToDylib[0] = &J->getMainJITDylib();
  856. for (auto JDItr = JITDylibs.begin(), JDEnd = JITDylibs.end();
  857. JDItr != JDEnd; ++JDItr) {
  858. orc::JITDylib *JD = J->getJITDylibByName(*JDItr);
  859. if (!JD) {
  860. JD = &ExitOnErr(J->createJITDylib(*JDItr));
  861. J->getMainJITDylib().addToLinkOrder(*JD);
  862. JD->addToLinkOrder(J->getMainJITDylib());
  863. }
  864. IdxToDylib[JITDylibs.getPosition(JDItr - JITDylibs.begin())] = JD;
  865. }
  866. for (auto EMItr = ExtraModules.begin(), EMEnd = ExtraModules.end();
  867. EMItr != EMEnd; ++EMItr) {
  868. auto M = ExitOnErr(loadModule(*EMItr, TSCtx));
  869. auto EMIdx = ExtraModules.getPosition(EMItr - ExtraModules.begin());
  870. assert(EMIdx != 0 && "ExtraModule should have index > 0");
  871. auto JDItr = std::prev(IdxToDylib.lower_bound(EMIdx));
  872. auto &JD = *JDItr->second;
  873. ExitOnErr(AddModule(JD, std::move(M)));
  874. }
  875. for (auto EAItr = ExtraArchives.begin(), EAEnd = ExtraArchives.end();
  876. EAItr != EAEnd; ++EAItr) {
  877. auto EAIdx = ExtraArchives.getPosition(EAItr - ExtraArchives.begin());
  878. assert(EAIdx != 0 && "ExtraArchive should have index > 0");
  879. auto JDItr = std::prev(IdxToDylib.lower_bound(EAIdx));
  880. auto &JD = *JDItr->second;
  881. JD.addGenerator(ExitOnErr(orc::StaticLibraryDefinitionGenerator::Load(
  882. J->getObjLinkingLayer(), EAItr->c_str(), *TT)));
  883. }
  884. }
  885. // Add the objects.
  886. for (auto &ObjPath : ExtraObjects) {
  887. auto Obj = ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(ObjPath)));
  888. ExitOnErr(J->addObjectFile(std::move(Obj)));
  889. }
  890. // Run any static constructors.
  891. ExitOnErr(J->initialize(J->getMainJITDylib()));
  892. // Run any -thread-entry points.
  893. std::vector<std::thread> AltEntryThreads;
  894. for (auto &ThreadEntryPoint : ThreadEntryPoints) {
  895. auto EntryPointSym = ExitOnErr(J->lookup(ThreadEntryPoint));
  896. typedef void (*EntryPointPtr)();
  897. auto EntryPoint =
  898. reinterpret_cast<EntryPointPtr>(static_cast<uintptr_t>(EntryPointSym.getAddress()));
  899. AltEntryThreads.push_back(std::thread([EntryPoint]() { EntryPoint(); }));
  900. }
  901. // Resolve and run the main function.
  902. JITEvaluatedSymbol MainSym = ExitOnErr(J->lookup(EntryFunc));
  903. int Result;
  904. if (EPC) {
  905. // ExecutorProcessControl-based execution with JITLink.
  906. Result = ExitOnErr(
  907. EPC->runAsMain(orc::ExecutorAddr(MainSym.getAddress()), InputArgv));
  908. } else {
  909. // Manual in-process execution with RuntimeDyld.
  910. using MainFnTy = int(int, char *[]);
  911. auto MainFn = jitTargetAddressToFunction<MainFnTy *>(MainSym.getAddress());
  912. Result = orc::runAsMain(MainFn, InputArgv, StringRef(InputFile));
  913. }
  914. // Wait for -entry-point threads.
  915. for (auto &AltEntryThread : AltEntryThreads)
  916. AltEntryThread.join();
  917. // Run destructors.
  918. ExitOnErr(J->deinitialize(J->getMainJITDylib()));
  919. return Result;
  920. }
  921. void disallowOrcOptions() {
  922. // Make sure nobody used an orc-lazy specific option accidentally.
  923. if (LazyJITCompileThreads != 0) {
  924. errs() << "-compile-threads requires -jit-kind=orc-lazy\n";
  925. exit(1);
  926. }
  927. if (!ThreadEntryPoints.empty()) {
  928. errs() << "-thread-entry requires -jit-kind=orc-lazy\n";
  929. exit(1);
  930. }
  931. if (PerModuleLazy) {
  932. errs() << "-per-module-lazy requires -jit-kind=orc-lazy\n";
  933. exit(1);
  934. }
  935. }
  936. Expected<std::unique_ptr<orc::ExecutorProcessControl>> launchRemote() {
  937. #ifndef LLVM_ON_UNIX
  938. llvm_unreachable("launchRemote not supported on non-Unix platforms");
  939. #else
  940. int PipeFD[2][2];
  941. pid_t ChildPID;
  942. // Create two pipes.
  943. if (pipe(PipeFD[0]) != 0 || pipe(PipeFD[1]) != 0)
  944. perror("Error creating pipe: ");
  945. ChildPID = fork();
  946. if (ChildPID == 0) {
  947. // In the child...
  948. // Close the parent ends of the pipes
  949. close(PipeFD[0][1]);
  950. close(PipeFD[1][0]);
  951. // Execute the child process.
  952. std::unique_ptr<char[]> ChildPath, ChildIn, ChildOut;
  953. {
  954. ChildPath.reset(new char[ChildExecPath.size() + 1]);
  955. std::copy(ChildExecPath.begin(), ChildExecPath.end(), &ChildPath[0]);
  956. ChildPath[ChildExecPath.size()] = '\0';
  957. std::string ChildInStr = utostr(PipeFD[0][0]);
  958. ChildIn.reset(new char[ChildInStr.size() + 1]);
  959. std::copy(ChildInStr.begin(), ChildInStr.end(), &ChildIn[0]);
  960. ChildIn[ChildInStr.size()] = '\0';
  961. std::string ChildOutStr = utostr(PipeFD[1][1]);
  962. ChildOut.reset(new char[ChildOutStr.size() + 1]);
  963. std::copy(ChildOutStr.begin(), ChildOutStr.end(), &ChildOut[0]);
  964. ChildOut[ChildOutStr.size()] = '\0';
  965. }
  966. char * const args[] = { &ChildPath[0], &ChildIn[0], &ChildOut[0], nullptr };
  967. int rc = execv(ChildExecPath.c_str(), args);
  968. if (rc != 0)
  969. perror("Error executing child process: ");
  970. llvm_unreachable("Error executing child process");
  971. }
  972. // else we're the parent...
  973. // Close the child ends of the pipes
  974. close(PipeFD[0][0]);
  975. close(PipeFD[1][1]);
  976. // Return a SimpleRemoteEPC instance connected to our end of the pipes.
  977. return orc::SimpleRemoteEPC::Create<orc::FDSimpleRemoteEPCTransport>(
  978. std::make_unique<llvm::orc::InPlaceTaskDispatcher>(),
  979. llvm::orc::SimpleRemoteEPC::Setup(), PipeFD[1][0], PipeFD[0][1]);
  980. #endif
  981. }