blob: 8d74b2326d73f12c50d92d83707d7c56c633a0dd [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"
Jim Grosbach706f03a2012-09-05 16:50:34 +000018#include "RecordingMemoryManager.h"
19#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"
44#include "llvm/Support/Signals.h"
Chandler Carruth7fc162f2013-03-26 02:25:37 +000045#include "llvm/Support/SourceMgr.h"
Evan Cheng3e74d6f2011-08-24 18:08:43 +000046#include "llvm/Support/TargetSelect.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000047#include "llvm/Support/raw_ostream.h"
Daniel Maleae16e6872013-06-28 19:11:40 +000048#include "llvm/Transforms/Instrumentation.h"
Chris Lattner02040322007-04-27 17:02:33 +000049#include <cerrno>
NAKAMURA Takumia13d14a2010-10-22 14:53:59 +000050
51#ifdef __CYGWIN__
52#include <cygwin/version.h>
53#if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
54#define DO_NOTHING_ATEXIT 1
55#endif
56#endif
57
Brian Gaeked0fde302003-11-11 22:41:34 +000058using namespace llvm;
59
Chris Lattnerfe11a972002-12-23 23:59:41 +000060namespace {
61 cl::opt<std::string>
Gabor Greifa99be512007-07-05 17:07:56 +000062 InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
Chris Lattner5ff62e92002-07-22 02:10:13 +000063
Chris Lattnerfe11a972002-12-23 23:59:41 +000064 cl::list<std::string>
65 InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
Chris Lattner5ff62e92002-07-22 02:10:13 +000066
Chris Lattnerfe11a972002-12-23 23:59:41 +000067 cl::opt<bool> ForceInterpreter("force-interpreter",
Misha Brukman3d8a54d2003-09-25 18:10:34 +000068 cl::desc("Force interpretation: disable JIT"),
69 cl::init(false));
Evan Chenge1a4eda2008-08-08 08:12:06 +000070
Daniel Dunbar6d135972010-11-17 16:06:37 +000071 cl::opt<bool> UseMCJIT(
72 "use-mcjit", cl::desc("Enable use of the MC-based JIT (if available)"),
73 cl::init(false));
74
Daniel Maleae16e6872013-06-28 19:11:40 +000075 cl::opt<bool> DebugIR(
76 "debug-ir", cl::desc("Generate debug information to allow debugging IR."),
77 cl::init(false));
78
Jim Grosbach706f03a2012-09-05 16:50:34 +000079 // The MCJIT supports building for a target address space separate from
80 // the JIT compilation process. Use a forked process and a copying
81 // memory manager with IPC to execute using this functionality.
82 cl::opt<bool> RemoteMCJIT("remote-mcjit",
83 cl::desc("Execute MCJIT'ed code in a separate process."),
84 cl::init(false));
85
Evan Cheng712e80e2009-05-04 23:05:19 +000086 // Determine optimization level.
87 cl::opt<char>
88 OptLevel("O",
89 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
90 "(default = '-O2')"),
91 cl::Prefix,
92 cl::ZeroOrMore,
93 cl::init(' '));
Evan Chenge1a4eda2008-08-08 08:12:06 +000094
Chris Lattner3015e602005-12-16 05:00:21 +000095 cl::opt<std::string>
Chris Lattner60844d42005-12-16 05:19:18 +000096 TargetTriple("mtriple", cl::desc("Override target triple for module"));
Evan Chengec740e32008-11-05 23:21:52 +000097
98 cl::opt<std::string>
Jeffrey Yasskin46882612010-02-05 16:19:36 +000099 MArch("march",
100 cl::desc("Architecture to generate assembly for (see --version)"));
101
102 cl::opt<std::string>
103 MCPU("mcpu",
104 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
105 cl::value_desc("cpu-name"),
106 cl::init(""));
107
108 cl::list<std::string>
109 MAttrs("mattr",
110 cl::CommaSeparated,
111 cl::desc("Target specific attributes (-mattr=help for details)"),
112 cl::value_desc("a1,+a2,-a3,..."));
113
114 cl::opt<std::string>
Evan Chengec740e32008-11-05 23:21:52 +0000115 EntryFunc("entry-function",
116 cl::desc("Specify the entry function (default = 'main') "
117 "of the executable"),
118 cl::value_desc("function"),
119 cl::init("main"));
Eli Benderskya66a1852012-01-16 08:56:09 +0000120
Chris Lattnere69671d2003-10-28 22:51:44 +0000121 cl::opt<std::string>
122 FakeArgv0("fake-argv0",
123 cl::desc("Override the 'argv[0]' value passed into the executing"
124 " program"), cl::value_desc("executable"));
Eli Benderskya66a1852012-01-16 08:56:09 +0000125
Chris Lattner43f249a2006-09-14 06:17:09 +0000126 cl::opt<bool>
127 DisableCoreFiles("disable-core-files", cl::Hidden,
128 cl::desc("Disable emission of core files if possible"));
Evan Chengc290a5b2008-04-22 06:51:41 +0000129
130 cl::opt<bool>
Evan Cheng03dace82008-05-21 18:20:21 +0000131 NoLazyCompilation("disable-lazy-compilation",
Evan Chengc290a5b2008-04-22 06:51:41 +0000132 cl::desc("Disable JIT lazy compilation"),
133 cl::init(false));
Evan Cheng43966132011-07-19 06:37:02 +0000134
135 cl::opt<Reloc::Model>
136 RelocModel("relocation-model",
137 cl::desc("Choose relocation model"),
138 cl::init(Reloc::Default),
139 cl::values(
140 clEnumValN(Reloc::Default, "default",
141 "Target default relocation model"),
142 clEnumValN(Reloc::Static, "static",
143 "Non-relocatable code"),
144 clEnumValN(Reloc::PIC_, "pic",
145 "Fully relocatable, position independent code"),
146 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
147 "Relocatable external references, non-relocatable code"),
148 clEnumValEnd));
Evan Cheng34ad6db2011-07-20 07:51:56 +0000149
150 cl::opt<llvm::CodeModel::Model>
151 CMModel("code-model",
152 cl::desc("Choose code model"),
153 cl::init(CodeModel::JITDefault),
154 cl::values(clEnumValN(CodeModel::JITDefault, "default",
155 "Target default JIT code model"),
156 clEnumValN(CodeModel::Small, "small",
157 "Small code model"),
158 clEnumValN(CodeModel::Kernel, "kernel",
159 "Kernel code model"),
160 clEnumValN(CodeModel::Medium, "medium",
161 "Medium code model"),
162 clEnumValN(CodeModel::Large, "large",
163 "Large code model"),
164 clEnumValEnd));
165
Nick Lewycky9a148412012-04-18 08:34:12 +0000166 cl::opt<bool>
Tim Northover77b4c692012-10-12 09:55:13 +0000167 GenerateSoftFloatCalls("soft-float",
168 cl::desc("Generate software floating point library calls"),
169 cl::init(false));
170
171 cl::opt<llvm::FloatABI::ABIType>
172 FloatABIForCalls("float-abi",
173 cl::desc("Choose float ABI type"),
174 cl::init(FloatABI::Default),
175 cl::values(
176 clEnumValN(FloatABI::Default, "default",
177 "Target default float ABI type"),
178 clEnumValN(FloatABI::Soft, "soft",
179 "Soft float ABI (implied by -soft-float)"),
180 clEnumValN(FloatABI::Hard, "hard",
181 "Hard float ABI (uses FP registers)"),
182 clEnumValEnd));
183 cl::opt<bool>
Nick Lewycky9a148412012-04-18 08:34:12 +0000184// In debug builds, make this default to true.
185#ifdef NDEBUG
186#define EMIT_DEBUG false
187#else
188#define EMIT_DEBUG true
189#endif
190 EmitJitDebugInfo("jit-emit-debug",
191 cl::desc("Emit debug information to debugger"),
192 cl::init(EMIT_DEBUG));
193#undef EMIT_DEBUG
194
195 static cl::opt<bool>
196 EmitJitDebugInfoToDisk("jit-emit-debug-to-disk",
197 cl::Hidden,
198 cl::desc("Emit debug info objfiles to disk"),
199 cl::init(false));
Chris Lattnerfe11a972002-12-23 23:59:41 +0000200}
Chris Lattner43e3f7c2001-10-27 08:43:52 +0000201
Reid Spencerf70d6772007-03-03 18:21:44 +0000202static ExecutionEngine *EE = 0;
203
204static void do_shutdown() {
NAKAMURA Takumia13d14a2010-10-22 14:53:59 +0000205 // Cygwin-1.5 invokes DLL's dtors before atexit handler.
206#ifndef DO_NOTHING_ATEXIT
Reid Spencerf70d6772007-03-03 18:21:44 +0000207 delete EE;
208 llvm_shutdown();
NAKAMURA Takumia13d14a2010-10-22 14:53:59 +0000209#endif
Reid Spencerf70d6772007-03-03 18:21:44 +0000210}
211
Jim Grosbach706f03a2012-09-05 16:50:34 +0000212void layoutRemoteTargetMemory(RemoteTarget *T, RecordingMemoryManager *JMM) {
213 // Lay out our sections in order, with all the code sections first, then
214 // all the data sections.
215 uint64_t CurOffset = 0;
216 unsigned MaxAlign = T->getPageAlignment();
217 SmallVector<std::pair<const void*, uint64_t>, 16> Offsets;
218 SmallVector<unsigned, 16> Sizes;
219 for (RecordingMemoryManager::const_code_iterator I = JMM->code_begin(),
220 E = JMM->code_end();
221 I != E; ++I) {
222 DEBUG(dbgs() << "code region: size " << I->first.size()
223 << ", alignment " << I->second << "\n");
224 // Align the current offset up to whatever is needed for the next
225 // section.
226 unsigned Align = I->second;
227 CurOffset = (CurOffset + Align - 1) / Align * Align;
228 // Save off the address of the new section and allocate its space.
229 Offsets.push_back(std::pair<const void*,uint64_t>(I->first.base(), CurOffset));
230 Sizes.push_back(I->first.size());
231 CurOffset += I->first.size();
232 }
233 // Adjust to keep code and data aligned on seperate pages.
234 CurOffset = (CurOffset + MaxAlign - 1) / MaxAlign * MaxAlign;
235 unsigned FirstDataIndex = Offsets.size();
236 for (RecordingMemoryManager::const_data_iterator I = JMM->data_begin(),
237 E = JMM->data_end();
238 I != E; ++I) {
239 DEBUG(dbgs() << "data region: size " << I->first.size()
240 << ", alignment " << I->second << "\n");
241 // Align the current offset up to whatever is needed for the next
242 // section.
243 unsigned Align = I->second;
244 CurOffset = (CurOffset + Align - 1) / Align * Align;
245 // Save off the address of the new section and allocate its space.
246 Offsets.push_back(std::pair<const void*,uint64_t>(I->first.base(), CurOffset));
247 Sizes.push_back(I->first.size());
248 CurOffset += I->first.size();
249 }
250
251 // Allocate space in the remote target.
252 uint64_t RemoteAddr;
253 if (T->allocateSpace(CurOffset, MaxAlign, RemoteAddr))
254 report_fatal_error(T->getErrorMsg());
255 // Map the section addresses so relocations will get updated in the local
256 // copies of the sections.
257 for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
258 uint64_t Addr = RemoteAddr + Offsets[i].second;
259 EE->mapSectionAddress(const_cast<void*>(Offsets[i].first), Addr);
260
261 DEBUG(dbgs() << " Mapping local: " << Offsets[i].first
Tim Northovera73a6142013-05-19 09:55:06 +0000262 << " to remote: 0x" << format("%llx", Addr) << "\n");
Jim Grosbach706f03a2012-09-05 16:50:34 +0000263
264 }
Andrew Kaylor28989882012-11-05 20:57:16 +0000265
266 // Trigger application of relocations
267 EE->finalizeObject();
268
Jim Grosbach706f03a2012-09-05 16:50:34 +0000269 // Now load it all to the target.
270 for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
271 uint64_t Addr = RemoteAddr + Offsets[i].second;
272
273 if (i < FirstDataIndex) {
274 T->loadCode(Addr, Offsets[i].first, Sizes[i]);
275
276 DEBUG(dbgs() << " loading code: " << Offsets[i].first
Tim Northovera73a6142013-05-19 09:55:06 +0000277 << " to remote: 0x" << format("%llx", Addr) << "\n");
Jim Grosbach706f03a2012-09-05 16:50:34 +0000278 } else {
279 T->loadData(Addr, Offsets[i].first, Sizes[i]);
280
281 DEBUG(dbgs() << " loading data: " << Offsets[i].first
Tim Northovera73a6142013-05-19 09:55:06 +0000282 << " to remote: 0x" << format("%llx", Addr) << "\n");
Jim Grosbach706f03a2012-09-05 16:50:34 +0000283 }
284
285 }
286}
287
Chris Lattner92101ac2001-08-23 17:05:04 +0000288//===----------------------------------------------------------------------===//
Chris Lattner92101ac2001-08-23 17:05:04 +0000289// main Driver function
290//
Misha Brukmanc4fb6fd2003-10-14 21:39:53 +0000291int main(int argc, char **argv, char * const *envp) {
Chris Lattnercc14d252009-03-06 05:34:10 +0000292 sys::PrintStackTraceOnErrorSignal();
293 PrettyStackTraceProgram X(argc, argv);
Eli Benderskya66a1852012-01-16 08:56:09 +0000294
Owen Anderson0d7c6952009-07-15 22:16:10 +0000295 LLVMContext &Context = getGlobalContext();
Reid Spencerf70d6772007-03-03 18:21:44 +0000296 atexit(do_shutdown); // Call llvm_shutdown() on exit.
Daniel Dunbar494d6632009-07-16 02:04:54 +0000297
298 // If we have a native target, initialize it to ensure it is linked in and
299 // usable by the JIT.
300 InitializeNativeTarget();
Jim Grosbach31649e62011-03-18 22:48:41 +0000301 InitializeNativeTargetAsmPrinter();
Jim Grosbach68372322012-11-05 19:06:05 +0000302 InitializeNativeTargetAsmParser();
Daniel Dunbar494d6632009-07-16 02:04:54 +0000303
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000304 cl::ParseCommandLineOptions(argc, argv,
Dan Gohman82a13c92007-10-08 15:45:12 +0000305 "llvm interpreter & dynamic compiler\n");
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000306
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000307 // If the user doesn't want core files, disable them.
308 if (DisableCoreFiles)
309 sys::Process::PreventCoreFiles();
Eli Benderskya66a1852012-01-16 08:56:09 +0000310
Gabor Greifa99be512007-07-05 17:07:56 +0000311 // Load the bitcode...
Daniel Dunbar46a27162010-11-13 00:28:01 +0000312 SMDiagnostic Err;
313 Module *Mod = ParseIRFile(InputFile, Err, Context);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000314 if (!Mod) {
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000315 Err.print(argv[0], errs());
Daniel Dunbar46a27162010-11-13 00:28:01 +0000316 return 1;
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000317 }
318
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000319 // If not jitting lazily, load the whole bitcode file eagerly too.
Daniel Dunbar46a27162010-11-13 00:28:01 +0000320 std::string ErrorMsg;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000321 if (NoLazyCompilation) {
322 if (Mod->MaterializeAllPermanently(&ErrorMsg)) {
323 errs() << argv[0] << ": bitcode didn't read correctly.\n";
324 errs() << "Reason: " << ErrorMsg << "\n";
325 exit(1);
326 }
Evan Chengc290a5b2008-04-22 06:51:41 +0000327 }
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000328
Daniel Maleae16e6872013-06-28 19:11:40 +0000329 if (DebugIR) {
330 if (!UseMCJIT) {
331 errs() << "warning: -debug-ir used without -use-mcjit. Only partial debug"
332 << " information will be emitted by the non-MC JIT engine. To see full"
333 << " source debug information, enable the flag '-use-mcjit'.\n";
334
335 }
336 ModulePass *DebugIRPass = createDebugIRPass();
337 DebugIRPass->runOnModule(*Mod);
338 }
339
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000340 EngineBuilder builder(Mod);
Jeffrey Yasskin46882612010-02-05 16:19:36 +0000341 builder.setMArch(MArch);
342 builder.setMCPU(MCPU);
343 builder.setMAttrs(MAttrs);
Evan Cheng43966132011-07-19 06:37:02 +0000344 builder.setRelocationModel(RelocModel);
Evan Cheng34ad6db2011-07-20 07:51:56 +0000345 builder.setCodeModel(CMModel);
Daniel Dunbar4dc31362009-07-18 08:07:13 +0000346 builder.setErrorStr(&ErrorMsg);
347 builder.setEngineKind(ForceInterpreter
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000348 ? EngineKind::Interpreter
349 : EngineKind::JIT);
350
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000351 // If we are supposed to override the target triple, do so now.
352 if (!TargetTriple.empty())
Duncan Sands75ebbce2010-08-28 01:30:02 +0000353 Mod->setTargetTriple(Triple::normalize(TargetTriple));
Evan Chengc290a5b2008-04-22 06:51:41 +0000354
Eli Benderskya66a1852012-01-16 08:56:09 +0000355 // Enable MCJIT if desired.
Filip Pizlo13a3cf12013-05-14 19:29:00 +0000356 RTDyldMemoryManager *RTDyldMM = 0;
Eli Benderskya66a1852012-01-16 08:56:09 +0000357 if (UseMCJIT && !ForceInterpreter) {
Daniel Dunbar6d135972010-11-17 16:06:37 +0000358 builder.setUseMCJIT(true);
Jim Grosbach706f03a2012-09-05 16:50:34 +0000359 if (RemoteMCJIT)
Filip Pizlo13a3cf12013-05-14 19:29:00 +0000360 RTDyldMM = new RecordingMemoryManager();
Jim Grosbach706f03a2012-09-05 16:50:34 +0000361 else
Filip Pizlo13a3cf12013-05-14 19:29:00 +0000362 RTDyldMM = new SectionMemoryManager();
363 builder.setMCJITMemoryManager(RTDyldMM);
Benjamin Kramer65145512012-05-20 17:24:08 +0000364 } else {
Jim Grosbach706f03a2012-09-05 16:50:34 +0000365 if (RemoteMCJIT) {
366 errs() << "error: Remote process execution requires -use-mcjit\n";
367 exit(1);
368 }
Benjamin Kramer65145512012-05-20 17:24:08 +0000369 builder.setJITMemoryManager(ForceInterpreter ? 0 :
370 JITMemoryManager::CreateDefaultMemManager());
Eli Benderskya66a1852012-01-16 08:56:09 +0000371 }
Daniel Dunbar6d135972010-11-17 16:06:37 +0000372
Evan Cheng712e80e2009-05-04 23:05:19 +0000373 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
374 switch (OptLevel) {
375 default:
Dan Gohman65f57c22009-07-15 16:35:29 +0000376 errs() << argv[0] << ": invalid optimization level.\n";
Evan Cheng712e80e2009-05-04 23:05:19 +0000377 return 1;
378 case ' ': break;
379 case '0': OLvl = CodeGenOpt::None; break;
Evan Chengbf57b522009-10-16 21:02:20 +0000380 case '1': OLvl = CodeGenOpt::Less; break;
Evan Cheng712e80e2009-05-04 23:05:19 +0000381 case '2': OLvl = CodeGenOpt::Default; break;
382 case '3': OLvl = CodeGenOpt::Aggressive; break;
383 }
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000384 builder.setOptLevel(OLvl);
385
Tim Northover77b4c692012-10-12 09:55:13 +0000386 TargetOptions Options;
387 Options.UseSoftFloat = GenerateSoftFloatCalls;
388 if (FloatABIForCalls != FloatABI::Default)
389 Options.FloatABIType = FloatABIForCalls;
390 if (GenerateSoftFloatCalls)
391 FloatABIForCalls = FloatABI::Soft;
392
Jim Grosbach706f03a2012-09-05 16:50:34 +0000393 // Remote target execution doesn't handle EH or debug registration.
394 if (!RemoteMCJIT) {
Jim Grosbach706f03a2012-09-05 16:50:34 +0000395 Options.JITEmitDebugInfo = EmitJitDebugInfo;
396 Options.JITEmitDebugInfoToDisk = EmitJitDebugInfoToDisk;
Jim Grosbach706f03a2012-09-05 16:50:34 +0000397 }
Nick Lewycky9a148412012-04-18 08:34:12 +0000398
Tim Northover77b4c692012-10-12 09:55:13 +0000399 builder.setTargetOptions(Options);
400
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000401 EE = builder.create();
Chris Lattnerfd15bee2009-07-07 18:31:09 +0000402 if (!EE) {
403 if (!ErrorMsg.empty())
Dan Gohman65f57c22009-07-15 16:35:29 +0000404 errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n";
Chris Lattnerfd15bee2009-07-07 18:31:09 +0000405 else
Dan Gohman65f57c22009-07-15 16:35:29 +0000406 errs() << argv[0] << ": unknown error creating EE!\n";
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000407 exit(1);
408 }
409
Eli Bendersky61b18512012-03-13 08:33:15 +0000410 // The following functions have no effect if their respective profiling
411 // support wasn't enabled in the build configuration.
412 EE->RegisterJITEventListener(
413 JITEventListener::createOProfileJITEventListener());
414 EE->RegisterJITEventListener(
415 JITEventListener::createIntelJITEventListener());
Jeffrey Yasskindf5a7da2009-06-25 02:04:04 +0000416
Jim Grosbach706f03a2012-09-05 16:50:34 +0000417 if (!NoLazyCompilation && RemoteMCJIT) {
418 errs() << "warning: remote mcjit does not support lazy compilation\n";
419 NoLazyCompilation = true;
420 }
Jeffrey Yasskin18fec732009-10-27 22:39:42 +0000421 EE->DisableLazyCompilation(NoLazyCompilation);
Evan Chengc290a5b2008-04-22 06:51:41 +0000422
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000423 // If the user specifically requested an argv[0] to pass into the program,
424 // do it now.
425 if (!FakeArgv0.empty()) {
426 InputFile = FakeArgv0;
427 } else {
428 // Otherwise, if there is a .bc suffix on the executable strip it off, it
429 // might confuse the program.
Benjamin Kramer3bb37e92010-04-15 11:33:14 +0000430 if (StringRef(InputFile).endswith(".bc"))
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000431 InputFile.erase(InputFile.length() - 3);
432 }
433
434 // Add the module's name to the start of the vector of arguments to main().
435 InputArgv.insert(InputArgv.begin(), InputFile);
436
437 // Call the main function from M as if its signature were:
438 // int main (int argc, char **argv, const char **envp)
439 // using the contents of Args to determine argc & argv, and the contents of
440 // EnvVars to determine envp.
441 //
Evan Chengec740e32008-11-05 23:21:52 +0000442 Function *EntryFn = Mod->getFunction(EntryFunc);
443 if (!EntryFn) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000444 errs() << '\'' << EntryFunc << "\' function not found in module.\n";
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000445 return -1;
446 }
447
Eli Benderskya66a1852012-01-16 08:56:09 +0000448 // If the program doesn't explicitly call exit, we will need the Exit
449 // function later on to make an explicit call, so get the function now.
Owen Anderson1d0be152009-08-13 21:58:54 +0000450 Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
451 Type::getInt32Ty(Context),
452 NULL);
Eli Benderskya66a1852012-01-16 08:56:09 +0000453
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000454 // Reset errno to zero on entry to main.
455 errno = 0;
Eli Benderskya66a1852012-01-16 08:56:09 +0000456
Jim Grosbach706f03a2012-09-05 16:50:34 +0000457 // Remote target MCJIT doesn't (yet) support static constructors. No reason
458 // it couldn't. This is a limitation of the LLI implemantation, not the
459 // MCJIT itself. FIXME.
460 //
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000461 // Run static constructors.
Andrew Kaylor257a0092012-11-27 19:49:00 +0000462 if (!RemoteMCJIT) {
463 if (UseMCJIT && !ForceInterpreter) {
464 // Give MCJIT a chance to apply relocations and set page permissions.
465 EE->finalizeObject();
466 }
467 EE->runStaticConstructorsDestructors(false);
468 }
Evan Chengc290a5b2008-04-22 06:51:41 +0000469
470 if (NoLazyCompilation) {
471 for (Module::iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) {
472 Function *Fn = &*I;
Evan Chengec740e32008-11-05 23:21:52 +0000473 if (Fn != EntryFn && !Fn->isDeclaration())
Evan Chengc290a5b2008-04-22 06:51:41 +0000474 EE->getPointerToFunction(Fn);
475 }
476 }
477
Jim Grosbach706f03a2012-09-05 16:50:34 +0000478 int Result;
479 if (RemoteMCJIT) {
Filip Pizlo13a3cf12013-05-14 19:29:00 +0000480 RecordingMemoryManager *MM = static_cast<RecordingMemoryManager*>(RTDyldMM);
Jim Grosbach706f03a2012-09-05 16:50:34 +0000481 // Everything is prepared now, so lay out our program for the target
482 // address space, assign the section addresses to resolve any relocations,
483 // and send it to the target.
484 RemoteTarget Target;
485 Target.create();
Jim Grosbach5da959d2012-08-28 23:22:30 +0000486
Jim Grosbach706f03a2012-09-05 16:50:34 +0000487 // Ask for a pointer to the entry function. This triggers the actual
488 // compilation.
489 (void)EE->getPointerToFunction(EntryFn);
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000490
Jim Grosbach706f03a2012-09-05 16:50:34 +0000491 // Enough has been compiled to execute the entry function now, so
492 // layout the target memory.
493 layoutRemoteTargetMemory(&Target, MM);
Eli Benderskya66a1852012-01-16 08:56:09 +0000494
Jim Grosbach706f03a2012-09-05 16:50:34 +0000495 // Since we're executing in a (at least simulated) remote address space,
496 // we can't use the ExecutionEngine::runFunctionAsMain(). We have to
497 // grab the function address directly here and tell the remote target
498 // to execute the function.
499 // FIXME: argv and envp handling.
500 uint64_t Entry = (uint64_t)EE->getPointerToFunction(EntryFn);
501
Tim Northovera73a6142013-05-19 09:55:06 +0000502 DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"
503 << format("%llx", Entry) << "\n");
Jim Grosbach706f03a2012-09-05 16:50:34 +0000504
505 if (Target.executeCode(Entry, Result))
506 errs() << "ERROR: " << Target.getErrorMsg() << "\n";
507
508 Target.stop();
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000509 } else {
Tim Northovera668b462012-09-20 08:46:30 +0000510 // Trigger compilation separately so code regions that need to be
511 // invalidated will be known.
512 (void)EE->getPointerToFunction(EntryFn);
Jim Grosbach706f03a2012-09-05 16:50:34 +0000513 // Clear instruction cache before code will be executed.
Filip Pizlo13a3cf12013-05-14 19:29:00 +0000514 if (RTDyldMM)
515 static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
Jim Grosbach706f03a2012-09-05 16:50:34 +0000516
517 // Run main.
518 Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000519 }
Jim Grosbach706f03a2012-09-05 16:50:34 +0000520
521 // Like static constructors, the remote target MCJIT support doesn't handle
522 // this yet. It could. FIXME.
523 if (!RemoteMCJIT) {
524 // Run static destructors.
525 EE->runStaticConstructorsDestructors(true);
526
527 // If the program didn't call exit explicitly, we should call it now.
528 // This ensures that any atexit handlers get called correctly.
529 if (Function *ExitF = dyn_cast<Function>(Exit)) {
530 std::vector<GenericValue> Args;
531 GenericValue ResultGV;
532 ResultGV.IntVal = APInt(32, Result);
533 Args.push_back(ResultGV);
534 EE->runFunction(ExitF, Args);
535 errs() << "ERROR: exit(" << Result << ") returned!\n";
536 abort();
537 } else {
538 errs() << "ERROR: exit defined with wrong prototype!\n";
539 abort();
540 }
541 }
542 return Result;
Chris Lattner92101ac2001-08-23 17:05:04 +0000543}