lli.cpp 36 KB

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