llvm.org GIT mirror llvm / 2d6d585
Adding MCJIT and MemoryBuffer unit tests Patch by Daniel Malea. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@165246 91177308-0d34-0410-b5e6-96231b3b80d8 Andrew Kaylor 8 years ago
11 changed file(s) with 869 addition(s) and 1 deletion(s). Raw diff Collapse all Expand all
66 )
77
88 add_subdirectory(JIT)
9 add_subdirectory(MCJIT)
0 set(LLVM_LINK_COMPONENTS
1 asmparser
2 bitreader
3 bitwriter
4 mcjit
5 jit
6 nativecodegen
7 )
8
9 set(MCJITTestsSources
10 MCJITTest.cpp
11 SectionMemoryManager.cpp
12 )
13
14 if(MSVC)
15 list(APPEND MCJITTestsSources MCJITTests.def)
16 endif()
17
18 add_llvm_unittest(MCJITTests
19 ${MCJITTestsSources}
20 )
21
22 if(MINGW OR CYGWIN)
23 set_property(TARGET MCJITTests PROPERTY LINK_FLAGS -Wl,--export-all-symbols)
24 endif()
0 //===- MCJITTest.cpp - Unit tests for the MCJIT ---------------------------===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This test suite verifies basic MCJIT functionality such as making function
10 // calls, using global variables, and compiling multpile modules.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/ExecutionEngine/MCJIT.h"
15 #include "MCJITTestBase.h"
16 #include "SectionMemoryManager.h"
17 #include "gtest/gtest.h"
18
19 using namespace llvm;
20
21 class MCJITTest : public testing::Test, public MCJITTestBase {
22 protected:
23
24 virtual void SetUp() {
25 M.reset(createEmptyModule("
"));
26 }
27 };
28
29 namespace {
30
31 // FIXME: In order to JIT an empty module, there needs to be
32 // an interface to ExecutionEngine that forces compilation but
33 // does require retrieval of a pointer to a function/global.
34 /*
35 TEST_F(MCJITTest, empty_module) {
36 createJIT(M.take());
37 //EXPECT_NE(0, TheJIT->getObjectImage())
38 // << "Unable to generate executable loaded object image";
39 }
40 */
41
42 TEST_F(MCJITTest, global_variable) {
43 SKIP_UNSUPPORTED_PLATFORM;
44
45 int initialValue = 5;
46 GlobalValue *Global = insertGlobalInt32(M.get(), "test_global", initialValue);
47 createJIT(M.take());
48 void *globalPtr = TheJIT->getPointerToGlobal(Global);
49 EXPECT_TRUE(0 != globalPtr)
50 << "Unable to get pointer to global value from JIT";
51
52 EXPECT_EQ(initialValue, *(int32_t*)globalPtr)
53 << "Unexpected initial value of global";
54 }
55
56 TEST_F(MCJITTest, add_function) {
57 SKIP_UNSUPPORTED_PLATFORM;
58
59 Function *F = insertAddFunction(M.get());
60 createJIT(M.take());
61 void *addPtr = TheJIT->getPointerToFunction(F);
62 EXPECT_TRUE(0 != addPtr)
63 << "Unable to get pointer to function from JIT";
64
65 int (*AddPtrTy)(int, int) = (int(*)(int, int))(intptr_t)addPtr;
66 EXPECT_EQ(0, AddPtrTy(0, 0));
67 EXPECT_EQ(3, AddPtrTy(1, 2));
68 EXPECT_EQ(-5, AddPtrTy(-2, -3));
69 }
70
71 TEST_F(MCJITTest, run_main) {
72 SKIP_UNSUPPORTED_PLATFORM;
73
74 int rc = 6;
75 Function *Main = insertMainFunction(M.get(), 6);
76 createJIT(M.take());
77 void *vPtr = TheJIT->getPointerToFunction(Main);
78 EXPECT_TRUE(0 != vPtr)
79 << "Unable to get pointer to main() from JIT";
80
81 int (*FuncPtr)(void) = (int(*)(void))(intptr_t)vPtr;
82 int returnCode = FuncPtr();
83 EXPECT_EQ(returnCode, rc);
84 }
85
86 TEST_F(MCJITTest, return_global) {
87 SKIP_UNSUPPORTED_PLATFORM;
88
89 int32_t initialNum = 7;
90 GlobalVariable *GV = insertGlobalInt32(M.get(), "myglob", initialNum);
91
92 Function *ReturnGlobal = startFunction(M.get(),
93 "ReturnGlobal");
94 Value *ReadGlobal = Builder.CreateLoad(GV);
95 endFunctionWithRet(ReturnGlobal, ReadGlobal);
96
97 createJIT(M.take());
98 void *rgvPtr = TheJIT->getPointerToFunction(ReturnGlobal);
99 EXPECT_TRUE(0 != rgvPtr);
100
101 int32_t(*FuncPtr)(void) = (int32_t(*)(void))(intptr_t)rgvPtr;
102 EXPECT_EQ(initialNum, FuncPtr())
103 << "Invalid value for global returned from JITted function";
104 }
105
106 // FIXME: This case fails due to a bug with getPointerToGlobal().
107 // The bug is due to MCJIT not having an implementation of getPointerToGlobal()
108 // which results in falling back on the ExecutionEngine implementation that
109 // allocates a new memory block for the global instead of using the same
110 // global variable that is emitted by MCJIT. Hence, the pointer (gvPtr below)
111 // has the correct initial value, but updates to the real global (accessed by
112 // JITted code) are not propagated. Instead, getPointerToGlobal() should return
113 // a pointer into the loaded ObjectImage to reference the emitted global.
114 /*
115 TEST_F(MCJITTest, increment_global) {
116 SKIP_UNSUPPORTED_PLATFORM;
117
118 int32_t initialNum = 5;
119 Function *IncrementGlobal = startFunction(M.get(), "IncrementGlobal");
120 GlobalVariable *GV = insertGlobalInt32(M.get(), "my_global", initialNum);
121 Value *DerefGV = Builder.CreateLoad(GV);
122 Value *AddResult = Builder.CreateAdd(DerefGV,
123 ConstantInt::get(Context, APInt(32, 1)));
124 Builder.CreateStore(AddResult, GV);
125 endFunctionWithRet(IncrementGlobal, AddResult);
126
127 createJIT(M.take());
128 void *gvPtr = TheJIT->getPointerToGlobal(GV);
129 EXPECT_EQ(initialNum, *(int32_t*)gvPtr);
130
131 void *vPtr = TheJIT->getPointerToFunction(IncrementGlobal);
132 EXPECT_TRUE(0 != vPtr)
133 << "Unable to get pointer to main() from JIT";
134
135 int32_t(*FuncPtr)(void) = (int32_t(*)(void))(intptr_t)vPtr;
136
137 for(int i = 1; i < 3; ++i) {
138 int32_t result = FuncPtr();
139 EXPECT_EQ(initialNum + i, result); // OK
140 EXPECT_EQ(initialNum + i, *(int32_t*)gvPtr); // FAILS
141 }
142 }
143 */
144
145 TEST_F(MCJITTest, multiple_functions) {
146 SKIP_UNSUPPORTED_PLATFORM;
147
148 unsigned int numLevels = 23;
149 int32_t innerRetVal= 5;
150
151 Function *Inner = startFunction(M.get(), "Inner");
152 endFunctionWithRet(Inner, ConstantInt::get(Context, APInt(32, innerRetVal)));
153
154 Function *Outer;
155 for (unsigned int i = 0; i < numLevels; ++i) {
156 std::stringstream funcName;
157 funcName << "level_" << i;
158 Outer = startFunction(M.get(), funcName.str());
159 Value *innerResult = Builder.CreateCall(Inner);
160 endFunctionWithRet(Outer, innerResult);
161
162 Inner = Outer;
163 }
164
165 createJIT(M.take());
166 void *vPtr = TheJIT->getPointerToFunction(Outer);
167 EXPECT_TRUE(0 != vPtr)
168 << "Unable to get pointer to outer function from JIT";
169
170 int32_t(*FuncPtr)(void) = (int32_t(*)(void))(intptr_t)vPtr;
171 EXPECT_EQ(innerRetVal, FuncPtr())
172 << "Incorrect result returned from function";
173 }
174
175 // FIXME: ExecutionEngine has no support empty modules
176 /*
177 TEST_F(MCJITTest, multiple_empty_modules) {
178 SKIP_UNSUPPORTED_PLATFORM;
179
180 createJIT(M.take());
181 // JIT-compile
182 EXPECT_NE(0, TheJIT->getObjectImage())
183 << "Unable to generate executable loaded object image";
184
185 TheJIT->addModule(createEmptyModule(""));
186 TheJIT->addModule(createEmptyModule(""));
187
188 // JIT again
189 EXPECT_NE(0, TheJIT->getObjectImage())
190 << "Unable to generate executable loaded object image";
191 }
192 */
193
194 // FIXME: MCJIT must support multiple modules
195 /*
196 TEST_F(MCJITTest, multiple_modules) {
197 SKIP_UNSUPPORTED_PLATFORM;
198
199 Function *Callee = insertAddFunction(M.get());
200 createJIT(M.take());
201
202 // caller function is defined in a different module
203 M.reset(createEmptyModule(""));
204
205 Function *CalleeRef = insertExternalReferenceToFunction(M.get(), Callee);
206 Function *Caller = insertSimpleCallFunction(M.get(), CalleeRef);
207
208 TheJIT->addModule(M.take());
209
210 // get a function pointer in a module that was not used in EE construction
211 void *vPtr = TheJIT->getPointerToFunction(Caller);
212 EXPECT_NE(0, vPtr)
213 << "Unable to get pointer to caller function from JIT";
214
215 int(*FuncPtr)(int, int) = (int(*)(int, int))(intptr_t)vPtr;
216 EXPECT_EQ(0, FuncPtr(0, 0));
217 EXPECT_EQ(30, FuncPtr(10, 20));
218 EXPECT_EQ(-30, FuncPtr(-10, -20));
219
220 // ensure caller is destroyed before callee (free use before def)
221 M.reset();
222 }
223 */
224
225 }
0 //===- MCJITTestBase.h - Common base class for MCJIT Unit tests ----------===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This class implements common functionality required by the MCJIT unit tests,
10 // as well as logic to skip tests on unsupported architectures and operating
11 // systems.
12 //
13 //===----------------------------------------------------------------------===//
14
15
16 #ifndef MCJIT_TEST_BASE_H
17 #define MCJIT_TEST_BASE_H
18
19 #include "llvm/ADT/Triple.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/Config/config.h"
22 #include "llvm/ExecutionEngine/ExecutionEngine.h"
23 #include "llvm/Function.h"
24 #include "llvm/IRBuilder.h"
25 #include "llvm/LLVMContext.h"
26 #include "llvm/Module.h"
27 #include "llvm/Support/CodeGen.h"
28 #include "llvm/Support/Host.h"
29 #include "llvm/Support/TargetSelect.h"
30 #include "llvm/TypeBuilder.h"
31
32 #include "SectionMemoryManager.h"
33
34 // Used to skip tests on unsupported architectures and operating systems.
35 // To skip a test, add this macro at the top of a test-case in a suite that
36 // inherits from MCJITTestBase. See MCJITTest.cpp for examples.
37 #define SKIP_UNSUPPORTED_PLATFORM \
38 do \
39 if (!ArchSupportsMCJIT() || !OSSupportsMCJIT()) \
40 return; \
41 while(0);
42
43 namespace llvm {
44
45 class MCJITTestBase {
46 protected:
47
48 MCJITTestBase()
49 : OptLevel(CodeGenOpt::None)
50 , RelocModel(Reloc::Default)
51 , CodeModel(CodeModel::Default)
52 , MArch("")
53 , Builder(Context)
54 , MM(new SectionMemoryManager)
55 , HostTriple(LLVM_HOSTTRIPLE)
56 {
57 InitializeNativeTarget();
58 InitializeNativeTargetAsmPrinter();
59
60 #ifdef LLVM_ON_WIN32
61 // On Windows, generate ELF objects by specifying "-elf" in triple
62 HostTriple += "-elf";
63 #endif // LLVM_ON_WIN32
64 HostTriple = Triple::normalize(HostTriple);
65
66 // The architectures below are known to be compatible with MCJIT as they
67 // are copied from test/ExecutionEngine/MCJIT/lit.local.cfg and should be
68 // kept in sync.
69 SupportedArchs.push_back(Triple::arm);
70 SupportedArchs.push_back(Triple::mips);
71 SupportedArchs.push_back(Triple::x86);
72 SupportedArchs.push_back(Triple::x86_64);
73
74 // The operating systems below are known to be incompatible with MCJIT as
75 // they are copied from the test/ExecutionEngine/MCJIT/lit.local.cfg and
76 // should be kept in sync.
77 UnsupportedOSs.push_back(Triple::Cygwin);
78 UnsupportedOSs.push_back(Triple::Darwin);
79 }
80
81 /// Returns true if the host architecture is known to support MCJIT
82 bool ArchSupportsMCJIT() {
83 Triple Host(HostTriple);
84 if (std::find(SupportedArchs.begin(), SupportedArchs.end(), Host.getArch())
85 == SupportedArchs.end()) {
86 return false;
87 }
88 return true;
89 }
90
91 /// Returns true if the host OS is known to support MCJIT
92 bool OSSupportsMCJIT() {
93 Triple Host(HostTriple);
94 if (std::find(UnsupportedOSs.begin(), UnsupportedOSs.end(), Host.getOS())
95 == UnsupportedOSs.end()) {
96 return true;
97 }
98 return false;
99 }
100
101 Module *createEmptyModule(StringRef Name) {
102 Module * M = new Module(Name, Context);
103 M->setTargetTriple(Triple::normalize(HostTriple));
104 return M;
105 }
106
107 template
108 Function *startFunction(Module *M, StringRef Name) {
109 Function *Result = Function::Create(
110 TypeBuilder::get(Context),
111 GlobalValue::ExternalLinkage, Name, M);
112
113 BasicBlock *BB = BasicBlock::Create(Context, Name, Result);
114 Builder.SetInsertPoint(BB);
115
116 return Result;
117 }
118
119 void endFunctionWithRet(Function *Func, Value *RetValue) {
120 Builder.CreateRet(RetValue);
121 }
122
123 // Inserts a simple function that invokes Callee and takes the same arguments:
124 // int Caller(...) { return Callee(...); }
125 template
126 Function *insertSimpleCallFunction(Module *M, Function *Callee) {
127 Function *Result = startFunction(M, "caller");
128
129 SmallVector CallArgs;
130
131 Function::arg_iterator arg_iter = Result->arg_begin();
132 for(;arg_iter != Result->arg_end(); ++arg_iter)
133 CallArgs.push_back(arg_iter);
134
135 Value *ReturnCode = Builder.CreateCall(Callee, CallArgs);
136 Builder.CreateRet(ReturnCode);
137 return Result;
138 }
139
140 // Inserts a function named 'main' that returns a uint32_t:
141 // int32_t main() { return X; }
142 // where X is given by returnCode
143 Function *insertMainFunction(Module *M, uint32_t returnCode) {
144 Function *Result = startFunction(M, "main");
145
146 Value *ReturnVal = ConstantInt::get(Context, APInt(32, returnCode));
147 endFunctionWithRet(Result, ReturnVal);
148
149 return Result;
150 }
151
152 // Inserts a function
153 // int32_t add(int32_t a, int32_t b) { return a + b; }
154 // in the current module and returns a pointer to it.
155 Function *insertAddFunction(Module *M, StringRef Name = "add") {
156 Function *Result = startFunction(M, Name);
157
158 Function::arg_iterator args = Result->arg_begin();
159 Value *Arg1 = args;
160 Value *Arg2 = ++args;
161 Value *AddResult = Builder.CreateAdd(Arg1, Arg2);
162
163 endFunctionWithRet(Result, AddResult);
164
165 return Result;
166 }
167
168 // Inserts an declaration to a function defined elsewhere
169 Function *insertExternalReferenceToFunction(Module *M, StringRef Name,
170 FunctionType *FuncTy) {
171 Function *Result = Function::Create(FuncTy,
172 GlobalValue::ExternalLinkage,
173 Name, M);
174 return Result;
175 }
176
177 // Inserts an declaration to a function defined elsewhere
178 Function *insertExternalReferenceToFunction(Module *M, Function *Func) {
179 Function *Result = Function::Create(Func->getFunctionType(),
180 GlobalValue::AvailableExternallyLinkage,
181 Func->getName(), M);
182 return Result;
183 }
184
185 // Inserts a global variable of type int32
186 GlobalVariable *insertGlobalInt32(Module *M,
187 StringRef name,
188 int32_t InitialValue) {
189 Type *GlobalTy = TypeBuilder, true>::get(Context);
190 Constant *IV = ConstantInt::get(Context, APInt(32, InitialValue));
191 GlobalVariable *Global = new GlobalVariable(*M,
192 GlobalTy,
193 false,
194 GlobalValue::ExternalLinkage,
195 IV,
196 name);
197 return Global;
198 }
199
200 void createJIT(Module *M) {
201
202 // Due to the EngineBuilder constructor, it is required to have a Module
203 // in order to construct an ExecutionEngine (i.e. MCJIT)
204 assert(M != 0 && "a non-null Module must be provided to create MCJIT");
205
206 EngineBuilder EB(M);
207 std::string Error;
208 TheJIT.reset(EB.setEngineKind(EngineKind::JIT)
209 .setUseMCJIT(true) /* can this be folded into the EngineKind enum? */
210 .setJITMemoryManager(MM)
211 .setErrorStr(&Error)
212 .setOptLevel(CodeGenOpt::None)
213 .setAllocateGVsWithCode(false) /*does this do anything?*/
214 .setCodeModel(CodeModel::JITDefault)
215 .setRelocationModel(Reloc::Default)
216 .setMArch(MArch)
217 .setMCPU(sys::getHostCPUName())
218 //.setMAttrs(MAttrs)
219 .create());
220 // At this point, we cannot modify the module any more.
221 assert(TheJIT.get() != NULL && "error creating MCJIT with EngineBuilder");
222 }
223
224 LLVMContext Context;
225 CodeGenOpt::Level OptLevel;
226 Reloc::Model RelocModel;
227 CodeModel::Model CodeModel;
228 StringRef MArch;
229 SmallVector MAttrs;
230 OwningPtr TM;
231 OwningPtr TheJIT;
232 IRBuilder<> Builder;
233 JITMemoryManager *MM;
234
235 std::string HostTriple;
236 SmallVector SupportedArchs;
237 SmallVector UnsupportedOSs;
238
239 OwningPtr M;
240 };
241
242 } // namespace llvm
243
244 #endif // MCJIT_TEST_H
0 ##===- unittests/ExecutionEngine/MCJIT/Makefile ------------*- Makefile -*-===##
1 #
2 # The LLVM Compiler Infrastructure
3 #
4 # This file is distributed under the University of Illinois Open Source
5 # License. See LICENSE.TXT for details.
6 #
7 ##===----------------------------------------------------------------------===##
8
9 LEVEL = ../../..
10 TESTNAME = MCJIT
11 LINK_COMPONENTS := core jit mcjit native support
12
13 include $(LEVEL)/Makefile.config
14 include $(LLVM_SRC_ROOT)/unittests/Makefile.unittest
15
16 # Permit these tests to use the MCJIT's symbolic lookup.
17 LD.Flags += $(RDYNAMIC)
0 //===-- SectionMemoryManager.cpp - The memory manager for MCJIT -----------===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the implementation of the section-based memory manager
10 // used by MCJIT.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Config/config.h"
15 #include "llvm/Support/DynamicLibrary.h"
16
17 #include "SectionMemoryManager.h"
18
19 #ifdef __linux__
20 // These includes used by SectionMemoryManager::getPointerToNamedFunction()
21 // for Glibc trickery. Look comments in this function for more information.
22 #ifdef HAVE_SYS_STAT_H
23 #include
24 #endif
25 #include
26 #include
27 #endif
28
29 namespace llvm {
30
31 uint8_t *SectionMemoryManager::allocateDataSection(uintptr_t Size,
32 unsigned Alignment,
33 unsigned SectionID) {
34 if (!Alignment)
35 Alignment = 16;
36 uint8_t *Addr = (uint8_t*)calloc((Size + Alignment - 1)/Alignment, Alignment);
37 AllocatedDataMem.push_back(sys::MemoryBlock(Addr, Size));
38 return Addr;
39 }
40
41 uint8_t *SectionMemoryManager::allocateCodeSection(uintptr_t Size,
42 unsigned Alignment,
43 unsigned SectionID) {
44 if (!Alignment)
45 Alignment = 16;
46 unsigned NeedAllocate = Alignment * ((Size + Alignment - 1)/Alignment + 1);
47 uintptr_t Addr = 0;
48 // Look in the list of free code memory regions and use a block there if one
49 // is available.
50 for (int i = 0, e = FreeCodeMem.size(); i != e; ++i) {
51 sys::MemoryBlock &MB = FreeCodeMem[i];
52 if (MB.size() >= NeedAllocate) {
53 Addr = (uintptr_t)MB.base();
54 uintptr_t EndOfBlock = Addr + MB.size();
55 // Align the address.
56 Addr = (Addr + Alignment - 1) & ~(uintptr_t)(Alignment - 1);
57 // Store cutted free memory block.
58 FreeCodeMem[i] = sys::MemoryBlock((void*)(Addr + Size),
59 EndOfBlock - Addr - Size);
60 return (uint8_t*)Addr;
61 }
62 }
63
64 // No pre-allocated free block was large enough. Allocate a new memory region.
65 sys::MemoryBlock MB = sys::Memory::AllocateRWX(NeedAllocate, 0, 0);
66
67 AllocatedCodeMem.push_back(MB);
68 Addr = (uintptr_t)MB.base();
69 uintptr_t EndOfBlock = Addr + MB.size();
70 // Align the address.
71 Addr = (Addr + Alignment - 1) & ~(uintptr_t)(Alignment - 1);
72 // The AllocateRWX may allocate much more memory than we need. In this case,
73 // we store the unused memory as a free memory block.
74 unsigned FreeSize = EndOfBlock-Addr-Size;
75 if (FreeSize > 16)
76 FreeCodeMem.push_back(sys::MemoryBlock((void*)(Addr + Size), FreeSize));
77
78 // Return aligned address
79 return (uint8_t*)Addr;
80 }
81
82 void SectionMemoryManager::invalidateInstructionCache() {
83 for (int i = 0, e = AllocatedCodeMem.size(); i != e; ++i)
84 sys::Memory::InvalidateInstructionCache(AllocatedCodeMem[i].base(),
85 AllocatedCodeMem[i].size());
86 }
87
88 void *SectionMemoryManager::getPointerToNamedFunction(const std::string &Name,
89 bool AbortOnFailure) {
90 #if defined(__linux__)
91 //===--------------------------------------------------------------------===//
92 // Function stubs that are invoked instead of certain library calls
93 //
94 // Force the following functions to be linked in to anything that uses the
95 // JIT. This is a hack designed to work around the all-too-clever Glibc
96 // strategy of making these functions work differently when inlined vs. when
97 // not inlined, and hiding their real definitions in a separate archive file
98 // that the dynamic linker can't see. For more info, search for
99 // 'libc_nonshared.a' on Google, or read http://llvm.org/PR274.
100 if (Name == "stat") return (void*)(intptr_t)&stat;
101 if (Name == "fstat") return (void*)(intptr_t)&fstat;
102 if (Name == "lstat") return (void*)(intptr_t)&lstat;
103 if (Name == "stat64") return (void*)(intptr_t)&stat64;
104 if (Name == "fstat64") return (void*)(intptr_t)&fstat64;
105 if (Name == "lstat64") return (void*)(intptr_t)&lstat64;
106 if (Name == "atexit") return (void*)(intptr_t)&atexit;
107 if (Name == "mknod") return (void*)(intptr_t)&mknod;
108 #endif // __linux__
109
110 const char *NameStr = Name.c_str();
111 void *Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(NameStr);
112 if (Ptr) return Ptr;
113
114 // If it wasn't found and if it starts with an underscore ('_') character,
115 // try again without the underscore.
116 if (NameStr[0] == '_') {
117 Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(NameStr+1);
118 if (Ptr) return Ptr;
119 }
120
121 if (AbortOnFailure)
122 report_fatal_error("Program used external function '" + Name +
123 "' which could not be resolved!");
124 return 0;
125 }
126
127 SectionMemoryManager::~SectionMemoryManager() {
128 for (unsigned i = 0, e = AllocatedCodeMem.size(); i != e; ++i)
129 sys::Memory::ReleaseRWX(AllocatedCodeMem[i]);
130 for (unsigned i = 0, e = AllocatedDataMem.size(); i != e; ++i)
131 free(AllocatedDataMem[i].base());
132 }
133
134 } // namespace llvm
0 //===-- SectionMemoryManager.h - Memory allocator for MCJIT -----*- C++ -*-===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains the declaration of a section-based memory manager used by
10 // the MCJIT execution engine.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_EXECUTION_ENGINE_SECTION_MEMORY_MANAGER_H
15 #define LLVM_EXECUTION_ENGINE_SECTION_MEMORY_MANAGER_H
16
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ExecutionEngine/JITMemoryManager.h"
19 #include "llvm/Support/ErrorHandling.h"
20 #include "llvm/Support/Memory.h"
21
22 namespace llvm {
23
24 // Section-based memory manager for MCJIT
25 class SectionMemoryManager : public JITMemoryManager {
26
27 public:
28
29 SectionMemoryManager() { }
30 ~SectionMemoryManager();
31
32 virtual uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
33 unsigned SectionID);
34
35 virtual uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
36 unsigned SectionID);
37
38 virtual void *getPointerToNamedFunction(const std::string &Name,
39 bool AbortOnFailure = true);
40
41 // Invalidate instruction cache for code sections. Some platforms with
42 // separate data cache and instruction cache require explicit cache flush,
43 // otherwise JIT code manipulations (like resolved relocations) will get to
44 // the data cache but not to the instruction cache.
45 virtual void invalidateInstructionCache();
46
47 private:
48
49 SmallVector AllocatedDataMem;
50 SmallVector AllocatedCodeMem;
51 SmallVector FreeCodeMem;
52
53 public:
54 ///
55 /// Functions below are not used by MCJIT, but must be implemented because
56 /// they are declared as pure virtuals in the base class.
57 ///
58
59 virtual void setMemoryWritable() {
60 llvm_unreachable("Unexpected call!");
61 }
62 virtual void setMemoryExecutable() {
63 llvm_unreachable("Unexpected call!");
64 }
65 virtual void setPoisonMemory(bool poison) {
66 llvm_unreachable("Unexpected call!");
67 }
68 virtual void AllocateGOT() {
69 llvm_unreachable("Unexpected call!");
70 }
71 virtual uint8_t *getGOTBase() const {
72 llvm_unreachable("Unexpected call!");
73 return 0;
74 }
75 virtual uint8_t *startFunctionBody(const Function *F,
76 uintptr_t &ActualSize){
77 llvm_unreachable("Unexpected call!");
78 return 0;
79 }
80 virtual uint8_t *allocateStub(const GlobalValue* F, unsigned StubSize,
81 unsigned Alignment) {
82 llvm_unreachable("Unexpected call!");
83 return 0;
84 }
85 virtual void endFunctionBody(const Function *F, uint8_t *FunctionStart,
86 uint8_t *FunctionEnd) {
87 llvm_unreachable("Unexpected call!");
88 }
89 virtual uint8_t *allocateSpace(intptr_t Size, unsigned Alignment) {
90 llvm_unreachable("Unexpected call!");
91 return 0;
92 }
93 virtual uint8_t *allocateGlobal(uintptr_t Size, unsigned Alignment) {
94 llvm_unreachable("Unexpected call!");
95 return 0;
96 }
97 virtual void deallocateFunctionBody(void *Body) {
98 llvm_unreachable("Unexpected call!");
99 }
100 virtual uint8_t *startExceptionTable(const Function *F,
101 uintptr_t &ActualSize) {
102 llvm_unreachable("Unexpected call!");
103 return 0;
104 }
105 virtual void endExceptionTable(const Function *F, uint8_t *TableStart,
106 uint8_t *TableEnd, uint8_t *FrameRegister) {
107 llvm_unreachable("Unexpected call!");
108 }
109 virtual void deallocateExceptionTable(void *ET) {
110 llvm_unreachable("Unexpected call!");
111 }
112 };
113
114 }
115
116 #endif // LLVM_EXECUTION_ENGINE_SECTION_MEMORY_MANAGER_H
99 LEVEL = ../..
1010 TESTNAME = ExecutionEngine
1111 LINK_COMPONENTS :=interpreter
12 PARALLEL_DIRS = JIT
12 PARALLEL_DIRS = JIT MCJIT
1313
1414 include $(LEVEL)/Makefile.config
1515 include $(LLVM_SRC_ROOT)/unittests/Makefile.unittest
1616 LeakDetectorTest.cpp
1717 ManagedStatic.cpp
1818 MathExtrasTest.cpp
19 MemoryBufferTest.cpp
1920 MemoryTest.cpp
2021 Path.cpp
2122 RegexTest.cpp
0 //===- llvm/unittest/Support/MemoryBufferTest.cpp - MemoryBuffer tests ----===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements unit tests for the MemoryBuffer support class.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "llvm/Support/MemoryBuffer.h"
14 #include "llvm/ADT/OwningPtr.h"
15
16 #include "gtest/gtest.h"
17
18 using namespace llvm;
19
20 class MemoryBufferTest : public testing::Test {
21 protected:
22 MemoryBufferTest()
23 : data("this is some data")
24 { }
25
26 virtual void SetUp() { }
27
28 typedef OwningPtr OwningBuffer;
29
30 std::string data;
31 };
32
33 namespace {
34
35 TEST_F(MemoryBufferTest, get) {
36 // Default name and null-terminator flag
37 OwningBuffer MB1(MemoryBuffer::getMemBuffer(data));
38 EXPECT_TRUE(0 != MB1.get());
39
40 // RequiresNullTerminator = false
41 OwningBuffer MB2(MemoryBuffer::getMemBuffer(data, "one", false));
42 EXPECT_TRUE(0 != MB2.get());
43
44 // RequiresNullTerminator = true
45 OwningBuffer MB3(MemoryBuffer::getMemBuffer(data, "two", true));
46 EXPECT_TRUE(0 != MB3.get());
47
48 // verify all 3 buffers point to the same address
49 EXPECT_EQ(MB1->getBufferStart(), MB2->getBufferStart());
50 EXPECT_EQ(MB2->getBufferStart(), MB3->getBufferStart());
51
52 // verify the original data is unmodified after deleting the buffers
53 MB1.reset();
54 MB2.reset();
55 MB3.reset();
56 EXPECT_EQ("this is some data", data);
57 }
58
59 TEST_F(MemoryBufferTest, copy) {
60 // copy with no name
61 OwningBuffer MBC1(MemoryBuffer::getMemBufferCopy(data));
62 EXPECT_TRUE(0 != MBC1.get());
63
64 // copy with a name
65 OwningBuffer MBC2(MemoryBuffer::getMemBufferCopy(data, "copy"));
66 EXPECT_TRUE(0 != MBC2.get());
67
68 // verify the two copies do not point to the same place
69 EXPECT_NE(MBC1->getBufferStart(), MBC2->getBufferStart());
70 }
71
72 TEST_F(MemoryBufferTest, make_new) {
73 // 0-sized buffer
74 OwningBuffer Zero(MemoryBuffer::getNewUninitMemBuffer(0));
75 EXPECT_TRUE(0 != Zero.get());
76
77 // uninitialized buffer with no name
78 OwningBuffer One(MemoryBuffer::getNewUninitMemBuffer(321));
79 EXPECT_TRUE(0 != One.get());
80
81 // uninitialized buffer with name
82 OwningBuffer Two(MemoryBuffer::getNewUninitMemBuffer(123, "bla"));
83 EXPECT_TRUE(0 != Two.get());
84
85 // 0-initialized buffer with no name
86 OwningBuffer Three(MemoryBuffer::getNewMemBuffer(321, data));
87 EXPECT_TRUE(0 != Three.get());
88 for (size_t i = 0; i < 321; ++i)
89 EXPECT_EQ(0, Three->getBufferStart()[0]);
90
91 // 0-initialized buffer with name
92 OwningBuffer Four(MemoryBuffer::getNewMemBuffer(123, "zeros"));
93 EXPECT_TRUE(0 != Four.get());
94 for (size_t i = 0; i < 123; ++i)
95 EXPECT_EQ(0, Four->getBufferStart()[0]);
96 }
97
98 }