Path: blob/21.2-virgl/src/gallium/auxiliary/gallivm/lp_bld_init.c
4565 views
/**************************************************************************1*2* Copyright 2009 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 above copyright notice and this permission notice (including the14* next paragraph) shall be included in all copies or substantial portions15* of the Software.16*17* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS18* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF19* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.20* IN NO EVENT SHALL VMWARE AND/OR ITS SUPPLIERS BE LIABLE FOR21* ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,22* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE23* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.24*25**************************************************************************/262728#include "pipe/p_config.h"29#include "pipe/p_compiler.h"30#include "util/u_cpu_detect.h"31#include "util/u_debug.h"32#include "util/u_memory.h"33#include "util/simple_list.h"34#include "util/os_time.h"35#include "lp_bld.h"36#include "lp_bld_debug.h"37#include "lp_bld_misc.h"38#include "lp_bld_init.h"3940#include <llvm/Config/llvm-config.h>41#include <llvm-c/Analysis.h>42#include <llvm-c/Transforms/Scalar.h>43#if LLVM_VERSION_MAJOR >= 744#include <llvm-c/Transforms/Utils.h>45#endif46#include <llvm-c/BitWriter.h>47#if GALLIVM_HAVE_CORO48#if LLVM_VERSION_MAJOR <= 8 && (defined(PIPE_ARCH_AARCH64) || defined (PIPE_ARCH_ARM) || defined(PIPE_ARCH_S390))49#include <llvm-c/Transforms/IPO.h>50#endif51#include <llvm-c/Transforms/Coroutines.h>52#endif5354unsigned gallivm_perf = 0;5556static const struct debug_named_value lp_bld_perf_flags[] = {57{ "no_brilinear", GALLIVM_PERF_NO_BRILINEAR, "disable brilinear optimization" },58{ "no_rho_approx", GALLIVM_PERF_NO_RHO_APPROX, "disable rho_approx optimization" },59{ "no_quad_lod", GALLIVM_PERF_NO_QUAD_LOD, "disable quad_lod optimization" },60{ "no_aos_sampling", GALLIVM_PERF_NO_AOS_SAMPLING, "disable aos sampling optimization" },61{ "nopt", GALLIVM_PERF_NO_OPT, "disable optimization passes to speed up shader compilation" },62{ "no_filter_hacks", GALLIVM_PERF_NO_BRILINEAR | GALLIVM_PERF_NO_RHO_APPROX |63GALLIVM_PERF_NO_QUAD_LOD, "disable filter optimization hacks" },64DEBUG_NAMED_VALUE_END65};6667#ifdef DEBUG68unsigned gallivm_debug = 0;6970static const struct debug_named_value lp_bld_debug_flags[] = {71{ "tgsi", GALLIVM_DEBUG_TGSI, NULL },72{ "ir", GALLIVM_DEBUG_IR, NULL },73{ "asm", GALLIVM_DEBUG_ASM, NULL },74{ "perf", GALLIVM_DEBUG_PERF, NULL },75{ "gc", GALLIVM_DEBUG_GC, NULL },76{ "dumpbc", GALLIVM_DEBUG_DUMP_BC, NULL },77DEBUG_NAMED_VALUE_END78};7980DEBUG_GET_ONCE_FLAGS_OPTION(gallivm_debug, "GALLIVM_DEBUG", lp_bld_debug_flags, 0)81#endif828384static boolean gallivm_initialized = FALSE;8586unsigned lp_native_vector_width;878889/*90* Optimization values are:91* - 0: None (-O0)92* - 1: Less (-O1)93* - 2: Default (-O2, -Os)94* - 3: Aggressive (-O3)95*96* See also CodeGenOpt::Level in llvm/Target/TargetMachine.h97*/98enum LLVM_CodeGenOpt_Level {99None, // -O0100Less, // -O1101Default, // -O2, -Os102Aggressive // -O3103};104105106/**107* Create the LLVM (optimization) pass manager and install108* relevant optimization passes.109* \return TRUE for success, FALSE for failure110*/111static boolean112create_pass_manager(struct gallivm_state *gallivm)113{114assert(!gallivm->passmgr);115assert(gallivm->target);116117gallivm->passmgr = LLVMCreateFunctionPassManagerForModule(gallivm->module);118if (!gallivm->passmgr)119return FALSE;120121#if GALLIVM_HAVE_CORO122gallivm->cgpassmgr = LLVMCreatePassManager();123#endif124/*125* TODO: some per module pass manager with IPO passes might be helpful -126* the generated texture functions may benefit from inlining if they are127* simple, or constant propagation into them, etc.128*/129130{131char *td_str;132// New ones from the Module.133td_str = LLVMCopyStringRepOfTargetData(gallivm->target);134LLVMSetDataLayout(gallivm->module, td_str);135free(td_str);136}137138#if GALLIVM_HAVE_CORO139#if LLVM_VERSION_MAJOR <= 8 && (defined(PIPE_ARCH_AARCH64) || defined (PIPE_ARCH_ARM) || defined(PIPE_ARCH_S390))140LLVMAddArgumentPromotionPass(gallivm->cgpassmgr);141LLVMAddFunctionAttrsPass(gallivm->cgpassmgr);142#endif143LLVMAddCoroEarlyPass(gallivm->cgpassmgr);144LLVMAddCoroSplitPass(gallivm->cgpassmgr);145LLVMAddCoroElidePass(gallivm->cgpassmgr);146#endif147148if ((gallivm_perf & GALLIVM_PERF_NO_OPT) == 0) {149/*150* TODO: Evaluate passes some more - keeping in mind151* both quality of generated code and compile times.152*/153/*154* NOTE: if you change this, don't forget to change the output155* with GALLIVM_DEBUG_DUMP_BC in gallivm_compile_module.156*/157LLVMAddScalarReplAggregatesPass(gallivm->passmgr);158LLVMAddEarlyCSEPass(gallivm->passmgr);159LLVMAddCFGSimplificationPass(gallivm->passmgr);160/*161* FIXME: LICM is potentially quite useful. However, for some162* rather crazy shaders the compile time can reach _hours_ per shader,163* due to licm implying lcssa (since llvm 3.5), which can take forever.164* Even for sane shaders, the cost of licm is rather high (and not just165* due to lcssa, licm itself too), though mostly only in cases when it166* can actually move things, so having to disable it is a pity.167* LLVMAddLICMPass(gallivm->passmgr);168*/169LLVMAddReassociatePass(gallivm->passmgr);170LLVMAddPromoteMemoryToRegisterPass(gallivm->passmgr);171#if LLVM_VERSION_MAJOR <= 11172LLVMAddConstantPropagationPass(gallivm->passmgr);173#else174LLVMAddInstructionSimplifyPass(gallivm->passmgr);175#endif176LLVMAddInstructionCombiningPass(gallivm->passmgr);177LLVMAddGVNPass(gallivm->passmgr);178}179else {180/* We need at least this pass to prevent the backends to fail in181* unexpected ways.182*/183LLVMAddPromoteMemoryToRegisterPass(gallivm->passmgr);184}185#if GALLIVM_HAVE_CORO186LLVMAddCoroCleanupPass(gallivm->passmgr);187#endif188189return TRUE;190}191192193/**194* Free gallivm object's LLVM allocations, but not any generated code195* nor the gallivm object itself.196*/197void198gallivm_free_ir(struct gallivm_state *gallivm)199{200if (gallivm->passmgr) {201LLVMDisposePassManager(gallivm->passmgr);202}203204#if GALLIVM_HAVE_CORO205if (gallivm->cgpassmgr) {206LLVMDisposePassManager(gallivm->cgpassmgr);207}208#endif209210if (gallivm->engine) {211/* This will already destroy any associated module */212LLVMDisposeExecutionEngine(gallivm->engine);213} else if (gallivm->module) {214LLVMDisposeModule(gallivm->module);215}216217if (gallivm->cache) {218lp_free_objcache(gallivm->cache->jit_obj_cache);219free(gallivm->cache->data);220}221FREE(gallivm->module_name);222223if (gallivm->target) {224LLVMDisposeTargetData(gallivm->target);225}226227if (gallivm->builder)228LLVMDisposeBuilder(gallivm->builder);229230/* The LLVMContext should be owned by the parent of gallivm. */231232gallivm->engine = NULL;233gallivm->target = NULL;234gallivm->module = NULL;235gallivm->module_name = NULL;236gallivm->cgpassmgr = NULL;237gallivm->passmgr = NULL;238gallivm->context = NULL;239gallivm->builder = NULL;240gallivm->cache = NULL;241}242243244/**245* Free LLVM-generated code. Should be done AFTER gallivm_free_ir().246*/247static void248gallivm_free_code(struct gallivm_state *gallivm)249{250assert(!gallivm->module);251assert(!gallivm->engine);252lp_free_generated_code(gallivm->code);253gallivm->code = NULL;254lp_free_memory_manager(gallivm->memorymgr);255gallivm->memorymgr = NULL;256}257258259static boolean260init_gallivm_engine(struct gallivm_state *gallivm)261{262if (1) {263enum LLVM_CodeGenOpt_Level optlevel;264char *error = NULL;265int ret;266267if (gallivm_perf & GALLIVM_PERF_NO_OPT) {268optlevel = None;269}270else {271optlevel = Default;272}273274ret = lp_build_create_jit_compiler_for_module(&gallivm->engine,275&gallivm->code,276gallivm->cache,277gallivm->module,278gallivm->memorymgr,279(unsigned) optlevel,280&error);281if (ret) {282_debug_printf("%s\n", error);283LLVMDisposeMessage(error);284goto fail;285}286}287288if (0) {289/*290* Dump the data layout strings.291*/292293LLVMTargetDataRef target = LLVMGetExecutionEngineTargetData(gallivm->engine);294char *data_layout;295char *engine_data_layout;296297data_layout = LLVMCopyStringRepOfTargetData(gallivm->target);298engine_data_layout = LLVMCopyStringRepOfTargetData(target);299300if (1) {301debug_printf("module target data = %s\n", data_layout);302debug_printf("engine target data = %s\n", engine_data_layout);303}304305free(data_layout);306free(engine_data_layout);307}308309return TRUE;310311fail:312return FALSE;313}314315316/**317* Allocate gallivm LLVM objects.318* \return TRUE for success, FALSE for failure319*/320static boolean321init_gallivm_state(struct gallivm_state *gallivm, const char *name,322LLVMContextRef context, struct lp_cached_code *cache)323{324assert(!gallivm->context);325assert(!gallivm->module);326327if (!lp_build_init())328return FALSE;329330gallivm->context = context;331gallivm->cache = cache;332if (!gallivm->context)333goto fail;334335gallivm->module_name = NULL;336if (name) {337size_t size = strlen(name) + 1;338gallivm->module_name = MALLOC(size);339if (gallivm->module_name) {340memcpy(gallivm->module_name, name, size);341}342}343344gallivm->module = LLVMModuleCreateWithNameInContext(name,345gallivm->context);346if (!gallivm->module)347goto fail;348349gallivm->builder = LLVMCreateBuilderInContext(gallivm->context);350if (!gallivm->builder)351goto fail;352353gallivm->memorymgr = lp_get_default_memory_manager();354if (!gallivm->memorymgr)355goto fail;356357/* FIXME: MC-JIT only allows compiling one module at a time, and it must be358* complete when MC-JIT is created. So defer the MC-JIT engine creation for359* now.360*/361362/*363* MC-JIT engine compiles the module immediately on creation, so we can't364* obtain the target data from it. Instead we create a target data layout365* from a string.366*367* The produced layout strings are not precisely the same, but should make368* no difference for the kind of optimization passes we run.369*370* For reference this is the layout string on x64:371*372* e-p:64:64:64-S128-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f16:16:16-f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-s0:64:64-f80:128:128-f128:128:128-n8:16:32:64373*374* See also:375* - http://llvm.org/docs/LangRef.html#datalayout376*/377378{379const unsigned pointer_size = 8 * sizeof(void *);380char layout[512];381snprintf(layout, sizeof layout, "%c-p:%u:%u:%u-i64:64:64-a0:0:%u-s0:%u:%u",382#if UTIL_ARCH_LITTLE_ENDIAN383'e', // little endian384#else385'E', // big endian386#endif387pointer_size, pointer_size, pointer_size, // pointer size, abi alignment, preferred alignment388pointer_size, // aggregate preferred alignment389pointer_size, pointer_size); // stack objects abi alignment, preferred alignment390391gallivm->target = LLVMCreateTargetData(layout);392if (!gallivm->target) {393return FALSE;394}395}396397if (!create_pass_manager(gallivm))398goto fail;399400return TRUE;401402fail:403gallivm_free_ir(gallivm);404gallivm_free_code(gallivm);405return FALSE;406}407408409boolean410lp_build_init(void)411{412if (gallivm_initialized)413return TRUE;414415416/* LLVMLinkIn* are no-ops at runtime. They just ensure the respective417* component is linked at buildtime, which is sufficient for its static418* constructors to be called at load time.419*/420LLVMLinkInMCJIT();421422#ifdef DEBUG423gallivm_debug = debug_get_option_gallivm_debug();424#endif425426gallivm_perf = debug_get_flags_option("GALLIVM_PERF", lp_bld_perf_flags, 0 );427428lp_set_target_options();429430util_cpu_detect();431432/* For simulating less capable machines */433#ifdef DEBUG434if (debug_get_bool_option("LP_FORCE_SSE2", FALSE)) {435extern struct util_cpu_caps_t util_cpu_caps;436assert(util_cpu_caps.has_sse2);437util_cpu_caps.has_sse3 = 0;438util_cpu_caps.has_ssse3 = 0;439util_cpu_caps.has_sse4_1 = 0;440util_cpu_caps.has_sse4_2 = 0;441util_cpu_caps.has_avx = 0;442util_cpu_caps.has_avx2 = 0;443util_cpu_caps.has_f16c = 0;444util_cpu_caps.has_fma = 0;445}446#endif447448if (util_get_cpu_caps()->has_avx2 || util_get_cpu_caps()->has_avx) {449lp_native_vector_width = 256;450} else {451/* Leave it at 128, even when no SIMD extensions are available.452* Really needs to be a multiple of 128 so can fit 4 floats.453*/454lp_native_vector_width = 128;455}456457lp_native_vector_width = debug_get_num_option("LP_NATIVE_VECTOR_WIDTH",458lp_native_vector_width);459460#if LLVM_VERSION_MAJOR < 4461if (lp_native_vector_width <= 128) {462/* Hide AVX support, as often LLVM AVX intrinsics are only guarded by463* "util_get_cpu_caps()->has_avx" predicate, and lack the464* "lp_native_vector_width > 128" predicate. And also to ensure a more465* consistent behavior, allowing one to test SSE2 on AVX machines.466* XXX: should not play games with util_cpu_caps directly as it might467* get used for other things outside llvm too.468*/469util_get_cpu_caps()->has_avx = 0;470util_get_cpu_caps()->has_avx2 = 0;471util_get_cpu_caps()->has_f16c = 0;472util_get_cpu_caps()->has_fma = 0;473}474#endif475476#ifdef PIPE_ARCH_PPC_64477/* Set the NJ bit in VSCR to 0 so denormalized values are handled as478* specified by IEEE standard (PowerISA 2.06 - Section 6.3). This guarantees479* that some rounding and half-float to float handling does not round480* incorrectly to 0.481* XXX: should eventually follow same logic on all platforms.482* Right now denorms get explicitly disabled (but elsewhere) for x86,483* whereas ppc64 explicitly enables them...484*/485if (util_get_cpu_caps()->has_altivec) {486unsigned short mask[] = { 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF,4870xFFFF, 0xFFFF, 0xFFFE, 0xFFFF };488__asm (489"mfvscr %%v1\n"490"vand %0,%%v1,%0\n"491"mtvscr %0"492:493: "r" (*mask)494);495}496#endif497498gallivm_initialized = TRUE;499500return TRUE;501}502503504505/**506* Create a new gallivm_state object.507*/508struct gallivm_state *509gallivm_create(const char *name, LLVMContextRef context,510struct lp_cached_code *cache)511{512struct gallivm_state *gallivm;513514gallivm = CALLOC_STRUCT(gallivm_state);515if (gallivm) {516if (!init_gallivm_state(gallivm, name, context, cache)) {517FREE(gallivm);518gallivm = NULL;519}520}521522assert(gallivm != NULL);523return gallivm;524}525526527/**528* Destroy a gallivm_state object.529*/530void531gallivm_destroy(struct gallivm_state *gallivm)532{533gallivm_free_ir(gallivm);534gallivm_free_code(gallivm);535FREE(gallivm);536}537538539/**540* Validate a function.541* Verification is only done with debug builds.542*/543void544gallivm_verify_function(struct gallivm_state *gallivm,545LLVMValueRef func)546{547/* Verify the LLVM IR. If invalid, dump and abort */548#ifdef DEBUG549if (LLVMVerifyFunction(func, LLVMPrintMessageAction)) {550lp_debug_dump_value(func);551assert(0);552return;553}554#endif555556if (gallivm_debug & GALLIVM_DEBUG_IR) {557/* Print the LLVM IR to stderr */558lp_debug_dump_value(func);559debug_printf("\n");560}561}562563564/**565* Compile a module.566* This does IR optimization on all functions in the module.567*/568void569gallivm_compile_module(struct gallivm_state *gallivm)570{571LLVMValueRef func;572int64_t time_begin = 0;573574assert(!gallivm->compiled);575576if (gallivm->builder) {577LLVMDisposeBuilder(gallivm->builder);578gallivm->builder = NULL;579}580581if (gallivm->cache && gallivm->cache->data_size) {582goto skip_cached;583}584585/* Dump bitcode to a file */586if (gallivm_debug & GALLIVM_DEBUG_DUMP_BC) {587char filename[256];588assert(gallivm->module_name);589snprintf(filename, sizeof(filename), "ir_%s.bc", gallivm->module_name);590LLVMWriteBitcodeToFile(gallivm->module, filename);591debug_printf("%s written\n", filename);592debug_printf("Invoke as \"opt %s %s | llc -O%d %s%s\"\n",593gallivm_debug & GALLIVM_PERF_NO_OPT ? "-mem2reg" :594"-sroa -early-cse -simplifycfg -reassociate "595"-mem2reg -constprop -instcombine -gvn",596filename, gallivm_debug & GALLIVM_PERF_NO_OPT ? 0 : 2,597"[-mcpu=<-mcpu option>] ",598"[-mattr=<-mattr option(s)>]");599}600601if (gallivm_debug & GALLIVM_DEBUG_PERF)602time_begin = os_time_get();603604#if GALLIVM_HAVE_CORO605LLVMRunPassManager(gallivm->cgpassmgr, gallivm->module);606#endif607/* Run optimization passes */608LLVMInitializeFunctionPassManager(gallivm->passmgr);609func = LLVMGetFirstFunction(gallivm->module);610while (func) {611if (0) {612debug_printf("optimizing func %s...\n", LLVMGetValueName(func));613}614615/* Disable frame pointer omission on debug/profile builds */616/* XXX: And workaround http://llvm.org/PR21435 */617#if defined(DEBUG) || defined(PROFILE) || defined(PIPE_ARCH_X86) || defined(PIPE_ARCH_X86_64)618LLVMAddTargetDependentFunctionAttr(func, "no-frame-pointer-elim", "true");619LLVMAddTargetDependentFunctionAttr(func, "no-frame-pointer-elim-non-leaf", "true");620#endif621622LLVMRunFunctionPassManager(gallivm->passmgr, func);623func = LLVMGetNextFunction(func);624}625LLVMFinalizeFunctionPassManager(gallivm->passmgr);626627if (gallivm_debug & GALLIVM_DEBUG_PERF) {628int64_t time_end = os_time_get();629int time_msec = (int)((time_end - time_begin) / 1000);630assert(gallivm->module_name);631debug_printf("optimizing module %s took %d msec\n",632gallivm->module_name, time_msec);633}634635/* Setting the module's DataLayout to an empty string will cause the636* ExecutionEngine to copy to the DataLayout string from its target machine637* to the module. As of LLVM 3.8 the module and the execution engine are638* required to have the same DataLayout.639*640* We must make sure we do this after running the optimization passes,641* because those passes need a correct datalayout string. For example, if642* those optimization passes see an empty datalayout, they will assume this643* is a little endian target and will do optimizations that break big endian644* machines.645*646* TODO: This is just a temporary work-around. The correct solution is for647* gallivm_init_state() to create a TargetMachine and pull the DataLayout648* from there. Currently, the TargetMachine used by llvmpipe is being649* implicitly created by the EngineBuilder in650* lp_build_create_jit_compiler_for_module()651*/652skip_cached:653LLVMSetDataLayout(gallivm->module, "");654assert(!gallivm->engine);655if (!init_gallivm_engine(gallivm)) {656assert(0);657}658assert(gallivm->engine);659660++gallivm->compiled;661662if (gallivm->debug_printf_hook)663LLVMAddGlobalMapping(gallivm->engine, gallivm->debug_printf_hook, debug_printf);664665if (gallivm_debug & GALLIVM_DEBUG_ASM) {666LLVMValueRef llvm_func = LLVMGetFirstFunction(gallivm->module);667668while (llvm_func) {669/*670* Need to filter out functions which don't have an implementation,671* such as the intrinsics. May not be sufficient in case of IPO?672* LLVMGetPointerToGlobal() will abort otherwise.673*/674if (!LLVMIsDeclaration(llvm_func)) {675void *func_code = LLVMGetPointerToGlobal(gallivm->engine, llvm_func);676lp_disassemble(llvm_func, func_code);677}678llvm_func = LLVMGetNextFunction(llvm_func);679}680}681682#if defined(PROFILE)683{684LLVMValueRef llvm_func = LLVMGetFirstFunction(gallivm->module);685686while (llvm_func) {687if (!LLVMIsDeclaration(llvm_func)) {688void *func_code = LLVMGetPointerToGlobal(gallivm->engine, llvm_func);689lp_profile(llvm_func, func_code);690}691llvm_func = LLVMGetNextFunction(llvm_func);692}693}694#endif695}696697698699func_pointer700gallivm_jit_function(struct gallivm_state *gallivm,701LLVMValueRef func)702{703void *code;704func_pointer jit_func;705int64_t time_begin = 0;706707assert(gallivm->compiled);708assert(gallivm->engine);709710if (gallivm_debug & GALLIVM_DEBUG_PERF)711time_begin = os_time_get();712713code = LLVMGetPointerToGlobal(gallivm->engine, func);714assert(code);715jit_func = pointer_to_func(code);716717if (gallivm_debug & GALLIVM_DEBUG_PERF) {718int64_t time_end = os_time_get();719int time_msec = (int)(time_end - time_begin) / 1000;720debug_printf(" jitting func %s took %d msec\n",721LLVMGetValueName(func), time_msec);722}723724return jit_func;725}726727unsigned gallivm_get_perf_flags(void)728{729return gallivm_perf;730}731732733