blob: fad747af06ceecd77793ac3fa58cf45fa0c98fc4 [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 Capensa07b3fb2022-07-28 04:18:58 -040039#include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
Nicolas Capens4804ac82020-11-02 22:06:55 -050040#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
Nicolas Capens41a73022020-01-30 00:30:14 -050041#include "llvm/Transforms/Scalar.h"
42#include "llvm/Transforms/Scalar/GVN.h"
43
Nicolas Capensea5f37f2022-04-19 16:08:20 -040044#if LLVM_VERSION_MAJOR >= 13 // New pass manager
45# include "llvm/IR/PassManager.h"
46# include "llvm/Passes/PassBuilder.h"
47# include "llvm/Transforms/Scalar/ADCE.h"
48# include "llvm/Transforms/Scalar/DeadStoreElimination.h"
49# include "llvm/Transforms/Scalar/EarlyCSE.h"
50# include "llvm/Transforms/Scalar/LICM.h"
51# include "llvm/Transforms/Scalar/Reassociate.h"
52# include "llvm/Transforms/Scalar/SCCP.h"
53# include "llvm/Transforms/Scalar/SROA.h"
54# include "llvm/Transforms/Scalar/SimplifyCFG.h"
55#else // Legacy pass manager
56# include "llvm/IR/LegacyPassManager.h"
Nicolas Capens88fe9ce2022-04-19 18:32:26 -040057# include "llvm/Pass.h"
58# include "llvm/Transforms/Coroutines.h"
59# include "llvm/Transforms/IPO.h"
Nicolas Capensea5f37f2022-04-19 16:08:20 -040060#endif
61
Nicolas Capens41a73022020-01-30 00:30:14 -050062#ifdef _MSC_VER
63 __pragma(warning(pop))
64#endif
65
Nicolas Capensaafa1082022-08-04 13:40:58 -040066#if defined(__unix__) || defined(__APPLE__) || defined(__Fuchsia__)
67# define ADDRESS_SANITIZER_INSTRUMENTATION_SUPPORTED true
68# if __has_feature(memory_sanitizer) || __has_feature(address_sanitizer)
69# include <dlfcn.h> // dlsym()
70# endif
71#else
72# define ADDRESS_SANITIZER_INSTRUMENTATION_SUPPORTED false
Nicolas Capensa07b3fb2022-07-28 04:18:58 -040073#endif
74
Nicolas Capens79d4c6c2022-04-22 17:20:26 -040075#ifndef REACTOR_ASM_EMIT_DIR
76# define REACTOR_ASM_EMIT_DIR "./"
77#endif
78
Nicolas Capens41a73022020-01-30 00:30:14 -050079#if defined(_WIN64)
80 extern "C" void __chkstk();
81#elif defined(_WIN32)
82extern "C" void _chkstk();
83#endif
84
Anton D. Kachalovac4e1d22020-02-11 15:44:27 +010085#ifdef __ARM_EABI__
86extern "C" signed __aeabi_idivmod();
87#endif
88
Nicolas Capens47c3ca12020-11-02 16:33:08 -050089#if __has_feature(memory_sanitizer)
Nicolas Capensdc8cbfa2021-06-10 17:09:50 -040090# include "sanitizer/msan_interface.h"
Nicolas Capens47c3ca12020-11-02 16:33:08 -050091
Nicolas Capens4804ac82020-11-02 22:06:55 -050092// MemorySanitizer uses thread-local storage (TLS) data arrays for passing around
93// the 'shadow' values of function arguments and return values. The LLVM JIT can't
94// access TLS directly, but it calls __emutls_get_address() to obtain the address.
95// Typically, it would be passed a pointer to an __emutls_control structure with a
96// name starting with "__emutls_v." that represents the TLS. Both the address of
97// __emutls_get_address and the __emutls_v. structures are provided to the JIT by
98// the symbol resolver, which can be overridden.
99// We take advantage of this by substituting __emutls_get_address() with our own
100// implementation, namely rr::getTLSAddress(), and substituting the __emutls_v
101// variables with rr::MSanTLS enums. getTLSAddress() can then provide the address
102// of the real TLS variable corresponding to the enum, in statically compiled C++.
103
104// Forward declare the real TLS variables used by MemorySanitizer. These are
105// defined in llvm-project/compiler-rt/lib/msan/msan.cpp.
106extern __thread unsigned long long __msan_param_tls[];
Nicolas Capens11e432d2022-05-04 16:42:19 -0400107extern __thread unsigned int __msan_param_origin_tls[];
Nicolas Capens4804ac82020-11-02 22:06:55 -0500108extern __thread unsigned long long __msan_retval_tls[];
Nicolas Capens11e432d2022-05-04 16:42:19 -0400109extern __thread unsigned int __msan_retval_origin_tls;
Nicolas Capens4804ac82020-11-02 22:06:55 -0500110extern __thread unsigned long long __msan_va_arg_tls[];
Nicolas Capens11e432d2022-05-04 16:42:19 -0400111extern __thread unsigned int __msan_va_arg_origin_tls[];
Nicolas Capens4804ac82020-11-02 22:06:55 -0500112extern __thread unsigned long long __msan_va_arg_overflow_size_tls;
Nicolas Capens11e432d2022-05-04 16:42:19 -0400113extern __thread unsigned int __msan_origin_tls;
Nicolas Capens4804ac82020-11-02 22:06:55 -0500114
115namespace rr {
116
117enum class MSanTLS
118{
Nicolas Capens11e432d2022-05-04 16:42:19 -0400119 param = 1, // __msan_param_tls
120 param_origin, //__msan_param_origin_tls
121 retval, // __msan_retval_tls
122 retval_origin, //__msan_retval_origin_tls
123 va_arg, // __msan_va_arg_tls
124 va_arg_origin, // __msan_va_arg_origin_tls
125 va_arg_overflow_size, // __msan_va_arg_overflow_size_tls
126 origin, //__msan_origin_tls
Nicolas Capens4804ac82020-11-02 22:06:55 -0500127};
128
129static void *getTLSAddress(void *control)
130{
131 auto tlsIndex = static_cast<MSanTLS>(reinterpret_cast<uintptr_t>(control));
132 switch(tlsIndex)
133 {
Nicolas Capens112faf42019-12-13 17:32:26 -0500134 case MSanTLS::param: return reinterpret_cast<void *>(&__msan_param_tls);
Nicolas Capens11e432d2022-05-04 16:42:19 -0400135 case MSanTLS::param_origin: return reinterpret_cast<void *>(&__msan_param_origin_tls);
Nicolas Capens112faf42019-12-13 17:32:26 -0500136 case MSanTLS::retval: return reinterpret_cast<void *>(&__msan_retval_tls);
Nicolas Capens11e432d2022-05-04 16:42:19 -0400137 case MSanTLS::retval_origin: return reinterpret_cast<void *>(&__msan_retval_origin_tls);
Nicolas Capens112faf42019-12-13 17:32:26 -0500138 case MSanTLS::va_arg: return reinterpret_cast<void *>(&__msan_va_arg_tls);
Nicolas Capens11e432d2022-05-04 16:42:19 -0400139 case MSanTLS::va_arg_origin: return reinterpret_cast<void *>(&__msan_va_arg_origin_tls);
Nicolas Capens112faf42019-12-13 17:32:26 -0500140 case MSanTLS::va_arg_overflow_size: return reinterpret_cast<void *>(&__msan_va_arg_overflow_size_tls);
Nicolas Capens11e432d2022-05-04 16:42:19 -0400141 case MSanTLS::origin: return reinterpret_cast<void *>(&__msan_origin_tls);
142
Nicolas Capens112faf42019-12-13 17:32:26 -0500143 default:
144 UNSUPPORTED("MemorySanitizer used an unrecognized TLS variable: %d", tlsIndex);
145 return nullptr;
Nicolas Capens4804ac82020-11-02 22:06:55 -0500146 }
147}
148
149} // namespace rr
Nicolas Capens47c3ca12020-11-02 16:33:08 -0500150#endif
151
Nicolas Capens41a73022020-01-30 00:30:14 -0500152namespace {
153
Nicolas Capens25f0f852021-01-07 20:46:36 -0500154// TODO(b/174587935): Eliminate command-line parsing.
155bool parseCommandLineOptionsOnce(int argc, const char *const *argv)
156{
157 // Use a static immediately invoked lambda to make this thread safe
158 static auto initialized = [=]() {
Nicolas Capensa8da8472021-02-05 04:48:15 -0500159 return llvm::cl::ParseCommandLineOptions(argc, argv);
Nicolas Capens25f0f852021-01-07 20:46:36 -0500160 }();
161
162 return initialized;
163}
164
Nicolas Capens41a73022020-01-30 00:30:14 -0500165// JITGlobals is a singleton that holds all the immutable machine specific
166// information for the host device.
167class JITGlobals
168{
169public:
Nicolas Capens41a73022020-01-30 00:30:14 -0500170 static JITGlobals *get();
171
Nicolas Capens79d4c6c2022-04-22 17:20:26 -0400172 llvm::orc::JITTargetMachineBuilder getTargetMachineBuilder() const;
Ben Claytonee18f392020-10-19 16:54:21 -0400173 const llvm::DataLayout &getDataLayout() const;
Nicolas Capens827e9a22020-11-02 11:04:24 -0500174 const llvm::Triple &getTargetTriple() const;
Nicolas Capens41a73022020-01-30 00:30:14 -0500175
176private:
Nicolas Capens827e9a22020-11-02 11:04:24 -0500177 JITGlobals(llvm::orc::JITTargetMachineBuilder &&jitTargetMachineBuilder, llvm::DataLayout &&dataLayout);
Ben Claytonee18f392020-10-19 16:54:21 -0400178
Nicolas Capens79d4c6c2022-04-22 17:20:26 -0400179 static llvm::CodeGenOpt::Level toLLVM(int level);
Nicolas Capens827e9a22020-11-02 11:04:24 -0500180
181 const llvm::orc::JITTargetMachineBuilder jitTargetMachineBuilder;
Ben Claytonee18f392020-10-19 16:54:21 -0400182 const llvm::DataLayout dataLayout;
Nicolas Capens41a73022020-01-30 00:30:14 -0500183};
184
185JITGlobals *JITGlobals::get()
186{
Ben Claytonee18f392020-10-19 16:54:21 -0400187 static JITGlobals instance = [] {
Nicolas Capens25f0f852021-01-07 20:46:36 -0500188 const char *argv[] = {
189 "Reactor",
Nicolas Capensa8da8472021-02-05 04:48:15 -0500190#if defined(__i386__) || defined(__x86_64__)
191 "-x86-asm-syntax=intel", // Use Intel syntax rather than the default AT&T
192#endif
Nicolas Capensf679fc12021-06-25 14:50:41 -0400193#if LLVM_VERSION_MAJOR <= 12
Nicolas Capensf13461d2022-04-20 15:33:24 -0400194 "-warn-stack-size=524288", // Warn when a function uses more than 512 KiB of stack memory
Nicolas Capens84bc1982021-06-15 21:44:31 -0400195#endif
Nicolas Capens25f0f852021-01-07 20:46:36 -0500196 };
197
198 parseCommandLineOptionsOnce(sizeof(argv) / sizeof(argv[0]), argv);
199
Ben Claytonee18f392020-10-19 16:54:21 -0400200 llvm::InitializeNativeTarget();
201 llvm::InitializeNativeTargetAsmPrinter();
202 llvm::InitializeNativeTargetAsmParser();
203
Nicolas Capens827e9a22020-11-02 11:04:24 -0500204 // TODO(b/171236524): JITTargetMachineBuilder::detectHost() currently uses the target triple of the host,
205 // rather than a valid triple for the current process. Once fixed, we can use that function instead.
206 llvm::orc::JITTargetMachineBuilder jitTargetMachineBuilder(llvm::Triple(LLVM_DEFAULT_TARGET_TRIPLE));
207
208 // Retrieve host CPU name and sub-target features and add them to builder.
209 // Relocation model, code model and codegen opt level are kept to default values.
210 llvm::StringMap<bool> cpuFeatures;
211 bool ok = llvm::sys::getHostCPUFeatures(cpuFeatures);
212
213#if defined(__i386__) || defined(__x86_64__) || \
214 (defined(__linux__) && (defined(__arm__) || defined(__aarch64__)))
215 ASSERT_MSG(ok, "llvm::sys::getHostCPUFeatures returned false");
216#else
217 (void)ok; // getHostCPUFeatures always returns false on other platforms
218#endif
219
220 for(auto &feature : cpuFeatures)
221 {
222 jitTargetMachineBuilder.getFeatures().AddFeature(feature.first(), feature.second);
223 }
224
225#if LLVM_VERSION_MAJOR >= 11 /* TODO(b/165000222): Unconditional after LLVM 11 upgrade */
226 jitTargetMachineBuilder.setCPU(std::string(llvm::sys::getHostCPUName()));
227#else
228 jitTargetMachineBuilder.setCPU(llvm::sys::getHostCPUName());
229#endif
230
Nicolas Capens4804ac82020-11-02 22:06:55 -0500231 // Reactor's MemorySanitizer support depends on intercepting __emutls_get_address calls.
232 ASSERT(!__has_feature(memory_sanitizer) || (jitTargetMachineBuilder.getOptions().ExplicitEmulatedTLS &&
233 jitTargetMachineBuilder.getOptions().EmulatedTLS));
234
Nicolas Capens827e9a22020-11-02 11:04:24 -0500235 auto dataLayout = jitTargetMachineBuilder.getDefaultDataLayoutForTarget();
Ben Claytonee18f392020-10-19 16:54:21 -0400236 ASSERT_MSG(dataLayout, "JITTargetMachineBuilder::getDefaultDataLayoutForTarget() failed");
Nicolas Capens827e9a22020-11-02 11:04:24 -0500237
238 return JITGlobals(std::move(jitTargetMachineBuilder), std::move(dataLayout.get()));
Ben Claytonee18f392020-10-19 16:54:21 -0400239 }();
Nicolas Capens827e9a22020-11-02 11:04:24 -0500240
Nicolas Capens41a73022020-01-30 00:30:14 -0500241 return &instance;
242}
243
Nicolas Capens79d4c6c2022-04-22 17:20:26 -0400244llvm::orc::JITTargetMachineBuilder JITGlobals::getTargetMachineBuilder() const
Nicolas Capens41a73022020-01-30 00:30:14 -0500245{
Nicolas Capens827e9a22020-11-02 11:04:24 -0500246 llvm::orc::JITTargetMachineBuilder out = jitTargetMachineBuilder;
Nicolas Capens79d4c6c2022-04-22 17:20:26 -0400247 out.setCodeGenOptLevel(toLLVM(rr::getPragmaState(rr::OptimizationLevel)));
Nicolas Capens827e9a22020-11-02 11:04:24 -0500248
Ben Claytonee18f392020-10-19 16:54:21 -0400249 return out;
Nicolas Capens41a73022020-01-30 00:30:14 -0500250}
251
Ben Claytonee18f392020-10-19 16:54:21 -0400252const llvm::DataLayout &JITGlobals::getDataLayout() const
Nicolas Capens41a73022020-01-30 00:30:14 -0500253{
Ben Claytonee18f392020-10-19 16:54:21 -0400254 return dataLayout;
255}
Nicolas Capens41a73022020-01-30 00:30:14 -0500256
Nicolas Capens827e9a22020-11-02 11:04:24 -0500257const llvm::Triple &JITGlobals::getTargetTriple() const
Ben Claytonee18f392020-10-19 16:54:21 -0400258{
Nicolas Capens827e9a22020-11-02 11:04:24 -0500259 return jitTargetMachineBuilder.getTargetTriple();
Ben Claytonee18f392020-10-19 16:54:21 -0400260}
Nicolas Capens41a73022020-01-30 00:30:14 -0500261
Nicolas Capens827e9a22020-11-02 11:04:24 -0500262JITGlobals::JITGlobals(llvm::orc::JITTargetMachineBuilder &&jitTargetMachineBuilder, llvm::DataLayout &&dataLayout)
263 : jitTargetMachineBuilder(jitTargetMachineBuilder)
Ben Claytonee18f392020-10-19 16:54:21 -0400264 , dataLayout(dataLayout)
265{
Nicolas Capens41a73022020-01-30 00:30:14 -0500266}
267
Nicolas Capens79d4c6c2022-04-22 17:20:26 -0400268llvm::CodeGenOpt::Level JITGlobals::toLLVM(int level)
Nicolas Capens41a73022020-01-30 00:30:14 -0500269{
Nicolas Capens259ce702020-11-18 11:32:05 -0500270 // TODO(b/173257647): MemorySanitizer instrumentation produces IR which takes
271 // a lot longer to process by the machine code optimization passes. Disabling
272 // them has a negligible effect on code quality but compiles much faster.
273 if(__has_feature(memory_sanitizer))
274 {
275 return llvm::CodeGenOpt::None;
276 }
277
Nicolas Capens41a73022020-01-30 00:30:14 -0500278 switch(level)
279 {
Nicolas Capens79d4c6c2022-04-22 17:20:26 -0400280 case 0: return llvm::CodeGenOpt::None;
281 case 1: return llvm::CodeGenOpt::Less;
282 case 2: return llvm::CodeGenOpt::Default;
283 case 3: return llvm::CodeGenOpt::Aggressive;
Nicolas Capens112faf42019-12-13 17:32:26 -0500284 default: UNREACHABLE("Unknown Optimization Level %d", int(level));
Nicolas Capens41a73022020-01-30 00:30:14 -0500285 }
Nicolas Capens259ce702020-11-18 11:32:05 -0500286
Nicolas Capens00ecdf92020-10-30 21:13:40 -0400287 return llvm::CodeGenOpt::Default;
Nicolas Capens41a73022020-01-30 00:30:14 -0500288}
289
David 'Digit' Turner48f3f6c2020-03-23 14:23:10 +0100290class MemoryMapper final : public llvm::SectionMemoryManager::MemoryMapper
Nicolas Capens41a73022020-01-30 00:30:14 -0500291{
292public:
293 MemoryMapper() {}
294 ~MemoryMapper() final {}
295
296 llvm::sys::MemoryBlock allocateMappedMemory(
297 llvm::SectionMemoryManager::AllocationPurpose purpose,
298 size_t numBytes, const llvm::sys::MemoryBlock *const nearBlock,
299 unsigned flags, std::error_code &errorCode) final
300 {
301 errorCode = std::error_code();
302
303 // Round up numBytes to page size.
304 size_t pageSize = rr::memoryPageSize();
305 numBytes = (numBytes + pageSize - 1) & ~(pageSize - 1);
306
307 bool need_exec =
308 purpose == llvm::SectionMemoryManager::AllocationPurpose::Code;
309 void *addr = rr::allocateMemoryPages(
310 numBytes, flagsToPermissions(flags), need_exec);
311 if(!addr)
312 return llvm::sys::MemoryBlock();
313 return llvm::sys::MemoryBlock(addr, numBytes);
314 }
315
316 std::error_code protectMappedMemory(const llvm::sys::MemoryBlock &block,
317 unsigned flags)
318 {
319 // Round down base address to align with a page boundary. This matches
320 // DefaultMMapper behavior.
321 void *addr = block.base();
Nicolas Capens41a73022020-01-30 00:30:14 -0500322 size_t size = block.allocatedSize();
Nicolas Capens41a73022020-01-30 00:30:14 -0500323 size_t pageSize = rr::memoryPageSize();
324 addr = reinterpret_cast<void *>(
325 reinterpret_cast<uintptr_t>(addr) & ~(pageSize - 1));
326 size += reinterpret_cast<uintptr_t>(block.base()) -
327 reinterpret_cast<uintptr_t>(addr);
328
329 rr::protectMemoryPages(addr, size, flagsToPermissions(flags));
330 return std::error_code();
331 }
332
333 std::error_code releaseMappedMemory(llvm::sys::MemoryBlock &block)
334 {
Nicolas Capens41a73022020-01-30 00:30:14 -0500335 size_t size = block.allocatedSize();
Nicolas Capens41a73022020-01-30 00:30:14 -0500336
337 rr::deallocateMemoryPages(block.base(), size);
338 return std::error_code();
339 }
340
341private:
342 int flagsToPermissions(unsigned flags)
343 {
344 int result = 0;
345 if(flags & llvm::sys::Memory::MF_READ)
346 {
347 result |= rr::PERMISSION_READ;
348 }
349 if(flags & llvm::sys::Memory::MF_WRITE)
350 {
351 result |= rr::PERMISSION_WRITE;
352 }
353 if(flags & llvm::sys::Memory::MF_EXEC)
354 {
355 result |= rr::PERMISSION_EXECUTE;
356 }
357 return result;
358 }
359};
360
361template<typename T>
362T alignUp(T val, T alignment)
363{
364 return alignment * ((val + alignment - 1) / alignment);
365}
366
367void *alignedAlloc(size_t size, size_t alignment)
368{
369 ASSERT(alignment < 256);
370 auto allocation = new uint8_t[size + sizeof(uint8_t) + alignment];
371 auto aligned = allocation;
372 aligned += sizeof(uint8_t); // Make space for the base-address offset.
373 aligned = reinterpret_cast<uint8_t *>(alignUp(reinterpret_cast<uintptr_t>(aligned), alignment)); // align
374 auto offset = static_cast<uint8_t>(aligned - allocation);
375 aligned[-1] = offset;
376 return aligned;
377}
378
379void alignedFree(void *ptr)
380{
381 auto aligned = reinterpret_cast<uint8_t *>(ptr);
382 auto offset = aligned[-1];
383 auto allocation = aligned - offset;
384 delete[] allocation;
385}
386
387template<typename T>
388static void atomicLoad(void *ptr, void *ret, llvm::AtomicOrdering ordering)
389{
390 *reinterpret_cast<T *>(ret) = std::atomic_load_explicit<T>(reinterpret_cast<std::atomic<T> *>(ptr), rr::atomicOrdering(ordering));
391}
392
393template<typename T>
394static void atomicStore(void *ptr, void *val, llvm::AtomicOrdering ordering)
395{
396 std::atomic_store_explicit<T>(reinterpret_cast<std::atomic<T> *>(ptr), *reinterpret_cast<T *>(val), rr::atomicOrdering(ordering));
397}
398
399#ifdef __ANDROID__
400template<typename F>
401static uint32_t sync_fetch_and_op(uint32_t volatile *ptr, uint32_t val, F f)
402{
403 // Build an arbitrary op out of looped CAS
404 for(;;)
405 {
406 uint32_t expected = *ptr;
407 uint32_t desired = f(expected, val);
408
409 if(expected == __sync_val_compare_and_swap_4(ptr, expected, desired))
410 {
411 return expected;
412 }
413 }
414}
415#endif
416
Antonio Maioranoc1839ee2020-10-26 10:16:29 -0400417#if LLVM_VERSION_MAJOR >= 11 /* TODO(b/165000222): Unconditional after LLVM 11 upgrade */
418class ExternalSymbolGenerator : public llvm::orc::DefinitionGenerator
419#else
Ben Claytonee18f392020-10-19 16:54:21 -0400420class ExternalSymbolGenerator : public llvm::orc::JITDylib::DefinitionGenerator
Antonio Maioranoc1839ee2020-10-26 10:16:29 -0400421#endif
Nicolas Capens41a73022020-01-30 00:30:14 -0500422{
423 struct Atomic
424 {
425 static void load(size_t size, void *ptr, void *ret, llvm::AtomicOrdering ordering)
426 {
427 switch(size)
428 {
Nicolas Capens112faf42019-12-13 17:32:26 -0500429 case 1: atomicLoad<uint8_t>(ptr, ret, ordering); break;
430 case 2: atomicLoad<uint16_t>(ptr, ret, ordering); break;
431 case 4: atomicLoad<uint32_t>(ptr, ret, ordering); break;
432 case 8: atomicLoad<uint64_t>(ptr, ret, ordering); break;
433 default:
434 UNIMPLEMENTED_NO_BUG("Atomic::load(size: %d)", int(size));
Nicolas Capens41a73022020-01-30 00:30:14 -0500435 }
436 }
437 static void store(size_t size, void *ptr, void *ret, llvm::AtomicOrdering ordering)
438 {
439 switch(size)
440 {
Nicolas Capens112faf42019-12-13 17:32:26 -0500441 case 1: atomicStore<uint8_t>(ptr, ret, ordering); break;
442 case 2: atomicStore<uint16_t>(ptr, ret, ordering); break;
443 case 4: atomicStore<uint32_t>(ptr, ret, ordering); break;
444 case 8: atomicStore<uint64_t>(ptr, ret, ordering); break;
445 default:
446 UNIMPLEMENTED_NO_BUG("Atomic::store(size: %d)", int(size));
Nicolas Capens41a73022020-01-30 00:30:14 -0500447 }
448 }
449 };
450
Ben Claytonee18f392020-10-19 16:54:21 -0400451 static void nop() {}
452 static void neverCalled() { UNREACHABLE("Should never be called"); }
Nicolas Capens41a73022020-01-30 00:30:14 -0500453
Ben Claytonee18f392020-10-19 16:54:21 -0400454 static void *coroutine_alloc_frame(size_t size) { return alignedAlloc(size, 16); }
455 static void coroutine_free_frame(void *ptr) { alignedFree(ptr); }
Nicolas Capens41a73022020-01-30 00:30:14 -0500456
457#ifdef __ANDROID__
Ben Claytonee18f392020-10-19 16:54:21 -0400458 // forwarders since we can't take address of builtins
459 static void sync_synchronize() { __sync_synchronize(); }
460 static uint32_t sync_fetch_and_add_4(uint32_t *ptr, uint32_t val) { return __sync_fetch_and_add_4(ptr, val); }
461 static uint32_t sync_fetch_and_and_4(uint32_t *ptr, uint32_t val) { return __sync_fetch_and_and_4(ptr, val); }
462 static uint32_t sync_fetch_and_or_4(uint32_t *ptr, uint32_t val) { return __sync_fetch_and_or_4(ptr, val); }
463 static uint32_t sync_fetch_and_xor_4(uint32_t *ptr, uint32_t val) { return __sync_fetch_and_xor_4(ptr, val); }
464 static uint32_t sync_fetch_and_sub_4(uint32_t *ptr, uint32_t val) { return __sync_fetch_and_sub_4(ptr, val); }
465 static uint32_t sync_lock_test_and_set_4(uint32_t *ptr, uint32_t val) { return __sync_lock_test_and_set_4(ptr, val); }
466 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 -0500467
Ben Claytonee18f392020-10-19 16:54:21 -0400468 static uint32_t sync_fetch_and_max_4(uint32_t *ptr, uint32_t val)
469 {
470 return sync_fetch_and_op(ptr, val, [](int32_t a, int32_t b) { return std::max(a, b); });
471 }
472 static uint32_t sync_fetch_and_min_4(uint32_t *ptr, uint32_t val)
473 {
474 return sync_fetch_and_op(ptr, val, [](int32_t a, int32_t b) { return std::min(a, b); });
475 }
476 static uint32_t sync_fetch_and_umax_4(uint32_t *ptr, uint32_t val)
477 {
478 return sync_fetch_and_op(ptr, val, [](uint32_t a, uint32_t b) { return std::max(a, b); });
479 }
480 static uint32_t sync_fetch_and_umin_4(uint32_t *ptr, uint32_t val)
481 {
482 return sync_fetch_and_op(ptr, val, [](uint32_t a, uint32_t b) { return std::min(a, b); });
483 }
Nicolas Capens41a73022020-01-30 00:30:14 -0500484#endif
Nicolas Capens47c3ca12020-11-02 16:33:08 -0500485
Nicolas Capens41a73022020-01-30 00:30:14 -0500486 class Resolver
487 {
488 public:
Ben Claytonee18f392020-10-19 16:54:21 -0400489 using FunctionMap = llvm::StringMap<void *>;
Nicolas Capens41a73022020-01-30 00:30:14 -0500490
491 FunctionMap functions;
492
493 Resolver()
494 {
Antonio Maiorano8cbee412020-06-10 15:59:20 -0400495#ifdef ENABLE_RR_PRINT
Ben Claytonee18f392020-10-19 16:54:21 -0400496 functions.try_emplace("rr::DebugPrintf", reinterpret_cast<void *>(rr::DebugPrintf));
Antonio Maiorano8cbee412020-06-10 15:59:20 -0400497#endif
Ben Claytonee18f392020-10-19 16:54:21 -0400498 functions.try_emplace("nop", reinterpret_cast<void *>(nop));
499 functions.try_emplace("floorf", reinterpret_cast<void *>(floorf));
500 functions.try_emplace("nearbyintf", reinterpret_cast<void *>(nearbyintf));
501 functions.try_emplace("truncf", reinterpret_cast<void *>(truncf));
502 functions.try_emplace("printf", reinterpret_cast<void *>(printf));
503 functions.try_emplace("puts", reinterpret_cast<void *>(puts));
504 functions.try_emplace("fmodf", reinterpret_cast<void *>(fmodf));
Nicolas Capens41a73022020-01-30 00:30:14 -0500505
Ben Claytonee18f392020-10-19 16:54:21 -0400506 functions.try_emplace("sinf", reinterpret_cast<void *>(sinf));
507 functions.try_emplace("cosf", reinterpret_cast<void *>(cosf));
508 functions.try_emplace("asinf", reinterpret_cast<void *>(asinf));
509 functions.try_emplace("acosf", reinterpret_cast<void *>(acosf));
510 functions.try_emplace("atanf", reinterpret_cast<void *>(atanf));
511 functions.try_emplace("sinhf", reinterpret_cast<void *>(sinhf));
512 functions.try_emplace("coshf", reinterpret_cast<void *>(coshf));
513 functions.try_emplace("tanhf", reinterpret_cast<void *>(tanhf));
514 functions.try_emplace("asinhf", reinterpret_cast<void *>(asinhf));
515 functions.try_emplace("acoshf", reinterpret_cast<void *>(acoshf));
516 functions.try_emplace("atanhf", reinterpret_cast<void *>(atanhf));
517 functions.try_emplace("atan2f", reinterpret_cast<void *>(atan2f));
518 functions.try_emplace("powf", reinterpret_cast<void *>(powf));
519 functions.try_emplace("expf", reinterpret_cast<void *>(expf));
520 functions.try_emplace("logf", reinterpret_cast<void *>(logf));
521 functions.try_emplace("exp2f", reinterpret_cast<void *>(exp2f));
522 functions.try_emplace("log2f", reinterpret_cast<void *>(log2f));
Nicolas Capens75d79f22022-01-31 17:46:26 -0500523 functions.try_emplace("fmaf", reinterpret_cast<void *>(fmaf));
Nicolas Capens41a73022020-01-30 00:30:14 -0500524
Antonio Maioranoe9fa2092020-11-23 10:22:49 -0500525 functions.try_emplace("fmod", reinterpret_cast<void *>(static_cast<double (*)(double, double)>(fmod)));
Ben Claytonee18f392020-10-19 16:54:21 -0400526 functions.try_emplace("sin", reinterpret_cast<void *>(static_cast<double (*)(double)>(sin)));
527 functions.try_emplace("cos", reinterpret_cast<void *>(static_cast<double (*)(double)>(cos)));
528 functions.try_emplace("asin", reinterpret_cast<void *>(static_cast<double (*)(double)>(asin)));
529 functions.try_emplace("acos", reinterpret_cast<void *>(static_cast<double (*)(double)>(acos)));
530 functions.try_emplace("atan", reinterpret_cast<void *>(static_cast<double (*)(double)>(atan)));
531 functions.try_emplace("sinh", reinterpret_cast<void *>(static_cast<double (*)(double)>(sinh)));
532 functions.try_emplace("cosh", reinterpret_cast<void *>(static_cast<double (*)(double)>(cosh)));
533 functions.try_emplace("tanh", reinterpret_cast<void *>(static_cast<double (*)(double)>(tanh)));
534 functions.try_emplace("asinh", reinterpret_cast<void *>(static_cast<double (*)(double)>(asinh)));
535 functions.try_emplace("acosh", reinterpret_cast<void *>(static_cast<double (*)(double)>(acosh)));
536 functions.try_emplace("atanh", reinterpret_cast<void *>(static_cast<double (*)(double)>(atanh)));
537 functions.try_emplace("atan2", reinterpret_cast<void *>(static_cast<double (*)(double, double)>(atan2)));
538 functions.try_emplace("pow", reinterpret_cast<void *>(static_cast<double (*)(double, double)>(pow)));
539 functions.try_emplace("exp", reinterpret_cast<void *>(static_cast<double (*)(double)>(exp)));
540 functions.try_emplace("log", reinterpret_cast<void *>(static_cast<double (*)(double)>(log)));
541 functions.try_emplace("exp2", reinterpret_cast<void *>(static_cast<double (*)(double)>(exp2)));
542 functions.try_emplace("log2", reinterpret_cast<void *>(static_cast<double (*)(double)>(log2)));
Nicolas Capens41a73022020-01-30 00:30:14 -0500543
Ben Claytonee18f392020-10-19 16:54:21 -0400544 functions.try_emplace("atomic_load", reinterpret_cast<void *>(Atomic::load));
545 functions.try_emplace("atomic_store", reinterpret_cast<void *>(Atomic::store));
Nicolas Capens41a73022020-01-30 00:30:14 -0500546
547 // FIXME(b/119409619): use an allocator here so we can control all memory allocations
Ben Claytonee18f392020-10-19 16:54:21 -0400548 functions.try_emplace("coroutine_alloc_frame", reinterpret_cast<void *>(coroutine_alloc_frame));
549 functions.try_emplace("coroutine_free_frame", reinterpret_cast<void *>(coroutine_free_frame));
Nicolas Capens41a73022020-01-30 00:30:14 -0500550
Nicolas Capens4804ac82020-11-02 22:06:55 -0500551 functions.try_emplace("memset", reinterpret_cast<void *>(memset));
552
Nicolas Capens41a73022020-01-30 00:30:14 -0500553#ifdef __APPLE__
Nicolas Capens02966802022-08-02 00:24:26 -0400554 functions.try_emplace("__sincosf_stret", reinterpret_cast<void *>(__sincosf_stret));
Nicolas Capens41a73022020-01-30 00:30:14 -0500555#elif defined(__linux__)
Ben Claytonee18f392020-10-19 16:54:21 -0400556 functions.try_emplace("sincosf", reinterpret_cast<void *>(sincosf));
Nicolas Capens41a73022020-01-30 00:30:14 -0500557#elif defined(_WIN64)
Nicolas Capens02966802022-08-02 00:24:26 -0400558 functions.try_emplace("__chkstk", reinterpret_cast<void *>(__chkstk));
Nicolas Capens41a73022020-01-30 00:30:14 -0500559#elif defined(_WIN32)
Nicolas Capens02966802022-08-02 00:24:26 -0400560 functions.try_emplace("_chkstk", reinterpret_cast<void *>(_chkstk));
Nicolas Capens41a73022020-01-30 00:30:14 -0500561#endif
562
Anton D. Kachalovac4e1d22020-02-11 15:44:27 +0100563#ifdef __ARM_EABI__
Nicolas Capens02966802022-08-02 00:24:26 -0400564 functions.try_emplace("__aeabi_idivmod", reinterpret_cast<void *>(__aeabi_idivmod));
Anton D. Kachalovac4e1d22020-02-11 15:44:27 +0100565#endif
Nicolas Capens41a73022020-01-30 00:30:14 -0500566#ifdef __ANDROID__
Antonio Maiorano84f5eeb2020-10-20 20:39:34 -0400567 functions.try_emplace("aeabi_unwind_cpp_pr0", reinterpret_cast<void *>(neverCalled));
568 functions.try_emplace("sync_synchronize", reinterpret_cast<void *>(sync_synchronize));
569 functions.try_emplace("sync_fetch_and_add_4", reinterpret_cast<void *>(sync_fetch_and_add_4));
570 functions.try_emplace("sync_fetch_and_and_4", reinterpret_cast<void *>(sync_fetch_and_and_4));
571 functions.try_emplace("sync_fetch_and_or_4", reinterpret_cast<void *>(sync_fetch_and_or_4));
572 functions.try_emplace("sync_fetch_and_xor_4", reinterpret_cast<void *>(sync_fetch_and_xor_4));
573 functions.try_emplace("sync_fetch_and_sub_4", reinterpret_cast<void *>(sync_fetch_and_sub_4));
574 functions.try_emplace("sync_lock_test_and_set_4", reinterpret_cast<void *>(sync_lock_test_and_set_4));
575 functions.try_emplace("sync_val_compare_and_swap_4", reinterpret_cast<void *>(sync_val_compare_and_swap_4));
576 functions.try_emplace("sync_fetch_and_max_4", reinterpret_cast<void *>(sync_fetch_and_max_4));
577 functions.try_emplace("sync_fetch_and_min_4", reinterpret_cast<void *>(sync_fetch_and_min_4));
578 functions.try_emplace("sync_fetch_and_umax_4", reinterpret_cast<void *>(sync_fetch_and_umax_4));
579 functions.try_emplace("sync_fetch_and_umin_4", reinterpret_cast<void *>(sync_fetch_and_umin_4));
Nicolas Capens3e551b32020-11-13 21:04:36 +0000580
581# if defined(__i386__)
582 // TODO(b/172974501): Workaround for an x86-32 issue where an R_386_PC32 relocation is used
583 // When calling a C function from Reactor code, who's address is not associated with any symbol
584 // (since it's an absolute constant), but it still invokes the symbol resolver for "".
585 functions.try_emplace("", nullptr);
586# endif
Nicolas Capens41a73022020-01-30 00:30:14 -0500587#endif
Antonio Maioranodd48b7e2020-02-05 13:17:07 -0500588#if __has_feature(memory_sanitizer)
Nicolas Capens02966802022-08-02 00:24:26 -0400589 functions.try_emplace("__emutls_get_address", reinterpret_cast<void *>(rr::getTLSAddress));
590 functions.try_emplace("__emutls_v.__msan_param_tls", reinterpret_cast<void *>(static_cast<uintptr_t>(rr::MSanTLS::param)));
591 functions.try_emplace("__emutls_v.__msan_param_origin_tls", reinterpret_cast<void *>(static_cast<uintptr_t>(rr::MSanTLS::param_origin)));
592 functions.try_emplace("__emutls_v.__msan_retval_tls", reinterpret_cast<void *>(static_cast<uintptr_t>(rr::MSanTLS::retval)));
593 functions.try_emplace("__emutls_v.__msan_retval_origin_tls", reinterpret_cast<void *>(static_cast<uintptr_t>(rr::MSanTLS::retval_origin)));
594 functions.try_emplace("__emutls_v.__msan_va_arg_tls", reinterpret_cast<void *>(static_cast<uintptr_t>(rr::MSanTLS::va_arg)));
595 functions.try_emplace("__emutls_v.__msan_va_arg_origin_tls", reinterpret_cast<void *>(static_cast<uintptr_t>(rr::MSanTLS::va_arg_origin)));
596 functions.try_emplace("__emutls_v.__msan_va_arg_overflow_size_tls", reinterpret_cast<void *>(static_cast<uintptr_t>(rr::MSanTLS::va_arg_overflow_size)));
597 functions.try_emplace("__emutls_v.__msan_origin_tls", reinterpret_cast<void *>(static_cast<uintptr_t>(rr::MSanTLS::origin)));
Nicolas Capensdc8cbfa2021-06-10 17:09:50 -0400598
Nicolas Capens02966802022-08-02 00:24:26 -0400599 functions.try_emplace("__msan_unpoison", reinterpret_cast<void *>(__msan_unpoison));
600 functions.try_emplace("__msan_unpoison_param", reinterpret_cast<void *>(__msan_unpoison_param));
Antonio Maioranodd48b7e2020-02-05 13:17:07 -0500601#endif
Nicolas Capens41a73022020-01-30 00:30:14 -0500602 }
603 };
604
Antonio Maioranoc1839ee2020-10-26 10:16:29 -0400605 llvm::Error tryToGenerate(
606#if LLVM_VERSION_MAJOR >= 11 /* TODO(b/165000222): Unconditional after LLVM 11 upgrade */
607 llvm::orc::LookupState &state,
608#endif
609 llvm::orc::LookupKind kind,
610 llvm::orc::JITDylib &dylib,
611 llvm::orc::JITDylibLookupFlags flags,
612 const llvm::orc::SymbolLookupSet &set) override
Ben Claytonee18f392020-10-19 16:54:21 -0400613 {
614 static Resolver resolver;
Nicolas Capens41a73022020-01-30 00:30:14 -0500615
Ben Claytonee18f392020-10-19 16:54:21 -0400616 llvm::orc::SymbolMap symbols;
Nicolas Capens41a73022020-01-30 00:30:14 -0500617
Ben Claytonee18f392020-10-19 16:54:21 -0400618#if !defined(NDEBUG) || defined(DCHECK_ALWAYS_ON)
619 std::string missing;
620#endif // !defined(NDEBUG) || defined(DCHECK_ALWAYS_ON)
621
622 for(auto symbol : set)
623 {
624 auto name = symbol.first;
625
Nicolas Capens02966802022-08-02 00:24:26 -0400626#if defined(__APPLE__)
627 // Trim the underscore from the start of the symbol. LLVM adds it for Mach-O mangling convention.
628 ASSERT((*name)[0] == '_');
629 auto unmangled = (*name).drop_front(1);
630#else
631 auto unmangled = *name;
632#endif
Ben Claytonee18f392020-10-19 16:54:21 -0400633
Nicolas Capens02966802022-08-02 00:24:26 -0400634 auto it = resolver.functions.find(unmangled.str());
Ben Claytonee18f392020-10-19 16:54:21 -0400635 if(it != resolver.functions.end())
636 {
637 symbols[name] = llvm::JITEvaluatedSymbol(
638 static_cast<llvm::JITTargetAddress>(reinterpret_cast<uintptr_t>(it->second)),
639 llvm::JITSymbolFlags::Exported);
Nicolas Capens47c3ca12020-11-02 16:33:08 -0500640
641 continue;
Ben Claytonee18f392020-10-19 16:54:21 -0400642 }
Nicolas Capens47c3ca12020-11-02 16:33:08 -0500643
Nicolas Capensaafa1082022-08-04 13:40:58 -0400644#if __has_feature(memory_sanitizer) || (__has_feature(address_sanitizer) && ADDRESS_SANITIZER_INSTRUMENTATION_SUPPORTED)
Nicolas Capensa07b3fb2022-07-28 04:18:58 -0400645 // Sanitizers use a dynamically linked runtime. Instrumented routines reference some
646 // symbols from this library. Look them up dynamically in the default namespace.
Nicolas Capens47c3ca12020-11-02 16:33:08 -0500647 // Note this approach should not be used for other symbols, since they might not be
648 // visible (e.g. due to static linking), we may wish to provide an alternate
649 // implementation, and/or it would be a security vulnerability.
650
Nicolas Capens02966802022-08-02 00:24:26 -0400651 void *address = dlsym(RTLD_DEFAULT, unmangled.data());
Nicolas Capens47c3ca12020-11-02 16:33:08 -0500652
653 if(address)
Ben Claytonee18f392020-10-19 16:54:21 -0400654 {
Nicolas Capens47c3ca12020-11-02 16:33:08 -0500655 symbols[name] = llvm::JITEvaluatedSymbol(
656 static_cast<llvm::JITTargetAddress>(reinterpret_cast<uintptr_t>(address)),
657 llvm::JITSymbolFlags::Exported);
658
659 continue;
Ben Claytonee18f392020-10-19 16:54:21 -0400660 }
Nicolas Capens47c3ca12020-11-02 16:33:08 -0500661#endif
662
663#if !defined(NDEBUG) || defined(DCHECK_ALWAYS_ON)
Nicolas Capens02966802022-08-02 00:24:26 -0400664 missing += (missing.empty() ? "'" : ", '") + unmangled.str() + "'";
Nicolas Capens47c3ca12020-11-02 16:33:08 -0500665#endif
Ben Claytonee18f392020-10-19 16:54:21 -0400666 }
667
668#if !defined(NDEBUG) || defined(DCHECK_ALWAYS_ON)
Nicolas Capens47c3ca12020-11-02 16:33:08 -0500669 // Missing functions will likely make the module fail in non-obvious ways.
Ben Claytonee18f392020-10-19 16:54:21 -0400670 if(!missing.empty())
671 {
672 WARN("Missing external functions: %s", missing.c_str());
673 }
Nicolas Capens47c3ca12020-11-02 16:33:08 -0500674#endif
Ben Claytonee18f392020-10-19 16:54:21 -0400675
676 if(symbols.empty())
677 {
678 return llvm::Error::success();
679 }
680
681 return dylib.define(llvm::orc::absoluteSymbols(std::move(symbols)));
682 }
683};
Nicolas Capens41a73022020-01-30 00:30:14 -0500684
Antonio Maioranoec526ab2020-10-21 09:55:50 -0400685// As we must support different LLVM versions, add a generic Unwrap for functions that return Expected<T> or the actual T.
686// TODO(b/165000222): Remove after LLVM 11 upgrade
687template<typename T>
Nicolas Capens3fbdc262022-02-25 00:15:00 -0500688T &Unwrap(llvm::Expected<T> &&v)
Antonio Maioranoec526ab2020-10-21 09:55:50 -0400689{
Nicolas Capens3fbdc262022-02-25 00:15:00 -0500690 assert(v);
Antonio Maioranoec526ab2020-10-21 09:55:50 -0400691 return v.get();
692}
693template<typename T>
Nicolas Capens3fbdc262022-02-25 00:15:00 -0500694T &Unwrap(T &&v)
Antonio Maioranoec526ab2020-10-21 09:55:50 -0400695{
696 return v;
697}
698
Nicolas Capens25f0f852021-01-07 20:46:36 -0500699// Sets *fatal to true if a diagnostic is received which makes a routine invalid or unusable.
700struct FatalDiagnosticsHandler : public llvm::DiagnosticHandler
701{
702 FatalDiagnosticsHandler(bool *fatal)
703 : fatal(fatal)
704 {}
705
706 bool handleDiagnostics(const llvm::DiagnosticInfo &info) override
707 {
708 switch(info.getSeverity())
709 {
Nicolas Capens112faf42019-12-13 17:32:26 -0500710 case llvm::DS_Error:
711 ASSERT_MSG(false, "LLVM JIT compilation failure");
712 *fatal = true;
713 break;
714 case llvm::DS_Warning:
715 if(info.getKind() == llvm::DK_StackSize)
716 {
717 // Stack size limit exceeded
Nicolas Capens25f0f852021-01-07 20:46:36 -0500718 *fatal = true;
Nicolas Capens112faf42019-12-13 17:32:26 -0500719 }
720 break;
721 case llvm::DS_Remark:
722 break;
723 case llvm::DS_Note:
724 break;
Nicolas Capens25f0f852021-01-07 20:46:36 -0500725 }
726
727 return true; // Diagnostic handled, don't let LLVM print it.
728 }
729
730 bool *fatal;
731};
732
Nicolas Capens41a73022020-01-30 00:30:14 -0500733// JITRoutine is a rr::Routine that holds a LLVM JIT session, compiler and
734// object layer as each routine may require different target machine
735// settings and no Reactor routine directly links against another.
736class JITRoutine : public rr::Routine
737{
Nicolas Capens41a73022020-01-30 00:30:14 -0500738public:
739 JITRoutine(
740 std::unique_ptr<llvm::Module> module,
Nicolas Capens567e5602021-01-07 23:18:56 -0500741 std::unique_ptr<llvm::LLVMContext> context,
Antonio Maioranod1fbcb22020-11-27 13:59:04 -0500742 const char *name,
Nicolas Capens41a73022020-01-30 00:30:14 -0500743 llvm::Function **funcs,
Nicolas Capens79d4c6c2022-04-22 17:20:26 -0400744 size_t count)
Antonio Maioranod1fbcb22020-11-27 13:59:04 -0500745 : name(name)
Nicolas Capens44660402021-07-27 21:42:21 -0400746#if LLVM_VERSION_MAJOR >= 13
Nicolas Capens3fbdc262022-02-25 00:15:00 -0500747 , session(std::move(Unwrap(llvm::orc::SelfExecutorProcessControl::Create())))
Nicolas Capens44660402021-07-27 21:42:21 -0400748#endif
Nicolas Capensfca80842021-01-08 16:37:53 -0500749 , objectLayer(session, [this]() {
Nicolas Capens827e9a22020-11-02 11:04:24 -0500750 return std::make_unique<llvm::SectionMemoryManager>(&memoryMapper);
Ben Claytone02d8932020-10-21 18:37:33 +0100751 })
Nicolas Capens41a73022020-01-30 00:30:14 -0500752 , addresses(count)
753 {
Nicolas Capens25f0f852021-01-07 20:46:36 -0500754 bool fatalCompileIssue = false;
755 context->setDiagnosticHandler(std::make_unique<FatalDiagnosticsHandler>(&fatalCompileIssue), true);
756
Ben Claytonee18f392020-10-19 16:54:21 -0400757#ifdef ENABLE_RR_DEBUG_INFO
758 // TODO(b/165000222): Update this on next LLVM roll.
759 // https://github.com/llvm/llvm-project/commit/98f2bb4461072347dcca7d2b1b9571b3a6525801
760 // introduces RTDyldObjectLinkingLayer::registerJITEventListener().
761 // The current API does not appear to have any way to bind the
762 // rr::DebugInfo::NotifyFreeingObject event.
Daniele Vettorele1930f02022-03-04 15:44:31 +0000763# if LLVM_VERSION_MAJOR >= 12
764 objectLayer.setNotifyLoaded([](llvm::orc::MaterializationResponsibility &R,
765 const llvm::object::ObjectFile &obj,
766 const llvm::RuntimeDyld::LoadedObjectInfo &l) {
767 static std::atomic<uint64_t> unique_key{ 0 };
768 rr::DebugInfo::NotifyObjectEmitted(unique_key++, obj, l);
769 });
770# else
Ben Claytonee18f392020-10-19 16:54:21 -0400771 objectLayer.setNotifyLoaded([](llvm::orc::VModuleKey,
772 const llvm::object::ObjectFile &obj,
773 const llvm::RuntimeDyld::LoadedObjectInfo &l) {
774 static std::atomic<uint64_t> unique_key{ 0 };
775 rr::DebugInfo::NotifyObjectEmitted(unique_key++, obj, l);
776 });
Daniele Vettorele1930f02022-03-04 15:44:31 +0000777# endif
Ben Claytonee18f392020-10-19 16:54:21 -0400778#endif // ENABLE_RR_DEBUG_INFO
Ben Claytona7bc2b92020-03-26 11:24:49 +0000779
Ben Claytonee18f392020-10-19 16:54:21 -0400780 if(JITGlobals::get()->getTargetTriple().isOSBinFormatCOFF())
781 {
782 // Hack to support symbol visibility in COFF.
783 // Matches hack in llvm::orc::LLJIT::createObjectLinkingLayer().
784 // See documentation on these functions for more detail.
785 objectLayer.setOverrideObjectFlagsWithResponsibilityFlags(true);
786 objectLayer.setAutoClaimResponsibilityForObjectSymbols(true);
787 }
788
Nicolas Capens58d987a2021-01-07 23:24:25 -0500789 llvm::SmallVector<llvm::orc::SymbolStringPtr, 8> functionNames(count);
790 llvm::orc::MangleAndInterner mangle(session, JITGlobals::get()->getDataLayout());
791
Nicolas Capens41a73022020-01-30 00:30:14 -0500792 for(size_t i = 0; i < count; i++)
793 {
Nicolas Capensc13f4b12022-02-25 11:08:07 -0500794 llvm::Function *func = funcs[i];
Nicolas Capens58d987a2021-01-07 23:24:25 -0500795
Ben Claytonee18f392020-10-19 16:54:21 -0400796 if(!func->hasName())
797 {
798 func->setName("f" + llvm::Twine(i).str());
799 }
Nicolas Capens58d987a2021-01-07 23:24:25 -0500800
801 functionNames[i] = mangle(func->getName());
Nicolas Capens41a73022020-01-30 00:30:14 -0500802 }
803
Antonio Maiorano6f6ca292020-11-27 15:40:15 -0500804#ifdef ENABLE_RR_EMIT_ASM_FILE
Nicolas Capens79d4c6c2022-04-22 17:20:26 -0400805 const auto asmFilename = rr::AsmFile::generateFilename(REACTOR_ASM_EMIT_DIR, name);
806 rr::AsmFile::emitAsmFile(asmFilename, JITGlobals::get()->getTargetMachineBuilder(), *module);
Antonio Maiorano6f6ca292020-11-27 15:40:15 -0500807#endif
808
Nicolas Capens588d32c2021-01-08 00:40:09 -0500809 // Once the module is passed to the compileLayer, the llvm::Functions are freed.
810 // Make sure funcs are not referenced after this point.
Nicolas Capens41a73022020-01-30 00:30:14 -0500811 funcs = nullptr;
812
Nicolas Capens79d4c6c2022-04-22 17:20:26 -0400813 llvm::orc::IRCompileLayer compileLayer(session, objectLayer, std::make_unique<llvm::orc::ConcurrentIRCompiler>(JITGlobals::get()->getTargetMachineBuilder()));
Nicolas Capens588d32c2021-01-08 00:40:09 -0500814 llvm::orc::JITDylib &dylib(Unwrap(session.createJITDylib("<routine>")));
815 dylib.addGenerator(std::make_unique<ExternalSymbolGenerator>());
816
Nicolas Capens567e5602021-01-07 23:18:56 -0500817 llvm::cantFail(compileLayer.add(dylib, llvm::orc::ThreadSafeModule(std::move(module), std::move(context))));
Nicolas Capens41a73022020-01-30 00:30:14 -0500818
819 // Resolve the function addresses.
820 for(size_t i = 0; i < count; i++)
821 {
Nicolas Capens25f0f852021-01-07 20:46:36 -0500822 fatalCompileIssue = false; // May be set to true by session.lookup()
823
824 // This is where the actual compilation happens.
Nicolas Capens58d987a2021-01-07 23:24:25 -0500825 auto symbol = session.lookup({ &dylib }, functionNames[i]);
Nicolas Capens25f0f852021-01-07 20:46:36 -0500826
Ben Claytonee18f392020-10-19 16:54:21 -0400827 ASSERT_MSG(symbol, "Failed to lookup address of routine function %d: %s",
828 (int)i, llvm::toString(symbol.takeError()).c_str());
Nicolas Capens25f0f852021-01-07 20:46:36 -0500829
830 if(fatalCompileIssue)
831 {
832 addresses[i] = nullptr;
833 }
834 else // Successful compilation
835 {
836 addresses[i] = reinterpret_cast<void *>(static_cast<intptr_t>(symbol->getAddress()));
837 }
Nicolas Capens41a73022020-01-30 00:30:14 -0500838 }
Antonio Maiorano6f6ca292020-11-27 15:40:15 -0500839
840#ifdef ENABLE_RR_EMIT_ASM_FILE
841 rr::AsmFile::fixupAsmFile(asmFilename, addresses);
842#endif
Nicolas Capens41a73022020-01-30 00:30:14 -0500843 }
844
Antonio Maioranobb66fa42020-10-22 13:53:09 -0400845 ~JITRoutine()
846 {
Antonio Maioranoc1839ee2020-10-26 10:16:29 -0400847#if LLVM_VERSION_MAJOR >= 11 /* TODO(b/165000222): Unconditional after LLVM 11 upgrade */
848 if(auto err = session.endSession())
849 {
850 session.reportError(std::move(err));
851 }
Antonio Maioranobb66fa42020-10-22 13:53:09 -0400852#endif
853 }
854
Nicolas Capens41a73022020-01-30 00:30:14 -0500855 const void *getEntry(int index) const override
856 {
857 return addresses[index];
858 }
Nicolas Capens588d32c2021-01-08 00:40:09 -0500859
860private:
861 std::string name;
862 llvm::orc::ExecutionSession session;
Nicolas Capensfca80842021-01-08 16:37:53 -0500863 MemoryMapper memoryMapper;
Nicolas Capens588d32c2021-01-08 00:40:09 -0500864 llvm::orc::RTDyldObjectLinkingLayer objectLayer;
865 std::vector<const void *> addresses;
Nicolas Capens41a73022020-01-30 00:30:14 -0500866};
867
868} // anonymous namespace
869
870namespace rr {
871
Nicolas Capens79d4c6c2022-04-22 17:20:26 -0400872JITBuilder::JITBuilder()
873 : context(new llvm::LLVMContext())
Nicolas Capens567e5602021-01-07 23:18:56 -0500874 , module(new llvm::Module("", *context))
875 , builder(new llvm::IRBuilder<>(*context))
Nicolas Capens41a73022020-01-30 00:30:14 -0500876{
Nicolas Capens959f4192020-11-02 15:30:30 -0500877 module->setTargetTriple(LLVM_DEFAULT_TARGET_TRIPLE);
Ben Claytonee18f392020-10-19 16:54:21 -0400878 module->setDataLayout(JITGlobals::get()->getDataLayout());
Nicolas Capensdc8cbfa2021-06-10 17:09:50 -0400879
Nicolas Capens80de2012022-05-13 13:43:21 -0400880 msanInstrumentation = getPragmaState(MemorySanitizerInstrumentation);
Nicolas Capens41a73022020-01-30 00:30:14 -0500881}
882
Nicolas Capens79d4c6c2022-04-22 17:20:26 -0400883void JITBuilder::runPasses()
Nicolas Capens41a73022020-01-30 00:30:14 -0500884{
Nicolas Capens8e678f52022-04-26 11:47:34 -0400885#if defined(ENABLE_RR_LLVM_IR_VERIFICATION) || !defined(NDEBUG)
886 if(llvm::verifyModule(*module, &llvm::errs()))
887 {
888 llvm::report_fatal_error("Invalid LLVM module");
889 }
890#endif
891
Nicolas Capens45fce442022-04-26 16:55:58 -0400892 int optimizationLevel = getPragmaState(OptimizationLevel);
893
894#ifdef ENABLE_RR_DEBUG_INFO
895 if(debugInfo != nullptr)
Nicolas Capens88fe9ce2022-04-19 18:32:26 -0400896 {
Nicolas Capens45fce442022-04-26 16:55:58 -0400897 optimizationLevel = 0; // Don't optimize if we're generating debug info.
898 }
899#endif // ENABLE_RR_DEBUG_INFO
900
Nicolas Capens88fe9ce2022-04-19 18:32:26 -0400901#if LLVM_VERSION_MAJOR >= 13 // New pass manager
Nicolas Capensea5f37f2022-04-19 16:08:20 -0400902 llvm::LoopAnalysisManager lam;
903 llvm::FunctionAnalysisManager fam;
904 llvm::CGSCCAnalysisManager cgam;
905 llvm::ModuleAnalysisManager mam;
906 llvm::PassBuilder pb;
907
908 pb.registerModuleAnalyses(mam);
909 pb.registerCGSCCAnalyses(cgam);
910 pb.registerFunctionAnalyses(fam);
911 pb.registerLoopAnalyses(lam);
912 pb.crossRegisterProxies(lam, fam, cgam, mam);
913
914 llvm::ModulePassManager pm;
915 llvm::FunctionPassManager fpm;
916
Nicolas Capensb92f7ac2022-04-27 10:52:33 -0400917 if(coroutine.id)
918 {
Nicolas Capens9f2ef7c2022-04-28 00:50:26 -0400919 // Adds mandatory coroutine transforms.
920 pm = pb.buildO0DefaultPipeline(llvm::OptimizationLevel::O0);
Nicolas Capensb92f7ac2022-04-27 10:52:33 -0400921 }
922
Nicolas Capens45fce442022-04-26 16:55:58 -0400923 if(optimizationLevel > 0)
Nicolas Capensea5f37f2022-04-19 16:08:20 -0400924 {
Alexis Hetu647d3d22022-12-12 18:15:10 -0500925 fpm.addPass(llvm::SROAPass(llvm::SROAOptions::PreserveCFG));
Nicolas Capens79d4c6c2022-04-22 17:20:26 -0400926 fpm.addPass(llvm::InstCombinePass());
Nicolas Capensea5f37f2022-04-19 16:08:20 -0400927 }
928
929 if(!fpm.isEmpty())
930 {
931 pm.addPass(llvm::createModuleToFunctionPassAdaptor(std::move(fpm)));
932 }
933
Nicolas Capens69a53d92022-04-28 01:26:17 -0400934 if(__has_feature(memory_sanitizer) && msanInstrumentation)
935 {
936 llvm::MemorySanitizerOptions msanOpts(0 /* TrackOrigins */, false /* Recover */, false /* Kernel */, true /* EagerChecks */);
Nicolas Capens4e4d2b42022-09-07 15:54:28 -0400937 pm.addPass(llvm::MemorySanitizerPass(msanOpts));
Nicolas Capens69a53d92022-04-28 01:26:17 -0400938 }
939
Nicolas Capensaafa1082022-08-04 13:40:58 -0400940 if(__has_feature(address_sanitizer) && ADDRESS_SANITIZER_INSTRUMENTATION_SUPPORTED)
Nicolas Capensa07b3fb2022-07-28 04:18:58 -0400941 {
Nicolas Capens8c9c9f72022-09-07 10:24:08 -0400942 pm.addPass(llvm::AddressSanitizerPass(llvm::AddressSanitizerOptions{}));
Nicolas Capensa07b3fb2022-07-28 04:18:58 -0400943 }
944
Nicolas Capensea5f37f2022-04-19 16:08:20 -0400945 pm.run(*module, mam);
946#else // Legacy pass manager
Nicolas Capensb92f7ac2022-04-27 10:52:33 -0400947 llvm::legacy::PassManager passManager;
948
Nicolas Capens45fce442022-04-26 16:55:58 -0400949 if(coroutine.id)
950 {
951 // Run mandatory coroutine transforms.
Nicolas Capensb92f7ac2022-04-27 10:52:33 -0400952 passManager.add(llvm::createCoroEarlyLegacyPass());
953 passManager.add(llvm::createCoroSplitLegacyPass());
954 passManager.add(llvm::createCoroElideLegacyPass());
955 passManager.add(llvm::createBarrierNoopPass());
956 passManager.add(llvm::createCoroCleanupLegacyPass());
Nicolas Capens45fce442022-04-26 16:55:58 -0400957 }
958
Nicolas Capens45fce442022-04-26 16:55:58 -0400959 if(optimizationLevel > 0)
Nicolas Capens41a73022020-01-30 00:30:14 -0500960 {
Nicolas Capens79d4c6c2022-04-22 17:20:26 -0400961 passManager.add(llvm::createSROAPass());
962 passManager.add(llvm::createInstructionCombiningPass());
Nicolas Capens41a73022020-01-30 00:30:14 -0500963 }
964
Nicolas Capens69a53d92022-04-28 01:26:17 -0400965 if(__has_feature(memory_sanitizer) && msanInstrumentation)
966 {
Nicolas Capens11e432d2022-05-04 16:42:19 -0400967 llvm::MemorySanitizerOptions msanOpts(0 /* TrackOrigins */, false /* Recover */, false /* Kernel */);
968 passManager.add(llvm::createMemorySanitizerLegacyPassPass(msanOpts));
Nicolas Capens69a53d92022-04-28 01:26:17 -0400969 }
970
Nicolas Capensaafa1082022-08-04 13:40:58 -0400971 if(__has_feature(address_sanitizer) && ADDRESS_SANITIZER_INSTRUMENTATION_SUPPORTED)
Nicolas Capensa07b3fb2022-07-28 04:18:58 -0400972 {
973 passManager.add(llvm::createAddressSanitizerFunctionPass());
974 }
975
Ben Claytonee18f392020-10-19 16:54:21 -0400976 passManager.run(*module);
Nicolas Capensea5f37f2022-04-19 16:08:20 -0400977#endif
Nicolas Capens41a73022020-01-30 00:30:14 -0500978}
979
Nicolas Capens79d4c6c2022-04-22 17:20:26 -0400980std::shared_ptr<rr::Routine> JITBuilder::acquireRoutine(const char *name, llvm::Function **funcs, size_t count)
Nicolas Capens41a73022020-01-30 00:30:14 -0500981{
982 ASSERT(module);
Nicolas Capens79d4c6c2022-04-22 17:20:26 -0400983 return std::make_shared<JITRoutine>(std::move(module), std::move(context), name, funcs, count);
Nicolas Capens41a73022020-01-30 00:30:14 -0500984}
985
986} // namespace rr