1 /**************************************************************************
3 * Copyright 2009 VMware, Inc.
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the
8 * "Software"), to deal in the Software without restriction, including
9 * without limitation the rights to use, copy, modify, merge, publish,
10 * distribute, sub license, and/or sell copies of the Software, and to
11 * permit persons to whom the Software is furnished to do so, subject to
12 * the following conditions:
14 * The above copyright notice and this permission notice (including the
15 * next paragraph) shall be included in all copies or substantial portions
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
19 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
21 * IN NO EVENT SHALL VMWARE AND/OR ITS SUPPLIERS BE LIABLE FOR
22 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
23 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
24 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
26 **************************************************************************/
29 #include "pipe/p_config.h"
30 #include "pipe/p_compiler.h"
31 #include "util/u_cpu_detect.h"
32 #include "util/u_debug.h"
33 #include "util/u_memory.h"
34 #include "util/simple_list.h"
35 #include "util/os_time.h"
37 #include "lp_bld_debug.h"
38 #include "lp_bld_misc.h"
39 #include "lp_bld_init.h"
41 #include <llvm-c/Analysis.h>
42 #include <llvm-c/Transforms/Scalar.h>
43 #if HAVE_LLVM >= 0x0700
44 #include <llvm-c/Transforms/Utils.h>
46 #include <llvm-c/BitWriter.h>
49 /* Only MCJIT is available as of LLVM SVN r216982 */
50 #if HAVE_LLVM >= 0x0306
52 #elif defined(PIPE_ARCH_PPC_64) || defined(PIPE_ARCH_S390) || defined(PIPE_ARCH_ARM) || defined(PIPE_ARCH_AARCH64)
56 #if defined(USE_MCJIT)
57 static const bool use_mcjit
= USE_MCJIT
;
59 static bool use_mcjit
= FALSE
;
62 unsigned gallivm_perf
= 0;
64 static const struct debug_named_value lp_bld_perf_flags
[] = {
65 { "no_brilinear", GALLIVM_PERF_NO_BRILINEAR
, "disable brilinear optimization" },
66 { "no_rho_approx", GALLIVM_PERF_NO_RHO_APPROX
, "disable rho_approx optimization" },
67 { "no_quad_lod", GALLIVM_PERF_NO_QUAD_LOD
, "disable quad_lod optimization" },
68 { "no_aos_sampling", GALLIVM_PERF_NO_AOS_SAMPLING
, "disable aos sampling optimization" },
69 { "nopt", GALLIVM_PERF_NO_OPT
, "disable optimization passes to speed up shader compilation" },
70 { "no_filter_hacks", GALLIVM_PERF_NO_BRILINEAR
| GALLIVM_PERF_NO_RHO_APPROX
|
71 GALLIVM_PERF_NO_QUAD_LOD
, "disable filter optimization hacks" },
76 unsigned gallivm_debug
= 0;
78 static const struct debug_named_value lp_bld_debug_flags
[] = {
79 { "tgsi", GALLIVM_DEBUG_TGSI
, NULL
},
80 { "ir", GALLIVM_DEBUG_IR
, NULL
},
81 { "asm", GALLIVM_DEBUG_ASM
, NULL
},
82 { "perf", GALLIVM_DEBUG_PERF
, NULL
},
83 { "gc", GALLIVM_DEBUG_GC
, NULL
},
84 { "dumpbc", GALLIVM_DEBUG_DUMP_BC
, NULL
},
88 DEBUG_GET_ONCE_FLAGS_OPTION(gallivm_debug
, "GALLIVM_DEBUG", lp_bld_debug_flags
, 0)
92 static boolean gallivm_initialized
= FALSE
;
94 unsigned lp_native_vector_width
;
98 * Optimization values are:
101 * - 2: Default (-O2, -Os)
102 * - 3: Aggressive (-O3)
104 * See also CodeGenOpt::Level in llvm/Target/TargetMachine.h
106 enum LLVM_CodeGenOpt_Level
{
115 * Create the LLVM (optimization) pass manager and install
116 * relevant optimization passes.
117 * \return TRUE for success, FALSE for failure
120 create_pass_manager(struct gallivm_state
*gallivm
)
122 assert(!gallivm
->passmgr
);
123 assert(gallivm
->target
);
125 gallivm
->passmgr
= LLVMCreateFunctionPassManagerForModule(gallivm
->module
);
126 if (!gallivm
->passmgr
)
129 * TODO: some per module pass manager with IPO passes might be helpful -
130 * the generated texture functions may benefit from inlining if they are
131 * simple, or constant propagation into them, etc.
134 #if HAVE_LLVM < 0x0309
135 // Old versions of LLVM get the DataLayout from the pass manager.
136 LLVMAddTargetData(gallivm
->target
, gallivm
->passmgr
);
141 // New ones from the Module.
142 td_str
= LLVMCopyStringRepOfTargetData(gallivm
->target
);
143 LLVMSetDataLayout(gallivm
->module
, td_str
);
147 if ((gallivm_perf
& GALLIVM_PERF_NO_OPT
) == 0) {
149 * TODO: Evaluate passes some more - keeping in mind
150 * both quality of generated code and compile times.
153 * NOTE: if you change this, don't forget to change the output
154 * with GALLIVM_DEBUG_DUMP_BC in gallivm_compile_module.
156 LLVMAddScalarReplAggregatesPass(gallivm
->passmgr
);
157 LLVMAddEarlyCSEPass(gallivm
->passmgr
);
158 LLVMAddCFGSimplificationPass(gallivm
->passmgr
);
160 * FIXME: LICM is potentially quite useful. However, for some
161 * rather crazy shaders the compile time can reach _hours_ per shader,
162 * due to licm implying lcssa (since llvm 3.5), which can take forever.
163 * Even for sane shaders, the cost of licm is rather high (and not just
164 * due to lcssa, licm itself too), though mostly only in cases when it
165 * can actually move things, so having to disable it is a pity.
166 * LLVMAddLICMPass(gallivm->passmgr);
168 LLVMAddReassociatePass(gallivm
->passmgr
);
169 LLVMAddPromoteMemoryToRegisterPass(gallivm
->passmgr
);
170 LLVMAddConstantPropagationPass(gallivm
->passmgr
);
171 LLVMAddInstructionCombiningPass(gallivm
->passmgr
);
172 LLVMAddGVNPass(gallivm
->passmgr
);
175 /* We need at least this pass to prevent the backends to fail in
178 LLVMAddPromoteMemoryToRegisterPass(gallivm
->passmgr
);
186 * Free gallivm object's LLVM allocations, but not any generated code
187 * nor the gallivm object itself.
190 gallivm_free_ir(struct gallivm_state
*gallivm
)
192 if (gallivm
->passmgr
) {
193 LLVMDisposePassManager(gallivm
->passmgr
);
196 if (gallivm
->engine
) {
197 /* This will already destroy any associated module */
198 LLVMDisposeExecutionEngine(gallivm
->engine
);
199 } else if (gallivm
->module
) {
200 LLVMDisposeModule(gallivm
->module
);
203 FREE(gallivm
->module_name
);
206 /* Don't free the TargetData, it's owned by the exec engine */
208 if (gallivm
->target
) {
209 LLVMDisposeTargetData(gallivm
->target
);
213 if (gallivm
->builder
)
214 LLVMDisposeBuilder(gallivm
->builder
);
216 /* The LLVMContext should be owned by the parent of gallivm. */
218 gallivm
->engine
= NULL
;
219 gallivm
->target
= NULL
;
220 gallivm
->module
= NULL
;
221 gallivm
->module_name
= NULL
;
222 gallivm
->passmgr
= NULL
;
223 gallivm
->context
= NULL
;
224 gallivm
->builder
= NULL
;
229 * Free LLVM-generated code. Should be done AFTER gallivm_free_ir().
232 gallivm_free_code(struct gallivm_state
*gallivm
)
234 assert(!gallivm
->module
);
235 assert(!gallivm
->engine
);
236 lp_free_generated_code(gallivm
->code
);
237 gallivm
->code
= NULL
;
238 lp_free_memory_manager(gallivm
->memorymgr
);
239 gallivm
->memorymgr
= NULL
;
244 init_gallivm_engine(struct gallivm_state
*gallivm
)
247 enum LLVM_CodeGenOpt_Level optlevel
;
251 if (gallivm_perf
& GALLIVM_PERF_NO_OPT
) {
258 ret
= lp_build_create_jit_compiler_for_module(&gallivm
->engine
,
266 _debug_printf("%s\n", error
);
267 LLVMDisposeMessage(error
);
273 gallivm
->target
= LLVMGetExecutionEngineTargetData(gallivm
->engine
);
274 if (!gallivm
->target
)
279 * Dump the data layout strings.
282 LLVMTargetDataRef target
= LLVMGetExecutionEngineTargetData(gallivm
->engine
);
284 char *engine_data_layout
;
286 data_layout
= LLVMCopyStringRepOfTargetData(gallivm
->target
);
287 engine_data_layout
= LLVMCopyStringRepOfTargetData(target
);
290 debug_printf("module target data = %s\n", data_layout
);
291 debug_printf("engine target data = %s\n", engine_data_layout
);
295 free(engine_data_layout
);
307 * Allocate gallivm LLVM objects.
308 * \return TRUE for success, FALSE for failure
311 init_gallivm_state(struct gallivm_state
*gallivm
, const char *name
,
312 LLVMContextRef context
)
314 assert(!gallivm
->context
);
315 assert(!gallivm
->module
);
317 if (!lp_build_init())
320 gallivm
->context
= context
;
322 if (!gallivm
->context
)
325 gallivm
->module_name
= NULL
;
327 size_t size
= strlen(name
) + 1;
328 gallivm
->module_name
= MALLOC(size
);
329 if (gallivm
->module_name
) {
330 memcpy(gallivm
->module_name
, name
, size
);
334 gallivm
->module
= LLVMModuleCreateWithNameInContext(name
,
336 if (!gallivm
->module
)
339 gallivm
->builder
= LLVMCreateBuilderInContext(gallivm
->context
);
340 if (!gallivm
->builder
)
343 gallivm
->memorymgr
= lp_get_default_memory_manager();
344 if (!gallivm
->memorymgr
)
347 /* FIXME: MC-JIT only allows compiling one module at a time, and it must be
348 * complete when MC-JIT is created. So defer the MC-JIT engine creation for
352 if (!init_gallivm_engine(gallivm
)) {
357 * MC-JIT engine compiles the module immediately on creation, so we can't
358 * obtain the target data from it. Instead we create a target data layout
361 * The produced layout strings are not precisely the same, but should make
362 * no difference for the kind of optimization passes we run.
364 * For reference this is the layout string on x64:
366 * 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:64
369 * - http://llvm.org/docs/LangRef.html#datalayout
373 const unsigned pointer_size
= 8 * sizeof(void *);
375 snprintf(layout
, sizeof layout
, "%c-p:%u:%u:%u-i64:64:64-a0:0:%u-s0:%u:%u",
376 #ifdef PIPE_ARCH_LITTLE_ENDIAN
377 'e', // little endian
381 pointer_size
, pointer_size
, pointer_size
, // pointer size, abi alignment, preferred alignment
382 pointer_size
, // aggregate preferred alignment
383 pointer_size
, pointer_size
); // stack objects abi alignment, preferred alignment
385 gallivm
->target
= LLVMCreateTargetData(layout
);
386 if (!gallivm
->target
) {
392 if (!create_pass_manager(gallivm
))
398 gallivm_free_ir(gallivm
);
399 gallivm_free_code(gallivm
);
407 if (gallivm_initialized
)
411 /* LLVMLinkIn* are no-ops at runtime. They just ensure the respective
412 * component is linked at buildtime, which is sufficient for its static
413 * constructors to be called at load time.
415 #if defined(USE_MCJIT)
422 use_mcjit
= debug_get_bool_option("GALLIVM_MCJIT", FALSE
);
428 gallivm_debug
= debug_get_option_gallivm_debug();
431 gallivm_perf
= debug_get_flags_option("GALLIVM_PERF", lp_bld_perf_flags
, 0 );
433 lp_set_target_options();
437 /* For simulating less capable machines */
439 if (debug_get_bool_option("LP_FORCE_SSE2", FALSE
)) {
440 assert(util_cpu_caps
.has_sse2
);
441 util_cpu_caps
.has_sse3
= 0;
442 util_cpu_caps
.has_ssse3
= 0;
443 util_cpu_caps
.has_sse4_1
= 0;
444 util_cpu_caps
.has_sse4_2
= 0;
445 util_cpu_caps
.has_avx
= 0;
446 util_cpu_caps
.has_avx2
= 0;
447 util_cpu_caps
.has_f16c
= 0;
448 util_cpu_caps
.has_fma
= 0;
452 /* AMD Bulldozer AVX's throughput is the same as SSE2; and because using
453 * 8-wide vector needs more floating ops than 4-wide (due to padding), it is
454 * actually more efficient to use 4-wide vectors on this processor.
457 * - http://www.anandtech.com/show/4955/the-bulldozer-review-amd-fx8150-tested/2
459 if (util_cpu_caps
.has_avx
&&
460 util_cpu_caps
.has_intel
) {
461 lp_native_vector_width
= 256;
463 /* Leave it at 128, even when no SIMD extensions are available.
464 * Really needs to be a multiple of 128 so can fit 4 floats.
466 lp_native_vector_width
= 128;
469 lp_native_vector_width
= debug_get_num_option("LP_NATIVE_VECTOR_WIDTH",
470 lp_native_vector_width
);
472 if (lp_native_vector_width
<= 128) {
473 /* Hide AVX support, as often LLVM AVX intrinsics are only guarded by
474 * "util_cpu_caps.has_avx" predicate, and lack the
475 * "lp_native_vector_width > 128" predicate. And also to ensure a more
476 * consistent behavior, allowing one to test SSE2 on AVX machines.
477 * XXX: should not play games with util_cpu_caps directly as it might
478 * get used for other things outside llvm too.
480 util_cpu_caps
.has_avx
= 0;
481 util_cpu_caps
.has_avx2
= 0;
482 util_cpu_caps
.has_f16c
= 0;
483 util_cpu_caps
.has_fma
= 0;
485 if (HAVE_LLVM
< 0x0304 || !use_mcjit
) {
486 /* AVX2 support has only been tested with LLVM 3.4, and it requires
488 util_cpu_caps
.has_avx2
= 0;
491 #ifdef PIPE_ARCH_PPC_64
492 /* Set the NJ bit in VSCR to 0 so denormalized values are handled as
493 * specified by IEEE standard (PowerISA 2.06 - Section 6.3). This guarantees
494 * that some rounding and half-float to float handling does not round
496 * XXX: should eventually follow same logic on all platforms.
497 * Right now denorms get explicitly disabled (but elsewhere) for x86,
498 * whereas ppc64 explicitly enables them...
500 if (util_cpu_caps
.has_altivec
) {
501 unsigned short mask
[] = { 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF,
502 0xFFFF, 0xFFFF, 0xFFFE, 0xFFFF };
513 gallivm_initialized
= TRUE
;
521 * Create a new gallivm_state object.
523 struct gallivm_state
*
524 gallivm_create(const char *name
, LLVMContextRef context
)
526 struct gallivm_state
*gallivm
;
528 gallivm
= CALLOC_STRUCT(gallivm_state
);
530 if (!init_gallivm_state(gallivm
, name
, context
)) {
541 * Destroy a gallivm_state object.
544 gallivm_destroy(struct gallivm_state
*gallivm
)
546 gallivm_free_ir(gallivm
);
547 gallivm_free_code(gallivm
);
553 * Validate a function.
554 * Verification is only done with debug builds.
557 gallivm_verify_function(struct gallivm_state
*gallivm
,
560 /* Verify the LLVM IR. If invalid, dump and abort */
562 if (LLVMVerifyFunction(func
, LLVMPrintMessageAction
)) {
563 lp_debug_dump_value(func
);
569 if (gallivm_debug
& GALLIVM_DEBUG_IR
) {
570 /* Print the LLVM IR to stderr */
571 lp_debug_dump_value(func
);
579 * This does IR optimization on all functions in the module.
582 gallivm_compile_module(struct gallivm_state
*gallivm
)
585 int64_t time_begin
= 0;
587 assert(!gallivm
->compiled
);
589 if (gallivm
->builder
) {
590 LLVMDisposeBuilder(gallivm
->builder
);
591 gallivm
->builder
= NULL
;
594 /* Dump bitcode to a file */
595 if (gallivm_debug
& GALLIVM_DEBUG_DUMP_BC
) {
597 assert(gallivm
->module_name
);
598 snprintf(filename
, sizeof(filename
), "ir_%s.bc", gallivm
->module_name
);
599 LLVMWriteBitcodeToFile(gallivm
->module
, filename
);
600 debug_printf("%s written\n", filename
);
601 debug_printf("Invoke as \"opt %s %s | llc -O%d %s%s\"\n",
602 gallivm_debug
& GALLIVM_PERF_NO_OPT
? "-mem2reg" :
603 "-sroa -early-cse -simplifycfg -reassociate "
604 "-mem2reg -constprop -instcombine -gvn",
605 filename
, gallivm_debug
& GALLIVM_PERF_NO_OPT
? 0 : 2,
606 (HAVE_LLVM
>= 0x0305) ? "[-mcpu=<-mcpu option>] " : "",
607 "[-mattr=<-mattr option(s)>]");
610 if (gallivm_debug
& GALLIVM_DEBUG_PERF
)
611 time_begin
= os_time_get();
613 /* Run optimization passes */
614 LLVMInitializeFunctionPassManager(gallivm
->passmgr
);
615 func
= LLVMGetFirstFunction(gallivm
->module
);
618 debug_printf("optimizing func %s...\n", LLVMGetValueName(func
));
621 /* Disable frame pointer omission on debug/profile builds */
622 /* XXX: And workaround http://llvm.org/PR21435 */
623 #if HAVE_LLVM >= 0x0307 && \
624 (defined(DEBUG) || defined(PROFILE) || \
625 defined(PIPE_ARCH_X86) || defined(PIPE_ARCH_X86_64))
626 LLVMAddTargetDependentFunctionAttr(func
, "no-frame-pointer-elim", "true");
627 LLVMAddTargetDependentFunctionAttr(func
, "no-frame-pointer-elim-non-leaf", "true");
630 LLVMRunFunctionPassManager(gallivm
->passmgr
, func
);
631 func
= LLVMGetNextFunction(func
);
633 LLVMFinalizeFunctionPassManager(gallivm
->passmgr
);
635 if (gallivm_debug
& GALLIVM_DEBUG_PERF
) {
636 int64_t time_end
= os_time_get();
637 int time_msec
= (int)((time_end
- time_begin
) / 1000);
638 assert(gallivm
->module_name
);
639 debug_printf("optimizing module %s took %d msec\n",
640 gallivm
->module_name
, time_msec
);
644 /* Setting the module's DataLayout to an empty string will cause the
645 * ExecutionEngine to copy to the DataLayout string from its target
646 * machine to the module. As of LLVM 3.8 the module and the execution
647 * engine are required to have the same DataLayout.
649 * We must make sure we do this after running the optimization passes,
650 * because those passes need a correct datalayout string. For example,
651 * if those optimization passes see an empty datalayout, they will assume
652 * this is a little endian target and will do optimizations that break big
655 * TODO: This is just a temporary work-around. The correct solution is
656 * for gallivm_init_state() to create a TargetMachine and pull the
657 * DataLayout from there. Currently, the TargetMachine used by llvmpipe
658 * is being implicitly created by the EngineBuilder in
659 * lp_build_create_jit_compiler_for_module()
661 LLVMSetDataLayout(gallivm
->module
, "");
662 assert(!gallivm
->engine
);
663 if (!init_gallivm_engine(gallivm
)) {
667 assert(gallivm
->engine
);
671 if (gallivm_debug
& GALLIVM_DEBUG_ASM
) {
672 LLVMValueRef llvm_func
= LLVMGetFirstFunction(gallivm
->module
);
676 * Need to filter out functions which don't have an implementation,
677 * such as the intrinsics. May not be sufficient in case of IPO?
678 * LLVMGetPointerToGlobal() will abort otherwise.
680 if (!LLVMIsDeclaration(llvm_func
)) {
681 void *func_code
= LLVMGetPointerToGlobal(gallivm
->engine
, llvm_func
);
682 lp_disassemble(llvm_func
, func_code
);
684 llvm_func
= LLVMGetNextFunction(llvm_func
);
690 LLVMValueRef llvm_func
= LLVMGetFirstFunction(gallivm
->module
);
693 if (!LLVMIsDeclaration(llvm_func
)) {
694 void *func_code
= LLVMGetPointerToGlobal(gallivm
->engine
, llvm_func
);
695 lp_profile(llvm_func
, func_code
);
697 llvm_func
= LLVMGetNextFunction(llvm_func
);
706 gallivm_jit_function(struct gallivm_state
*gallivm
,
710 func_pointer jit_func
;
711 int64_t time_begin
= 0;
713 assert(gallivm
->compiled
);
714 assert(gallivm
->engine
);
716 if (gallivm_debug
& GALLIVM_DEBUG_PERF
)
717 time_begin
= os_time_get();
719 code
= LLVMGetPointerToGlobal(gallivm
->engine
, func
);
721 jit_func
= pointer_to_func(code
);
723 if (gallivm_debug
& GALLIVM_DEBUG_PERF
) {
724 int64_t time_end
= os_time_get();
725 int time_msec
= (int)(time_end
- time_begin
) / 1000;
726 debug_printf(" jitting func %s took %d msec\n",
727 LLVMGetValueName(func
), time_msec
);