1*9880d681SAndroid Build Coastguard Worker //===- lli.cpp - LLVM Interpreter / Dynamic compiler ----------------------===//
2*9880d681SAndroid Build Coastguard Worker //
3*9880d681SAndroid Build Coastguard Worker // The LLVM Compiler Infrastructure
4*9880d681SAndroid Build Coastguard Worker //
5*9880d681SAndroid Build Coastguard Worker // This file is distributed under the University of Illinois Open Source
6*9880d681SAndroid Build Coastguard Worker // License. See LICENSE.TXT for details.
7*9880d681SAndroid Build Coastguard Worker //
8*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
9*9880d681SAndroid Build Coastguard Worker //
10*9880d681SAndroid Build Coastguard Worker // This utility provides a simple wrapper around the LLVM Execution Engines,
11*9880d681SAndroid Build Coastguard Worker // which allow the direct execution of LLVM programs through a Just-In-Time
12*9880d681SAndroid Build Coastguard Worker // compiler, or through an interpreter if no JIT is available for this platform.
13*9880d681SAndroid Build Coastguard Worker //
14*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
15*9880d681SAndroid Build Coastguard Worker
16*9880d681SAndroid Build Coastguard Worker #include "OrcLazyJIT.h"
17*9880d681SAndroid Build Coastguard Worker #include "RemoteJITUtils.h"
18*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/LLVMContext.h"
19*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/StringExtras.h"
20*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/Triple.h"
21*9880d681SAndroid Build Coastguard Worker #include "llvm/Bitcode/ReaderWriter.h"
22*9880d681SAndroid Build Coastguard Worker #include "llvm/CodeGen/LinkAllCodegenComponents.h"
23*9880d681SAndroid Build Coastguard Worker #include "llvm/ExecutionEngine/GenericValue.h"
24*9880d681SAndroid Build Coastguard Worker #include "llvm/ExecutionEngine/Interpreter.h"
25*9880d681SAndroid Build Coastguard Worker #include "llvm/ExecutionEngine/JITEventListener.h"
26*9880d681SAndroid Build Coastguard Worker #include "llvm/ExecutionEngine/MCJIT.h"
27*9880d681SAndroid Build Coastguard Worker #include "llvm/ExecutionEngine/ObjectCache.h"
28*9880d681SAndroid Build Coastguard Worker #include "llvm/ExecutionEngine/OrcMCJITReplacement.h"
29*9880d681SAndroid Build Coastguard Worker #include "llvm/ExecutionEngine/SectionMemoryManager.h"
30*9880d681SAndroid Build Coastguard Worker #include "llvm/ExecutionEngine/Orc/OrcRemoteTargetClient.h"
31*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/IRBuilder.h"
32*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Module.h"
33*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Type.h"
34*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/TypeBuilder.h"
35*9880d681SAndroid Build Coastguard Worker #include "llvm/IRReader/IRReader.h"
36*9880d681SAndroid Build Coastguard Worker #include "llvm/Object/Archive.h"
37*9880d681SAndroid Build Coastguard Worker #include "llvm/Object/ObjectFile.h"
38*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/CommandLine.h"
39*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/Debug.h"
40*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/DynamicLibrary.h"
41*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/Format.h"
42*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/ManagedStatic.h"
43*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/MathExtras.h"
44*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/Memory.h"
45*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/MemoryBuffer.h"
46*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/Path.h"
47*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/PluginLoader.h"
48*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/PrettyStackTrace.h"
49*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/Process.h"
50*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/Program.h"
51*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/Signals.h"
52*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/SourceMgr.h"
53*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/TargetSelect.h"
54*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/raw_ostream.h"
55*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Instrumentation.h"
56*9880d681SAndroid Build Coastguard Worker #include <cerrno>
57*9880d681SAndroid Build Coastguard Worker
58*9880d681SAndroid Build Coastguard Worker #ifdef __CYGWIN__
59*9880d681SAndroid Build Coastguard Worker #include <cygwin/version.h>
60*9880d681SAndroid Build Coastguard Worker #if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
61*9880d681SAndroid Build Coastguard Worker #define DO_NOTHING_ATEXIT 1
62*9880d681SAndroid Build Coastguard Worker #endif
63*9880d681SAndroid Build Coastguard Worker #endif
64*9880d681SAndroid Build Coastguard Worker
65*9880d681SAndroid Build Coastguard Worker using namespace llvm;
66*9880d681SAndroid Build Coastguard Worker
67*9880d681SAndroid Build Coastguard Worker #define DEBUG_TYPE "lli"
68*9880d681SAndroid Build Coastguard Worker
69*9880d681SAndroid Build Coastguard Worker namespace {
70*9880d681SAndroid Build Coastguard Worker
71*9880d681SAndroid Build Coastguard Worker enum class JITKind { MCJIT, OrcMCJITReplacement, OrcLazy };
72*9880d681SAndroid Build Coastguard Worker
73*9880d681SAndroid Build Coastguard Worker cl::opt<std::string>
74*9880d681SAndroid Build Coastguard Worker InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
75*9880d681SAndroid Build Coastguard Worker
76*9880d681SAndroid Build Coastguard Worker cl::list<std::string>
77*9880d681SAndroid Build Coastguard Worker InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
78*9880d681SAndroid Build Coastguard Worker
79*9880d681SAndroid Build Coastguard Worker cl::opt<bool> ForceInterpreter("force-interpreter",
80*9880d681SAndroid Build Coastguard Worker cl::desc("Force interpretation: disable JIT"),
81*9880d681SAndroid Build Coastguard Worker cl::init(false));
82*9880d681SAndroid Build Coastguard Worker
83*9880d681SAndroid Build Coastguard Worker cl::opt<JITKind> UseJITKind("jit-kind",
84*9880d681SAndroid Build Coastguard Worker cl::desc("Choose underlying JIT kind."),
85*9880d681SAndroid Build Coastguard Worker cl::init(JITKind::MCJIT),
86*9880d681SAndroid Build Coastguard Worker cl::values(
87*9880d681SAndroid Build Coastguard Worker clEnumValN(JITKind::MCJIT, "mcjit",
88*9880d681SAndroid Build Coastguard Worker "MCJIT"),
89*9880d681SAndroid Build Coastguard Worker clEnumValN(JITKind::OrcMCJITReplacement,
90*9880d681SAndroid Build Coastguard Worker "orc-mcjit",
91*9880d681SAndroid Build Coastguard Worker "Orc-based MCJIT replacement"),
92*9880d681SAndroid Build Coastguard Worker clEnumValN(JITKind::OrcLazy,
93*9880d681SAndroid Build Coastguard Worker "orc-lazy",
94*9880d681SAndroid Build Coastguard Worker "Orc-based lazy JIT."),
95*9880d681SAndroid Build Coastguard Worker clEnumValEnd));
96*9880d681SAndroid Build Coastguard Worker
97*9880d681SAndroid Build Coastguard Worker // The MCJIT supports building for a target address space separate from
98*9880d681SAndroid Build Coastguard Worker // the JIT compilation process. Use a forked process and a copying
99*9880d681SAndroid Build Coastguard Worker // memory manager with IPC to execute using this functionality.
100*9880d681SAndroid Build Coastguard Worker cl::opt<bool> RemoteMCJIT("remote-mcjit",
101*9880d681SAndroid Build Coastguard Worker cl::desc("Execute MCJIT'ed code in a separate process."),
102*9880d681SAndroid Build Coastguard Worker cl::init(false));
103*9880d681SAndroid Build Coastguard Worker
104*9880d681SAndroid Build Coastguard Worker // Manually specify the child process for remote execution. This overrides
105*9880d681SAndroid Build Coastguard Worker // the simulated remote execution that allocates address space for child
106*9880d681SAndroid Build Coastguard Worker // execution. The child process will be executed and will communicate with
107*9880d681SAndroid Build Coastguard Worker // lli via stdin/stdout pipes.
108*9880d681SAndroid Build Coastguard Worker cl::opt<std::string>
109*9880d681SAndroid Build Coastguard Worker ChildExecPath("mcjit-remote-process",
110*9880d681SAndroid Build Coastguard Worker cl::desc("Specify the filename of the process to launch "
111*9880d681SAndroid Build Coastguard Worker "for remote MCJIT execution. If none is specified,"
112*9880d681SAndroid Build Coastguard Worker "\n\tremote execution will be simulated in-process."),
113*9880d681SAndroid Build Coastguard Worker cl::value_desc("filename"), cl::init(""));
114*9880d681SAndroid Build Coastguard Worker
115*9880d681SAndroid Build Coastguard Worker // Determine optimization level.
116*9880d681SAndroid Build Coastguard Worker cl::opt<char>
117*9880d681SAndroid Build Coastguard Worker OptLevel("O",
118*9880d681SAndroid Build Coastguard Worker cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
119*9880d681SAndroid Build Coastguard Worker "(default = '-O2')"),
120*9880d681SAndroid Build Coastguard Worker cl::Prefix,
121*9880d681SAndroid Build Coastguard Worker cl::ZeroOrMore,
122*9880d681SAndroid Build Coastguard Worker cl::init(' '));
123*9880d681SAndroid Build Coastguard Worker
124*9880d681SAndroid Build Coastguard Worker cl::opt<std::string>
125*9880d681SAndroid Build Coastguard Worker TargetTriple("mtriple", cl::desc("Override target triple for module"));
126*9880d681SAndroid Build Coastguard Worker
127*9880d681SAndroid Build Coastguard Worker cl::opt<std::string>
128*9880d681SAndroid Build Coastguard Worker MArch("march",
129*9880d681SAndroid Build Coastguard Worker cl::desc("Architecture to generate assembly for (see --version)"));
130*9880d681SAndroid Build Coastguard Worker
131*9880d681SAndroid Build Coastguard Worker cl::opt<std::string>
132*9880d681SAndroid Build Coastguard Worker MCPU("mcpu",
133*9880d681SAndroid Build Coastguard Worker cl::desc("Target a specific cpu type (-mcpu=help for details)"),
134*9880d681SAndroid Build Coastguard Worker cl::value_desc("cpu-name"),
135*9880d681SAndroid Build Coastguard Worker cl::init(""));
136*9880d681SAndroid Build Coastguard Worker
137*9880d681SAndroid Build Coastguard Worker cl::list<std::string>
138*9880d681SAndroid Build Coastguard Worker MAttrs("mattr",
139*9880d681SAndroid Build Coastguard Worker cl::CommaSeparated,
140*9880d681SAndroid Build Coastguard Worker cl::desc("Target specific attributes (-mattr=help for details)"),
141*9880d681SAndroid Build Coastguard Worker cl::value_desc("a1,+a2,-a3,..."));
142*9880d681SAndroid Build Coastguard Worker
143*9880d681SAndroid Build Coastguard Worker cl::opt<std::string>
144*9880d681SAndroid Build Coastguard Worker EntryFunc("entry-function",
145*9880d681SAndroid Build Coastguard Worker cl::desc("Specify the entry function (default = 'main') "
146*9880d681SAndroid Build Coastguard Worker "of the executable"),
147*9880d681SAndroid Build Coastguard Worker cl::value_desc("function"),
148*9880d681SAndroid Build Coastguard Worker cl::init("main"));
149*9880d681SAndroid Build Coastguard Worker
150*9880d681SAndroid Build Coastguard Worker cl::list<std::string>
151*9880d681SAndroid Build Coastguard Worker ExtraModules("extra-module",
152*9880d681SAndroid Build Coastguard Worker cl::desc("Extra modules to be loaded"),
153*9880d681SAndroid Build Coastguard Worker cl::value_desc("input bitcode"));
154*9880d681SAndroid Build Coastguard Worker
155*9880d681SAndroid Build Coastguard Worker cl::list<std::string>
156*9880d681SAndroid Build Coastguard Worker ExtraObjects("extra-object",
157*9880d681SAndroid Build Coastguard Worker cl::desc("Extra object files to be loaded"),
158*9880d681SAndroid Build Coastguard Worker cl::value_desc("input object"));
159*9880d681SAndroid Build Coastguard Worker
160*9880d681SAndroid Build Coastguard Worker cl::list<std::string>
161*9880d681SAndroid Build Coastguard Worker ExtraArchives("extra-archive",
162*9880d681SAndroid Build Coastguard Worker cl::desc("Extra archive files to be loaded"),
163*9880d681SAndroid Build Coastguard Worker cl::value_desc("input archive"));
164*9880d681SAndroid Build Coastguard Worker
165*9880d681SAndroid Build Coastguard Worker cl::opt<bool>
166*9880d681SAndroid Build Coastguard Worker EnableCacheManager("enable-cache-manager",
167*9880d681SAndroid Build Coastguard Worker cl::desc("Use cache manager to save/load mdoules"),
168*9880d681SAndroid Build Coastguard Worker cl::init(false));
169*9880d681SAndroid Build Coastguard Worker
170*9880d681SAndroid Build Coastguard Worker cl::opt<std::string>
171*9880d681SAndroid Build Coastguard Worker ObjectCacheDir("object-cache-dir",
172*9880d681SAndroid Build Coastguard Worker cl::desc("Directory to store cached object files "
173*9880d681SAndroid Build Coastguard Worker "(must be user writable)"),
174*9880d681SAndroid Build Coastguard Worker cl::init(""));
175*9880d681SAndroid Build Coastguard Worker
176*9880d681SAndroid Build Coastguard Worker cl::opt<std::string>
177*9880d681SAndroid Build Coastguard Worker FakeArgv0("fake-argv0",
178*9880d681SAndroid Build Coastguard Worker cl::desc("Override the 'argv[0]' value passed into the executing"
179*9880d681SAndroid Build Coastguard Worker " program"), cl::value_desc("executable"));
180*9880d681SAndroid Build Coastguard Worker
181*9880d681SAndroid Build Coastguard Worker cl::opt<bool>
182*9880d681SAndroid Build Coastguard Worker DisableCoreFiles("disable-core-files", cl::Hidden,
183*9880d681SAndroid Build Coastguard Worker cl::desc("Disable emission of core files if possible"));
184*9880d681SAndroid Build Coastguard Worker
185*9880d681SAndroid Build Coastguard Worker cl::opt<bool>
186*9880d681SAndroid Build Coastguard Worker NoLazyCompilation("disable-lazy-compilation",
187*9880d681SAndroid Build Coastguard Worker cl::desc("Disable JIT lazy compilation"),
188*9880d681SAndroid Build Coastguard Worker cl::init(false));
189*9880d681SAndroid Build Coastguard Worker
190*9880d681SAndroid Build Coastguard Worker cl::opt<Reloc::Model> RelocModel(
191*9880d681SAndroid Build Coastguard Worker "relocation-model", cl::desc("Choose relocation model"),
192*9880d681SAndroid Build Coastguard Worker cl::values(
193*9880d681SAndroid Build Coastguard Worker clEnumValN(Reloc::Static, "static", "Non-relocatable code"),
194*9880d681SAndroid Build Coastguard Worker clEnumValN(Reloc::PIC_, "pic",
195*9880d681SAndroid Build Coastguard Worker "Fully relocatable, position independent code"),
196*9880d681SAndroid Build Coastguard Worker clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
197*9880d681SAndroid Build Coastguard Worker "Relocatable external references, non-relocatable code"),
198*9880d681SAndroid Build Coastguard Worker clEnumValEnd));
199*9880d681SAndroid Build Coastguard Worker
200*9880d681SAndroid Build Coastguard Worker cl::opt<llvm::CodeModel::Model>
201*9880d681SAndroid Build Coastguard Worker CMModel("code-model",
202*9880d681SAndroid Build Coastguard Worker cl::desc("Choose code model"),
203*9880d681SAndroid Build Coastguard Worker cl::init(CodeModel::JITDefault),
204*9880d681SAndroid Build Coastguard Worker cl::values(clEnumValN(CodeModel::JITDefault, "default",
205*9880d681SAndroid Build Coastguard Worker "Target default JIT code model"),
206*9880d681SAndroid Build Coastguard Worker clEnumValN(CodeModel::Small, "small",
207*9880d681SAndroid Build Coastguard Worker "Small code model"),
208*9880d681SAndroid Build Coastguard Worker clEnumValN(CodeModel::Kernel, "kernel",
209*9880d681SAndroid Build Coastguard Worker "Kernel code model"),
210*9880d681SAndroid Build Coastguard Worker clEnumValN(CodeModel::Medium, "medium",
211*9880d681SAndroid Build Coastguard Worker "Medium code model"),
212*9880d681SAndroid Build Coastguard Worker clEnumValN(CodeModel::Large, "large",
213*9880d681SAndroid Build Coastguard Worker "Large code model"),
214*9880d681SAndroid Build Coastguard Worker clEnumValEnd));
215*9880d681SAndroid Build Coastguard Worker
216*9880d681SAndroid Build Coastguard Worker cl::opt<bool>
217*9880d681SAndroid Build Coastguard Worker GenerateSoftFloatCalls("soft-float",
218*9880d681SAndroid Build Coastguard Worker cl::desc("Generate software floating point library calls"),
219*9880d681SAndroid Build Coastguard Worker cl::init(false));
220*9880d681SAndroid Build Coastguard Worker
221*9880d681SAndroid Build Coastguard Worker cl::opt<llvm::FloatABI::ABIType>
222*9880d681SAndroid Build Coastguard Worker FloatABIForCalls("float-abi",
223*9880d681SAndroid Build Coastguard Worker cl::desc("Choose float ABI type"),
224*9880d681SAndroid Build Coastguard Worker cl::init(FloatABI::Default),
225*9880d681SAndroid Build Coastguard Worker cl::values(
226*9880d681SAndroid Build Coastguard Worker clEnumValN(FloatABI::Default, "default",
227*9880d681SAndroid Build Coastguard Worker "Target default float ABI type"),
228*9880d681SAndroid Build Coastguard Worker clEnumValN(FloatABI::Soft, "soft",
229*9880d681SAndroid Build Coastguard Worker "Soft float ABI (implied by -soft-float)"),
230*9880d681SAndroid Build Coastguard Worker clEnumValN(FloatABI::Hard, "hard",
231*9880d681SAndroid Build Coastguard Worker "Hard float ABI (uses FP registers)"),
232*9880d681SAndroid Build Coastguard Worker clEnumValEnd));
233*9880d681SAndroid Build Coastguard Worker
234*9880d681SAndroid Build Coastguard Worker ExitOnError ExitOnErr;
235*9880d681SAndroid Build Coastguard Worker }
236*9880d681SAndroid Build Coastguard Worker
237*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
238*9880d681SAndroid Build Coastguard Worker // Object cache
239*9880d681SAndroid Build Coastguard Worker //
240*9880d681SAndroid Build Coastguard Worker // This object cache implementation writes cached objects to disk to the
241*9880d681SAndroid Build Coastguard Worker // directory specified by CacheDir, using a filename provided in the module
242*9880d681SAndroid Build Coastguard Worker // descriptor. The cache tries to load a saved object using that path if the
243*9880d681SAndroid Build Coastguard Worker // file exists. CacheDir defaults to "", in which case objects are cached
244*9880d681SAndroid Build Coastguard Worker // alongside their originating bitcodes.
245*9880d681SAndroid Build Coastguard Worker //
246*9880d681SAndroid Build Coastguard Worker class LLIObjectCache : public ObjectCache {
247*9880d681SAndroid Build Coastguard Worker public:
LLIObjectCache(const std::string & CacheDir)248*9880d681SAndroid Build Coastguard Worker LLIObjectCache(const std::string& CacheDir) : CacheDir(CacheDir) {
249*9880d681SAndroid Build Coastguard Worker // Add trailing '/' to cache dir if necessary.
250*9880d681SAndroid Build Coastguard Worker if (!this->CacheDir.empty() &&
251*9880d681SAndroid Build Coastguard Worker this->CacheDir[this->CacheDir.size() - 1] != '/')
252*9880d681SAndroid Build Coastguard Worker this->CacheDir += '/';
253*9880d681SAndroid Build Coastguard Worker }
~LLIObjectCache()254*9880d681SAndroid Build Coastguard Worker ~LLIObjectCache() override {}
255*9880d681SAndroid Build Coastguard Worker
notifyObjectCompiled(const Module * M,MemoryBufferRef Obj)256*9880d681SAndroid Build Coastguard Worker void notifyObjectCompiled(const Module *M, MemoryBufferRef Obj) override {
257*9880d681SAndroid Build Coastguard Worker const std::string &ModuleID = M->getModuleIdentifier();
258*9880d681SAndroid Build Coastguard Worker std::string CacheName;
259*9880d681SAndroid Build Coastguard Worker if (!getCacheFilename(ModuleID, CacheName))
260*9880d681SAndroid Build Coastguard Worker return;
261*9880d681SAndroid Build Coastguard Worker if (!CacheDir.empty()) { // Create user-defined cache dir.
262*9880d681SAndroid Build Coastguard Worker SmallString<128> dir(sys::path::parent_path(CacheName));
263*9880d681SAndroid Build Coastguard Worker sys::fs::create_directories(Twine(dir));
264*9880d681SAndroid Build Coastguard Worker }
265*9880d681SAndroid Build Coastguard Worker std::error_code EC;
266*9880d681SAndroid Build Coastguard Worker raw_fd_ostream outfile(CacheName, EC, sys::fs::F_None);
267*9880d681SAndroid Build Coastguard Worker outfile.write(Obj.getBufferStart(), Obj.getBufferSize());
268*9880d681SAndroid Build Coastguard Worker outfile.close();
269*9880d681SAndroid Build Coastguard Worker }
270*9880d681SAndroid Build Coastguard Worker
getObject(const Module * M)271*9880d681SAndroid Build Coastguard Worker std::unique_ptr<MemoryBuffer> getObject(const Module* M) override {
272*9880d681SAndroid Build Coastguard Worker const std::string &ModuleID = M->getModuleIdentifier();
273*9880d681SAndroid Build Coastguard Worker std::string CacheName;
274*9880d681SAndroid Build Coastguard Worker if (!getCacheFilename(ModuleID, CacheName))
275*9880d681SAndroid Build Coastguard Worker return nullptr;
276*9880d681SAndroid Build Coastguard Worker // Load the object from the cache filename
277*9880d681SAndroid Build Coastguard Worker ErrorOr<std::unique_ptr<MemoryBuffer>> IRObjectBuffer =
278*9880d681SAndroid Build Coastguard Worker MemoryBuffer::getFile(CacheName.c_str(), -1, false);
279*9880d681SAndroid Build Coastguard Worker // If the file isn't there, that's OK.
280*9880d681SAndroid Build Coastguard Worker if (!IRObjectBuffer)
281*9880d681SAndroid Build Coastguard Worker return nullptr;
282*9880d681SAndroid Build Coastguard Worker // MCJIT will want to write into this buffer, and we don't want that
283*9880d681SAndroid Build Coastguard Worker // because the file has probably just been mmapped. Instead we make
284*9880d681SAndroid Build Coastguard Worker // a copy. The filed-based buffer will be released when it goes
285*9880d681SAndroid Build Coastguard Worker // out of scope.
286*9880d681SAndroid Build Coastguard Worker return MemoryBuffer::getMemBufferCopy(IRObjectBuffer.get()->getBuffer());
287*9880d681SAndroid Build Coastguard Worker }
288*9880d681SAndroid Build Coastguard Worker
289*9880d681SAndroid Build Coastguard Worker private:
290*9880d681SAndroid Build Coastguard Worker std::string CacheDir;
291*9880d681SAndroid Build Coastguard Worker
getCacheFilename(const std::string & ModID,std::string & CacheName)292*9880d681SAndroid Build Coastguard Worker bool getCacheFilename(const std::string &ModID, std::string &CacheName) {
293*9880d681SAndroid Build Coastguard Worker std::string Prefix("file:");
294*9880d681SAndroid Build Coastguard Worker size_t PrefixLength = Prefix.length();
295*9880d681SAndroid Build Coastguard Worker if (ModID.substr(0, PrefixLength) != Prefix)
296*9880d681SAndroid Build Coastguard Worker return false;
297*9880d681SAndroid Build Coastguard Worker std::string CacheSubdir = ModID.substr(PrefixLength);
298*9880d681SAndroid Build Coastguard Worker #if defined(_WIN32)
299*9880d681SAndroid Build Coastguard Worker // Transform "X:\foo" => "/X\foo" for convenience.
300*9880d681SAndroid Build Coastguard Worker if (isalpha(CacheSubdir[0]) && CacheSubdir[1] == ':') {
301*9880d681SAndroid Build Coastguard Worker CacheSubdir[1] = CacheSubdir[0];
302*9880d681SAndroid Build Coastguard Worker CacheSubdir[0] = '/';
303*9880d681SAndroid Build Coastguard Worker }
304*9880d681SAndroid Build Coastguard Worker #endif
305*9880d681SAndroid Build Coastguard Worker CacheName = CacheDir + CacheSubdir;
306*9880d681SAndroid Build Coastguard Worker size_t pos = CacheName.rfind('.');
307*9880d681SAndroid Build Coastguard Worker CacheName.replace(pos, CacheName.length() - pos, ".o");
308*9880d681SAndroid Build Coastguard Worker return true;
309*9880d681SAndroid Build Coastguard Worker }
310*9880d681SAndroid Build Coastguard Worker };
311*9880d681SAndroid Build Coastguard Worker
312*9880d681SAndroid Build Coastguard Worker // On Mingw and Cygwin, an external symbol named '__main' is called from the
313*9880d681SAndroid Build Coastguard Worker // generated 'main' function to allow static intialization. To avoid linking
314*9880d681SAndroid Build Coastguard Worker // problems with remote targets (because lli's remote target support does not
315*9880d681SAndroid Build Coastguard Worker // currently handle external linking) we add a secondary module which defines
316*9880d681SAndroid Build Coastguard Worker // an empty '__main' function.
addCygMingExtraModule(ExecutionEngine & EE,LLVMContext & Context,StringRef TargetTripleStr)317*9880d681SAndroid Build Coastguard Worker static void addCygMingExtraModule(ExecutionEngine &EE, LLVMContext &Context,
318*9880d681SAndroid Build Coastguard Worker StringRef TargetTripleStr) {
319*9880d681SAndroid Build Coastguard Worker IRBuilder<> Builder(Context);
320*9880d681SAndroid Build Coastguard Worker Triple TargetTriple(TargetTripleStr);
321*9880d681SAndroid Build Coastguard Worker
322*9880d681SAndroid Build Coastguard Worker // Create a new module.
323*9880d681SAndroid Build Coastguard Worker std::unique_ptr<Module> M = make_unique<Module>("CygMingHelper", Context);
324*9880d681SAndroid Build Coastguard Worker M->setTargetTriple(TargetTripleStr);
325*9880d681SAndroid Build Coastguard Worker
326*9880d681SAndroid Build Coastguard Worker // Create an empty function named "__main".
327*9880d681SAndroid Build Coastguard Worker Function *Result;
328*9880d681SAndroid Build Coastguard Worker if (TargetTriple.isArch64Bit()) {
329*9880d681SAndroid Build Coastguard Worker Result = Function::Create(
330*9880d681SAndroid Build Coastguard Worker TypeBuilder<int64_t(void), false>::get(Context),
331*9880d681SAndroid Build Coastguard Worker GlobalValue::ExternalLinkage, "__main", M.get());
332*9880d681SAndroid Build Coastguard Worker } else {
333*9880d681SAndroid Build Coastguard Worker Result = Function::Create(
334*9880d681SAndroid Build Coastguard Worker TypeBuilder<int32_t(void), false>::get(Context),
335*9880d681SAndroid Build Coastguard Worker GlobalValue::ExternalLinkage, "__main", M.get());
336*9880d681SAndroid Build Coastguard Worker }
337*9880d681SAndroid Build Coastguard Worker BasicBlock *BB = BasicBlock::Create(Context, "__main", Result);
338*9880d681SAndroid Build Coastguard Worker Builder.SetInsertPoint(BB);
339*9880d681SAndroid Build Coastguard Worker Value *ReturnVal;
340*9880d681SAndroid Build Coastguard Worker if (TargetTriple.isArch64Bit())
341*9880d681SAndroid Build Coastguard Worker ReturnVal = ConstantInt::get(Context, APInt(64, 0));
342*9880d681SAndroid Build Coastguard Worker else
343*9880d681SAndroid Build Coastguard Worker ReturnVal = ConstantInt::get(Context, APInt(32, 0));
344*9880d681SAndroid Build Coastguard Worker Builder.CreateRet(ReturnVal);
345*9880d681SAndroid Build Coastguard Worker
346*9880d681SAndroid Build Coastguard Worker // Add this new module to the ExecutionEngine.
347*9880d681SAndroid Build Coastguard Worker EE.addModule(std::move(M));
348*9880d681SAndroid Build Coastguard Worker }
349*9880d681SAndroid Build Coastguard Worker
getOptLevel()350*9880d681SAndroid Build Coastguard Worker CodeGenOpt::Level getOptLevel() {
351*9880d681SAndroid Build Coastguard Worker switch (OptLevel) {
352*9880d681SAndroid Build Coastguard Worker default:
353*9880d681SAndroid Build Coastguard Worker errs() << "lli: Invalid optimization level.\n";
354*9880d681SAndroid Build Coastguard Worker exit(1);
355*9880d681SAndroid Build Coastguard Worker case '0': return CodeGenOpt::None;
356*9880d681SAndroid Build Coastguard Worker case '1': return CodeGenOpt::Less;
357*9880d681SAndroid Build Coastguard Worker case ' ':
358*9880d681SAndroid Build Coastguard Worker case '2': return CodeGenOpt::Default;
359*9880d681SAndroid Build Coastguard Worker case '3': return CodeGenOpt::Aggressive;
360*9880d681SAndroid Build Coastguard Worker }
361*9880d681SAndroid Build Coastguard Worker llvm_unreachable("Unrecognized opt level.");
362*9880d681SAndroid Build Coastguard Worker }
363*9880d681SAndroid Build Coastguard Worker
364*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
365*9880d681SAndroid Build Coastguard Worker // main Driver function
366*9880d681SAndroid Build Coastguard Worker //
main(int argc,char ** argv,char * const * envp)367*9880d681SAndroid Build Coastguard Worker int main(int argc, char **argv, char * const *envp) {
368*9880d681SAndroid Build Coastguard Worker sys::PrintStackTraceOnErrorSignal(argv[0]);
369*9880d681SAndroid Build Coastguard Worker PrettyStackTraceProgram X(argc, argv);
370*9880d681SAndroid Build Coastguard Worker
371*9880d681SAndroid Build Coastguard Worker atexit(llvm_shutdown); // Call llvm_shutdown() on exit.
372*9880d681SAndroid Build Coastguard Worker
373*9880d681SAndroid Build Coastguard Worker if (argc > 1)
374*9880d681SAndroid Build Coastguard Worker ExitOnErr.setBanner(std::string(argv[0]) + ": ");
375*9880d681SAndroid Build Coastguard Worker
376*9880d681SAndroid Build Coastguard Worker // If we have a native target, initialize it to ensure it is linked in and
377*9880d681SAndroid Build Coastguard Worker // usable by the JIT.
378*9880d681SAndroid Build Coastguard Worker InitializeNativeTarget();
379*9880d681SAndroid Build Coastguard Worker InitializeNativeTargetAsmPrinter();
380*9880d681SAndroid Build Coastguard Worker InitializeNativeTargetAsmParser();
381*9880d681SAndroid Build Coastguard Worker
382*9880d681SAndroid Build Coastguard Worker cl::ParseCommandLineOptions(argc, argv,
383*9880d681SAndroid Build Coastguard Worker "llvm interpreter & dynamic compiler\n");
384*9880d681SAndroid Build Coastguard Worker
385*9880d681SAndroid Build Coastguard Worker // If the user doesn't want core files, disable them.
386*9880d681SAndroid Build Coastguard Worker if (DisableCoreFiles)
387*9880d681SAndroid Build Coastguard Worker sys::Process::PreventCoreFiles();
388*9880d681SAndroid Build Coastguard Worker
389*9880d681SAndroid Build Coastguard Worker LLVMContext Context;
390*9880d681SAndroid Build Coastguard Worker
391*9880d681SAndroid Build Coastguard Worker // Load the bitcode...
392*9880d681SAndroid Build Coastguard Worker SMDiagnostic Err;
393*9880d681SAndroid Build Coastguard Worker std::unique_ptr<Module> Owner = parseIRFile(InputFile, Err, Context);
394*9880d681SAndroid Build Coastguard Worker Module *Mod = Owner.get();
395*9880d681SAndroid Build Coastguard Worker if (!Mod) {
396*9880d681SAndroid Build Coastguard Worker Err.print(argv[0], errs());
397*9880d681SAndroid Build Coastguard Worker return 1;
398*9880d681SAndroid Build Coastguard Worker }
399*9880d681SAndroid Build Coastguard Worker
400*9880d681SAndroid Build Coastguard Worker if (UseJITKind == JITKind::OrcLazy)
401*9880d681SAndroid Build Coastguard Worker return runOrcLazyJIT(std::move(Owner), argc, argv);
402*9880d681SAndroid Build Coastguard Worker
403*9880d681SAndroid Build Coastguard Worker if (EnableCacheManager) {
404*9880d681SAndroid Build Coastguard Worker std::string CacheName("file:");
405*9880d681SAndroid Build Coastguard Worker CacheName.append(InputFile);
406*9880d681SAndroid Build Coastguard Worker Mod->setModuleIdentifier(CacheName);
407*9880d681SAndroid Build Coastguard Worker }
408*9880d681SAndroid Build Coastguard Worker
409*9880d681SAndroid Build Coastguard Worker // If not jitting lazily, load the whole bitcode file eagerly too.
410*9880d681SAndroid Build Coastguard Worker if (NoLazyCompilation) {
411*9880d681SAndroid Build Coastguard Worker if (std::error_code EC = Mod->materializeAll()) {
412*9880d681SAndroid Build Coastguard Worker errs() << argv[0] << ": bitcode didn't read correctly.\n";
413*9880d681SAndroid Build Coastguard Worker errs() << "Reason: " << EC.message() << "\n";
414*9880d681SAndroid Build Coastguard Worker exit(1);
415*9880d681SAndroid Build Coastguard Worker }
416*9880d681SAndroid Build Coastguard Worker }
417*9880d681SAndroid Build Coastguard Worker
418*9880d681SAndroid Build Coastguard Worker std::string ErrorMsg;
419*9880d681SAndroid Build Coastguard Worker EngineBuilder builder(std::move(Owner));
420*9880d681SAndroid Build Coastguard Worker builder.setMArch(MArch);
421*9880d681SAndroid Build Coastguard Worker builder.setMCPU(MCPU);
422*9880d681SAndroid Build Coastguard Worker builder.setMAttrs(MAttrs);
423*9880d681SAndroid Build Coastguard Worker if (RelocModel.getNumOccurrences())
424*9880d681SAndroid Build Coastguard Worker builder.setRelocationModel(RelocModel);
425*9880d681SAndroid Build Coastguard Worker builder.setCodeModel(CMModel);
426*9880d681SAndroid Build Coastguard Worker builder.setErrorStr(&ErrorMsg);
427*9880d681SAndroid Build Coastguard Worker builder.setEngineKind(ForceInterpreter
428*9880d681SAndroid Build Coastguard Worker ? EngineKind::Interpreter
429*9880d681SAndroid Build Coastguard Worker : EngineKind::JIT);
430*9880d681SAndroid Build Coastguard Worker builder.setUseOrcMCJITReplacement(UseJITKind == JITKind::OrcMCJITReplacement);
431*9880d681SAndroid Build Coastguard Worker
432*9880d681SAndroid Build Coastguard Worker // If we are supposed to override the target triple, do so now.
433*9880d681SAndroid Build Coastguard Worker if (!TargetTriple.empty())
434*9880d681SAndroid Build Coastguard Worker Mod->setTargetTriple(Triple::normalize(TargetTriple));
435*9880d681SAndroid Build Coastguard Worker
436*9880d681SAndroid Build Coastguard Worker // Enable MCJIT if desired.
437*9880d681SAndroid Build Coastguard Worker RTDyldMemoryManager *RTDyldMM = nullptr;
438*9880d681SAndroid Build Coastguard Worker if (!ForceInterpreter) {
439*9880d681SAndroid Build Coastguard Worker if (RemoteMCJIT)
440*9880d681SAndroid Build Coastguard Worker RTDyldMM = new ForwardingMemoryManager();
441*9880d681SAndroid Build Coastguard Worker else
442*9880d681SAndroid Build Coastguard Worker RTDyldMM = new SectionMemoryManager();
443*9880d681SAndroid Build Coastguard Worker
444*9880d681SAndroid Build Coastguard Worker // Deliberately construct a temp std::unique_ptr to pass in. Do not null out
445*9880d681SAndroid Build Coastguard Worker // RTDyldMM: We still use it below, even though we don't own it.
446*9880d681SAndroid Build Coastguard Worker builder.setMCJITMemoryManager(
447*9880d681SAndroid Build Coastguard Worker std::unique_ptr<RTDyldMemoryManager>(RTDyldMM));
448*9880d681SAndroid Build Coastguard Worker } else if (RemoteMCJIT) {
449*9880d681SAndroid Build Coastguard Worker errs() << "error: Remote process execution does not work with the "
450*9880d681SAndroid Build Coastguard Worker "interpreter.\n";
451*9880d681SAndroid Build Coastguard Worker exit(1);
452*9880d681SAndroid Build Coastguard Worker }
453*9880d681SAndroid Build Coastguard Worker
454*9880d681SAndroid Build Coastguard Worker builder.setOptLevel(getOptLevel());
455*9880d681SAndroid Build Coastguard Worker
456*9880d681SAndroid Build Coastguard Worker TargetOptions Options;
457*9880d681SAndroid Build Coastguard Worker if (FloatABIForCalls != FloatABI::Default)
458*9880d681SAndroid Build Coastguard Worker Options.FloatABIType = FloatABIForCalls;
459*9880d681SAndroid Build Coastguard Worker
460*9880d681SAndroid Build Coastguard Worker builder.setTargetOptions(Options);
461*9880d681SAndroid Build Coastguard Worker
462*9880d681SAndroid Build Coastguard Worker std::unique_ptr<ExecutionEngine> EE(builder.create());
463*9880d681SAndroid Build Coastguard Worker if (!EE) {
464*9880d681SAndroid Build Coastguard Worker if (!ErrorMsg.empty())
465*9880d681SAndroid Build Coastguard Worker errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n";
466*9880d681SAndroid Build Coastguard Worker else
467*9880d681SAndroid Build Coastguard Worker errs() << argv[0] << ": unknown error creating EE!\n";
468*9880d681SAndroid Build Coastguard Worker exit(1);
469*9880d681SAndroid Build Coastguard Worker }
470*9880d681SAndroid Build Coastguard Worker
471*9880d681SAndroid Build Coastguard Worker std::unique_ptr<LLIObjectCache> CacheManager;
472*9880d681SAndroid Build Coastguard Worker if (EnableCacheManager) {
473*9880d681SAndroid Build Coastguard Worker CacheManager.reset(new LLIObjectCache(ObjectCacheDir));
474*9880d681SAndroid Build Coastguard Worker EE->setObjectCache(CacheManager.get());
475*9880d681SAndroid Build Coastguard Worker }
476*9880d681SAndroid Build Coastguard Worker
477*9880d681SAndroid Build Coastguard Worker // Load any additional modules specified on the command line.
478*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) {
479*9880d681SAndroid Build Coastguard Worker std::unique_ptr<Module> XMod = parseIRFile(ExtraModules[i], Err, Context);
480*9880d681SAndroid Build Coastguard Worker if (!XMod) {
481*9880d681SAndroid Build Coastguard Worker Err.print(argv[0], errs());
482*9880d681SAndroid Build Coastguard Worker return 1;
483*9880d681SAndroid Build Coastguard Worker }
484*9880d681SAndroid Build Coastguard Worker if (EnableCacheManager) {
485*9880d681SAndroid Build Coastguard Worker std::string CacheName("file:");
486*9880d681SAndroid Build Coastguard Worker CacheName.append(ExtraModules[i]);
487*9880d681SAndroid Build Coastguard Worker XMod->setModuleIdentifier(CacheName);
488*9880d681SAndroid Build Coastguard Worker }
489*9880d681SAndroid Build Coastguard Worker EE->addModule(std::move(XMod));
490*9880d681SAndroid Build Coastguard Worker }
491*9880d681SAndroid Build Coastguard Worker
492*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0, e = ExtraObjects.size(); i != e; ++i) {
493*9880d681SAndroid Build Coastguard Worker Expected<object::OwningBinary<object::ObjectFile>> Obj =
494*9880d681SAndroid Build Coastguard Worker object::ObjectFile::createObjectFile(ExtraObjects[i]);
495*9880d681SAndroid Build Coastguard Worker if (!Obj) {
496*9880d681SAndroid Build Coastguard Worker // TODO: Actually report errors helpfully.
497*9880d681SAndroid Build Coastguard Worker consumeError(Obj.takeError());
498*9880d681SAndroid Build Coastguard Worker Err.print(argv[0], errs());
499*9880d681SAndroid Build Coastguard Worker return 1;
500*9880d681SAndroid Build Coastguard Worker }
501*9880d681SAndroid Build Coastguard Worker object::OwningBinary<object::ObjectFile> &O = Obj.get();
502*9880d681SAndroid Build Coastguard Worker EE->addObjectFile(std::move(O));
503*9880d681SAndroid Build Coastguard Worker }
504*9880d681SAndroid Build Coastguard Worker
505*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) {
506*9880d681SAndroid Build Coastguard Worker ErrorOr<std::unique_ptr<MemoryBuffer>> ArBufOrErr =
507*9880d681SAndroid Build Coastguard Worker MemoryBuffer::getFileOrSTDIN(ExtraArchives[i]);
508*9880d681SAndroid Build Coastguard Worker if (!ArBufOrErr) {
509*9880d681SAndroid Build Coastguard Worker Err.print(argv[0], errs());
510*9880d681SAndroid Build Coastguard Worker return 1;
511*9880d681SAndroid Build Coastguard Worker }
512*9880d681SAndroid Build Coastguard Worker std::unique_ptr<MemoryBuffer> &ArBuf = ArBufOrErr.get();
513*9880d681SAndroid Build Coastguard Worker
514*9880d681SAndroid Build Coastguard Worker Expected<std::unique_ptr<object::Archive>> ArOrErr =
515*9880d681SAndroid Build Coastguard Worker object::Archive::create(ArBuf->getMemBufferRef());
516*9880d681SAndroid Build Coastguard Worker if (!ArOrErr) {
517*9880d681SAndroid Build Coastguard Worker std::string Buf;
518*9880d681SAndroid Build Coastguard Worker raw_string_ostream OS(Buf);
519*9880d681SAndroid Build Coastguard Worker logAllUnhandledErrors(ArOrErr.takeError(), OS, "");
520*9880d681SAndroid Build Coastguard Worker OS.flush();
521*9880d681SAndroid Build Coastguard Worker errs() << Buf;
522*9880d681SAndroid Build Coastguard Worker return 1;
523*9880d681SAndroid Build Coastguard Worker }
524*9880d681SAndroid Build Coastguard Worker std::unique_ptr<object::Archive> &Ar = ArOrErr.get();
525*9880d681SAndroid Build Coastguard Worker
526*9880d681SAndroid Build Coastguard Worker object::OwningBinary<object::Archive> OB(std::move(Ar), std::move(ArBuf));
527*9880d681SAndroid Build Coastguard Worker
528*9880d681SAndroid Build Coastguard Worker EE->addArchive(std::move(OB));
529*9880d681SAndroid Build Coastguard Worker }
530*9880d681SAndroid Build Coastguard Worker
531*9880d681SAndroid Build Coastguard Worker // If the target is Cygwin/MingW and we are generating remote code, we
532*9880d681SAndroid Build Coastguard Worker // need an extra module to help out with linking.
533*9880d681SAndroid Build Coastguard Worker if (RemoteMCJIT && Triple(Mod->getTargetTriple()).isOSCygMing()) {
534*9880d681SAndroid Build Coastguard Worker addCygMingExtraModule(*EE, Context, Mod->getTargetTriple());
535*9880d681SAndroid Build Coastguard Worker }
536*9880d681SAndroid Build Coastguard Worker
537*9880d681SAndroid Build Coastguard Worker // The following functions have no effect if their respective profiling
538*9880d681SAndroid Build Coastguard Worker // support wasn't enabled in the build configuration.
539*9880d681SAndroid Build Coastguard Worker EE->RegisterJITEventListener(
540*9880d681SAndroid Build Coastguard Worker JITEventListener::createOProfileJITEventListener());
541*9880d681SAndroid Build Coastguard Worker EE->RegisterJITEventListener(
542*9880d681SAndroid Build Coastguard Worker JITEventListener::createIntelJITEventListener());
543*9880d681SAndroid Build Coastguard Worker
544*9880d681SAndroid Build Coastguard Worker if (!NoLazyCompilation && RemoteMCJIT) {
545*9880d681SAndroid Build Coastguard Worker errs() << "warning: remote mcjit does not support lazy compilation\n";
546*9880d681SAndroid Build Coastguard Worker NoLazyCompilation = true;
547*9880d681SAndroid Build Coastguard Worker }
548*9880d681SAndroid Build Coastguard Worker EE->DisableLazyCompilation(NoLazyCompilation);
549*9880d681SAndroid Build Coastguard Worker
550*9880d681SAndroid Build Coastguard Worker // If the user specifically requested an argv[0] to pass into the program,
551*9880d681SAndroid Build Coastguard Worker // do it now.
552*9880d681SAndroid Build Coastguard Worker if (!FakeArgv0.empty()) {
553*9880d681SAndroid Build Coastguard Worker InputFile = static_cast<std::string>(FakeArgv0);
554*9880d681SAndroid Build Coastguard Worker } else {
555*9880d681SAndroid Build Coastguard Worker // Otherwise, if there is a .bc suffix on the executable strip it off, it
556*9880d681SAndroid Build Coastguard Worker // might confuse the program.
557*9880d681SAndroid Build Coastguard Worker if (StringRef(InputFile).endswith(".bc"))
558*9880d681SAndroid Build Coastguard Worker InputFile.erase(InputFile.length() - 3);
559*9880d681SAndroid Build Coastguard Worker }
560*9880d681SAndroid Build Coastguard Worker
561*9880d681SAndroid Build Coastguard Worker // Add the module's name to the start of the vector of arguments to main().
562*9880d681SAndroid Build Coastguard Worker InputArgv.insert(InputArgv.begin(), InputFile);
563*9880d681SAndroid Build Coastguard Worker
564*9880d681SAndroid Build Coastguard Worker // Call the main function from M as if its signature were:
565*9880d681SAndroid Build Coastguard Worker // int main (int argc, char **argv, const char **envp)
566*9880d681SAndroid Build Coastguard Worker // using the contents of Args to determine argc & argv, and the contents of
567*9880d681SAndroid Build Coastguard Worker // EnvVars to determine envp.
568*9880d681SAndroid Build Coastguard Worker //
569*9880d681SAndroid Build Coastguard Worker Function *EntryFn = Mod->getFunction(EntryFunc);
570*9880d681SAndroid Build Coastguard Worker if (!EntryFn) {
571*9880d681SAndroid Build Coastguard Worker errs() << '\'' << EntryFunc << "\' function not found in module.\n";
572*9880d681SAndroid Build Coastguard Worker return -1;
573*9880d681SAndroid Build Coastguard Worker }
574*9880d681SAndroid Build Coastguard Worker
575*9880d681SAndroid Build Coastguard Worker // Reset errno to zero on entry to main.
576*9880d681SAndroid Build Coastguard Worker errno = 0;
577*9880d681SAndroid Build Coastguard Worker
578*9880d681SAndroid Build Coastguard Worker int Result = -1;
579*9880d681SAndroid Build Coastguard Worker
580*9880d681SAndroid Build Coastguard Worker // Sanity check use of remote-jit: LLI currently only supports use of the
581*9880d681SAndroid Build Coastguard Worker // remote JIT on Unix platforms.
582*9880d681SAndroid Build Coastguard Worker if (RemoteMCJIT) {
583*9880d681SAndroid Build Coastguard Worker #ifndef LLVM_ON_UNIX
584*9880d681SAndroid Build Coastguard Worker errs() << "Warning: host does not support external remote targets.\n"
585*9880d681SAndroid Build Coastguard Worker << " Defaulting to local execution\n";
586*9880d681SAndroid Build Coastguard Worker return -1;
587*9880d681SAndroid Build Coastguard Worker #else
588*9880d681SAndroid Build Coastguard Worker if (ChildExecPath.empty()) {
589*9880d681SAndroid Build Coastguard Worker errs() << "-remote-mcjit requires -mcjit-remote-process.\n";
590*9880d681SAndroid Build Coastguard Worker exit(1);
591*9880d681SAndroid Build Coastguard Worker } else if (!sys::fs::can_execute(ChildExecPath)) {
592*9880d681SAndroid Build Coastguard Worker errs() << "Unable to find usable child executable: '" << ChildExecPath
593*9880d681SAndroid Build Coastguard Worker << "'\n";
594*9880d681SAndroid Build Coastguard Worker return -1;
595*9880d681SAndroid Build Coastguard Worker }
596*9880d681SAndroid Build Coastguard Worker #endif
597*9880d681SAndroid Build Coastguard Worker }
598*9880d681SAndroid Build Coastguard Worker
599*9880d681SAndroid Build Coastguard Worker if (!RemoteMCJIT) {
600*9880d681SAndroid Build Coastguard Worker // If the program doesn't explicitly call exit, we will need the Exit
601*9880d681SAndroid Build Coastguard Worker // function later on to make an explicit call, so get the function now.
602*9880d681SAndroid Build Coastguard Worker Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
603*9880d681SAndroid Build Coastguard Worker Type::getInt32Ty(Context),
604*9880d681SAndroid Build Coastguard Worker nullptr);
605*9880d681SAndroid Build Coastguard Worker
606*9880d681SAndroid Build Coastguard Worker // Run static constructors.
607*9880d681SAndroid Build Coastguard Worker if (!ForceInterpreter) {
608*9880d681SAndroid Build Coastguard Worker // Give MCJIT a chance to apply relocations and set page permissions.
609*9880d681SAndroid Build Coastguard Worker EE->finalizeObject();
610*9880d681SAndroid Build Coastguard Worker }
611*9880d681SAndroid Build Coastguard Worker EE->runStaticConstructorsDestructors(false);
612*9880d681SAndroid Build Coastguard Worker
613*9880d681SAndroid Build Coastguard Worker // Trigger compilation separately so code regions that need to be
614*9880d681SAndroid Build Coastguard Worker // invalidated will be known.
615*9880d681SAndroid Build Coastguard Worker (void)EE->getPointerToFunction(EntryFn);
616*9880d681SAndroid Build Coastguard Worker // Clear instruction cache before code will be executed.
617*9880d681SAndroid Build Coastguard Worker if (RTDyldMM)
618*9880d681SAndroid Build Coastguard Worker static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
619*9880d681SAndroid Build Coastguard Worker
620*9880d681SAndroid Build Coastguard Worker // Run main.
621*9880d681SAndroid Build Coastguard Worker Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
622*9880d681SAndroid Build Coastguard Worker
623*9880d681SAndroid Build Coastguard Worker // Run static destructors.
624*9880d681SAndroid Build Coastguard Worker EE->runStaticConstructorsDestructors(true);
625*9880d681SAndroid Build Coastguard Worker
626*9880d681SAndroid Build Coastguard Worker // If the program didn't call exit explicitly, we should call it now.
627*9880d681SAndroid Build Coastguard Worker // This ensures that any atexit handlers get called correctly.
628*9880d681SAndroid Build Coastguard Worker if (Function *ExitF = dyn_cast<Function>(Exit)) {
629*9880d681SAndroid Build Coastguard Worker std::vector<GenericValue> Args;
630*9880d681SAndroid Build Coastguard Worker GenericValue ResultGV;
631*9880d681SAndroid Build Coastguard Worker ResultGV.IntVal = APInt(32, Result);
632*9880d681SAndroid Build Coastguard Worker Args.push_back(ResultGV);
633*9880d681SAndroid Build Coastguard Worker EE->runFunction(ExitF, Args);
634*9880d681SAndroid Build Coastguard Worker errs() << "ERROR: exit(" << Result << ") returned!\n";
635*9880d681SAndroid Build Coastguard Worker abort();
636*9880d681SAndroid Build Coastguard Worker } else {
637*9880d681SAndroid Build Coastguard Worker errs() << "ERROR: exit defined with wrong prototype!\n";
638*9880d681SAndroid Build Coastguard Worker abort();
639*9880d681SAndroid Build Coastguard Worker }
640*9880d681SAndroid Build Coastguard Worker } else {
641*9880d681SAndroid Build Coastguard Worker // else == "if (RemoteMCJIT)"
642*9880d681SAndroid Build Coastguard Worker
643*9880d681SAndroid Build Coastguard Worker // Remote target MCJIT doesn't (yet) support static constructors. No reason
644*9880d681SAndroid Build Coastguard Worker // it couldn't. This is a limitation of the LLI implemantation, not the
645*9880d681SAndroid Build Coastguard Worker // MCJIT itself. FIXME.
646*9880d681SAndroid Build Coastguard Worker
647*9880d681SAndroid Build Coastguard Worker // Lanch the remote process and get a channel to it.
648*9880d681SAndroid Build Coastguard Worker std::unique_ptr<FDRPCChannel> C = launchRemote();
649*9880d681SAndroid Build Coastguard Worker if (!C) {
650*9880d681SAndroid Build Coastguard Worker errs() << "Failed to launch remote JIT.\n";
651*9880d681SAndroid Build Coastguard Worker exit(1);
652*9880d681SAndroid Build Coastguard Worker }
653*9880d681SAndroid Build Coastguard Worker
654*9880d681SAndroid Build Coastguard Worker // Create a remote target client running over the channel.
655*9880d681SAndroid Build Coastguard Worker typedef orc::remote::OrcRemoteTargetClient<orc::remote::RPCChannel> MyRemote;
656*9880d681SAndroid Build Coastguard Worker MyRemote R = ExitOnErr(MyRemote::Create(*C));
657*9880d681SAndroid Build Coastguard Worker
658*9880d681SAndroid Build Coastguard Worker // Create a remote memory manager.
659*9880d681SAndroid Build Coastguard Worker std::unique_ptr<MyRemote::RCMemoryManager> RemoteMM;
660*9880d681SAndroid Build Coastguard Worker ExitOnErr(R.createRemoteMemoryManager(RemoteMM));
661*9880d681SAndroid Build Coastguard Worker
662*9880d681SAndroid Build Coastguard Worker // Forward MCJIT's memory manager calls to the remote memory manager.
663*9880d681SAndroid Build Coastguard Worker static_cast<ForwardingMemoryManager*>(RTDyldMM)->setMemMgr(
664*9880d681SAndroid Build Coastguard Worker std::move(RemoteMM));
665*9880d681SAndroid Build Coastguard Worker
666*9880d681SAndroid Build Coastguard Worker // Forward MCJIT's symbol resolution calls to the remote.
667*9880d681SAndroid Build Coastguard Worker static_cast<ForwardingMemoryManager*>(RTDyldMM)->setResolver(
668*9880d681SAndroid Build Coastguard Worker orc::createLambdaResolver(
669*9880d681SAndroid Build Coastguard Worker [](const std::string &Name) { return nullptr; },
670*9880d681SAndroid Build Coastguard Worker [&](const std::string &Name) {
671*9880d681SAndroid Build Coastguard Worker if (auto Addr = ExitOnErr(R.getSymbolAddress(Name)))
672*9880d681SAndroid Build Coastguard Worker return RuntimeDyld::SymbolInfo(Addr, JITSymbolFlags::Exported);
673*9880d681SAndroid Build Coastguard Worker return RuntimeDyld::SymbolInfo(nullptr);
674*9880d681SAndroid Build Coastguard Worker }
675*9880d681SAndroid Build Coastguard Worker ));
676*9880d681SAndroid Build Coastguard Worker
677*9880d681SAndroid Build Coastguard Worker // Grab the target address of the JIT'd main function on the remote and call
678*9880d681SAndroid Build Coastguard Worker // it.
679*9880d681SAndroid Build Coastguard Worker // FIXME: argv and envp handling.
680*9880d681SAndroid Build Coastguard Worker orc::TargetAddress Entry = EE->getFunctionAddress(EntryFn->getName().str());
681*9880d681SAndroid Build Coastguard Worker EE->finalizeObject();
682*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"
683*9880d681SAndroid Build Coastguard Worker << format("%llx", Entry) << "\n");
684*9880d681SAndroid Build Coastguard Worker Result = ExitOnErr(R.callIntVoid(Entry));
685*9880d681SAndroid Build Coastguard Worker
686*9880d681SAndroid Build Coastguard Worker // Like static constructors, the remote target MCJIT support doesn't handle
687*9880d681SAndroid Build Coastguard Worker // this yet. It could. FIXME.
688*9880d681SAndroid Build Coastguard Worker
689*9880d681SAndroid Build Coastguard Worker // Delete the EE - we need to tear it down *before* we terminate the session
690*9880d681SAndroid Build Coastguard Worker // with the remote, otherwise it'll crash when it tries to release resources
691*9880d681SAndroid Build Coastguard Worker // on a remote that has already been disconnected.
692*9880d681SAndroid Build Coastguard Worker EE.reset();
693*9880d681SAndroid Build Coastguard Worker
694*9880d681SAndroid Build Coastguard Worker // Signal the remote target that we're done JITing.
695*9880d681SAndroid Build Coastguard Worker ExitOnErr(R.terminateSession());
696*9880d681SAndroid Build Coastguard Worker }
697*9880d681SAndroid Build Coastguard Worker
698*9880d681SAndroid Build Coastguard Worker return Result;
699*9880d681SAndroid Build Coastguard Worker }
700*9880d681SAndroid Build Coastguard Worker
launchRemote()701*9880d681SAndroid Build Coastguard Worker std::unique_ptr<FDRPCChannel> launchRemote() {
702*9880d681SAndroid Build Coastguard Worker #ifndef LLVM_ON_UNIX
703*9880d681SAndroid Build Coastguard Worker llvm_unreachable("launchRemote not supported on non-Unix platforms");
704*9880d681SAndroid Build Coastguard Worker #else
705*9880d681SAndroid Build Coastguard Worker int PipeFD[2][2];
706*9880d681SAndroid Build Coastguard Worker pid_t ChildPID;
707*9880d681SAndroid Build Coastguard Worker
708*9880d681SAndroid Build Coastguard Worker // Create two pipes.
709*9880d681SAndroid Build Coastguard Worker if (pipe(PipeFD[0]) != 0 || pipe(PipeFD[1]) != 0)
710*9880d681SAndroid Build Coastguard Worker perror("Error creating pipe: ");
711*9880d681SAndroid Build Coastguard Worker
712*9880d681SAndroid Build Coastguard Worker ChildPID = fork();
713*9880d681SAndroid Build Coastguard Worker
714*9880d681SAndroid Build Coastguard Worker if (ChildPID == 0) {
715*9880d681SAndroid Build Coastguard Worker // In the child...
716*9880d681SAndroid Build Coastguard Worker
717*9880d681SAndroid Build Coastguard Worker // Close the parent ends of the pipes
718*9880d681SAndroid Build Coastguard Worker close(PipeFD[0][1]);
719*9880d681SAndroid Build Coastguard Worker close(PipeFD[1][0]);
720*9880d681SAndroid Build Coastguard Worker
721*9880d681SAndroid Build Coastguard Worker
722*9880d681SAndroid Build Coastguard Worker // Execute the child process.
723*9880d681SAndroid Build Coastguard Worker std::unique_ptr<char[]> ChildPath, ChildIn, ChildOut;
724*9880d681SAndroid Build Coastguard Worker {
725*9880d681SAndroid Build Coastguard Worker ChildPath.reset(new char[ChildExecPath.size() + 1]);
726*9880d681SAndroid Build Coastguard Worker std::copy(ChildExecPath.begin(), ChildExecPath.end(), &ChildPath[0]);
727*9880d681SAndroid Build Coastguard Worker ChildPath[ChildExecPath.size()] = '\0';
728*9880d681SAndroid Build Coastguard Worker std::string ChildInStr = utostr(PipeFD[0][0]);
729*9880d681SAndroid Build Coastguard Worker ChildIn.reset(new char[ChildInStr.size() + 1]);
730*9880d681SAndroid Build Coastguard Worker std::copy(ChildInStr.begin(), ChildInStr.end(), &ChildIn[0]);
731*9880d681SAndroid Build Coastguard Worker ChildIn[ChildInStr.size()] = '\0';
732*9880d681SAndroid Build Coastguard Worker std::string ChildOutStr = utostr(PipeFD[1][1]);
733*9880d681SAndroid Build Coastguard Worker ChildOut.reset(new char[ChildOutStr.size() + 1]);
734*9880d681SAndroid Build Coastguard Worker std::copy(ChildOutStr.begin(), ChildOutStr.end(), &ChildOut[0]);
735*9880d681SAndroid Build Coastguard Worker ChildOut[ChildOutStr.size()] = '\0';
736*9880d681SAndroid Build Coastguard Worker }
737*9880d681SAndroid Build Coastguard Worker
738*9880d681SAndroid Build Coastguard Worker char * const args[] = { &ChildPath[0], &ChildIn[0], &ChildOut[0], nullptr };
739*9880d681SAndroid Build Coastguard Worker int rc = execv(ChildExecPath.c_str(), args);
740*9880d681SAndroid Build Coastguard Worker if (rc != 0)
741*9880d681SAndroid Build Coastguard Worker perror("Error executing child process: ");
742*9880d681SAndroid Build Coastguard Worker llvm_unreachable("Error executing child process");
743*9880d681SAndroid Build Coastguard Worker }
744*9880d681SAndroid Build Coastguard Worker // else we're the parent...
745*9880d681SAndroid Build Coastguard Worker
746*9880d681SAndroid Build Coastguard Worker // Close the child ends of the pipes
747*9880d681SAndroid Build Coastguard Worker close(PipeFD[0][0]);
748*9880d681SAndroid Build Coastguard Worker close(PipeFD[1][1]);
749*9880d681SAndroid Build Coastguard Worker
750*9880d681SAndroid Build Coastguard Worker // Return an RPC channel connected to our end of the pipes.
751*9880d681SAndroid Build Coastguard Worker return llvm::make_unique<FDRPCChannel>(PipeFD[1][0], PipeFD[0][1]);
752*9880d681SAndroid Build Coastguard Worker #endif
753*9880d681SAndroid Build Coastguard Worker }
754