blob: b284aa011220ef8f7d935134badac3018f4a3fb0 [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"
Antonio Maiorano6f6ca292020-11-27 15:40:15 -050019#include "LLVMAsm.hpp"
Nicolas Capensc9991d42021-06-16 00:46:28 -040020#include "PragmaInternals.hpp"
Nicolas Capens41a73022020-01-30 00:30:14 -050021#include "Routine.hpp"
22
Nicolas Capens41a73022020-01-30 00:30:14 -050023// TODO(b/143539525): Eliminate when warning has been fixed.
24#ifdef _MSC_VER
25__pragma(warning(push))
26 __pragma(warning(disable : 4146)) // unary minus operator applied to unsigned type, result still unsigned
27#endif
28
Nicolas Capens41a73022020-01-30 00:30:14 -050029#include "llvm/ExecutionEngine/Orc/CompileUtils.h"
30#include "llvm/ExecutionEngine/Orc/IRCompileLayer.h"
Nicolas Capens41a73022020-01-30 00:30:14 -050031#include "llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h"
Nicolas Capens41a73022020-01-30 00:30:14 -050032#include "llvm/ExecutionEngine/SectionMemoryManager.h"
Nicolas Capens25f0f852021-01-07 20:46:36 -050033#include "llvm/IR/DiagnosticInfo.h"
Nicolas Capens88fe9ce2022-04-19 18:32:26 -040034#include "llvm/IR/Verifier.h"
Nicolas Capens25f0f852021-01-07 20:46:36 -050035#include "llvm/Support/CommandLine.h"
Nicolas Capens827e9a22020-11-02 11:04:24 -050036#include "llvm/Support/Host.h"
Nicolas Capens41a73022020-01-30 00:30:14 -050037#include "llvm/Support/TargetSelect.h"
Nicolas Capens41a73022020-01-30 00:30:14 -050038#include "llvm/Transforms/InstCombine/InstCombine.h"
Nicolas Capens4804ac82020-11-02 22:06:55 -050039#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
Nicolas Capens41a73022020-01-30 00:30:14 -050040#include "llvm/Transforms/Scalar.h"
41#include "llvm/Transforms/Scalar/GVN.h"
42
Nicolas Capensea5f37f2022-04-19 16:08:20 -040043#if LLVM_VERSION_MAJOR >= 13 // New pass manager
44# include "llvm/IR/PassManager.h"
45# include "llvm/Passes/PassBuilder.h"
46# include "llvm/Transforms/Scalar/ADCE.h"
47# include "llvm/Transforms/Scalar/DeadStoreElimination.h"
48# include "llvm/Transforms/Scalar/EarlyCSE.h"
49# include "llvm/Transforms/Scalar/LICM.h"
50# include "llvm/Transforms/Scalar/Reassociate.h"
51# include "llvm/Transforms/Scalar/SCCP.h"
52# include "llvm/Transforms/Scalar/SROA.h"
53# include "llvm/Transforms/Scalar/SimplifyCFG.h"
54#else // Legacy pass manager
55# include "llvm/IR/LegacyPassManager.h"
Nicolas Capens88fe9ce2022-04-19 18:32:26 -040056# include "llvm/Pass.h"
57# include "llvm/Transforms/Coroutines.h"
58# include "llvm/Transforms/IPO.h"
Nicolas Capensea5f37f2022-04-19 16:08:20 -040059#endif
60
Nicolas Capens41a73022020-01-30 00:30:14 -050061#ifdef _MSC_VER
62 __pragma(warning(pop))
63#endif
64
Nicolas Capens79d4c6c2022-04-22 17:20:26 -040065#ifndef REACTOR_ASM_EMIT_DIR
66# define REACTOR_ASM_EMIT_DIR "./"
67#endif
68
Nicolas Capens41a73022020-01-30 00:30:14 -050069#if defined(_WIN64)
70 extern "C" void __chkstk();
71#elif defined(_WIN32)
72extern "C" void _chkstk();
73#endif
74
Anton D. Kachalovac4e1d22020-02-11 15:44:27 +010075#ifdef __ARM_EABI__
76extern "C" signed __aeabi_idivmod();
77#endif
78
Nicolas Capens47c3ca12020-11-02 16:33:08 -050079#if __has_feature(memory_sanitizer)
Nicolas Capensdc5bb212020-11-02 23:01:59 -050080
Nicolas Capensdc8cbfa2021-06-10 17:09:50 -040081// TODO(b/155148722): Remove when we no longer unpoison any writes.
82# include "sanitizer/msan_interface.h"
Nicolas Capens47c3ca12020-11-02 16:33:08 -050083
84# include <dlfcn.h> // dlsym()
Nicolas Capens4804ac82020-11-02 22:06:55 -050085
86// MemorySanitizer uses thread-local storage (TLS) data arrays for passing around
87// the 'shadow' values of function arguments and return values. The LLVM JIT can't
88// access TLS directly, but it calls __emutls_get_address() to obtain the address.
89// Typically, it would be passed a pointer to an __emutls_control structure with a
90// name starting with "__emutls_v." that represents the TLS. Both the address of
91// __emutls_get_address and the __emutls_v. structures are provided to the JIT by
92// the symbol resolver, which can be overridden.
93// We take advantage of this by substituting __emutls_get_address() with our own
94// implementation, namely rr::getTLSAddress(), and substituting the __emutls_v
95// variables with rr::MSanTLS enums. getTLSAddress() can then provide the address
96// of the real TLS variable corresponding to the enum, in statically compiled C++.
97
98// Forward declare the real TLS variables used by MemorySanitizer. These are
99// defined in llvm-project/compiler-rt/lib/msan/msan.cpp.
100extern __thread unsigned long long __msan_param_tls[];
101extern __thread unsigned long long __msan_retval_tls[];
102extern __thread unsigned long long __msan_va_arg_tls[];
103extern __thread unsigned long long __msan_va_arg_overflow_size_tls;
104
105namespace rr {
106
107enum class MSanTLS
108{
109 param = 1, // __msan_param_tls
110 retval, // __msan_retval_tls
111 va_arg, // __msan_va_arg_tls
112 va_arg_overflow_size // __msan_va_arg_overflow_size_tls
113};
114
115static void *getTLSAddress(void *control)
116{
117 auto tlsIndex = static_cast<MSanTLS>(reinterpret_cast<uintptr_t>(control));
118 switch(tlsIndex)
119 {
120
Nicolas Capens112faf42019-12-13 17:32:26 -0500121 case MSanTLS::param: return reinterpret_cast<void *>(&__msan_param_tls);
122 case MSanTLS::retval: return reinterpret_cast<void *>(&__msan_retval_tls);
123 case MSanTLS::va_arg: return reinterpret_cast<void *>(&__msan_va_arg_tls);
124 case MSanTLS::va_arg_overflow_size: return reinterpret_cast<void *>(&__msan_va_arg_overflow_size_tls);
125 default:
126 UNSUPPORTED("MemorySanitizer used an unrecognized TLS variable: %d", tlsIndex);
127 return nullptr;
Nicolas Capens4804ac82020-11-02 22:06:55 -0500128 }
129}
130
131} // namespace rr
Nicolas Capens47c3ca12020-11-02 16:33:08 -0500132#endif
133
Nicolas Capens41a73022020-01-30 00:30:14 -0500134namespace {
135
Nicolas Capens25f0f852021-01-07 20:46:36 -0500136// TODO(b/174587935): Eliminate command-line parsing.
137bool parseCommandLineOptionsOnce(int argc, const char *const *argv)
138{
139 // Use a static immediately invoked lambda to make this thread safe
140 static auto initialized = [=]() {
Nicolas Capensa8da8472021-02-05 04:48:15 -0500141 return llvm::cl::ParseCommandLineOptions(argc, argv);
Nicolas Capens25f0f852021-01-07 20:46:36 -0500142 }();
143
144 return initialized;
145}
146
Nicolas Capens41a73022020-01-30 00:30:14 -0500147// JITGlobals is a singleton that holds all the immutable machine specific
148// information for the host device.
149class JITGlobals
150{
151public:
Nicolas Capens41a73022020-01-30 00:30:14 -0500152 static JITGlobals *get();
153
Nicolas Capens79d4c6c2022-04-22 17:20:26 -0400154 llvm::orc::JITTargetMachineBuilder getTargetMachineBuilder() const;
Ben Claytonee18f392020-10-19 16:54:21 -0400155 const llvm::DataLayout &getDataLayout() const;
Nicolas Capens827e9a22020-11-02 11:04:24 -0500156 const llvm::Triple &getTargetTriple() const;
Nicolas Capens41a73022020-01-30 00:30:14 -0500157
158private:
Nicolas Capens827e9a22020-11-02 11:04:24 -0500159 JITGlobals(llvm::orc::JITTargetMachineBuilder &&jitTargetMachineBuilder, llvm::DataLayout &&dataLayout);
Ben Claytonee18f392020-10-19 16:54:21 -0400160
Nicolas Capens79d4c6c2022-04-22 17:20:26 -0400161 static llvm::CodeGenOpt::Level toLLVM(int level);
Nicolas Capens827e9a22020-11-02 11:04:24 -0500162
163 const llvm::orc::JITTargetMachineBuilder jitTargetMachineBuilder;
Ben Claytonee18f392020-10-19 16:54:21 -0400164 const llvm::DataLayout dataLayout;
Nicolas Capens41a73022020-01-30 00:30:14 -0500165};
166
167JITGlobals *JITGlobals::get()
168{
Ben Claytonee18f392020-10-19 16:54:21 -0400169 static JITGlobals instance = [] {
Nicolas Capens25f0f852021-01-07 20:46:36 -0500170 const char *argv[] = {
171 "Reactor",
Nicolas Capensa8da8472021-02-05 04:48:15 -0500172#if defined(__i386__) || defined(__x86_64__)
173 "-x86-asm-syntax=intel", // Use Intel syntax rather than the default AT&T
174#endif
Nicolas Capensf679fc12021-06-25 14:50:41 -0400175#if LLVM_VERSION_MAJOR <= 12
Nicolas Capensf13461d2022-04-20 15:33:24 -0400176 "-warn-stack-size=524288", // Warn when a function uses more than 512 KiB of stack memory
Nicolas Capens84bc1982021-06-15 21:44:31 -0400177#endif
Nicolas Capens25f0f852021-01-07 20:46:36 -0500178 };
179
180 parseCommandLineOptionsOnce(sizeof(argv) / sizeof(argv[0]), argv);
181
Ben Claytonee18f392020-10-19 16:54:21 -0400182 llvm::InitializeNativeTarget();
183 llvm::InitializeNativeTargetAsmPrinter();
184 llvm::InitializeNativeTargetAsmParser();
185
Nicolas Capens827e9a22020-11-02 11:04:24 -0500186 // TODO(b/171236524): JITTargetMachineBuilder::detectHost() currently uses the target triple of the host,
187 // rather than a valid triple for the current process. Once fixed, we can use that function instead.
188 llvm::orc::JITTargetMachineBuilder jitTargetMachineBuilder(llvm::Triple(LLVM_DEFAULT_TARGET_TRIPLE));
189
190 // Retrieve host CPU name and sub-target features and add them to builder.
191 // Relocation model, code model and codegen opt level are kept to default values.
192 llvm::StringMap<bool> cpuFeatures;
193 bool ok = llvm::sys::getHostCPUFeatures(cpuFeatures);
194
195#if defined(__i386__) || defined(__x86_64__) || \
196 (defined(__linux__) && (defined(__arm__) || defined(__aarch64__)))
197 ASSERT_MSG(ok, "llvm::sys::getHostCPUFeatures returned false");
198#else
199 (void)ok; // getHostCPUFeatures always returns false on other platforms
200#endif
201
202 for(auto &feature : cpuFeatures)
203 {
204 jitTargetMachineBuilder.getFeatures().AddFeature(feature.first(), feature.second);
205 }
206
207#if LLVM_VERSION_MAJOR >= 11 /* TODO(b/165000222): Unconditional after LLVM 11 upgrade */
208 jitTargetMachineBuilder.setCPU(std::string(llvm::sys::getHostCPUName()));
209#else
210 jitTargetMachineBuilder.setCPU(llvm::sys::getHostCPUName());
211#endif
212
Nicolas Capens4804ac82020-11-02 22:06:55 -0500213 // Reactor's MemorySanitizer support depends on intercepting __emutls_get_address calls.
214 ASSERT(!__has_feature(memory_sanitizer) || (jitTargetMachineBuilder.getOptions().ExplicitEmulatedTLS &&
215 jitTargetMachineBuilder.getOptions().EmulatedTLS));
216
Nicolas Capens827e9a22020-11-02 11:04:24 -0500217 auto dataLayout = jitTargetMachineBuilder.getDefaultDataLayoutForTarget();
Ben Claytonee18f392020-10-19 16:54:21 -0400218 ASSERT_MSG(dataLayout, "JITTargetMachineBuilder::getDefaultDataLayoutForTarget() failed");
Nicolas Capens827e9a22020-11-02 11:04:24 -0500219
220 return JITGlobals(std::move(jitTargetMachineBuilder), std::move(dataLayout.get()));
Ben Claytonee18f392020-10-19 16:54:21 -0400221 }();
Nicolas Capens827e9a22020-11-02 11:04:24 -0500222
Nicolas Capens41a73022020-01-30 00:30:14 -0500223 return &instance;
224}
225
Nicolas Capens79d4c6c2022-04-22 17:20:26 -0400226llvm::orc::JITTargetMachineBuilder JITGlobals::getTargetMachineBuilder() const
Nicolas Capens41a73022020-01-30 00:30:14 -0500227{
Nicolas Capens827e9a22020-11-02 11:04:24 -0500228 llvm::orc::JITTargetMachineBuilder out = jitTargetMachineBuilder;
Nicolas Capens79d4c6c2022-04-22 17:20:26 -0400229 out.setCodeGenOptLevel(toLLVM(rr::getPragmaState(rr::OptimizationLevel)));
Nicolas Capens827e9a22020-11-02 11:04:24 -0500230
Ben Claytonee18f392020-10-19 16:54:21 -0400231 return out;
Nicolas Capens41a73022020-01-30 00:30:14 -0500232}
233
Ben Claytonee18f392020-10-19 16:54:21 -0400234const llvm::DataLayout &JITGlobals::getDataLayout() const
Nicolas Capens41a73022020-01-30 00:30:14 -0500235{
Ben Claytonee18f392020-10-19 16:54:21 -0400236 return dataLayout;
237}
Nicolas Capens41a73022020-01-30 00:30:14 -0500238
Nicolas Capens827e9a22020-11-02 11:04:24 -0500239const llvm::Triple &JITGlobals::getTargetTriple() const
Ben Claytonee18f392020-10-19 16:54:21 -0400240{
Nicolas Capens827e9a22020-11-02 11:04:24 -0500241 return jitTargetMachineBuilder.getTargetTriple();
Ben Claytonee18f392020-10-19 16:54:21 -0400242}
Nicolas Capens41a73022020-01-30 00:30:14 -0500243
Nicolas Capens827e9a22020-11-02 11:04:24 -0500244JITGlobals::JITGlobals(llvm::orc::JITTargetMachineBuilder &&jitTargetMachineBuilder, llvm::DataLayout &&dataLayout)
245 : jitTargetMachineBuilder(jitTargetMachineBuilder)
Ben Claytonee18f392020-10-19 16:54:21 -0400246 , dataLayout(dataLayout)
247{
Nicolas Capens41a73022020-01-30 00:30:14 -0500248}
249
Nicolas Capens79d4c6c2022-04-22 17:20:26 -0400250llvm::CodeGenOpt::Level JITGlobals::toLLVM(int level)
Nicolas Capens41a73022020-01-30 00:30:14 -0500251{
Nicolas Capens259ce702020-11-18 11:32:05 -0500252 // TODO(b/173257647): MemorySanitizer instrumentation produces IR which takes
253 // a lot longer to process by the machine code optimization passes. Disabling
254 // them has a negligible effect on code quality but compiles much faster.
255 if(__has_feature(memory_sanitizer))
256 {
257 return llvm::CodeGenOpt::None;
258 }
259
Nicolas Capens41a73022020-01-30 00:30:14 -0500260 switch(level)
261 {
Nicolas Capens79d4c6c2022-04-22 17:20:26 -0400262 case 0: return llvm::CodeGenOpt::None;
263 case 1: return llvm::CodeGenOpt::Less;
264 case 2: return llvm::CodeGenOpt::Default;
265 case 3: return llvm::CodeGenOpt::Aggressive;
Nicolas Capens112faf42019-12-13 17:32:26 -0500266 default: UNREACHABLE("Unknown Optimization Level %d", int(level));
Nicolas Capens41a73022020-01-30 00:30:14 -0500267 }
Nicolas Capens259ce702020-11-18 11:32:05 -0500268
Nicolas Capens00ecdf92020-10-30 21:13:40 -0400269 return llvm::CodeGenOpt::Default;
Nicolas Capens41a73022020-01-30 00:30:14 -0500270}
271
David 'Digit' Turner48f3f6c2020-03-23 14:23:10 +0100272class MemoryMapper final : public llvm::SectionMemoryManager::MemoryMapper
Nicolas Capens41a73022020-01-30 00:30:14 -0500273{
274public:
275 MemoryMapper() {}
276 ~MemoryMapper() final {}
277
278 llvm::sys::MemoryBlock allocateMappedMemory(
279 llvm::SectionMemoryManager::AllocationPurpose purpose,
280 size_t numBytes, const llvm::sys::MemoryBlock *const nearBlock,
281 unsigned flags, std::error_code &errorCode) final
282 {
283 errorCode = std::error_code();
284
285 // Round up numBytes to page size.
286 size_t pageSize = rr::memoryPageSize();
287 numBytes = (numBytes + pageSize - 1) & ~(pageSize - 1);
288
289 bool need_exec =
290 purpose == llvm::SectionMemoryManager::AllocationPurpose::Code;
291 void *addr = rr::allocateMemoryPages(
292 numBytes, flagsToPermissions(flags), need_exec);
293 if(!addr)
294 return llvm::sys::MemoryBlock();
295 return llvm::sys::MemoryBlock(addr, numBytes);
296 }
297
298 std::error_code protectMappedMemory(const llvm::sys::MemoryBlock &block,
299 unsigned flags)
300 {
301 // Round down base address to align with a page boundary. This matches
302 // DefaultMMapper behavior.
303 void *addr = block.base();
Nicolas Capens41a73022020-01-30 00:30:14 -0500304 size_t size = block.allocatedSize();
Nicolas Capens41a73022020-01-30 00:30:14 -0500305 size_t pageSize = rr::memoryPageSize();
306 addr = reinterpret_cast<void *>(
307 reinterpret_cast<uintptr_t>(addr) & ~(pageSize - 1));
308 size += reinterpret_cast<uintptr_t>(block.base()) -
309 reinterpret_cast<uintptr_t>(addr);
310
311 rr::protectMemoryPages(addr, size, flagsToPermissions(flags));
312 return std::error_code();
313 }
314
315 std::error_code releaseMappedMemory(llvm::sys::MemoryBlock &block)
316 {
Nicolas Capens41a73022020-01-30 00:30:14 -0500317 size_t size = block.allocatedSize();
Nicolas Capens41a73022020-01-30 00:30:14 -0500318
319 rr::deallocateMemoryPages(block.base(), size);
320 return std::error_code();
321 }
322
323private:
324 int flagsToPermissions(unsigned flags)
325 {
326 int result = 0;
327 if(flags & llvm::sys::Memory::MF_READ)
328 {
329 result |= rr::PERMISSION_READ;
330 }
331 if(flags & llvm::sys::Memory::MF_WRITE)
332 {
333 result |= rr::PERMISSION_WRITE;
334 }
335 if(flags & llvm::sys::Memory::MF_EXEC)
336 {
337 result |= rr::PERMISSION_EXECUTE;
338 }
339 return result;
340 }
341};
342
343template<typename T>
344T alignUp(T val, T alignment)
345{
346 return alignment * ((val + alignment - 1) / alignment);
347}
348
349void *alignedAlloc(size_t size, size_t alignment)
350{
351 ASSERT(alignment < 256);
352 auto allocation = new uint8_t[size + sizeof(uint8_t) + alignment];
353 auto aligned = allocation;
354 aligned += sizeof(uint8_t); // Make space for the base-address offset.
355 aligned = reinterpret_cast<uint8_t *>(alignUp(reinterpret_cast<uintptr_t>(aligned), alignment)); // align
356 auto offset = static_cast<uint8_t>(aligned - allocation);
357 aligned[-1] = offset;
358 return aligned;
359}
360
361void alignedFree(void *ptr)
362{
363 auto aligned = reinterpret_cast<uint8_t *>(ptr);
364 auto offset = aligned[-1];
365 auto allocation = aligned - offset;
366 delete[] allocation;
367}
368
369template<typename T>
370static void atomicLoad(void *ptr, void *ret, llvm::AtomicOrdering ordering)
371{
372 *reinterpret_cast<T *>(ret) = std::atomic_load_explicit<T>(reinterpret_cast<std::atomic<T> *>(ptr), rr::atomicOrdering(ordering));
373}
374
375template<typename T>
376static void atomicStore(void *ptr, void *val, llvm::AtomicOrdering ordering)
377{
378 std::atomic_store_explicit<T>(reinterpret_cast<std::atomic<T> *>(ptr), *reinterpret_cast<T *>(val), rr::atomicOrdering(ordering));
379}
380
381#ifdef __ANDROID__
382template<typename F>
383static uint32_t sync_fetch_and_op(uint32_t volatile *ptr, uint32_t val, F f)
384{
385 // Build an arbitrary op out of looped CAS
386 for(;;)
387 {
388 uint32_t expected = *ptr;
389 uint32_t desired = f(expected, val);
390
391 if(expected == __sync_val_compare_and_swap_4(ptr, expected, desired))
392 {
393 return expected;
394 }
395 }
396}
397#endif
398
Antonio Maioranoc1839ee2020-10-26 10:16:29 -0400399#if LLVM_VERSION_MAJOR >= 11 /* TODO(b/165000222): Unconditional after LLVM 11 upgrade */
400class ExternalSymbolGenerator : public llvm::orc::DefinitionGenerator
401#else
Ben Claytonee18f392020-10-19 16:54:21 -0400402class ExternalSymbolGenerator : public llvm::orc::JITDylib::DefinitionGenerator
Antonio Maioranoc1839ee2020-10-26 10:16:29 -0400403#endif
Nicolas Capens41a73022020-01-30 00:30:14 -0500404{
405 struct Atomic
406 {
407 static void load(size_t size, void *ptr, void *ret, llvm::AtomicOrdering ordering)
408 {
409 switch(size)
410 {
Nicolas Capens112faf42019-12-13 17:32:26 -0500411 case 1: atomicLoad<uint8_t>(ptr, ret, ordering); break;
412 case 2: atomicLoad<uint16_t>(ptr, ret, ordering); break;
413 case 4: atomicLoad<uint32_t>(ptr, ret, ordering); break;
414 case 8: atomicLoad<uint64_t>(ptr, ret, ordering); break;
415 default:
416 UNIMPLEMENTED_NO_BUG("Atomic::load(size: %d)", int(size));
Nicolas Capens41a73022020-01-30 00:30:14 -0500417 }
418 }
419 static void store(size_t size, void *ptr, void *ret, llvm::AtomicOrdering ordering)
420 {
421 switch(size)
422 {
Nicolas Capens112faf42019-12-13 17:32:26 -0500423 case 1: atomicStore<uint8_t>(ptr, ret, ordering); break;
424 case 2: atomicStore<uint16_t>(ptr, ret, ordering); break;
425 case 4: atomicStore<uint32_t>(ptr, ret, ordering); break;
426 case 8: atomicStore<uint64_t>(ptr, ret, ordering); break;
427 default:
428 UNIMPLEMENTED_NO_BUG("Atomic::store(size: %d)", int(size));
Nicolas Capens41a73022020-01-30 00:30:14 -0500429 }
430 }
431 };
432
Ben Claytonee18f392020-10-19 16:54:21 -0400433 static void nop() {}
434 static void neverCalled() { UNREACHABLE("Should never be called"); }
Nicolas Capens41a73022020-01-30 00:30:14 -0500435
Ben Claytonee18f392020-10-19 16:54:21 -0400436 static void *coroutine_alloc_frame(size_t size) { return alignedAlloc(size, 16); }
437 static void coroutine_free_frame(void *ptr) { alignedFree(ptr); }
Nicolas Capens41a73022020-01-30 00:30:14 -0500438
439#ifdef __ANDROID__
Ben Claytonee18f392020-10-19 16:54:21 -0400440 // forwarders since we can't take address of builtins
441 static void sync_synchronize() { __sync_synchronize(); }
442 static uint32_t sync_fetch_and_add_4(uint32_t *ptr, uint32_t val) { return __sync_fetch_and_add_4(ptr, val); }
443 static uint32_t sync_fetch_and_and_4(uint32_t *ptr, uint32_t val) { return __sync_fetch_and_and_4(ptr, val); }
444 static uint32_t sync_fetch_and_or_4(uint32_t *ptr, uint32_t val) { return __sync_fetch_and_or_4(ptr, val); }
445 static uint32_t sync_fetch_and_xor_4(uint32_t *ptr, uint32_t val) { return __sync_fetch_and_xor_4(ptr, val); }
446 static uint32_t sync_fetch_and_sub_4(uint32_t *ptr, uint32_t val) { return __sync_fetch_and_sub_4(ptr, val); }
447 static uint32_t sync_lock_test_and_set_4(uint32_t *ptr, uint32_t val) { return __sync_lock_test_and_set_4(ptr, val); }
448 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 -0500449
Ben Claytonee18f392020-10-19 16:54:21 -0400450 static uint32_t sync_fetch_and_max_4(uint32_t *ptr, uint32_t val)
451 {
452 return sync_fetch_and_op(ptr, val, [](int32_t a, int32_t b) { return std::max(a, b); });
453 }
454 static uint32_t sync_fetch_and_min_4(uint32_t *ptr, uint32_t val)
455 {
456 return sync_fetch_and_op(ptr, val, [](int32_t a, int32_t b) { return std::min(a, b); });
457 }
458 static uint32_t sync_fetch_and_umax_4(uint32_t *ptr, uint32_t val)
459 {
460 return sync_fetch_and_op(ptr, val, [](uint32_t a, uint32_t b) { return std::max(a, b); });
461 }
462 static uint32_t sync_fetch_and_umin_4(uint32_t *ptr, uint32_t val)
463 {
464 return sync_fetch_and_op(ptr, val, [](uint32_t a, uint32_t b) { return std::min(a, b); });
465 }
Nicolas Capens41a73022020-01-30 00:30:14 -0500466#endif
Nicolas Capens47c3ca12020-11-02 16:33:08 -0500467
Nicolas Capens41a73022020-01-30 00:30:14 -0500468 class Resolver
469 {
470 public:
Ben Claytonee18f392020-10-19 16:54:21 -0400471 using FunctionMap = llvm::StringMap<void *>;
Nicolas Capens41a73022020-01-30 00:30:14 -0500472
473 FunctionMap functions;
474
475 Resolver()
476 {
Antonio Maiorano8cbee412020-06-10 15:59:20 -0400477#ifdef ENABLE_RR_PRINT
Ben Claytonee18f392020-10-19 16:54:21 -0400478 functions.try_emplace("rr::DebugPrintf", reinterpret_cast<void *>(rr::DebugPrintf));
Antonio Maiorano8cbee412020-06-10 15:59:20 -0400479#endif
Ben Claytonee18f392020-10-19 16:54:21 -0400480 functions.try_emplace("nop", reinterpret_cast<void *>(nop));
481 functions.try_emplace("floorf", reinterpret_cast<void *>(floorf));
482 functions.try_emplace("nearbyintf", reinterpret_cast<void *>(nearbyintf));
483 functions.try_emplace("truncf", reinterpret_cast<void *>(truncf));
484 functions.try_emplace("printf", reinterpret_cast<void *>(printf));
485 functions.try_emplace("puts", reinterpret_cast<void *>(puts));
486 functions.try_emplace("fmodf", reinterpret_cast<void *>(fmodf));
Nicolas Capens41a73022020-01-30 00:30:14 -0500487
Ben Claytonee18f392020-10-19 16:54:21 -0400488 functions.try_emplace("sinf", reinterpret_cast<void *>(sinf));
489 functions.try_emplace("cosf", reinterpret_cast<void *>(cosf));
490 functions.try_emplace("asinf", reinterpret_cast<void *>(asinf));
491 functions.try_emplace("acosf", reinterpret_cast<void *>(acosf));
492 functions.try_emplace("atanf", reinterpret_cast<void *>(atanf));
493 functions.try_emplace("sinhf", reinterpret_cast<void *>(sinhf));
494 functions.try_emplace("coshf", reinterpret_cast<void *>(coshf));
495 functions.try_emplace("tanhf", reinterpret_cast<void *>(tanhf));
496 functions.try_emplace("asinhf", reinterpret_cast<void *>(asinhf));
497 functions.try_emplace("acoshf", reinterpret_cast<void *>(acoshf));
498 functions.try_emplace("atanhf", reinterpret_cast<void *>(atanhf));
499 functions.try_emplace("atan2f", reinterpret_cast<void *>(atan2f));
500 functions.try_emplace("powf", reinterpret_cast<void *>(powf));
501 functions.try_emplace("expf", reinterpret_cast<void *>(expf));
502 functions.try_emplace("logf", reinterpret_cast<void *>(logf));
503 functions.try_emplace("exp2f", reinterpret_cast<void *>(exp2f));
504 functions.try_emplace("log2f", reinterpret_cast<void *>(log2f));
Nicolas Capens75d79f22022-01-31 17:46:26 -0500505 functions.try_emplace("fmaf", reinterpret_cast<void *>(fmaf));
Nicolas Capens41a73022020-01-30 00:30:14 -0500506
Antonio Maioranoe9fa2092020-11-23 10:22:49 -0500507 functions.try_emplace("fmod", reinterpret_cast<void *>(static_cast<double (*)(double, double)>(fmod)));
Ben Claytonee18f392020-10-19 16:54:21 -0400508 functions.try_emplace("sin", reinterpret_cast<void *>(static_cast<double (*)(double)>(sin)));
509 functions.try_emplace("cos", reinterpret_cast<void *>(static_cast<double (*)(double)>(cos)));
510 functions.try_emplace("asin", reinterpret_cast<void *>(static_cast<double (*)(double)>(asin)));
511 functions.try_emplace("acos", reinterpret_cast<void *>(static_cast<double (*)(double)>(acos)));
512 functions.try_emplace("atan", reinterpret_cast<void *>(static_cast<double (*)(double)>(atan)));
513 functions.try_emplace("sinh", reinterpret_cast<void *>(static_cast<double (*)(double)>(sinh)));
514 functions.try_emplace("cosh", reinterpret_cast<void *>(static_cast<double (*)(double)>(cosh)));
515 functions.try_emplace("tanh", reinterpret_cast<void *>(static_cast<double (*)(double)>(tanh)));
516 functions.try_emplace("asinh", reinterpret_cast<void *>(static_cast<double (*)(double)>(asinh)));
517 functions.try_emplace("acosh", reinterpret_cast<void *>(static_cast<double (*)(double)>(acosh)));
518 functions.try_emplace("atanh", reinterpret_cast<void *>(static_cast<double (*)(double)>(atanh)));
519 functions.try_emplace("atan2", reinterpret_cast<void *>(static_cast<double (*)(double, double)>(atan2)));
520 functions.try_emplace("pow", reinterpret_cast<void *>(static_cast<double (*)(double, double)>(pow)));
521 functions.try_emplace("exp", reinterpret_cast<void *>(static_cast<double (*)(double)>(exp)));
522 functions.try_emplace("log", reinterpret_cast<void *>(static_cast<double (*)(double)>(log)));
523 functions.try_emplace("exp2", reinterpret_cast<void *>(static_cast<double (*)(double)>(exp2)));
524 functions.try_emplace("log2", reinterpret_cast<void *>(static_cast<double (*)(double)>(log2)));
Nicolas Capens41a73022020-01-30 00:30:14 -0500525
Ben Claytonee18f392020-10-19 16:54:21 -0400526 functions.try_emplace("atomic_load", reinterpret_cast<void *>(Atomic::load));
527 functions.try_emplace("atomic_store", reinterpret_cast<void *>(Atomic::store));
Nicolas Capens41a73022020-01-30 00:30:14 -0500528
529 // FIXME(b/119409619): use an allocator here so we can control all memory allocations
Ben Claytonee18f392020-10-19 16:54:21 -0400530 functions.try_emplace("coroutine_alloc_frame", reinterpret_cast<void *>(coroutine_alloc_frame));
531 functions.try_emplace("coroutine_free_frame", reinterpret_cast<void *>(coroutine_free_frame));
Nicolas Capens41a73022020-01-30 00:30:14 -0500532
Nicolas Capens4804ac82020-11-02 22:06:55 -0500533 functions.try_emplace("memset", reinterpret_cast<void *>(memset));
534
Nicolas Capens41a73022020-01-30 00:30:14 -0500535#ifdef __APPLE__
Ben Claytonee18f392020-10-19 16:54:21 -0400536 functions.try_emplace("sincosf_stret", reinterpret_cast<void *>(__sincosf_stret));
Nicolas Capens41a73022020-01-30 00:30:14 -0500537#elif defined(__linux__)
Ben Claytonee18f392020-10-19 16:54:21 -0400538 functions.try_emplace("sincosf", reinterpret_cast<void *>(sincosf));
Nicolas Capens41a73022020-01-30 00:30:14 -0500539#elif defined(_WIN64)
Ben Claytonee18f392020-10-19 16:54:21 -0400540 functions.try_emplace("chkstk", reinterpret_cast<void *>(__chkstk));
Nicolas Capens41a73022020-01-30 00:30:14 -0500541#elif defined(_WIN32)
Ben Claytonee18f392020-10-19 16:54:21 -0400542 functions.try_emplace("chkstk", reinterpret_cast<void *>(_chkstk));
Nicolas Capens41a73022020-01-30 00:30:14 -0500543#endif
544
Anton D. Kachalovac4e1d22020-02-11 15:44:27 +0100545#ifdef __ARM_EABI__
Ben Claytonee18f392020-10-19 16:54:21 -0400546 functions.try_emplace("aeabi_idivmod", reinterpret_cast<void *>(__aeabi_idivmod));
Anton D. Kachalovac4e1d22020-02-11 15:44:27 +0100547#endif
Nicolas Capens41a73022020-01-30 00:30:14 -0500548#ifdef __ANDROID__
Antonio Maiorano84f5eeb2020-10-20 20:39:34 -0400549 functions.try_emplace("aeabi_unwind_cpp_pr0", reinterpret_cast<void *>(neverCalled));
550 functions.try_emplace("sync_synchronize", reinterpret_cast<void *>(sync_synchronize));
551 functions.try_emplace("sync_fetch_and_add_4", reinterpret_cast<void *>(sync_fetch_and_add_4));
552 functions.try_emplace("sync_fetch_and_and_4", reinterpret_cast<void *>(sync_fetch_and_and_4));
553 functions.try_emplace("sync_fetch_and_or_4", reinterpret_cast<void *>(sync_fetch_and_or_4));
554 functions.try_emplace("sync_fetch_and_xor_4", reinterpret_cast<void *>(sync_fetch_and_xor_4));
555 functions.try_emplace("sync_fetch_and_sub_4", reinterpret_cast<void *>(sync_fetch_and_sub_4));
556 functions.try_emplace("sync_lock_test_and_set_4", reinterpret_cast<void *>(sync_lock_test_and_set_4));
557 functions.try_emplace("sync_val_compare_and_swap_4", reinterpret_cast<void *>(sync_val_compare_and_swap_4));
558 functions.try_emplace("sync_fetch_and_max_4", reinterpret_cast<void *>(sync_fetch_and_max_4));
559 functions.try_emplace("sync_fetch_and_min_4", reinterpret_cast<void *>(sync_fetch_and_min_4));
560 functions.try_emplace("sync_fetch_and_umax_4", reinterpret_cast<void *>(sync_fetch_and_umax_4));
561 functions.try_emplace("sync_fetch_and_umin_4", reinterpret_cast<void *>(sync_fetch_and_umin_4));
Nicolas Capens3e551b32020-11-13 21:04:36 +0000562
563# if defined(__i386__)
564 // TODO(b/172974501): Workaround for an x86-32 issue where an R_386_PC32 relocation is used
565 // When calling a C function from Reactor code, who's address is not associated with any symbol
566 // (since it's an absolute constant), but it still invokes the symbol resolver for "".
567 functions.try_emplace("", nullptr);
568# endif
Nicolas Capens41a73022020-01-30 00:30:14 -0500569#endif
Antonio Maioranodd48b7e2020-02-05 13:17:07 -0500570#if __has_feature(memory_sanitizer)
Nicolas Capens4804ac82020-11-02 22:06:55 -0500571 functions.try_emplace("emutls_get_address", reinterpret_cast<void *>(rr::getTLSAddress));
572 functions.try_emplace("emutls_v.__msan_retval_tls", reinterpret_cast<void *>(static_cast<uintptr_t>(rr::MSanTLS::retval)));
573 functions.try_emplace("emutls_v.__msan_param_tls", reinterpret_cast<void *>(static_cast<uintptr_t>(rr::MSanTLS::param)));
574 functions.try_emplace("emutls_v.__msan_va_arg_tls", reinterpret_cast<void *>(static_cast<uintptr_t>(rr::MSanTLS::va_arg)));
575 functions.try_emplace("emutls_v.__msan_va_arg_overflow_size_tls", reinterpret_cast<void *>(static_cast<uintptr_t>(rr::MSanTLS::va_arg_overflow_size)));
Nicolas Capensdc8cbfa2021-06-10 17:09:50 -0400576
577 // TODO(b/155148722): Remove when we no longer unpoison any writes.
578 functions.try_emplace("msan_unpoison", reinterpret_cast<void *>(__msan_unpoison));
579 functions.try_emplace("msan_unpoison_param", reinterpret_cast<void *>(__msan_unpoison_param));
Antonio Maioranodd48b7e2020-02-05 13:17:07 -0500580#endif
Nicolas Capens41a73022020-01-30 00:30:14 -0500581 }
582 };
583
Antonio Maioranoc1839ee2020-10-26 10:16:29 -0400584 llvm::Error tryToGenerate(
585#if LLVM_VERSION_MAJOR >= 11 /* TODO(b/165000222): Unconditional after LLVM 11 upgrade */
586 llvm::orc::LookupState &state,
587#endif
588 llvm::orc::LookupKind kind,
589 llvm::orc::JITDylib &dylib,
590 llvm::orc::JITDylibLookupFlags flags,
591 const llvm::orc::SymbolLookupSet &set) override
Ben Claytonee18f392020-10-19 16:54:21 -0400592 {
593 static Resolver resolver;
Nicolas Capens41a73022020-01-30 00:30:14 -0500594
Ben Claytonee18f392020-10-19 16:54:21 -0400595 llvm::orc::SymbolMap symbols;
Nicolas Capens41a73022020-01-30 00:30:14 -0500596
Ben Claytonee18f392020-10-19 16:54:21 -0400597#if !defined(NDEBUG) || defined(DCHECK_ALWAYS_ON)
598 std::string missing;
599#endif // !defined(NDEBUG) || defined(DCHECK_ALWAYS_ON)
600
601 for(auto symbol : set)
602 {
603 auto name = symbol.first;
604
605 // Trim off any underscores from the start of the symbol. LLVM likes
606 // to append these on macOS.
607 auto trimmed = (*name).drop_while([](char c) { return c == '_'; });
608
609 auto it = resolver.functions.find(trimmed.str());
610 if(it != resolver.functions.end())
611 {
612 symbols[name] = llvm::JITEvaluatedSymbol(
613 static_cast<llvm::JITTargetAddress>(reinterpret_cast<uintptr_t>(it->second)),
614 llvm::JITSymbolFlags::Exported);
Nicolas Capens47c3ca12020-11-02 16:33:08 -0500615
616 continue;
Ben Claytonee18f392020-10-19 16:54:21 -0400617 }
Nicolas Capens47c3ca12020-11-02 16:33:08 -0500618
619#if __has_feature(memory_sanitizer)
620 // MemorySanitizer uses a dynamically linked runtime. Instrumented routines reference
621 // some symbols from this library. Look them up dynamically in the default namespace.
622 // Note this approach should not be used for other symbols, since they might not be
623 // visible (e.g. due to static linking), we may wish to provide an alternate
624 // implementation, and/or it would be a security vulnerability.
625
626 void *address = dlsym(RTLD_DEFAULT, (*symbol.first).data());
627
628 if(address)
Ben Claytonee18f392020-10-19 16:54:21 -0400629 {
Nicolas Capens47c3ca12020-11-02 16:33:08 -0500630 symbols[name] = llvm::JITEvaluatedSymbol(
631 static_cast<llvm::JITTargetAddress>(reinterpret_cast<uintptr_t>(address)),
632 llvm::JITSymbolFlags::Exported);
633
634 continue;
Ben Claytonee18f392020-10-19 16:54:21 -0400635 }
Nicolas Capens47c3ca12020-11-02 16:33:08 -0500636#endif
637
638#if !defined(NDEBUG) || defined(DCHECK_ALWAYS_ON)
639 missing += (missing.empty() ? "'" : ", '") + (*name).str() + "'";
640#endif
Ben Claytonee18f392020-10-19 16:54:21 -0400641 }
642
643#if !defined(NDEBUG) || defined(DCHECK_ALWAYS_ON)
Nicolas Capens47c3ca12020-11-02 16:33:08 -0500644 // Missing functions will likely make the module fail in non-obvious ways.
Ben Claytonee18f392020-10-19 16:54:21 -0400645 if(!missing.empty())
646 {
647 WARN("Missing external functions: %s", missing.c_str());
648 }
Nicolas Capens47c3ca12020-11-02 16:33:08 -0500649#endif
Ben Claytonee18f392020-10-19 16:54:21 -0400650
651 if(symbols.empty())
652 {
653 return llvm::Error::success();
654 }
655
656 return dylib.define(llvm::orc::absoluteSymbols(std::move(symbols)));
657 }
658};
Nicolas Capens41a73022020-01-30 00:30:14 -0500659
Antonio Maioranoec526ab2020-10-21 09:55:50 -0400660// As we must support different LLVM versions, add a generic Unwrap for functions that return Expected<T> or the actual T.
661// TODO(b/165000222): Remove after LLVM 11 upgrade
662template<typename T>
Nicolas Capens3fbdc262022-02-25 00:15:00 -0500663T &Unwrap(llvm::Expected<T> &&v)
Antonio Maioranoec526ab2020-10-21 09:55:50 -0400664{
Nicolas Capens3fbdc262022-02-25 00:15:00 -0500665 assert(v);
Antonio Maioranoec526ab2020-10-21 09:55:50 -0400666 return v.get();
667}
668template<typename T>
Nicolas Capens3fbdc262022-02-25 00:15:00 -0500669T &Unwrap(T &&v)
Antonio Maioranoec526ab2020-10-21 09:55:50 -0400670{
671 return v;
672}
673
Nicolas Capens25f0f852021-01-07 20:46:36 -0500674// Sets *fatal to true if a diagnostic is received which makes a routine invalid or unusable.
675struct FatalDiagnosticsHandler : public llvm::DiagnosticHandler
676{
677 FatalDiagnosticsHandler(bool *fatal)
678 : fatal(fatal)
679 {}
680
681 bool handleDiagnostics(const llvm::DiagnosticInfo &info) override
682 {
683 switch(info.getSeverity())
684 {
Nicolas Capens112faf42019-12-13 17:32:26 -0500685 case llvm::DS_Error:
686 ASSERT_MSG(false, "LLVM JIT compilation failure");
687 *fatal = true;
688 break;
689 case llvm::DS_Warning:
690 if(info.getKind() == llvm::DK_StackSize)
691 {
692 // Stack size limit exceeded
Nicolas Capens25f0f852021-01-07 20:46:36 -0500693 *fatal = true;
Nicolas Capens112faf42019-12-13 17:32:26 -0500694 }
695 break;
696 case llvm::DS_Remark:
697 break;
698 case llvm::DS_Note:
699 break;
Nicolas Capens25f0f852021-01-07 20:46:36 -0500700 }
701
702 return true; // Diagnostic handled, don't let LLVM print it.
703 }
704
705 bool *fatal;
706};
707
Nicolas Capens41a73022020-01-30 00:30:14 -0500708// JITRoutine is a rr::Routine that holds a LLVM JIT session, compiler and
709// object layer as each routine may require different target machine
710// settings and no Reactor routine directly links against another.
711class JITRoutine : public rr::Routine
712{
Nicolas Capens41a73022020-01-30 00:30:14 -0500713public:
714 JITRoutine(
715 std::unique_ptr<llvm::Module> module,
Nicolas Capens567e5602021-01-07 23:18:56 -0500716 std::unique_ptr<llvm::LLVMContext> context,
Antonio Maioranod1fbcb22020-11-27 13:59:04 -0500717 const char *name,
Nicolas Capens41a73022020-01-30 00:30:14 -0500718 llvm::Function **funcs,
Nicolas Capens79d4c6c2022-04-22 17:20:26 -0400719 size_t count)
Antonio Maioranod1fbcb22020-11-27 13:59:04 -0500720 : name(name)
Nicolas Capens44660402021-07-27 21:42:21 -0400721#if LLVM_VERSION_MAJOR >= 13
Nicolas Capens3fbdc262022-02-25 00:15:00 -0500722 , session(std::move(Unwrap(llvm::orc::SelfExecutorProcessControl::Create())))
Nicolas Capens44660402021-07-27 21:42:21 -0400723#endif
Nicolas Capensfca80842021-01-08 16:37:53 -0500724 , objectLayer(session, [this]() {
Nicolas Capens827e9a22020-11-02 11:04:24 -0500725 return std::make_unique<llvm::SectionMemoryManager>(&memoryMapper);
Ben Claytone02d8932020-10-21 18:37:33 +0100726 })
Nicolas Capens41a73022020-01-30 00:30:14 -0500727 , addresses(count)
728 {
Nicolas Capens25f0f852021-01-07 20:46:36 -0500729 bool fatalCompileIssue = false;
730 context->setDiagnosticHandler(std::make_unique<FatalDiagnosticsHandler>(&fatalCompileIssue), true);
731
Ben Claytonee18f392020-10-19 16:54:21 -0400732#ifdef ENABLE_RR_DEBUG_INFO
733 // TODO(b/165000222): Update this on next LLVM roll.
734 // https://github.com/llvm/llvm-project/commit/98f2bb4461072347dcca7d2b1b9571b3a6525801
735 // introduces RTDyldObjectLinkingLayer::registerJITEventListener().
736 // The current API does not appear to have any way to bind the
737 // rr::DebugInfo::NotifyFreeingObject event.
Daniele Vettorele1930f02022-03-04 15:44:31 +0000738# if LLVM_VERSION_MAJOR >= 12
739 objectLayer.setNotifyLoaded([](llvm::orc::MaterializationResponsibility &R,
740 const llvm::object::ObjectFile &obj,
741 const llvm::RuntimeDyld::LoadedObjectInfo &l) {
742 static std::atomic<uint64_t> unique_key{ 0 };
743 rr::DebugInfo::NotifyObjectEmitted(unique_key++, obj, l);
744 });
745# else
Ben Claytonee18f392020-10-19 16:54:21 -0400746 objectLayer.setNotifyLoaded([](llvm::orc::VModuleKey,
747 const llvm::object::ObjectFile &obj,
748 const llvm::RuntimeDyld::LoadedObjectInfo &l) {
749 static std::atomic<uint64_t> unique_key{ 0 };
750 rr::DebugInfo::NotifyObjectEmitted(unique_key++, obj, l);
751 });
Daniele Vettorele1930f02022-03-04 15:44:31 +0000752# endif
Ben Claytonee18f392020-10-19 16:54:21 -0400753#endif // ENABLE_RR_DEBUG_INFO
Ben Claytona7bc2b92020-03-26 11:24:49 +0000754
Ben Claytonee18f392020-10-19 16:54:21 -0400755 if(JITGlobals::get()->getTargetTriple().isOSBinFormatCOFF())
756 {
757 // Hack to support symbol visibility in COFF.
758 // Matches hack in llvm::orc::LLJIT::createObjectLinkingLayer().
759 // See documentation on these functions for more detail.
760 objectLayer.setOverrideObjectFlagsWithResponsibilityFlags(true);
761 objectLayer.setAutoClaimResponsibilityForObjectSymbols(true);
762 }
763
Nicolas Capens58d987a2021-01-07 23:24:25 -0500764 llvm::SmallVector<llvm::orc::SymbolStringPtr, 8> functionNames(count);
765 llvm::orc::MangleAndInterner mangle(session, JITGlobals::get()->getDataLayout());
766
Nicolas Capens41a73022020-01-30 00:30:14 -0500767 for(size_t i = 0; i < count; i++)
768 {
Nicolas Capensc13f4b12022-02-25 11:08:07 -0500769 llvm::Function *func = funcs[i];
Nicolas Capens58d987a2021-01-07 23:24:25 -0500770
Ben Claytonee18f392020-10-19 16:54:21 -0400771 if(!func->hasName())
772 {
773 func->setName("f" + llvm::Twine(i).str());
774 }
Nicolas Capens58d987a2021-01-07 23:24:25 -0500775
776 functionNames[i] = mangle(func->getName());
Nicolas Capens41a73022020-01-30 00:30:14 -0500777 }
778
Antonio Maiorano6f6ca292020-11-27 15:40:15 -0500779#ifdef ENABLE_RR_EMIT_ASM_FILE
Nicolas Capens79d4c6c2022-04-22 17:20:26 -0400780 const auto asmFilename = rr::AsmFile::generateFilename(REACTOR_ASM_EMIT_DIR, name);
781 rr::AsmFile::emitAsmFile(asmFilename, JITGlobals::get()->getTargetMachineBuilder(), *module);
Antonio Maiorano6f6ca292020-11-27 15:40:15 -0500782#endif
783
Nicolas Capens588d32c2021-01-08 00:40:09 -0500784 // Once the module is passed to the compileLayer, the llvm::Functions are freed.
785 // Make sure funcs are not referenced after this point.
Nicolas Capens41a73022020-01-30 00:30:14 -0500786 funcs = nullptr;
787
Nicolas Capens79d4c6c2022-04-22 17:20:26 -0400788 llvm::orc::IRCompileLayer compileLayer(session, objectLayer, std::make_unique<llvm::orc::ConcurrentIRCompiler>(JITGlobals::get()->getTargetMachineBuilder()));
Nicolas Capens588d32c2021-01-08 00:40:09 -0500789 llvm::orc::JITDylib &dylib(Unwrap(session.createJITDylib("<routine>")));
790 dylib.addGenerator(std::make_unique<ExternalSymbolGenerator>());
791
Nicolas Capens567e5602021-01-07 23:18:56 -0500792 llvm::cantFail(compileLayer.add(dylib, llvm::orc::ThreadSafeModule(std::move(module), std::move(context))));
Nicolas Capens41a73022020-01-30 00:30:14 -0500793
794 // Resolve the function addresses.
795 for(size_t i = 0; i < count; i++)
796 {
Nicolas Capens25f0f852021-01-07 20:46:36 -0500797 fatalCompileIssue = false; // May be set to true by session.lookup()
798
799 // This is where the actual compilation happens.
Nicolas Capens58d987a2021-01-07 23:24:25 -0500800 auto symbol = session.lookup({ &dylib }, functionNames[i]);
Nicolas Capens25f0f852021-01-07 20:46:36 -0500801
Ben Claytonee18f392020-10-19 16:54:21 -0400802 ASSERT_MSG(symbol, "Failed to lookup address of routine function %d: %s",
803 (int)i, llvm::toString(symbol.takeError()).c_str());
Nicolas Capens25f0f852021-01-07 20:46:36 -0500804
805 if(fatalCompileIssue)
806 {
807 addresses[i] = nullptr;
808 }
809 else // Successful compilation
810 {
811 addresses[i] = reinterpret_cast<void *>(static_cast<intptr_t>(symbol->getAddress()));
812 }
Nicolas Capens41a73022020-01-30 00:30:14 -0500813 }
Antonio Maiorano6f6ca292020-11-27 15:40:15 -0500814
815#ifdef ENABLE_RR_EMIT_ASM_FILE
816 rr::AsmFile::fixupAsmFile(asmFilename, addresses);
817#endif
Nicolas Capens41a73022020-01-30 00:30:14 -0500818 }
819
Antonio Maioranobb66fa42020-10-22 13:53:09 -0400820 ~JITRoutine()
821 {
Antonio Maioranoc1839ee2020-10-26 10:16:29 -0400822#if LLVM_VERSION_MAJOR >= 11 /* TODO(b/165000222): Unconditional after LLVM 11 upgrade */
823 if(auto err = session.endSession())
824 {
825 session.reportError(std::move(err));
826 }
Antonio Maioranobb66fa42020-10-22 13:53:09 -0400827#endif
828 }
829
Nicolas Capens41a73022020-01-30 00:30:14 -0500830 const void *getEntry(int index) const override
831 {
832 return addresses[index];
833 }
Nicolas Capens588d32c2021-01-08 00:40:09 -0500834
835private:
836 std::string name;
837 llvm::orc::ExecutionSession session;
Nicolas Capensfca80842021-01-08 16:37:53 -0500838 MemoryMapper memoryMapper;
Nicolas Capens588d32c2021-01-08 00:40:09 -0500839 llvm::orc::RTDyldObjectLinkingLayer objectLayer;
840 std::vector<const void *> addresses;
Nicolas Capens41a73022020-01-30 00:30:14 -0500841};
842
843} // anonymous namespace
844
845namespace rr {
846
Nicolas Capens79d4c6c2022-04-22 17:20:26 -0400847JITBuilder::JITBuilder()
848 : context(new llvm::LLVMContext())
Nicolas Capens567e5602021-01-07 23:18:56 -0500849 , module(new llvm::Module("", *context))
850 , builder(new llvm::IRBuilder<>(*context))
Nicolas Capens41a73022020-01-30 00:30:14 -0500851{
Nicolas Capens959f4192020-11-02 15:30:30 -0500852 module->setTargetTriple(LLVM_DEFAULT_TARGET_TRIPLE);
Ben Claytonee18f392020-10-19 16:54:21 -0400853 module->setDataLayout(JITGlobals::get()->getDataLayout());
Nicolas Capensdc8cbfa2021-06-10 17:09:50 -0400854
Nicolas Capens80de2012022-05-13 13:43:21 -0400855 msanInstrumentation = getPragmaState(MemorySanitizerInstrumentation);
Nicolas Capens41a73022020-01-30 00:30:14 -0500856}
857
Nicolas Capens79d4c6c2022-04-22 17:20:26 -0400858void JITBuilder::runPasses()
Nicolas Capens41a73022020-01-30 00:30:14 -0500859{
Nicolas Capens8e678f52022-04-26 11:47:34 -0400860#if defined(ENABLE_RR_LLVM_IR_VERIFICATION) || !defined(NDEBUG)
861 if(llvm::verifyModule(*module, &llvm::errs()))
862 {
863 llvm::report_fatal_error("Invalid LLVM module");
864 }
865#endif
866
Nicolas Capens45fce442022-04-26 16:55:58 -0400867 int optimizationLevel = getPragmaState(OptimizationLevel);
868
869#ifdef ENABLE_RR_DEBUG_INFO
870 if(debugInfo != nullptr)
Nicolas Capens88fe9ce2022-04-19 18:32:26 -0400871 {
Nicolas Capens45fce442022-04-26 16:55:58 -0400872 optimizationLevel = 0; // Don't optimize if we're generating debug info.
873 }
874#endif // ENABLE_RR_DEBUG_INFO
875
Nicolas Capens88fe9ce2022-04-19 18:32:26 -0400876#if LLVM_VERSION_MAJOR >= 13 // New pass manager
Nicolas Capensea5f37f2022-04-19 16:08:20 -0400877 llvm::LoopAnalysisManager lam;
878 llvm::FunctionAnalysisManager fam;
879 llvm::CGSCCAnalysisManager cgam;
880 llvm::ModuleAnalysisManager mam;
881 llvm::PassBuilder pb;
882
883 pb.registerModuleAnalyses(mam);
884 pb.registerCGSCCAnalyses(cgam);
885 pb.registerFunctionAnalyses(fam);
886 pb.registerLoopAnalyses(lam);
887 pb.crossRegisterProxies(lam, fam, cgam, mam);
888
889 llvm::ModulePassManager pm;
890 llvm::FunctionPassManager fpm;
891
Nicolas Capensb92f7ac2022-04-27 10:52:33 -0400892 if(coroutine.id)
893 {
Nicolas Capens9f2ef7c2022-04-28 00:50:26 -0400894 // Adds mandatory coroutine transforms.
895 pm = pb.buildO0DefaultPipeline(llvm::OptimizationLevel::O0);
Nicolas Capensb92f7ac2022-04-27 10:52:33 -0400896 }
897
Nicolas Capens45fce442022-04-26 16:55:58 -0400898 if(optimizationLevel > 0)
Nicolas Capensea5f37f2022-04-19 16:08:20 -0400899 {
Nicolas Capens79d4c6c2022-04-22 17:20:26 -0400900 fpm.addPass(llvm::SROAPass());
901 fpm.addPass(llvm::InstCombinePass());
Nicolas Capensea5f37f2022-04-19 16:08:20 -0400902 }
903
904 if(!fpm.isEmpty())
905 {
906 pm.addPass(llvm::createModuleToFunctionPassAdaptor(std::move(fpm)));
907 }
908
Nicolas Capens69a53d92022-04-28 01:26:17 -0400909 if(__has_feature(memory_sanitizer) && msanInstrumentation)
910 {
911 llvm::MemorySanitizerOptions msanOpts(0 /* TrackOrigins */, false /* Recover */, false /* Kernel */, true /* EagerChecks */);
912 pm.addPass(llvm::ModuleMemorySanitizerPass(msanOpts));
913 pm.addPass(llvm::createModuleToFunctionPassAdaptor(llvm::MemorySanitizerPass(msanOpts)));
914 }
915
Nicolas Capensea5f37f2022-04-19 16:08:20 -0400916 pm.run(*module, mam);
917#else // Legacy pass manager
Nicolas Capensb92f7ac2022-04-27 10:52:33 -0400918 llvm::legacy::PassManager passManager;
919
Nicolas Capens45fce442022-04-26 16:55:58 -0400920 if(coroutine.id)
921 {
922 // Run mandatory coroutine transforms.
Nicolas Capensb92f7ac2022-04-27 10:52:33 -0400923 passManager.add(llvm::createCoroEarlyLegacyPass());
924 passManager.add(llvm::createCoroSplitLegacyPass());
925 passManager.add(llvm::createCoroElideLegacyPass());
926 passManager.add(llvm::createBarrierNoopPass());
927 passManager.add(llvm::createCoroCleanupLegacyPass());
Nicolas Capens45fce442022-04-26 16:55:58 -0400928 }
929
Nicolas Capens45fce442022-04-26 16:55:58 -0400930 if(optimizationLevel > 0)
Nicolas Capens41a73022020-01-30 00:30:14 -0500931 {
Nicolas Capens79d4c6c2022-04-22 17:20:26 -0400932 passManager.add(llvm::createSROAPass());
933 passManager.add(llvm::createInstructionCombiningPass());
Nicolas Capens41a73022020-01-30 00:30:14 -0500934 }
935
Nicolas Capens69a53d92022-04-28 01:26:17 -0400936 if(__has_feature(memory_sanitizer) && msanInstrumentation)
937 {
938 passManager.add(llvm::createMemorySanitizerLegacyPassPass());
939 }
940
Ben Claytonee18f392020-10-19 16:54:21 -0400941 passManager.run(*module);
Nicolas Capensea5f37f2022-04-19 16:08:20 -0400942#endif
Nicolas Capens41a73022020-01-30 00:30:14 -0500943}
944
Nicolas Capens79d4c6c2022-04-22 17:20:26 -0400945std::shared_ptr<rr::Routine> JITBuilder::acquireRoutine(const char *name, llvm::Function **funcs, size_t count)
Nicolas Capens41a73022020-01-30 00:30:14 -0500946{
947 ASSERT(module);
Nicolas Capens79d4c6c2022-04-22 17:20:26 -0400948 return std::make_shared<JITRoutine>(std::move(module), std::move(context), name, funcs, count);
Nicolas Capens41a73022020-01-30 00:30:14 -0500949}
950
951} // namespace rr