blob: ac0d2192724f4e6bd03719f5c72c9396320bd066 [file] [log] [blame]
Chris Lattnerfe11a972002-12-23 23:59:41 +00001//===- lli.cpp - LLVM Interpreter / Dynamic compiler ----------------------===//
Misha Brukman3da94ae2005-04-22 00:00:37 +00002//
John Criswell7c0e0222003-10-20 17:47:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner21c62da2007-12-29 20:44:31 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman3da94ae2005-04-22 00:00:37 +00007//
John Criswell7c0e0222003-10-20 17:47:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner92101ac2001-08-23 17:05:04 +00009//
Chris Lattner7efea1d2003-12-26 05:07:35 +000010// This utility provides a simple wrapper around the LLVM Execution Engines,
11// which allow the direct execution of LLVM programs through a Just-In-Time
Torok Edwindb9c0282009-07-03 12:11:32 +000012// compiler, or through an interpreter if no JIT is available for this platform.
Chris Lattner92101ac2001-08-23 17:05:04 +000013//
14//===----------------------------------------------------------------------===//
15
Jim Grosbach706f03a2012-09-05 16:50:34 +000016#define DEBUG_TYPE "lli"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000017#include "llvm/IR/LLVMContext.h"
Andrew Kaylorb868e912013-10-04 00:49:38 +000018#include "RemoteMemoryManager.h"
Jim Grosbach706f03a2012-09-05 16:50:34 +000019#include "RemoteTarget.h"
Duncan Sands75ebbce2010-08-28 01:30:02 +000020#include "llvm/ADT/Triple.h"
Chris Lattnerc1e6d682007-05-06 04:58:26 +000021#include "llvm/Bitcode/ReaderWriter.h"
Chris Lattnerd3a680a2006-08-01 22:34:35 +000022#include "llvm/CodeGen/LinkAllCodegenComponents.h"
Brian Gaeked1cab3e2003-09-05 19:42:34 +000023#include "llvm/ExecutionEngine/GenericValue.h"
Jeffrey Yasskindf5a7da2009-06-25 02:04:04 +000024#include "llvm/ExecutionEngine/Interpreter.h"
25#include "llvm/ExecutionEngine/JIT.h"
26#include "llvm/ExecutionEngine/JITEventListener.h"
Jim Grosbachbf9ab932012-01-11 21:12:51 +000027#include "llvm/ExecutionEngine/JITMemoryManager.h"
Daniel Dunbar6aec2982010-11-17 16:06:43 +000028#include "llvm/ExecutionEngine/MCJIT.h"
Andrew Kaylor257a0092012-11-27 19:49:00 +000029#include "llvm/ExecutionEngine/SectionMemoryManager.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000030#include "llvm/IR/Module.h"
31#include "llvm/IR/Type.h"
Chandler Carruth7fc162f2013-03-26 02:25:37 +000032#include "llvm/IRReader/IRReader.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000033#include "llvm/Support/CommandLine.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000034#include "llvm/Support/Debug.h"
35#include "llvm/Support/DynamicLibrary.h"
36#include "llvm/Support/Format.h"
Chris Lattnerc30598b2006-12-06 01:18:01 +000037#include "llvm/Support/ManagedStatic.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000038#include "llvm/Support/MathExtras.h"
39#include "llvm/Support/Memory.h"
Chris Lattnerc1e6d682007-05-06 04:58:26 +000040#include "llvm/Support/MemoryBuffer.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000041#include "llvm/Support/PluginLoader.h"
Chris Lattnercc14d252009-03-06 05:34:10 +000042#include "llvm/Support/PrettyStackTrace.h"
Michael J. Spencer1f6efa32010-11-29 18:16:10 +000043#include "llvm/Support/Process.h"
Andrew Kaylor0ab5c6c2013-10-02 17:12:36 +000044#include "llvm/Support/Program.h"
Michael J. Spencer1f6efa32010-11-29 18:16:10 +000045#include "llvm/Support/Signals.h"
Chandler Carruth7fc162f2013-03-26 02:25:37 +000046#include "llvm/Support/SourceMgr.h"
Evan Cheng3e74d6f2011-08-24 18:08:43 +000047#include "llvm/Support/TargetSelect.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000048#include "llvm/Support/raw_ostream.h"
Daniel Maleae16e6872013-06-28 19:11:40 +000049#include "llvm/Transforms/Instrumentation.h"
Chris Lattner02040322007-04-27 17:02:33 +000050#include <cerrno>
NAKAMURA Takumia13d14a2010-10-22 14:53:59 +000051
52#ifdef __CYGWIN__
53#include <cygwin/version.h>
54#if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
55#define DO_NOTHING_ATEXIT 1
56#endif
57#endif
58
Brian Gaeked0fde302003-11-11 22:41:34 +000059using namespace llvm;
60
Chris Lattnerfe11a972002-12-23 23:59:41 +000061namespace {
62 cl::opt<std::string>
Gabor Greifa99be512007-07-05 17:07:56 +000063 InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
Chris Lattner5ff62e92002-07-22 02:10:13 +000064
Chris Lattnerfe11a972002-12-23 23:59:41 +000065 cl::list<std::string>
66 InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
Chris Lattner5ff62e92002-07-22 02:10:13 +000067
Chris Lattnerfe11a972002-12-23 23:59:41 +000068 cl::opt<bool> ForceInterpreter("force-interpreter",
Misha Brukman3d8a54d2003-09-25 18:10:34 +000069 cl::desc("Force interpretation: disable JIT"),
70 cl::init(false));
Evan Chenge1a4eda2008-08-08 08:12:06 +000071
Daniel Dunbar6d135972010-11-17 16:06:37 +000072 cl::opt<bool> UseMCJIT(
73 "use-mcjit", cl::desc("Enable use of the MC-based JIT (if available)"),
74 cl::init(false));
75
Daniel Maleae16e6872013-06-28 19:11:40 +000076 cl::opt<bool> DebugIR(
77 "debug-ir", cl::desc("Generate debug information to allow debugging IR."),
78 cl::init(false));
79
Jim Grosbach706f03a2012-09-05 16:50:34 +000080 // The MCJIT supports building for a target address space separate from
81 // the JIT compilation process. Use a forked process and a copying
82 // memory manager with IPC to execute using this functionality.
83 cl::opt<bool> RemoteMCJIT("remote-mcjit",
84 cl::desc("Execute MCJIT'ed code in a separate process."),
85 cl::init(false));
86
Andrew Kaylor0ab5c6c2013-10-02 17:12:36 +000087 // Manually specify the child process for remote execution. This overrides
88 // the simulated remote execution that allocates address space for child
89 // execution. The child process resides in the disk and communicates with lli
90 // via stdin/stdout pipes.
91 cl::opt<std::string>
92 MCJITRemoteProcess("mcjit-remote-process",
93 cl::desc("Specify the filename of the process to launch "
94 "for remote MCJIT execution. If none is specified,"
95 "\n\tremote execution will be simulated in-process."),
96 cl::value_desc("filename"),
97 cl::init(""));
98
Evan Cheng712e80e2009-05-04 23:05:19 +000099 // Determine optimization level.
100 cl::opt<char>
101 OptLevel("O",
102 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
103 "(default = '-O2')"),
104 cl::Prefix,
105 cl::ZeroOrMore,
106 cl::init(' '));
Evan Chenge1a4eda2008-08-08 08:12:06 +0000107
Chris Lattner3015e602005-12-16 05:00:21 +0000108 cl::opt<std::string>
Chris Lattner60844d42005-12-16 05:19:18 +0000109 TargetTriple("mtriple", cl::desc("Override target triple for module"));
Evan Chengec740e32008-11-05 23:21:52 +0000110
111 cl::opt<std::string>
Jeffrey Yasskin46882612010-02-05 16:19:36 +0000112 MArch("march",
113 cl::desc("Architecture to generate assembly for (see --version)"));
114
115 cl::opt<std::string>
116 MCPU("mcpu",
117 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
118 cl::value_desc("cpu-name"),
119 cl::init(""));
120
121 cl::list<std::string>
122 MAttrs("mattr",
123 cl::CommaSeparated,
124 cl::desc("Target specific attributes (-mattr=help for details)"),
125 cl::value_desc("a1,+a2,-a3,..."));
126
127 cl::opt<std::string>
Evan Chengec740e32008-11-05 23:21:52 +0000128 EntryFunc("entry-function",
129 cl::desc("Specify the entry function (default = 'main') "
130 "of the executable"),
131 cl::value_desc("function"),
132 cl::init("main"));
Eli Benderskya66a1852012-01-16 08:56:09 +0000133
Andrew Kaylorb868e912013-10-04 00:49:38 +0000134 cl::list<std::string>
135 ExtraModules("extra-modules",
136 cl::CommaSeparated,
137 cl::desc("Extra modules to be loaded"),
138 cl::value_desc("<input bitcode 2>,<input bitcode 3>,..."));
139
Chris Lattnere69671d2003-10-28 22:51:44 +0000140 cl::opt<std::string>
141 FakeArgv0("fake-argv0",
142 cl::desc("Override the 'argv[0]' value passed into the executing"
143 " program"), cl::value_desc("executable"));
Eli Benderskya66a1852012-01-16 08:56:09 +0000144
Chris Lattner43f249a2006-09-14 06:17:09 +0000145 cl::opt<bool>
146 DisableCoreFiles("disable-core-files", cl::Hidden,
147 cl::desc("Disable emission of core files if possible"));
Evan Chengc290a5b2008-04-22 06:51:41 +0000148
149 cl::opt<bool>
Evan Cheng03dace82008-05-21 18:20:21 +0000150 NoLazyCompilation("disable-lazy-compilation",
Evan Chengc290a5b2008-04-22 06:51:41 +0000151 cl::desc("Disable JIT lazy compilation"),
152 cl::init(false));
Evan Cheng43966132011-07-19 06:37:02 +0000153
154 cl::opt<Reloc::Model>
155 RelocModel("relocation-model",
156 cl::desc("Choose relocation model"),
157 cl::init(Reloc::Default),
158 cl::values(
159 clEnumValN(Reloc::Default, "default",
160 "Target default relocation model"),
161 clEnumValN(Reloc::Static, "static",
162 "Non-relocatable code"),
163 clEnumValN(Reloc::PIC_, "pic",
164 "Fully relocatable, position independent code"),
165 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
166 "Relocatable external references, non-relocatable code"),
167 clEnumValEnd));
Evan Cheng34ad6db2011-07-20 07:51:56 +0000168
169 cl::opt<llvm::CodeModel::Model>
170 CMModel("code-model",
171 cl::desc("Choose code model"),
172 cl::init(CodeModel::JITDefault),
173 cl::values(clEnumValN(CodeModel::JITDefault, "default",
174 "Target default JIT code model"),
175 clEnumValN(CodeModel::Small, "small",
176 "Small code model"),
177 clEnumValN(CodeModel::Kernel, "kernel",
178 "Kernel code model"),
179 clEnumValN(CodeModel::Medium, "medium",
180 "Medium code model"),
181 clEnumValN(CodeModel::Large, "large",
182 "Large code model"),
183 clEnumValEnd));
184
Nick Lewycky9a148412012-04-18 08:34:12 +0000185 cl::opt<bool>
Tim Northover77b4c692012-10-12 09:55:13 +0000186 GenerateSoftFloatCalls("soft-float",
187 cl::desc("Generate software floating point library calls"),
188 cl::init(false));
189
190 cl::opt<llvm::FloatABI::ABIType>
191 FloatABIForCalls("float-abi",
192 cl::desc("Choose float ABI type"),
193 cl::init(FloatABI::Default),
194 cl::values(
195 clEnumValN(FloatABI::Default, "default",
196 "Target default float ABI type"),
197 clEnumValN(FloatABI::Soft, "soft",
198 "Soft float ABI (implied by -soft-float)"),
199 clEnumValN(FloatABI::Hard, "hard",
200 "Hard float ABI (uses FP registers)"),
201 clEnumValEnd));
202 cl::opt<bool>
Nick Lewycky9a148412012-04-18 08:34:12 +0000203// In debug builds, make this default to true.
204#ifdef NDEBUG
205#define EMIT_DEBUG false
206#else
207#define EMIT_DEBUG true
208#endif
209 EmitJitDebugInfo("jit-emit-debug",
210 cl::desc("Emit debug information to debugger"),
211 cl::init(EMIT_DEBUG));
212#undef EMIT_DEBUG
213
214 static cl::opt<bool>
215 EmitJitDebugInfoToDisk("jit-emit-debug-to-disk",
216 cl::Hidden,
217 cl::desc("Emit debug info objfiles to disk"),
218 cl::init(false));
Chris Lattnerfe11a972002-12-23 23:59:41 +0000219}
Chris Lattner43e3f7c2001-10-27 08:43:52 +0000220
Reid Spencerf70d6772007-03-03 18:21:44 +0000221static ExecutionEngine *EE = 0;
222
223static void do_shutdown() {
NAKAMURA Takumia13d14a2010-10-22 14:53:59 +0000224 // Cygwin-1.5 invokes DLL's dtors before atexit handler.
225#ifndef DO_NOTHING_ATEXIT
Reid Spencerf70d6772007-03-03 18:21:44 +0000226 delete EE;
227 llvm_shutdown();
NAKAMURA Takumia13d14a2010-10-22 14:53:59 +0000228#endif
Reid Spencerf70d6772007-03-03 18:21:44 +0000229}
230
Chris Lattner92101ac2001-08-23 17:05:04 +0000231//===----------------------------------------------------------------------===//
Chris Lattner92101ac2001-08-23 17:05:04 +0000232// main Driver function
233//
Misha Brukmanc4fb6fd2003-10-14 21:39:53 +0000234int main(int argc, char **argv, char * const *envp) {
Chris Lattnercc14d252009-03-06 05:34:10 +0000235 sys::PrintStackTraceOnErrorSignal();
236 PrettyStackTraceProgram X(argc, argv);
Eli Benderskya66a1852012-01-16 08:56:09 +0000237
Owen Anderson0d7c6952009-07-15 22:16:10 +0000238 LLVMContext &Context = getGlobalContext();
Reid Spencerf70d6772007-03-03 18:21:44 +0000239 atexit(do_shutdown); // Call llvm_shutdown() on exit.
Daniel Dunbar494d6632009-07-16 02:04:54 +0000240
241 // If we have a native target, initialize it to ensure it is linked in and
242 // usable by the JIT.
243 InitializeNativeTarget();
Jim Grosbach31649e62011-03-18 22:48:41 +0000244 InitializeNativeTargetAsmPrinter();
Jim Grosbach68372322012-11-05 19:06:05 +0000245 InitializeNativeTargetAsmParser();
Daniel Dunbar494d6632009-07-16 02:04:54 +0000246
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000247 cl::ParseCommandLineOptions(argc, argv,
Dan Gohman82a13c92007-10-08 15:45:12 +0000248 "llvm interpreter & dynamic compiler\n");
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000249
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000250 // If the user doesn't want core files, disable them.
251 if (DisableCoreFiles)
252 sys::Process::PreventCoreFiles();
Eli Benderskya66a1852012-01-16 08:56:09 +0000253
Gabor Greifa99be512007-07-05 17:07:56 +0000254 // Load the bitcode...
Daniel Dunbar46a27162010-11-13 00:28:01 +0000255 SMDiagnostic Err;
256 Module *Mod = ParseIRFile(InputFile, Err, Context);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000257 if (!Mod) {
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000258 Err.print(argv[0], errs());
Daniel Dunbar46a27162010-11-13 00:28:01 +0000259 return 1;
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000260 }
261
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000262 // If not jitting lazily, load the whole bitcode file eagerly too.
Daniel Dunbar46a27162010-11-13 00:28:01 +0000263 std::string ErrorMsg;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000264 if (NoLazyCompilation) {
265 if (Mod->MaterializeAllPermanently(&ErrorMsg)) {
266 errs() << argv[0] << ": bitcode didn't read correctly.\n";
267 errs() << "Reason: " << ErrorMsg << "\n";
268 exit(1);
269 }
Evan Chengc290a5b2008-04-22 06:51:41 +0000270 }
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000271
Daniel Maleae16e6872013-06-28 19:11:40 +0000272 if (DebugIR) {
273 if (!UseMCJIT) {
274 errs() << "warning: -debug-ir used without -use-mcjit. Only partial debug"
275 << " information will be emitted by the non-MC JIT engine. To see full"
276 << " source debug information, enable the flag '-use-mcjit'.\n";
277
278 }
279 ModulePass *DebugIRPass = createDebugIRPass();
280 DebugIRPass->runOnModule(*Mod);
281 }
282
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000283 EngineBuilder builder(Mod);
Jeffrey Yasskin46882612010-02-05 16:19:36 +0000284 builder.setMArch(MArch);
285 builder.setMCPU(MCPU);
286 builder.setMAttrs(MAttrs);
Evan Cheng43966132011-07-19 06:37:02 +0000287 builder.setRelocationModel(RelocModel);
Evan Cheng34ad6db2011-07-20 07:51:56 +0000288 builder.setCodeModel(CMModel);
Daniel Dunbar4dc31362009-07-18 08:07:13 +0000289 builder.setErrorStr(&ErrorMsg);
290 builder.setEngineKind(ForceInterpreter
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000291 ? EngineKind::Interpreter
292 : EngineKind::JIT);
293
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000294 // If we are supposed to override the target triple, do so now.
295 if (!TargetTriple.empty())
Duncan Sands75ebbce2010-08-28 01:30:02 +0000296 Mod->setTargetTriple(Triple::normalize(TargetTriple));
Evan Chengc290a5b2008-04-22 06:51:41 +0000297
Eli Benderskya66a1852012-01-16 08:56:09 +0000298 // Enable MCJIT if desired.
Filip Pizlo13a3cf12013-05-14 19:29:00 +0000299 RTDyldMemoryManager *RTDyldMM = 0;
Eli Benderskya66a1852012-01-16 08:56:09 +0000300 if (UseMCJIT && !ForceInterpreter) {
Daniel Dunbar6d135972010-11-17 16:06:37 +0000301 builder.setUseMCJIT(true);
Jim Grosbach706f03a2012-09-05 16:50:34 +0000302 if (RemoteMCJIT)
Andrew Kaylorb868e912013-10-04 00:49:38 +0000303 RTDyldMM = new RemoteMemoryManager();
Jim Grosbach706f03a2012-09-05 16:50:34 +0000304 else
Filip Pizlo13a3cf12013-05-14 19:29:00 +0000305 RTDyldMM = new SectionMemoryManager();
306 builder.setMCJITMemoryManager(RTDyldMM);
Benjamin Kramer65145512012-05-20 17:24:08 +0000307 } else {
Jim Grosbach706f03a2012-09-05 16:50:34 +0000308 if (RemoteMCJIT) {
309 errs() << "error: Remote process execution requires -use-mcjit\n";
310 exit(1);
311 }
Benjamin Kramer65145512012-05-20 17:24:08 +0000312 builder.setJITMemoryManager(ForceInterpreter ? 0 :
313 JITMemoryManager::CreateDefaultMemManager());
Eli Benderskya66a1852012-01-16 08:56:09 +0000314 }
Daniel Dunbar6d135972010-11-17 16:06:37 +0000315
Evan Cheng712e80e2009-05-04 23:05:19 +0000316 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
317 switch (OptLevel) {
318 default:
Dan Gohman65f57c22009-07-15 16:35:29 +0000319 errs() << argv[0] << ": invalid optimization level.\n";
Evan Cheng712e80e2009-05-04 23:05:19 +0000320 return 1;
321 case ' ': break;
322 case '0': OLvl = CodeGenOpt::None; break;
Evan Chengbf57b522009-10-16 21:02:20 +0000323 case '1': OLvl = CodeGenOpt::Less; break;
Evan Cheng712e80e2009-05-04 23:05:19 +0000324 case '2': OLvl = CodeGenOpt::Default; break;
325 case '3': OLvl = CodeGenOpt::Aggressive; break;
326 }
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000327 builder.setOptLevel(OLvl);
328
Tim Northover77b4c692012-10-12 09:55:13 +0000329 TargetOptions Options;
330 Options.UseSoftFloat = GenerateSoftFloatCalls;
331 if (FloatABIForCalls != FloatABI::Default)
332 Options.FloatABIType = FloatABIForCalls;
333 if (GenerateSoftFloatCalls)
334 FloatABIForCalls = FloatABI::Soft;
335
Jim Grosbach706f03a2012-09-05 16:50:34 +0000336 // Remote target execution doesn't handle EH or debug registration.
337 if (!RemoteMCJIT) {
Jim Grosbach706f03a2012-09-05 16:50:34 +0000338 Options.JITEmitDebugInfo = EmitJitDebugInfo;
339 Options.JITEmitDebugInfoToDisk = EmitJitDebugInfoToDisk;
Jim Grosbach706f03a2012-09-05 16:50:34 +0000340 }
Nick Lewycky9a148412012-04-18 08:34:12 +0000341
Tim Northover77b4c692012-10-12 09:55:13 +0000342 builder.setTargetOptions(Options);
343
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000344 EE = builder.create();
Chris Lattnerfd15bee2009-07-07 18:31:09 +0000345 if (!EE) {
346 if (!ErrorMsg.empty())
Dan Gohman65f57c22009-07-15 16:35:29 +0000347 errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n";
Chris Lattnerfd15bee2009-07-07 18:31:09 +0000348 else
Dan Gohman65f57c22009-07-15 16:35:29 +0000349 errs() << argv[0] << ": unknown error creating EE!\n";
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000350 exit(1);
351 }
352
Andrew Kaylorb868e912013-10-04 00:49:38 +0000353 // Load any additional modules specified on the command line.
354 for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) {
355 Module *XMod = ParseIRFile(ExtraModules[i], Err, Context);
356 if (!XMod) {
357 Err.print(argv[0], errs());
358 return 1;
359 }
360 EE->addModule(XMod);
361 }
362
Eli Bendersky61b18512012-03-13 08:33:15 +0000363 // The following functions have no effect if their respective profiling
364 // support wasn't enabled in the build configuration.
365 EE->RegisterJITEventListener(
366 JITEventListener::createOProfileJITEventListener());
367 EE->RegisterJITEventListener(
368 JITEventListener::createIntelJITEventListener());
Jeffrey Yasskindf5a7da2009-06-25 02:04:04 +0000369
Jim Grosbach706f03a2012-09-05 16:50:34 +0000370 if (!NoLazyCompilation && RemoteMCJIT) {
371 errs() << "warning: remote mcjit does not support lazy compilation\n";
372 NoLazyCompilation = true;
373 }
Jeffrey Yasskin18fec732009-10-27 22:39:42 +0000374 EE->DisableLazyCompilation(NoLazyCompilation);
Evan Chengc290a5b2008-04-22 06:51:41 +0000375
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000376 // If the user specifically requested an argv[0] to pass into the program,
377 // do it now.
378 if (!FakeArgv0.empty()) {
379 InputFile = FakeArgv0;
380 } else {
381 // Otherwise, if there is a .bc suffix on the executable strip it off, it
382 // might confuse the program.
Benjamin Kramer3bb37e92010-04-15 11:33:14 +0000383 if (StringRef(InputFile).endswith(".bc"))
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000384 InputFile.erase(InputFile.length() - 3);
385 }
386
387 // Add the module's name to the start of the vector of arguments to main().
388 InputArgv.insert(InputArgv.begin(), InputFile);
389
390 // Call the main function from M as if its signature were:
391 // int main (int argc, char **argv, const char **envp)
392 // using the contents of Args to determine argc & argv, and the contents of
393 // EnvVars to determine envp.
394 //
Evan Chengec740e32008-11-05 23:21:52 +0000395 Function *EntryFn = Mod->getFunction(EntryFunc);
396 if (!EntryFn) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000397 errs() << '\'' << EntryFunc << "\' function not found in module.\n";
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000398 return -1;
399 }
400
Eli Benderskya66a1852012-01-16 08:56:09 +0000401 // If the program doesn't explicitly call exit, we will need the Exit
402 // function later on to make an explicit call, so get the function now.
Owen Anderson1d0be152009-08-13 21:58:54 +0000403 Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
404 Type::getInt32Ty(Context),
405 NULL);
Eli Benderskya66a1852012-01-16 08:56:09 +0000406
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000407 // Reset errno to zero on entry to main.
408 errno = 0;
Eli Benderskya66a1852012-01-16 08:56:09 +0000409
Andrew Kaylorf1881562013-10-02 18:04:40 +0000410 int Result;
411
Andrew Kaylor257a0092012-11-27 19:49:00 +0000412 if (!RemoteMCJIT) {
Andrew Kaylorf1881562013-10-02 18:04:40 +0000413 // Run static constructors.
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000414 if (UseMCJIT && !ForceInterpreter) {
415 // Give MCJIT a chance to apply relocations and set page permissions.
416 EE->finalizeObject();
417 }
418 EE->runStaticConstructorsDestructors(false);
Evan Chengc290a5b2008-04-22 06:51:41 +0000419
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000420 if (!UseMCJIT && NoLazyCompilation) {
421 for (Module::iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) {
422 Function *Fn = &*I;
423 if (Fn != EntryFn && !Fn->isDeclaration())
424 EE->getPointerToFunction(Fn);
425 }
Evan Chengc290a5b2008-04-22 06:51:41 +0000426 }
Evan Chengc290a5b2008-04-22 06:51:41 +0000427
Andrew Kaylorf1881562013-10-02 18:04:40 +0000428 // Trigger compilation separately so code regions that need to be
429 // invalidated will be known.
430 (void)EE->getPointerToFunction(EntryFn);
431 // Clear instruction cache before code will be executed.
432 if (RTDyldMM)
433 static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
434
435 // Run main.
436 Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
437
438 // Run static destructors.
439 EE->runStaticConstructorsDestructors(true);
440
441 // If the program didn't call exit explicitly, we should call it now.
442 // This ensures that any atexit handlers get called correctly.
443 if (Function *ExitF = dyn_cast<Function>(Exit)) {
444 std::vector<GenericValue> Args;
445 GenericValue ResultGV;
446 ResultGV.IntVal = APInt(32, Result);
447 Args.push_back(ResultGV);
448 EE->runFunction(ExitF, Args);
449 errs() << "ERROR: exit(" << Result << ") returned!\n";
450 abort();
451 } else {
452 errs() << "ERROR: exit defined with wrong prototype!\n";
453 abort();
454 }
455 } else {
456 // else == "if (RemoteMCJIT)"
457
458 // Remote target MCJIT doesn't (yet) support static constructors. No reason
459 // it couldn't. This is a limitation of the LLI implemantation, not the
460 // MCJIT itself. FIXME.
461 //
Andrew Kaylorb868e912013-10-04 00:49:38 +0000462 RemoteMemoryManager *MM = static_cast<RemoteMemoryManager*>(RTDyldMM);
Jim Grosbach706f03a2012-09-05 16:50:34 +0000463 // Everything is prepared now, so lay out our program for the target
464 // address space, assign the section addresses to resolve any relocations,
465 // and send it to the target.
Andrew Kaylor0ab5c6c2013-10-02 17:12:36 +0000466
467 OwningPtr<RemoteTarget> Target;
468 if (!MCJITRemoteProcess.empty()) { // Remote execution on a child process
469 if (!RemoteTarget::hostSupportsExternalRemoteTarget()) {
470 errs() << "Warning: host does not support external remote targets.\n"
471 << " Defaulting to simulated remote execution\n";
472 Target.reset(RemoteTarget::createRemoteTarget());
473 } else {
474 std::string ChildEXE = sys::FindProgramByName(MCJITRemoteProcess);
475 if (ChildEXE == "") {
476 errs() << "Unable to find child target: '\''" << MCJITRemoteProcess << "\'\n";
477 return -1;
478 }
Richard Smithd34a4d62013-10-02 21:33:12 +0000479 Target.reset(RemoteTarget::createExternalRemoteTarget(ChildEXE));
Andrew Kaylor0ab5c6c2013-10-02 17:12:36 +0000480 }
481 } else {
482 // No child process name provided, use simulated remote execution.
483 Target.reset(RemoteTarget::createRemoteTarget());
484 }
485
Andrew Kaylorb868e912013-10-04 00:49:38 +0000486 // Give the memory manager a pointer to our remote target interface object.
487 MM->setRemoteTarget(Target.get());
488
489 // Create the remote target.
Andrew Kaylor0ab5c6c2013-10-02 17:12:36 +0000490 Target->create();
Jim Grosbach5da959d2012-08-28 23:22:30 +0000491
Andrew Kaylorb868e912013-10-04 00:49:38 +0000492// FIXME: Don't commit like this. I don't think these calls are necessary.
493#if 0
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000494 // Trigger compilation.
495 EE->generateCodeForModule(Mod);
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000496
Andrew Kaylorb868e912013-10-04 00:49:38 +0000497 // Get everything ready to execute.
498 EE->finalizeModule(Mod);
499#endif
Eli Benderskya66a1852012-01-16 08:56:09 +0000500
Jim Grosbach706f03a2012-09-05 16:50:34 +0000501 // Since we're executing in a (at least simulated) remote address space,
502 // we can't use the ExecutionEngine::runFunctionAsMain(). We have to
503 // grab the function address directly here and tell the remote target
504 // to execute the function.
Andrew Kaylorb868e912013-10-04 00:49:38 +0000505 //
506 // Our memory manager will map generated code into the remote address
507 // space as it is loaded and copy the bits over during the finalizeMemory
508 // operation.
509 //
Jim Grosbach706f03a2012-09-05 16:50:34 +0000510 // FIXME: argv and envp handling.
Andrew Kaylor0ab5c6c2013-10-02 17:12:36 +0000511 uint64_t Entry = EE->getFunctionAddress(EntryFn->getName().str());
Jim Grosbach706f03a2012-09-05 16:50:34 +0000512
Tim Northovera73a6142013-05-19 09:55:06 +0000513 DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"
514 << format("%llx", Entry) << "\n");
Jim Grosbach706f03a2012-09-05 16:50:34 +0000515
Andrew Kaylor0ab5c6c2013-10-02 17:12:36 +0000516 if (Target->executeCode(Entry, Result))
517 errs() << "ERROR: " << Target->getErrorMsg() << "\n";
Jim Grosbach706f03a2012-09-05 16:50:34 +0000518
Andrew Kaylorf1881562013-10-02 18:04:40 +0000519 // Like static constructors, the remote target MCJIT support doesn't handle
520 // this yet. It could. FIXME.
521
522 // Stop the remote target
Andrew Kaylor0ab5c6c2013-10-02 17:12:36 +0000523 Target->stop();
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000524 }
Jim Grosbach706f03a2012-09-05 16:50:34 +0000525
Jim Grosbach706f03a2012-09-05 16:50:34 +0000526 return Result;
Chris Lattner92101ac2001-08-23 17:05:04 +0000527}