blob: 36c85e8d87e80cabba006f3731d948bac5cfaf47 [file] [log] [blame]
Nicolas Capens41a73022020-01-30 00:30:14 -05001// Copyright 2020 The SwiftShader Authors. All Rights Reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#include "LLVMReactor.hpp"
16
17#include "Debug.hpp"
18#include "ExecutableMemory.hpp"
19#include "Routine.hpp"
20
Nicolas Capens41a73022020-01-30 00:30:14 -050021// TODO(b/143539525): Eliminate when warning has been fixed.
22#ifdef _MSC_VER
23__pragma(warning(push))
24 __pragma(warning(disable : 4146)) // unary minus operator applied to unsigned type, result still unsigned
25#endif
26
Nicolas Capens41a73022020-01-30 00:30:14 -050027#include "llvm/ExecutionEngine/Orc/CompileUtils.h"
28#include "llvm/ExecutionEngine/Orc/IRCompileLayer.h"
Nicolas Capens41a73022020-01-30 00:30:14 -050029#include "llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h"
Nicolas Capens41a73022020-01-30 00:30:14 -050030#include "llvm/ExecutionEngine/SectionMemoryManager.h"
Nicolas Capens41a73022020-01-30 00:30:14 -050031#include "llvm/IR/LegacyPassManager.h"
Nicolas Capens41a73022020-01-30 00:30:14 -050032#include "llvm/Support/TargetSelect.h"
Nicolas Capens41a73022020-01-30 00:30:14 -050033#include "llvm/Transforms/InstCombine/InstCombine.h"
34#include "llvm/Transforms/Scalar.h"
35#include "llvm/Transforms/Scalar/GVN.h"
36
Nicolas Capens41a73022020-01-30 00:30:14 -050037#ifdef _MSC_VER
38 __pragma(warning(pop))
39#endif
40
Nicolas Capens41a73022020-01-30 00:30:14 -050041#if defined(_WIN64)
42 extern "C" void __chkstk();
43#elif defined(_WIN32)
44extern "C" void _chkstk();
45#endif
46
Anton D. Kachalovac4e1d22020-02-11 15:44:27 +010047#ifdef __ARM_EABI__
48extern "C" signed __aeabi_idivmod();
49#endif
50
Nicolas Capens47c3ca12020-11-02 16:33:08 -050051#if __has_feature(memory_sanitizer)
52# include "sanitizer/msan_interface.h" // TODO(b/155148722): Remove when we no longer unpoison all writes.
53
54# include <dlfcn.h> // dlsym()
55#endif
56
Nicolas Capens41a73022020-01-30 00:30:14 -050057namespace {
58
Nicolas Capens41a73022020-01-30 00:30:14 -050059// JITGlobals is a singleton that holds all the immutable machine specific
60// information for the host device.
61class JITGlobals
62{
63public:
Nicolas Capens41a73022020-01-30 00:30:14 -050064 static JITGlobals *get();
65
Ben Claytonee18f392020-10-19 16:54:21 -040066 llvm::orc::JITTargetMachineBuilder getTargetMachineBuilder(rr::Optimization::Level optLevel) const;
67 const llvm::DataLayout &getDataLayout() const;
68 const llvm::Triple getTargetTriple() const;
Nicolas Capens41a73022020-01-30 00:30:14 -050069
70private:
Ben Claytonee18f392020-10-19 16:54:21 -040071 JITGlobals(const llvm::orc::JITTargetMachineBuilder &jtmb, const llvm::DataLayout &dataLayout);
72
Nicolas Capens41a73022020-01-30 00:30:14 -050073 static llvm::CodeGenOpt::Level toLLVM(rr::Optimization::Level level);
Ben Claytonee18f392020-10-19 16:54:21 -040074 const llvm::orc::JITTargetMachineBuilder jtmb;
75 const llvm::DataLayout dataLayout;
Nicolas Capens41a73022020-01-30 00:30:14 -050076};
77
78JITGlobals *JITGlobals::get()
79{
Ben Claytonee18f392020-10-19 16:54:21 -040080 static JITGlobals instance = [] {
81 llvm::InitializeNativeTarget();
82 llvm::InitializeNativeTargetAsmPrinter();
83 llvm::InitializeNativeTargetAsmParser();
84
85 auto jtmb = llvm::orc::JITTargetMachineBuilder::detectHost();
86 ASSERT_MSG(jtmb, "JITTargetMachineBuilder::detectHost() failed");
87 auto dataLayout = jtmb->getDefaultDataLayoutForTarget();
88 ASSERT_MSG(dataLayout, "JITTargetMachineBuilder::getDefaultDataLayoutForTarget() failed");
89 return JITGlobals(jtmb.get(), dataLayout.get());
90 }();
Nicolas Capens41a73022020-01-30 00:30:14 -050091 return &instance;
92}
93
Ben Claytonee18f392020-10-19 16:54:21 -040094llvm::orc::JITTargetMachineBuilder JITGlobals::getTargetMachineBuilder(rr::Optimization::Level optLevel) const
Nicolas Capens41a73022020-01-30 00:30:14 -050095{
Ben Claytonee18f392020-10-19 16:54:21 -040096 llvm::orc::JITTargetMachineBuilder out = jtmb;
97 out.setCodeGenOptLevel(toLLVM(optLevel));
98 return out;
Nicolas Capens41a73022020-01-30 00:30:14 -050099}
100
Ben Claytonee18f392020-10-19 16:54:21 -0400101const llvm::DataLayout &JITGlobals::getDataLayout() const
Nicolas Capens41a73022020-01-30 00:30:14 -0500102{
Ben Claytonee18f392020-10-19 16:54:21 -0400103 return dataLayout;
104}
Nicolas Capens41a73022020-01-30 00:30:14 -0500105
Ben Claytonee18f392020-10-19 16:54:21 -0400106const llvm::Triple JITGlobals::getTargetTriple() const
107{
108 return jtmb.getTargetTriple();
109}
Nicolas Capens41a73022020-01-30 00:30:14 -0500110
Ben Claytonee18f392020-10-19 16:54:21 -0400111JITGlobals::JITGlobals(const llvm::orc::JITTargetMachineBuilder &jtmb, const llvm::DataLayout &dataLayout)
112 : jtmb(jtmb)
113 , dataLayout(dataLayout)
114{
Nicolas Capens41a73022020-01-30 00:30:14 -0500115}
116
117llvm::CodeGenOpt::Level JITGlobals::toLLVM(rr::Optimization::Level level)
118{
119 switch(level)
120 {
Nicolas Capens00ecdf92020-10-30 21:13:40 -0400121 case rr::Optimization::Level::None: return llvm::CodeGenOpt::None;
122 case rr::Optimization::Level::Less: return llvm::CodeGenOpt::Less;
123 case rr::Optimization::Level::Default: return llvm::CodeGenOpt::Default;
124 case rr::Optimization::Level::Aggressive: return llvm::CodeGenOpt::Aggressive;
Nicolas Capens41a73022020-01-30 00:30:14 -0500125 default: UNREACHABLE("Unknown Optimization Level %d", int(level));
126 }
Nicolas Capens00ecdf92020-10-30 21:13:40 -0400127 return llvm::CodeGenOpt::Default;
Nicolas Capens41a73022020-01-30 00:30:14 -0500128}
129
David 'Digit' Turner48f3f6c2020-03-23 14:23:10 +0100130class MemoryMapper final : public llvm::SectionMemoryManager::MemoryMapper
Nicolas Capens41a73022020-01-30 00:30:14 -0500131{
132public:
133 MemoryMapper() {}
134 ~MemoryMapper() final {}
135
136 llvm::sys::MemoryBlock allocateMappedMemory(
137 llvm::SectionMemoryManager::AllocationPurpose purpose,
138 size_t numBytes, const llvm::sys::MemoryBlock *const nearBlock,
139 unsigned flags, std::error_code &errorCode) final
140 {
141 errorCode = std::error_code();
142
143 // Round up numBytes to page size.
144 size_t pageSize = rr::memoryPageSize();
145 numBytes = (numBytes + pageSize - 1) & ~(pageSize - 1);
146
147 bool need_exec =
148 purpose == llvm::SectionMemoryManager::AllocationPurpose::Code;
149 void *addr = rr::allocateMemoryPages(
150 numBytes, flagsToPermissions(flags), need_exec);
151 if(!addr)
152 return llvm::sys::MemoryBlock();
153 return llvm::sys::MemoryBlock(addr, numBytes);
154 }
155
156 std::error_code protectMappedMemory(const llvm::sys::MemoryBlock &block,
157 unsigned flags)
158 {
159 // Round down base address to align with a page boundary. This matches
160 // DefaultMMapper behavior.
161 void *addr = block.base();
Nicolas Capens41a73022020-01-30 00:30:14 -0500162 size_t size = block.allocatedSize();
Nicolas Capens41a73022020-01-30 00:30:14 -0500163 size_t pageSize = rr::memoryPageSize();
164 addr = reinterpret_cast<void *>(
165 reinterpret_cast<uintptr_t>(addr) & ~(pageSize - 1));
166 size += reinterpret_cast<uintptr_t>(block.base()) -
167 reinterpret_cast<uintptr_t>(addr);
168
169 rr::protectMemoryPages(addr, size, flagsToPermissions(flags));
170 return std::error_code();
171 }
172
173 std::error_code releaseMappedMemory(llvm::sys::MemoryBlock &block)
174 {
Nicolas Capens41a73022020-01-30 00:30:14 -0500175 size_t size = block.allocatedSize();
Nicolas Capens41a73022020-01-30 00:30:14 -0500176
177 rr::deallocateMemoryPages(block.base(), size);
178 return std::error_code();
179 }
180
181private:
182 int flagsToPermissions(unsigned flags)
183 {
184 int result = 0;
185 if(flags & llvm::sys::Memory::MF_READ)
186 {
187 result |= rr::PERMISSION_READ;
188 }
189 if(flags & llvm::sys::Memory::MF_WRITE)
190 {
191 result |= rr::PERMISSION_WRITE;
192 }
193 if(flags & llvm::sys::Memory::MF_EXEC)
194 {
195 result |= rr::PERMISSION_EXECUTE;
196 }
197 return result;
198 }
199};
200
201template<typename T>
202T alignUp(T val, T alignment)
203{
204 return alignment * ((val + alignment - 1) / alignment);
205}
206
207void *alignedAlloc(size_t size, size_t alignment)
208{
209 ASSERT(alignment < 256);
210 auto allocation = new uint8_t[size + sizeof(uint8_t) + alignment];
211 auto aligned = allocation;
212 aligned += sizeof(uint8_t); // Make space for the base-address offset.
213 aligned = reinterpret_cast<uint8_t *>(alignUp(reinterpret_cast<uintptr_t>(aligned), alignment)); // align
214 auto offset = static_cast<uint8_t>(aligned - allocation);
215 aligned[-1] = offset;
216 return aligned;
217}
218
219void alignedFree(void *ptr)
220{
221 auto aligned = reinterpret_cast<uint8_t *>(ptr);
222 auto offset = aligned[-1];
223 auto allocation = aligned - offset;
224 delete[] allocation;
225}
226
227template<typename T>
228static void atomicLoad(void *ptr, void *ret, llvm::AtomicOrdering ordering)
229{
230 *reinterpret_cast<T *>(ret) = std::atomic_load_explicit<T>(reinterpret_cast<std::atomic<T> *>(ptr), rr::atomicOrdering(ordering));
231}
232
233template<typename T>
234static void atomicStore(void *ptr, void *val, llvm::AtomicOrdering ordering)
235{
236 std::atomic_store_explicit<T>(reinterpret_cast<std::atomic<T> *>(ptr), *reinterpret_cast<T *>(val), rr::atomicOrdering(ordering));
237}
238
239#ifdef __ANDROID__
240template<typename F>
241static uint32_t sync_fetch_and_op(uint32_t volatile *ptr, uint32_t val, F f)
242{
243 // Build an arbitrary op out of looped CAS
244 for(;;)
245 {
246 uint32_t expected = *ptr;
247 uint32_t desired = f(expected, val);
248
249 if(expected == __sync_val_compare_and_swap_4(ptr, expected, desired))
250 {
251 return expected;
252 }
253 }
254}
255#endif
256
Antonio Maioranoc1839ee2020-10-26 10:16:29 -0400257#if LLVM_VERSION_MAJOR >= 11 /* TODO(b/165000222): Unconditional after LLVM 11 upgrade */
258class ExternalSymbolGenerator : public llvm::orc::DefinitionGenerator
259#else
Ben Claytonee18f392020-10-19 16:54:21 -0400260class ExternalSymbolGenerator : public llvm::orc::JITDylib::DefinitionGenerator
Antonio Maioranoc1839ee2020-10-26 10:16:29 -0400261#endif
Nicolas Capens41a73022020-01-30 00:30:14 -0500262{
263 struct Atomic
264 {
265 static void load(size_t size, void *ptr, void *ret, llvm::AtomicOrdering ordering)
266 {
267 switch(size)
268 {
269 case 1: atomicLoad<uint8_t>(ptr, ret, ordering); break;
270 case 2: atomicLoad<uint16_t>(ptr, ret, ordering); break;
271 case 4: atomicLoad<uint32_t>(ptr, ret, ordering); break;
272 case 8: atomicLoad<uint64_t>(ptr, ret, ordering); break;
273 default:
Ben Claytonce54c592020-02-07 11:30:51 +0000274 UNIMPLEMENTED_NO_BUG("Atomic::load(size: %d)", int(size));
Nicolas Capens41a73022020-01-30 00:30:14 -0500275 }
276 }
277 static void store(size_t size, void *ptr, void *ret, llvm::AtomicOrdering ordering)
278 {
279 switch(size)
280 {
281 case 1: atomicStore<uint8_t>(ptr, ret, ordering); break;
282 case 2: atomicStore<uint16_t>(ptr, ret, ordering); break;
283 case 4: atomicStore<uint32_t>(ptr, ret, ordering); break;
284 case 8: atomicStore<uint64_t>(ptr, ret, ordering); break;
285 default:
Ben Claytonce54c592020-02-07 11:30:51 +0000286 UNIMPLEMENTED_NO_BUG("Atomic::store(size: %d)", int(size));
Nicolas Capens41a73022020-01-30 00:30:14 -0500287 }
288 }
289 };
290
Ben Claytonee18f392020-10-19 16:54:21 -0400291 static void nop() {}
292 static void neverCalled() { UNREACHABLE("Should never be called"); }
Nicolas Capens41a73022020-01-30 00:30:14 -0500293
Ben Claytonee18f392020-10-19 16:54:21 -0400294 static void *coroutine_alloc_frame(size_t size) { return alignedAlloc(size, 16); }
295 static void coroutine_free_frame(void *ptr) { alignedFree(ptr); }
Nicolas Capens41a73022020-01-30 00:30:14 -0500296
297#ifdef __ANDROID__
Ben Claytonee18f392020-10-19 16:54:21 -0400298 // forwarders since we can't take address of builtins
299 static void sync_synchronize() { __sync_synchronize(); }
300 static uint32_t sync_fetch_and_add_4(uint32_t *ptr, uint32_t val) { return __sync_fetch_and_add_4(ptr, val); }
301 static uint32_t sync_fetch_and_and_4(uint32_t *ptr, uint32_t val) { return __sync_fetch_and_and_4(ptr, val); }
302 static uint32_t sync_fetch_and_or_4(uint32_t *ptr, uint32_t val) { return __sync_fetch_and_or_4(ptr, val); }
303 static uint32_t sync_fetch_and_xor_4(uint32_t *ptr, uint32_t val) { return __sync_fetch_and_xor_4(ptr, val); }
304 static uint32_t sync_fetch_and_sub_4(uint32_t *ptr, uint32_t val) { return __sync_fetch_and_sub_4(ptr, val); }
305 static uint32_t sync_lock_test_and_set_4(uint32_t *ptr, uint32_t val) { return __sync_lock_test_and_set_4(ptr, val); }
306 static uint32_t sync_val_compare_and_swap_4(uint32_t *ptr, uint32_t expected, uint32_t desired) { return __sync_val_compare_and_swap_4(ptr, expected, desired); }
Nicolas Capens41a73022020-01-30 00:30:14 -0500307
Ben Claytonee18f392020-10-19 16:54:21 -0400308 static uint32_t sync_fetch_and_max_4(uint32_t *ptr, uint32_t val)
309 {
310 return sync_fetch_and_op(ptr, val, [](int32_t a, int32_t b) { return std::max(a, b); });
311 }
312 static uint32_t sync_fetch_and_min_4(uint32_t *ptr, uint32_t val)
313 {
314 return sync_fetch_and_op(ptr, val, [](int32_t a, int32_t b) { return std::min(a, b); });
315 }
316 static uint32_t sync_fetch_and_umax_4(uint32_t *ptr, uint32_t val)
317 {
318 return sync_fetch_and_op(ptr, val, [](uint32_t a, uint32_t b) { return std::max(a, b); });
319 }
320 static uint32_t sync_fetch_and_umin_4(uint32_t *ptr, uint32_t val)
321 {
322 return sync_fetch_and_op(ptr, val, [](uint32_t a, uint32_t b) { return std::min(a, b); });
323 }
Nicolas Capens41a73022020-01-30 00:30:14 -0500324#endif
Nicolas Capens47c3ca12020-11-02 16:33:08 -0500325
Nicolas Capens41a73022020-01-30 00:30:14 -0500326 class Resolver
327 {
328 public:
Ben Claytonee18f392020-10-19 16:54:21 -0400329 using FunctionMap = llvm::StringMap<void *>;
Nicolas Capens41a73022020-01-30 00:30:14 -0500330
331 FunctionMap functions;
332
333 Resolver()
334 {
Antonio Maiorano8cbee412020-06-10 15:59:20 -0400335#ifdef ENABLE_RR_PRINT
Ben Claytonee18f392020-10-19 16:54:21 -0400336 functions.try_emplace("rr::DebugPrintf", reinterpret_cast<void *>(rr::DebugPrintf));
Antonio Maiorano8cbee412020-06-10 15:59:20 -0400337#endif
Ben Claytonee18f392020-10-19 16:54:21 -0400338 functions.try_emplace("nop", reinterpret_cast<void *>(nop));
339 functions.try_emplace("floorf", reinterpret_cast<void *>(floorf));
340 functions.try_emplace("nearbyintf", reinterpret_cast<void *>(nearbyintf));
341 functions.try_emplace("truncf", reinterpret_cast<void *>(truncf));
342 functions.try_emplace("printf", reinterpret_cast<void *>(printf));
343 functions.try_emplace("puts", reinterpret_cast<void *>(puts));
344 functions.try_emplace("fmodf", reinterpret_cast<void *>(fmodf));
Nicolas Capens41a73022020-01-30 00:30:14 -0500345
Ben Claytonee18f392020-10-19 16:54:21 -0400346 functions.try_emplace("sinf", reinterpret_cast<void *>(sinf));
347 functions.try_emplace("cosf", reinterpret_cast<void *>(cosf));
348 functions.try_emplace("asinf", reinterpret_cast<void *>(asinf));
349 functions.try_emplace("acosf", reinterpret_cast<void *>(acosf));
350 functions.try_emplace("atanf", reinterpret_cast<void *>(atanf));
351 functions.try_emplace("sinhf", reinterpret_cast<void *>(sinhf));
352 functions.try_emplace("coshf", reinterpret_cast<void *>(coshf));
353 functions.try_emplace("tanhf", reinterpret_cast<void *>(tanhf));
354 functions.try_emplace("asinhf", reinterpret_cast<void *>(asinhf));
355 functions.try_emplace("acoshf", reinterpret_cast<void *>(acoshf));
356 functions.try_emplace("atanhf", reinterpret_cast<void *>(atanhf));
357 functions.try_emplace("atan2f", reinterpret_cast<void *>(atan2f));
358 functions.try_emplace("powf", reinterpret_cast<void *>(powf));
359 functions.try_emplace("expf", reinterpret_cast<void *>(expf));
360 functions.try_emplace("logf", reinterpret_cast<void *>(logf));
361 functions.try_emplace("exp2f", reinterpret_cast<void *>(exp2f));
362 functions.try_emplace("log2f", reinterpret_cast<void *>(log2f));
Nicolas Capens41a73022020-01-30 00:30:14 -0500363
Ben Claytonee18f392020-10-19 16:54:21 -0400364 functions.try_emplace("sin", reinterpret_cast<void *>(static_cast<double (*)(double)>(sin)));
365 functions.try_emplace("cos", reinterpret_cast<void *>(static_cast<double (*)(double)>(cos)));
366 functions.try_emplace("asin", reinterpret_cast<void *>(static_cast<double (*)(double)>(asin)));
367 functions.try_emplace("acos", reinterpret_cast<void *>(static_cast<double (*)(double)>(acos)));
368 functions.try_emplace("atan", reinterpret_cast<void *>(static_cast<double (*)(double)>(atan)));
369 functions.try_emplace("sinh", reinterpret_cast<void *>(static_cast<double (*)(double)>(sinh)));
370 functions.try_emplace("cosh", reinterpret_cast<void *>(static_cast<double (*)(double)>(cosh)));
371 functions.try_emplace("tanh", reinterpret_cast<void *>(static_cast<double (*)(double)>(tanh)));
372 functions.try_emplace("asinh", reinterpret_cast<void *>(static_cast<double (*)(double)>(asinh)));
373 functions.try_emplace("acosh", reinterpret_cast<void *>(static_cast<double (*)(double)>(acosh)));
374 functions.try_emplace("atanh", reinterpret_cast<void *>(static_cast<double (*)(double)>(atanh)));
375 functions.try_emplace("atan2", reinterpret_cast<void *>(static_cast<double (*)(double, double)>(atan2)));
376 functions.try_emplace("pow", reinterpret_cast<void *>(static_cast<double (*)(double, double)>(pow)));
377 functions.try_emplace("exp", reinterpret_cast<void *>(static_cast<double (*)(double)>(exp)));
378 functions.try_emplace("log", reinterpret_cast<void *>(static_cast<double (*)(double)>(log)));
379 functions.try_emplace("exp2", reinterpret_cast<void *>(static_cast<double (*)(double)>(exp2)));
380 functions.try_emplace("log2", reinterpret_cast<void *>(static_cast<double (*)(double)>(log2)));
Nicolas Capens41a73022020-01-30 00:30:14 -0500381
Ben Claytonee18f392020-10-19 16:54:21 -0400382 functions.try_emplace("atomic_load", reinterpret_cast<void *>(Atomic::load));
383 functions.try_emplace("atomic_store", reinterpret_cast<void *>(Atomic::store));
Nicolas Capens41a73022020-01-30 00:30:14 -0500384
385 // FIXME(b/119409619): use an allocator here so we can control all memory allocations
Ben Claytonee18f392020-10-19 16:54:21 -0400386 functions.try_emplace("coroutine_alloc_frame", reinterpret_cast<void *>(coroutine_alloc_frame));
387 functions.try_emplace("coroutine_free_frame", reinterpret_cast<void *>(coroutine_free_frame));
Nicolas Capens41a73022020-01-30 00:30:14 -0500388
389#ifdef __APPLE__
Ben Claytonee18f392020-10-19 16:54:21 -0400390 functions.try_emplace("sincosf_stret", reinterpret_cast<void *>(__sincosf_stret));
Nicolas Capens41a73022020-01-30 00:30:14 -0500391#elif defined(__linux__)
Ben Claytonee18f392020-10-19 16:54:21 -0400392 functions.try_emplace("sincosf", reinterpret_cast<void *>(sincosf));
Nicolas Capens41a73022020-01-30 00:30:14 -0500393#elif defined(_WIN64)
Ben Claytonee18f392020-10-19 16:54:21 -0400394 functions.try_emplace("chkstk", reinterpret_cast<void *>(__chkstk));
Nicolas Capens41a73022020-01-30 00:30:14 -0500395#elif defined(_WIN32)
Ben Claytonee18f392020-10-19 16:54:21 -0400396 functions.try_emplace("chkstk", reinterpret_cast<void *>(_chkstk));
Nicolas Capens41a73022020-01-30 00:30:14 -0500397#endif
398
Anton D. Kachalovac4e1d22020-02-11 15:44:27 +0100399#ifdef __ARM_EABI__
Ben Claytonee18f392020-10-19 16:54:21 -0400400 functions.try_emplace("aeabi_idivmod", reinterpret_cast<void *>(__aeabi_idivmod));
Anton D. Kachalovac4e1d22020-02-11 15:44:27 +0100401#endif
Nicolas Capens41a73022020-01-30 00:30:14 -0500402#ifdef __ANDROID__
Antonio Maiorano84f5eeb2020-10-20 20:39:34 -0400403 functions.try_emplace("aeabi_unwind_cpp_pr0", reinterpret_cast<void *>(neverCalled));
404 functions.try_emplace("sync_synchronize", reinterpret_cast<void *>(sync_synchronize));
405 functions.try_emplace("sync_fetch_and_add_4", reinterpret_cast<void *>(sync_fetch_and_add_4));
406 functions.try_emplace("sync_fetch_and_and_4", reinterpret_cast<void *>(sync_fetch_and_and_4));
407 functions.try_emplace("sync_fetch_and_or_4", reinterpret_cast<void *>(sync_fetch_and_or_4));
408 functions.try_emplace("sync_fetch_and_xor_4", reinterpret_cast<void *>(sync_fetch_and_xor_4));
409 functions.try_emplace("sync_fetch_and_sub_4", reinterpret_cast<void *>(sync_fetch_and_sub_4));
410 functions.try_emplace("sync_lock_test_and_set_4", reinterpret_cast<void *>(sync_lock_test_and_set_4));
411 functions.try_emplace("sync_val_compare_and_swap_4", reinterpret_cast<void *>(sync_val_compare_and_swap_4));
412 functions.try_emplace("sync_fetch_and_max_4", reinterpret_cast<void *>(sync_fetch_and_max_4));
413 functions.try_emplace("sync_fetch_and_min_4", reinterpret_cast<void *>(sync_fetch_and_min_4));
414 functions.try_emplace("sync_fetch_and_umax_4", reinterpret_cast<void *>(sync_fetch_and_umax_4));
415 functions.try_emplace("sync_fetch_and_umin_4", reinterpret_cast<void *>(sync_fetch_and_umin_4));
Nicolas Capens41a73022020-01-30 00:30:14 -0500416#endif
Antonio Maioranodd48b7e2020-02-05 13:17:07 -0500417#if __has_feature(memory_sanitizer)
Nicolas Capens47c3ca12020-11-02 16:33:08 -0500418 functions.try_emplace("msan_unpoison", reinterpret_cast<void *>(__msan_unpoison)); // TODO(b/155148722): Remove when we no longer unpoison all writes.
Antonio Maioranodd48b7e2020-02-05 13:17:07 -0500419#endif
Nicolas Capens41a73022020-01-30 00:30:14 -0500420 }
421 };
422
Antonio Maioranoc1839ee2020-10-26 10:16:29 -0400423 llvm::Error tryToGenerate(
424#if LLVM_VERSION_MAJOR >= 11 /* TODO(b/165000222): Unconditional after LLVM 11 upgrade */
425 llvm::orc::LookupState &state,
426#endif
427 llvm::orc::LookupKind kind,
428 llvm::orc::JITDylib &dylib,
429 llvm::orc::JITDylibLookupFlags flags,
430 const llvm::orc::SymbolLookupSet &set) override
Ben Claytonee18f392020-10-19 16:54:21 -0400431 {
432 static Resolver resolver;
Nicolas Capens41a73022020-01-30 00:30:14 -0500433
Ben Claytonee18f392020-10-19 16:54:21 -0400434 llvm::orc::SymbolMap symbols;
Nicolas Capens41a73022020-01-30 00:30:14 -0500435
Ben Claytonee18f392020-10-19 16:54:21 -0400436#if !defined(NDEBUG) || defined(DCHECK_ALWAYS_ON)
437 std::string missing;
438#endif // !defined(NDEBUG) || defined(DCHECK_ALWAYS_ON)
439
440 for(auto symbol : set)
441 {
442 auto name = symbol.first;
443
444 // Trim off any underscores from the start of the symbol. LLVM likes
445 // to append these on macOS.
446 auto trimmed = (*name).drop_while([](char c) { return c == '_'; });
447
448 auto it = resolver.functions.find(trimmed.str());
449 if(it != resolver.functions.end())
450 {
451 symbols[name] = llvm::JITEvaluatedSymbol(
452 static_cast<llvm::JITTargetAddress>(reinterpret_cast<uintptr_t>(it->second)),
453 llvm::JITSymbolFlags::Exported);
Nicolas Capens47c3ca12020-11-02 16:33:08 -0500454
455 continue;
Ben Claytonee18f392020-10-19 16:54:21 -0400456 }
Nicolas Capens47c3ca12020-11-02 16:33:08 -0500457
458#if __has_feature(memory_sanitizer)
459 // MemorySanitizer uses a dynamically linked runtime. Instrumented routines reference
460 // some symbols from this library. Look them up dynamically in the default namespace.
461 // Note this approach should not be used for other symbols, since they might not be
462 // visible (e.g. due to static linking), we may wish to provide an alternate
463 // implementation, and/or it would be a security vulnerability.
464
465 void *address = dlsym(RTLD_DEFAULT, (*symbol.first).data());
466
467 if(address)
Ben Claytonee18f392020-10-19 16:54:21 -0400468 {
Nicolas Capens47c3ca12020-11-02 16:33:08 -0500469 symbols[name] = llvm::JITEvaluatedSymbol(
470 static_cast<llvm::JITTargetAddress>(reinterpret_cast<uintptr_t>(address)),
471 llvm::JITSymbolFlags::Exported);
472
473 continue;
Ben Claytonee18f392020-10-19 16:54:21 -0400474 }
Nicolas Capens47c3ca12020-11-02 16:33:08 -0500475#endif
476
477#if !defined(NDEBUG) || defined(DCHECK_ALWAYS_ON)
478 missing += (missing.empty() ? "'" : ", '") + (*name).str() + "'";
479#endif
Ben Claytonee18f392020-10-19 16:54:21 -0400480 }
481
482#if !defined(NDEBUG) || defined(DCHECK_ALWAYS_ON)
Nicolas Capens47c3ca12020-11-02 16:33:08 -0500483 // Missing functions will likely make the module fail in non-obvious ways.
Ben Claytonee18f392020-10-19 16:54:21 -0400484 if(!missing.empty())
485 {
486 WARN("Missing external functions: %s", missing.c_str());
487 }
Nicolas Capens47c3ca12020-11-02 16:33:08 -0500488#endif
Ben Claytonee18f392020-10-19 16:54:21 -0400489
490 if(symbols.empty())
491 {
492 return llvm::Error::success();
493 }
494
495 return dylib.define(llvm::orc::absoluteSymbols(std::move(symbols)));
496 }
497};
Nicolas Capens41a73022020-01-30 00:30:14 -0500498
Antonio Maioranoec526ab2020-10-21 09:55:50 -0400499// As we must support different LLVM versions, add a generic Unwrap for functions that return Expected<T> or the actual T.
500// TODO(b/165000222): Remove after LLVM 11 upgrade
501template<typename T>
502auto &Unwrap(llvm::Expected<T> &&v)
503{
504 return v.get();
505}
506template<typename T>
507auto &Unwrap(T &&v)
508{
509 return v;
510}
511
Nicolas Capens41a73022020-01-30 00:30:14 -0500512// JITRoutine is a rr::Routine that holds a LLVM JIT session, compiler and
513// object layer as each routine may require different target machine
514// settings and no Reactor routine directly links against another.
515class JITRoutine : public rr::Routine
516{
Antonio Maioranobb66fa42020-10-22 13:53:09 -0400517 llvm::orc::ExecutionSession session;
Ben Claytonee18f392020-10-19 16:54:21 -0400518 llvm::orc::RTDyldObjectLinkingLayer objectLayer;
519 llvm::orc::IRCompileLayer compileLayer;
520 llvm::orc::MangleAndInterner mangle;
521 llvm::orc::ThreadSafeContext ctx;
Ben Claytonee18f392020-10-19 16:54:21 -0400522 llvm::orc::JITDylib &dylib;
523 std::vector<const void *> addresses;
Nicolas Capens41a73022020-01-30 00:30:14 -0500524
525public:
526 JITRoutine(
527 std::unique_ptr<llvm::Module> module,
528 llvm::Function **funcs,
529 size_t count,
530 const rr::Config &config)
Ben Claytone02d8932020-10-21 18:37:33 +0100531 : objectLayer(session, []() {
532 static MemoryMapper mm;
533 return std::make_unique<llvm::SectionMemoryManager>(&mm);
534 })
Ben Claytonee18f392020-10-19 16:54:21 -0400535 , compileLayer(session, objectLayer, std::make_unique<llvm::orc::ConcurrentIRCompiler>(JITGlobals::get()->getTargetMachineBuilder(config.getOptimization().getLevel())))
536 , mangle(session, JITGlobals::get()->getDataLayout())
537 , ctx(std::make_unique<llvm::LLVMContext>())
Antonio Maioranoec526ab2020-10-21 09:55:50 -0400538 , dylib(Unwrap(session.createJITDylib("<routine>")))
Nicolas Capens41a73022020-01-30 00:30:14 -0500539 , addresses(count)
540 {
Ben Claytona7bc2b92020-03-26 11:24:49 +0000541
Ben Claytonee18f392020-10-19 16:54:21 -0400542#ifdef ENABLE_RR_DEBUG_INFO
543 // TODO(b/165000222): Update this on next LLVM roll.
544 // https://github.com/llvm/llvm-project/commit/98f2bb4461072347dcca7d2b1b9571b3a6525801
545 // introduces RTDyldObjectLinkingLayer::registerJITEventListener().
546 // The current API does not appear to have any way to bind the
547 // rr::DebugInfo::NotifyFreeingObject event.
548 objectLayer.setNotifyLoaded([](llvm::orc::VModuleKey,
549 const llvm::object::ObjectFile &obj,
550 const llvm::RuntimeDyld::LoadedObjectInfo &l) {
551 static std::atomic<uint64_t> unique_key{ 0 };
552 rr::DebugInfo::NotifyObjectEmitted(unique_key++, obj, l);
553 });
554#endif // ENABLE_RR_DEBUG_INFO
Ben Claytona7bc2b92020-03-26 11:24:49 +0000555
Ben Claytonee18f392020-10-19 16:54:21 -0400556 if(JITGlobals::get()->getTargetTriple().isOSBinFormatCOFF())
557 {
558 // Hack to support symbol visibility in COFF.
559 // Matches hack in llvm::orc::LLJIT::createObjectLinkingLayer().
560 // See documentation on these functions for more detail.
561 objectLayer.setOverrideObjectFlagsWithResponsibilityFlags(true);
562 objectLayer.setAutoClaimResponsibilityForObjectSymbols(true);
563 }
564
565 dylib.addGenerator(std::make_unique<ExternalSymbolGenerator>());
566
567 llvm::SmallVector<llvm::orc::SymbolStringPtr, 8> names(count);
Nicolas Capens41a73022020-01-30 00:30:14 -0500568 for(size_t i = 0; i < count; i++)
569 {
570 auto func = funcs[i];
Nicolas Capens41a73022020-01-30 00:30:14 -0500571 func->setLinkage(llvm::GlobalValue::ExternalLinkage);
572 func->setDoesNotThrow();
Ben Claytonee18f392020-10-19 16:54:21 -0400573 if(!func->hasName())
574 {
575 func->setName("f" + llvm::Twine(i).str());
576 }
577 names[i] = mangle(func->getName());
Nicolas Capens41a73022020-01-30 00:30:14 -0500578 }
579
Nicolas Capens41a73022020-01-30 00:30:14 -0500580 // Once the module is passed to the compileLayer, the
581 // llvm::Functions are freed. Make sure funcs are not referenced
582 // after this point.
583 funcs = nullptr;
584
Ben Claytonee18f392020-10-19 16:54:21 -0400585 llvm::cantFail(compileLayer.add(dylib, llvm::orc::ThreadSafeModule(std::move(module), ctx)));
Nicolas Capens41a73022020-01-30 00:30:14 -0500586
587 // Resolve the function addresses.
588 for(size_t i = 0; i < count; i++)
589 {
Ben Claytonee18f392020-10-19 16:54:21 -0400590 auto symbol = session.lookup({ &dylib }, names[i]);
591 ASSERT_MSG(symbol, "Failed to lookup address of routine function %d: %s",
592 (int)i, llvm::toString(symbol.takeError()).c_str());
593 addresses[i] = reinterpret_cast<void *>(static_cast<intptr_t>(symbol->getAddress()));
Nicolas Capens41a73022020-01-30 00:30:14 -0500594 }
595 }
596
Antonio Maioranobb66fa42020-10-22 13:53:09 -0400597 ~JITRoutine()
598 {
Antonio Maioranoc1839ee2020-10-26 10:16:29 -0400599#if LLVM_VERSION_MAJOR >= 11 /* TODO(b/165000222): Unconditional after LLVM 11 upgrade */
600 if(auto err = session.endSession())
601 {
602 session.reportError(std::move(err));
603 }
Antonio Maioranobb66fa42020-10-22 13:53:09 -0400604#endif
605 }
606
Nicolas Capens41a73022020-01-30 00:30:14 -0500607 const void *getEntry(int index) const override
608 {
609 return addresses[index];
610 }
Nicolas Capens41a73022020-01-30 00:30:14 -0500611};
612
613} // anonymous namespace
614
615namespace rr {
616
617JITBuilder::JITBuilder(const rr::Config &config)
618 : config(config)
619 , module(new llvm::Module("", context))
620 , builder(new llvm::IRBuilder<>(context))
621{
Nicolas Capens959f4192020-11-02 15:30:30 -0500622 module->setTargetTriple(LLVM_DEFAULT_TARGET_TRIPLE);
Ben Claytonee18f392020-10-19 16:54:21 -0400623 module->setDataLayout(JITGlobals::get()->getDataLayout());
Nicolas Capens41a73022020-01-30 00:30:14 -0500624}
625
626void JITBuilder::optimize(const rr::Config &cfg)
627{
Nicolas Capens41a73022020-01-30 00:30:14 -0500628#ifdef ENABLE_RR_DEBUG_INFO
629 if(debugInfo != nullptr)
630 {
631 return; // Don't optimize if we're generating debug info.
632 }
633#endif // ENABLE_RR_DEBUG_INFO
634
Ben Claytonee18f392020-10-19 16:54:21 -0400635 llvm::legacy::PassManager passManager;
Nicolas Capens41a73022020-01-30 00:30:14 -0500636
637 for(auto pass : cfg.getOptimization().getPasses())
638 {
639 switch(pass)
640 {
641 case rr::Optimization::Pass::Disabled: break;
Ben Claytonee18f392020-10-19 16:54:21 -0400642 case rr::Optimization::Pass::CFGSimplification: passManager.add(llvm::createCFGSimplificationPass()); break;
643 case rr::Optimization::Pass::LICM: passManager.add(llvm::createLICMPass()); break;
644 case rr::Optimization::Pass::AggressiveDCE: passManager.add(llvm::createAggressiveDCEPass()); break;
645 case rr::Optimization::Pass::GVN: passManager.add(llvm::createGVNPass()); break;
646 case rr::Optimization::Pass::InstructionCombining: passManager.add(llvm::createInstructionCombiningPass()); break;
647 case rr::Optimization::Pass::Reassociate: passManager.add(llvm::createReassociatePass()); break;
648 case rr::Optimization::Pass::DeadStoreElimination: passManager.add(llvm::createDeadStoreEliminationPass()); break;
649 case rr::Optimization::Pass::SCCP: passManager.add(llvm::createSCCPPass()); break;
650 case rr::Optimization::Pass::ScalarReplAggregates: passManager.add(llvm::createSROAPass()); break;
651 case rr::Optimization::Pass::EarlyCSEPass: passManager.add(llvm::createEarlyCSEPass()); break;
Nicolas Capens41a73022020-01-30 00:30:14 -0500652 default:
653 UNREACHABLE("pass: %d", int(pass));
654 }
655 }
656
Ben Claytonee18f392020-10-19 16:54:21 -0400657 passManager.run(*module);
Nicolas Capens41a73022020-01-30 00:30:14 -0500658}
659
660std::shared_ptr<rr::Routine> JITBuilder::acquireRoutine(llvm::Function **funcs, size_t count, const rr::Config &cfg)
661{
662 ASSERT(module);
663 return std::make_shared<JITRoutine>(std::move(module), funcs, count, cfg);
664}
665
666} // namespace rr