Path: blob/21.2-virgl/src/gallium/auxiliary/gallivm/lp_bld_misc.cpp
4565 views
/**************************************************************************1*2* Copyright 2010 VMware, Inc.3* All Rights Reserved.4*5* Permission is hereby granted, free of charge, to any person obtaining a6* copy of this software and associated documentation files (the7* "Software"), to deal in the Software without restriction, including8* without limitation the rights to use, copy, modify, merge, publish,9* distribute, sub license, and/or sell copies of the Software, and to10* permit persons to whom the Software is furnished to do so, subject to11* the following conditions:12*13* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR14* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,15* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL16* THE COPYRIGHT HOLDERS, AUTHORS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM,17* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR18* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE19* USE OR OTHER DEALINGS IN THE SOFTWARE.20*21* The above copyright notice and this permission notice (including the22* next paragraph) shall be included in all copies or substantial portions23* of the Software.24*25**************************************************************************/262728/**29* The purpose of this module is to expose LLVM functionality not available30* through the C++ bindings.31*/323334// Undef these vars just to silence warnings35#undef PACKAGE_BUGREPORT36#undef PACKAGE_NAME37#undef PACKAGE_STRING38#undef PACKAGE_TARNAME39#undef PACKAGE_VERSION404142#include <stddef.h>4344#include <llvm/Config/llvm-config.h>4546#if LLVM_VERSION_MAJOR < 747// Workaround http://llvm.org/PR2362848#pragma push_macro("DEBUG")49#undef DEBUG50#endif5152#include <llvm/Config/llvm-config.h>53#include <llvm-c/Core.h>54#include <llvm-c/Support.h>55#include <llvm-c/ExecutionEngine.h>56#include <llvm/Target/TargetOptions.h>57#include <llvm/ExecutionEngine/ExecutionEngine.h>58#include <llvm/ADT/Triple.h>59#include <llvm/Analysis/TargetLibraryInfo.h>60#include <llvm/ExecutionEngine/SectionMemoryManager.h>61#include <llvm/Support/CommandLine.h>62#include <llvm/Support/Host.h>63#include <llvm/Support/PrettyStackTrace.h>64#include <llvm/ExecutionEngine/ObjectCache.h>65#include <llvm/Support/TargetSelect.h>6667#if LLVM_VERSION_MAJOR < 1168#include <llvm/IR/CallSite.h>69#endif70#include <llvm/IR/IRBuilder.h>71#include <llvm/IR/Module.h>72#include <llvm/Support/CBindingWrapping.h>7374#include <llvm/Config/llvm-config.h>75#if LLVM_USE_INTEL_JITEVENTS76#include <llvm/ExecutionEngine/JITEventListener.h>77#endif7879#if LLVM_VERSION_MAJOR < 780// Workaround http://llvm.org/PR2362881#pragma pop_macro("DEBUG")82#endif8384#include "c11/threads.h"85#include "os/os_thread.h"86#include "pipe/p_config.h"87#include "util/u_debug.h"88#include "util/u_cpu_detect.h"8990#include "lp_bld_misc.h"91#include "lp_bld_debug.h"9293namespace {9495class LLVMEnsureMultithreaded {96public:97LLVMEnsureMultithreaded()98{99if (!LLVMIsMultithreaded()) {100LLVMStartMultithreaded();101}102}103};104105static LLVMEnsureMultithreaded lLVMEnsureMultithreaded;106107}108109static once_flag init_native_targets_once_flag = ONCE_FLAG_INIT;110111static void init_native_targets()112{113// If we have a native target, initialize it to ensure it is linked in and114// usable by the JIT.115llvm::InitializeNativeTarget();116117llvm::InitializeNativeTargetAsmPrinter();118119llvm::InitializeNativeTargetDisassembler();120#if DEBUG121{122char *env_llc_options = getenv("GALLIVM_LLC_OPTIONS");123if (env_llc_options) {124char *option;125char *options[64] = {(char *) "llc"}; // Warning without cast126int n;127for (n = 0, option = strtok(env_llc_options, " "); option; n++, option = strtok(NULL, " ")) {128options[n + 1] = option;129}130if (gallivm_debug & (GALLIVM_DEBUG_IR | GALLIVM_DEBUG_ASM | GALLIVM_DEBUG_DUMP_BC)) {131debug_printf("llc additional options (%d):\n", n);132for (int i = 1; i <= n; i++)133debug_printf("\t%s\n", options[i]);134debug_printf("\n");135}136LLVMParseCommandLineOptions(n + 1, options, NULL);137}138}139#endif140}141142extern "C" void143lp_set_target_options(void)144{145/* The llvm target registry is not thread-safe, so drivers and gallium frontends146* that want to initialize targets should use the lp_set_target_options()147* function to safely initialize targets.148*149* LLVM targets should be initialized before the driver or gallium frontend tries150* to access the registry.151*/152call_once(&init_native_targets_once_flag, init_native_targets);153}154155extern "C"156LLVMTargetLibraryInfoRef157gallivm_create_target_library_info(const char *triple)158{159return reinterpret_cast<LLVMTargetLibraryInfoRef>(160new llvm::TargetLibraryInfoImpl(161llvm::Triple(triple)));162}163164extern "C"165void166gallivm_dispose_target_library_info(LLVMTargetLibraryInfoRef library_info)167{168delete reinterpret_cast<169llvm::TargetLibraryInfoImpl170*>(library_info);171}172173174typedef llvm::RTDyldMemoryManager BaseMemoryManager;175176177/*178* Delegating is tedious but the default manager class is hidden in an179* anonymous namespace in LLVM, so we cannot just derive from it to change180* its behavior.181*/182class DelegatingJITMemoryManager : public BaseMemoryManager {183184protected:185virtual BaseMemoryManager *mgr() const = 0;186187public:188/*189* From RTDyldMemoryManager190*/191virtual uint8_t *allocateCodeSection(uintptr_t Size,192unsigned Alignment,193unsigned SectionID,194llvm::StringRef SectionName) {195return mgr()->allocateCodeSection(Size, Alignment, SectionID,196SectionName);197}198virtual uint8_t *allocateDataSection(uintptr_t Size,199unsigned Alignment,200unsigned SectionID,201llvm::StringRef SectionName,202bool IsReadOnly) {203return mgr()->allocateDataSection(Size, Alignment, SectionID,204SectionName,205IsReadOnly);206}207virtual void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr, size_t Size) {208mgr()->registerEHFrames(Addr, LoadAddr, Size);209}210#if LLVM_VERSION_MAJOR >= 5211virtual void deregisterEHFrames() {212mgr()->deregisterEHFrames();213}214#else215virtual void deregisterEHFrames(uint8_t *Addr, uint64_t LoadAddr, size_t Size) {216mgr()->deregisterEHFrames(Addr, LoadAddr, Size);217}218#endif219virtual void *getPointerToNamedFunction(const std::string &Name,220bool AbortOnFailure=true) {221return mgr()->getPointerToNamedFunction(Name, AbortOnFailure);222}223virtual bool finalizeMemory(std::string *ErrMsg = 0) {224return mgr()->finalizeMemory(ErrMsg);225}226};227228229/*230* Delegate memory management to one shared manager for more efficient use231* of memory than creating a separate pool for each LLVM engine.232* Keep generated code until freeGeneratedCode() is called, instead of when233* memory manager is destroyed, which happens during engine destruction.234* This allows additional memory savings as we don't have to keep the engine235* around in order to use the code.236* All methods are delegated to the shared manager except destruction and237* deallocating code. For the latter we just remember what needs to be238* deallocated later. The shared manager is deleted once it is empty.239*/240class ShaderMemoryManager : public DelegatingJITMemoryManager {241242BaseMemoryManager *TheMM;243244struct GeneratedCode {245typedef std::vector<void *> Vec;246Vec FunctionBody, ExceptionTable;247BaseMemoryManager *TheMM;248249GeneratedCode(BaseMemoryManager *MM) {250TheMM = MM;251}252253~GeneratedCode() {254}255};256257GeneratedCode *code;258259BaseMemoryManager *mgr() const {260return TheMM;261}262263public:264265ShaderMemoryManager(BaseMemoryManager* MM) {266TheMM = MM;267code = new GeneratedCode(MM);268}269270virtual ~ShaderMemoryManager() {271/*272* 'code' is purposely not deleted. It is the user's responsibility273* to call getGeneratedCode() and freeGeneratedCode().274*/275}276277struct lp_generated_code *getGeneratedCode() {278return (struct lp_generated_code *) code;279}280281static void freeGeneratedCode(struct lp_generated_code *code) {282delete (GeneratedCode *) code;283}284285virtual void deallocateFunctionBody(void *Body) {286// remember for later deallocation287code->FunctionBody.push_back(Body);288}289};290291class LPObjectCache : public llvm::ObjectCache {292private:293bool has_object;294struct lp_cached_code *cache_out;295public:296LPObjectCache(struct lp_cached_code *cache) {297cache_out = cache;298has_object = false;299}300301~LPObjectCache() {302}303void notifyObjectCompiled(const llvm::Module *M, llvm::MemoryBufferRef Obj) {304const std::string ModuleID = M->getModuleIdentifier();305if (has_object)306fprintf(stderr, "CACHE ALREADY HAS MODULE OBJECT\n");307has_object = true;308cache_out->data_size = Obj.getBufferSize();309cache_out->data = malloc(cache_out->data_size);310memcpy(cache_out->data, Obj.getBufferStart(), cache_out->data_size);311}312313virtual std::unique_ptr<llvm::MemoryBuffer> getObject(const llvm::Module *M) {314if (cache_out->data_size) {315return llvm::MemoryBuffer::getMemBuffer(llvm::StringRef((const char *)cache_out->data, cache_out->data_size), "", false);316}317return NULL;318}319320};321322/**323* Same as LLVMCreateJITCompilerForModule, but:324* - allows using MCJIT and enabling AVX feature where available.325* - set target options326*327* See also:328* - llvm/lib/ExecutionEngine/ExecutionEngineBindings.cpp329* - llvm/tools/lli/lli.cpp330* - http://markmail.org/message/ttkuhvgj4cxxy2on#query:+page:1+mid:aju2dggerju3ivd3+state:results331*/332extern "C"333LLVMBool334lp_build_create_jit_compiler_for_module(LLVMExecutionEngineRef *OutJIT,335lp_generated_code **OutCode,336struct lp_cached_code *cache_out,337LLVMModuleRef M,338LLVMMCJITMemoryManagerRef CMM,339unsigned OptLevel,340char **OutError)341{342using namespace llvm;343344std::string Error;345EngineBuilder builder(std::unique_ptr<Module>(unwrap(M)));346347/**348* LLVM 3.1+ haven't more "extern unsigned llvm::StackAlignmentOverride" and349* friends for configuring code generation options, like stack alignment.350*/351TargetOptions options;352#if defined(PIPE_ARCH_X86)353options.StackAlignmentOverride = 4;354#endif355356builder.setEngineKind(EngineKind::JIT)357.setErrorStr(&Error)358.setTargetOptions(options)359.setOptLevel((CodeGenOpt::Level)OptLevel);360361#ifdef _WIN32362/*363* MCJIT works on Windows, but currently only through ELF object format.364*365* XXX: We could use `LLVM_HOST_TRIPLE "-elf"` but LLVM_HOST_TRIPLE has366* different strings for MinGW/MSVC, so better play it safe and be367* explicit.368*/369# ifdef _WIN64370LLVMSetTarget(M, "x86_64-pc-win32-elf");371# else372LLVMSetTarget(M, "i686-pc-win32-elf");373# endif374#endif375376llvm::SmallVector<std::string, 16> MAttrs;377378#if LLVM_VERSION_MAJOR >= 4 && (defined(PIPE_ARCH_X86) || defined(PIPE_ARCH_X86_64) || defined(PIPE_ARCH_ARM))379/* llvm-3.3+ implements sys::getHostCPUFeatures for Arm380* and llvm-3.7+ for x86, which allows us to enable/disable381* code generation based on the results of cpuid on these382* architectures.383*/384llvm::StringMap<bool> features;385llvm::sys::getHostCPUFeatures(features);386387for (StringMapIterator<bool> f = features.begin();388f != features.end();389++f) {390MAttrs.push_back(((*f).second ? "+" : "-") + (*f).first().str());391}392#elif defined(PIPE_ARCH_X86) || defined(PIPE_ARCH_X86_64)393/*394* We need to unset attributes because sometimes LLVM mistakenly assumes395* certain features are present given the processor name.396*397* https://bugs.freedesktop.org/show_bug.cgi?id=92214398* http://llvm.org/PR25021399* http://llvm.org/PR19429400* http://llvm.org/PR16721401*/402MAttrs.push_back(util_get_cpu_caps()->has_sse ? "+sse" : "-sse" );403MAttrs.push_back(util_get_cpu_caps()->has_sse2 ? "+sse2" : "-sse2" );404MAttrs.push_back(util_get_cpu_caps()->has_sse3 ? "+sse3" : "-sse3" );405MAttrs.push_back(util_get_cpu_caps()->has_ssse3 ? "+ssse3" : "-ssse3" );406MAttrs.push_back(util_get_cpu_caps()->has_sse4_1 ? "+sse4.1" : "-sse4.1");407MAttrs.push_back(util_get_cpu_caps()->has_sse4_2 ? "+sse4.2" : "-sse4.2");408/*409* AVX feature is not automatically detected from CPUID by the X86 target410* yet, because the old (yet default) JIT engine is not capable of411* emitting the opcodes. On newer llvm versions it is and at least some412* versions (tested with 3.3) will emit avx opcodes without this anyway.413*/414MAttrs.push_back(util_get_cpu_caps()->has_avx ? "+avx" : "-avx");415MAttrs.push_back(util_get_cpu_caps()->has_f16c ? "+f16c" : "-f16c");416MAttrs.push_back(util_get_cpu_caps()->has_fma ? "+fma" : "-fma");417MAttrs.push_back(util_get_cpu_caps()->has_avx2 ? "+avx2" : "-avx2");418/* disable avx512 and all subvariants */419MAttrs.push_back("-avx512cd");420MAttrs.push_back("-avx512er");421MAttrs.push_back("-avx512f");422MAttrs.push_back("-avx512pf");423MAttrs.push_back("-avx512bw");424MAttrs.push_back("-avx512dq");425MAttrs.push_back("-avx512vl");426#endif427#if defined(PIPE_ARCH_ARM)428if (!util_get_cpu_caps()->has_neon) {429MAttrs.push_back("-neon");430MAttrs.push_back("-crypto");431MAttrs.push_back("-vfp2");432}433#endif434435#if defined(PIPE_ARCH_PPC)436MAttrs.push_back(util_get_cpu_caps()->has_altivec ? "+altivec" : "-altivec");437#if (LLVM_VERSION_MAJOR < 4)438/*439* Make sure VSX instructions are disabled440* See LLVM bugs:441* https://llvm.org/bugs/show_bug.cgi?id=25503#c7 (fixed in 3.8.1)442* https://llvm.org/bugs/show_bug.cgi?id=26775 (fixed in 3.8.1)443* https://llvm.org/bugs/show_bug.cgi?id=33531 (fixed in 4.0)444* https://llvm.org/bugs/show_bug.cgi?id=34647 (llc performance on certain unusual shader IR; intro'd in 4.0, pending as of 5.0)445*/446if (util_get_cpu_caps()->has_altivec) {447MAttrs.push_back("-vsx");448}449#else450/*451* Bug 25503 is fixed, by the same fix that fixed452* bug 26775, in versions of LLVM later than 3.8 (starting with 3.8.1).453* BZ 33531 actually comprises more than one bug, all of454* which are fixed in LLVM 4.0.455*456* With LLVM 4.0 or higher:457* Make sure VSX instructions are ENABLED (if supported), unless458* VSX instructions are explicitly enabled/disabled via GALLIVM_VSX=1 or 0.459*/460if (util_get_cpu_caps()->has_altivec) {461MAttrs.push_back(util_get_cpu_caps()->has_vsx ? "+vsx" : "-vsx");462}463#endif464#endif465466builder.setMAttrs(MAttrs);467468if (gallivm_debug & (GALLIVM_DEBUG_IR | GALLIVM_DEBUG_ASM | GALLIVM_DEBUG_DUMP_BC)) {469int n = MAttrs.size();470if (n > 0) {471debug_printf("llc -mattr option(s): ");472for (int i = 0; i < n; i++)473debug_printf("%s%s", MAttrs[i].c_str(), (i < n - 1) ? "," : "");474debug_printf("\n");475}476}477478StringRef MCPU = llvm::sys::getHostCPUName();479/*480* The cpu bits are no longer set automatically, so need to set mcpu manually.481* Note that the MAttrs set above will be sort of ignored (since we should482* not set any which would not be set by specifying the cpu anyway).483* It ought to be safe though since getHostCPUName() should include bits484* not only from the cpu but environment as well (for instance if it's safe485* to use avx instructions which need OS support). According to486* http://llvm.org/bugs/show_bug.cgi?id=19429 however if I understand this487* right it may be necessary to specify older cpu (or disable mattrs) though488* when not using MCJIT so no instructions are generated which the old JIT489* can't handle. Not entirely sure if we really need to do anything yet.490*/491492#ifdef PIPE_ARCH_PPC_64493/*494* Large programs, e.g. gnome-shell and firefox, may tax the addressability495* of the Medium code model once dynamically generated JIT-compiled shader496* programs are linked in and relocated. Yet the default code model as of497* LLVM 8 is Medium or even Small.498* The cost of changing from Medium to Large is negligible:499* - an additional 8-byte pointer stored immediately before the shader entrypoint;500* - change an add-immediate (addis) instruction to a load (ld).501*/502builder.setCodeModel(CodeModel::Large);503504#if UTIL_ARCH_LITTLE_ENDIAN505/*506* Versions of LLVM prior to 4.0 lacked a table entry for "POWER8NVL",507* resulting in (big-endian) "generic" being returned on508* little-endian Power8NVL systems. The result was that code that509* attempted to load the least significant 32 bits of a 64-bit quantity510* from memory loaded the wrong half. This resulted in failures in some511* Piglit tests, e.g.512* .../arb_gpu_shader_fp64/execution/conversion/frag-conversion-explicit-double-uint513*/514if (MCPU == "generic")515MCPU = "pwr8";516#endif517#endif518builder.setMCPU(MCPU);519if (gallivm_debug & (GALLIVM_DEBUG_IR | GALLIVM_DEBUG_ASM | GALLIVM_DEBUG_DUMP_BC)) {520debug_printf("llc -mcpu option: %s\n", MCPU.str().c_str());521}522523ShaderMemoryManager *MM = NULL;524BaseMemoryManager* JMM = reinterpret_cast<BaseMemoryManager*>(CMM);525MM = new ShaderMemoryManager(JMM);526*OutCode = MM->getGeneratedCode();527528builder.setMCJITMemoryManager(std::unique_ptr<RTDyldMemoryManager>(MM));529MM = NULL; // ownership taken by std::unique_ptr530531ExecutionEngine *JIT;532533JIT = builder.create();534535if (cache_out) {536LPObjectCache *objcache = new LPObjectCache(cache_out);537JIT->setObjectCache(objcache);538cache_out->jit_obj_cache = (void *)objcache;539}540541#if LLVM_USE_INTEL_JITEVENTS542JITEventListener *JEL = JITEventListener::createIntelJITEventListener();543JIT->RegisterJITEventListener(JEL);544#endif545if (JIT) {546*OutJIT = wrap(JIT);547return 0;548}549lp_free_generated_code(*OutCode);550*OutCode = 0;551delete MM;552*OutError = strdup(Error.c_str());553return 1;554}555556557extern "C"558void559lp_free_generated_code(struct lp_generated_code *code)560{561ShaderMemoryManager::freeGeneratedCode(code);562}563564extern "C"565LLVMMCJITMemoryManagerRef566lp_get_default_memory_manager()567{568BaseMemoryManager *mm;569mm = new llvm::SectionMemoryManager();570return reinterpret_cast<LLVMMCJITMemoryManagerRef>(mm);571}572573extern "C"574void575lp_free_memory_manager(LLVMMCJITMemoryManagerRef memorymgr)576{577delete reinterpret_cast<BaseMemoryManager*>(memorymgr);578}579580extern "C" void581lp_free_objcache(void *objcache_ptr)582{583LPObjectCache *objcache = (LPObjectCache *)objcache_ptr;584delete objcache;585}586587extern "C" LLVMValueRef588lp_get_called_value(LLVMValueRef call)589{590return LLVMGetCalledValue(call);591}592593extern "C" bool594lp_is_function(LLVMValueRef v)595{596return LLVMGetValueKind(v) == LLVMFunctionValueKind;597}598599600