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 "os/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 #include <llvm-c/BitWriter.h>
46 /* Only MCJIT is available as of LLVM SVN r216982 */
47 #if HAVE_LLVM >= 0x0306
49 #elif defined(PIPE_ARCH_PPC_64) || defined(PIPE_ARCH_S390) || defined(PIPE_ARCH_ARM) || defined(PIPE_ARCH_AARCH64)
52 static bool USE_MCJIT
= 0;
57 unsigned gallivm_debug
= 0;
59 static const struct debug_named_value lp_bld_debug_flags
[] = {
60 { "tgsi", GALLIVM_DEBUG_TGSI
, NULL
},
61 { "ir", GALLIVM_DEBUG_IR
, NULL
},
62 { "asm", GALLIVM_DEBUG_ASM
, NULL
},
63 { "nopt", GALLIVM_DEBUG_NO_OPT
, NULL
},
64 { "perf", GALLIVM_DEBUG_PERF
, NULL
},
65 { "no_brilinear", GALLIVM_DEBUG_NO_BRILINEAR
, NULL
},
66 { "no_rho_approx", GALLIVM_DEBUG_NO_RHO_APPROX
, NULL
},
67 { "no_quad_lod", GALLIVM_DEBUG_NO_QUAD_LOD
, NULL
},
68 { "gc", GALLIVM_DEBUG_GC
, NULL
},
69 { "dumpbc", GALLIVM_DEBUG_DUMP_BC
, NULL
},
73 DEBUG_GET_ONCE_FLAGS_OPTION(gallivm_debug
, "GALLIVM_DEBUG", lp_bld_debug_flags
, 0)
77 static boolean gallivm_initialized
= FALSE
;
79 unsigned lp_native_vector_width
;
83 * Optimization values are:
86 * - 2: Default (-O2, -Os)
87 * - 3: Aggressive (-O3)
89 * See also CodeGenOpt::Level in llvm/Target/TargetMachine.h
91 enum LLVM_CodeGenOpt_Level
{
100 * Create the LLVM (optimization) pass manager and install
101 * relevant optimization passes.
102 * \return TRUE for success, FALSE for failure
105 create_pass_manager(struct gallivm_state
*gallivm
)
107 assert(!gallivm
->passmgr
);
108 assert(gallivm
->target
);
110 gallivm
->passmgr
= LLVMCreateFunctionPassManagerForModule(gallivm
->module
);
111 if (!gallivm
->passmgr
)
114 * TODO: some per module pass manager with IPO passes might be helpful -
115 * the generated texture functions may benefit from inlining if they are
116 * simple, or constant propagation into them, etc.
119 #if HAVE_LLVM < 0x0309
120 // Old versions of LLVM get the DataLayout from the pass manager.
121 LLVMAddTargetData(gallivm
->target
, gallivm
->passmgr
);
124 /* Setting the module's DataLayout to an empty string will cause the
125 * ExecutionEngine to copy to the DataLayout string from its target
126 * machine to the module. As of LLVM 3.8 the module and the execution
127 * engine are required to have the same DataLayout.
129 * TODO: This is just a temporary work-around. The correct solution is
130 * for gallivm_init_state() to create a TargetMachine and pull the
131 * DataLayout from there. Currently, the TargetMachine used by llvmpipe
132 * is being implicitly created by the EngineBuilder in
133 * lp_build_create_jit_compiler_for_module()
136 #if HAVE_LLVM < 0x0308
139 // New ones from the Module.
140 td_str
= LLVMCopyStringRepOfTargetData(gallivm
->target
);
141 LLVMSetDataLayout(gallivm
->module
, td_str
);
145 LLVMSetDataLayout(gallivm
->module
, "");
148 if ((gallivm_debug
& GALLIVM_DEBUG_NO_OPT
) == 0) {
149 /* These are the passes currently listed in llvm-c/Transforms/Scalar.h,
150 * but there are more on SVN.
151 * TODO: Add more passes.
153 LLVMAddScalarReplAggregatesPass(gallivm
->passmgr
);
154 LLVMAddLICMPass(gallivm
->passmgr
);
155 LLVMAddCFGSimplificationPass(gallivm
->passmgr
);
156 LLVMAddReassociatePass(gallivm
->passmgr
);
157 LLVMAddPromoteMemoryToRegisterPass(gallivm
->passmgr
);
158 LLVMAddConstantPropagationPass(gallivm
->passmgr
);
159 LLVMAddInstructionCombiningPass(gallivm
->passmgr
);
160 LLVMAddGVNPass(gallivm
->passmgr
);
163 /* We need at least this pass to prevent the backends to fail in
166 LLVMAddPromoteMemoryToRegisterPass(gallivm
->passmgr
);
174 * Free gallivm object's LLVM allocations, but not any generated code
175 * nor the gallivm object itself.
178 gallivm_free_ir(struct gallivm_state
*gallivm
)
180 if (gallivm
->passmgr
) {
181 LLVMDisposePassManager(gallivm
->passmgr
);
184 if (gallivm
->engine
) {
185 /* This will already destroy any associated module */
186 LLVMDisposeExecutionEngine(gallivm
->engine
);
187 } else if (gallivm
->module
) {
188 LLVMDisposeModule(gallivm
->module
);
191 FREE(gallivm
->module_name
);
194 /* Don't free the TargetData, it's owned by the exec engine */
196 if (gallivm
->target
) {
197 LLVMDisposeTargetData(gallivm
->target
);
201 if (gallivm
->builder
)
202 LLVMDisposeBuilder(gallivm
->builder
);
204 /* The LLVMContext should be owned by the parent of gallivm. */
206 gallivm
->engine
= NULL
;
207 gallivm
->target
= NULL
;
208 gallivm
->module
= NULL
;
209 gallivm
->module_name
= NULL
;
210 gallivm
->passmgr
= NULL
;
211 gallivm
->context
= NULL
;
212 gallivm
->builder
= NULL
;
217 * Free LLVM-generated code. Should be done AFTER gallivm_free_ir().
220 gallivm_free_code(struct gallivm_state
*gallivm
)
222 assert(!gallivm
->module
);
223 assert(!gallivm
->engine
);
224 lp_free_generated_code(gallivm
->code
);
225 gallivm
->code
= NULL
;
226 lp_free_memory_manager(gallivm
->memorymgr
);
227 gallivm
->memorymgr
= NULL
;
232 init_gallivm_engine(struct gallivm_state
*gallivm
)
235 enum LLVM_CodeGenOpt_Level optlevel
;
239 if (gallivm_debug
& GALLIVM_DEBUG_NO_OPT
) {
246 ret
= lp_build_create_jit_compiler_for_module(&gallivm
->engine
,
254 _debug_printf("%s\n", error
);
255 LLVMDisposeMessage(error
);
261 gallivm
->target
= LLVMGetExecutionEngineTargetData(gallivm
->engine
);
262 if (!gallivm
->target
)
267 * Dump the data layout strings.
270 LLVMTargetDataRef target
= LLVMGetExecutionEngineTargetData(gallivm
->engine
);
272 char *engine_data_layout
;
274 data_layout
= LLVMCopyStringRepOfTargetData(gallivm
->target
);
275 engine_data_layout
= LLVMCopyStringRepOfTargetData(target
);
278 debug_printf("module target data = %s\n", data_layout
);
279 debug_printf("engine target data = %s\n", engine_data_layout
);
283 free(engine_data_layout
);
295 * Allocate gallivm LLVM objects.
296 * \return TRUE for success, FALSE for failure
299 init_gallivm_state(struct gallivm_state
*gallivm
, const char *name
,
300 LLVMContextRef context
)
302 assert(!gallivm
->context
);
303 assert(!gallivm
->module
);
305 if (!lp_build_init())
308 gallivm
->context
= context
;
310 if (!gallivm
->context
)
313 gallivm
->module_name
= NULL
;
315 size_t size
= strlen(name
) + 1;
316 gallivm
->module_name
= MALLOC(size
);
317 if (gallivm
->module_name
) {
318 memcpy(gallivm
->module_name
, name
, size
);
322 gallivm
->module
= LLVMModuleCreateWithNameInContext(name
,
324 if (!gallivm
->module
)
327 gallivm
->builder
= LLVMCreateBuilderInContext(gallivm
->context
);
328 if (!gallivm
->builder
)
331 gallivm
->memorymgr
= lp_get_default_memory_manager();
332 if (!gallivm
->memorymgr
)
335 /* FIXME: MC-JIT only allows compiling one module at a time, and it must be
336 * complete when MC-JIT is created. So defer the MC-JIT engine creation for
340 if (!init_gallivm_engine(gallivm
)) {
345 * MC-JIT engine compiles the module immediately on creation, so we can't
346 * obtain the target data from it. Instead we create a target data layout
349 * The produced layout strings are not precisely the same, but should make
350 * no difference for the kind of optimization passes we run.
352 * For reference this is the layout string on x64:
354 * 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
357 * - http://llvm.org/docs/LangRef.html#datalayout
361 const unsigned pointer_size
= 8 * sizeof(void *);
363 util_snprintf(layout
, sizeof layout
, "%c-p:%u:%u:%u-i64:64:64-a0:0:%u-s0:%u:%u",
364 #ifdef PIPE_ARCH_LITTLE_ENDIAN
365 'e', // little endian
369 pointer_size
, pointer_size
, pointer_size
, // pointer size, abi alignment, preferred alignment
370 pointer_size
, // aggregate preferred alignment
371 pointer_size
, pointer_size
); // stack objects abi alignment, preferred alignment
373 gallivm
->target
= LLVMCreateTargetData(layout
);
374 if (!gallivm
->target
) {
380 if (!create_pass_manager(gallivm
))
386 gallivm_free_ir(gallivm
);
387 gallivm_free_code(gallivm
);
395 if (gallivm_initialized
)
399 #if !defined(USE_MCJIT)
400 USE_MCJIT
= debug_get_bool_option("GALLIVM_MCJIT", 0);
405 gallivm_debug
= debug_get_option_gallivm_debug();
408 lp_set_target_options();
412 /* For simulating less capable machines */
414 if (debug_get_bool_option("LP_FORCE_SSE2", FALSE
)) {
415 assert(util_cpu_caps
.has_sse2
);
416 util_cpu_caps
.has_sse3
= 0;
417 util_cpu_caps
.has_ssse3
= 0;
418 util_cpu_caps
.has_sse4_1
= 0;
419 util_cpu_caps
.has_sse4_2
= 0;
420 util_cpu_caps
.has_avx
= 0;
421 util_cpu_caps
.has_avx2
= 0;
422 util_cpu_caps
.has_f16c
= 0;
426 /* AMD Bulldozer AVX's throughput is the same as SSE2; and because using
427 * 8-wide vector needs more floating ops than 4-wide (due to padding), it is
428 * actually more efficient to use 4-wide vectors on this processor.
431 * - http://www.anandtech.com/show/4955/the-bulldozer-review-amd-fx8150-tested/2
433 if (util_cpu_caps
.has_avx
&&
434 util_cpu_caps
.has_intel
) {
435 lp_native_vector_width
= 256;
437 /* Leave it at 128, even when no SIMD extensions are available.
438 * Really needs to be a multiple of 128 so can fit 4 floats.
440 lp_native_vector_width
= 128;
443 lp_native_vector_width
= debug_get_num_option("LP_NATIVE_VECTOR_WIDTH",
444 lp_native_vector_width
);
446 if (lp_native_vector_width
<= 128) {
447 /* Hide AVX support, as often LLVM AVX intrinsics are only guarded by
448 * "util_cpu_caps.has_avx" predicate, and lack the
449 * "lp_native_vector_width > 128" predicate. And also to ensure a more
450 * consistent behavior, allowing one to test SSE2 on AVX machines.
451 * XXX: should not play games with util_cpu_caps directly as it might
452 * get used for other things outside llvm too.
454 util_cpu_caps
.has_avx
= 0;
455 util_cpu_caps
.has_avx2
= 0;
456 util_cpu_caps
.has_f16c
= 0;
459 #ifdef PIPE_ARCH_PPC_64
460 /* Set the NJ bit in VSCR to 0 so denormalized values are handled as
461 * specified by IEEE standard (PowerISA 2.06 - Section 6.3). This guarantees
462 * that some rounding and half-float to float handling does not round
464 * XXX: should eventually follow same logic on all platforms.
465 * Right now denorms get explicitly disabled (but elsewhere) for x86,
466 * whereas ppc64 explicitly enables them...
468 if (util_cpu_caps
.has_altivec
) {
469 unsigned short mask
[] = { 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF,
470 0xFFFF, 0xFFFF, 0xFFFE, 0xFFFF };
481 gallivm_initialized
= TRUE
;
489 * Create a new gallivm_state object.
491 struct gallivm_state
*
492 gallivm_create(const char *name
, LLVMContextRef context
)
494 struct gallivm_state
*gallivm
;
496 gallivm
= CALLOC_STRUCT(gallivm_state
);
498 if (!init_gallivm_state(gallivm
, name
, context
)) {
509 * Destroy a gallivm_state object.
512 gallivm_destroy(struct gallivm_state
*gallivm
)
514 gallivm_free_ir(gallivm
);
515 gallivm_free_code(gallivm
);
521 * Validate a function.
522 * Verification is only done with debug builds.
525 gallivm_verify_function(struct gallivm_state
*gallivm
,
528 /* Verify the LLVM IR. If invalid, dump and abort */
530 if (LLVMVerifyFunction(func
, LLVMPrintMessageAction
)) {
531 lp_debug_dump_value(func
);
537 if (gallivm_debug
& GALLIVM_DEBUG_IR
) {
538 /* Print the LLVM IR to stderr */
539 lp_debug_dump_value(func
);
547 * This does IR optimization on all functions in the module.
550 gallivm_compile_module(struct gallivm_state
*gallivm
)
553 int64_t time_begin
= 0;
555 assert(!gallivm
->compiled
);
557 if (gallivm
->builder
) {
558 LLVMDisposeBuilder(gallivm
->builder
);
559 gallivm
->builder
= NULL
;
562 if (gallivm_debug
& GALLIVM_DEBUG_PERF
)
563 time_begin
= os_time_get();
565 /* Run optimization passes */
566 LLVMInitializeFunctionPassManager(gallivm
->passmgr
);
567 func
= LLVMGetFirstFunction(gallivm
->module
);
570 debug_printf("optimizing func %s...\n", LLVMGetValueName(func
));
573 /* Disable frame pointer omission on debug/profile builds */
574 /* XXX: And workaround http://llvm.org/PR21435 */
575 #if HAVE_LLVM >= 0x0307 && \
576 (defined(DEBUG) || defined(PROFILE) || \
577 defined(PIPE_ARCH_X86) || defined(PIPE_ARCH_X86_64))
578 LLVMAddTargetDependentFunctionAttr(func
, "no-frame-pointer-elim", "true");
579 LLVMAddTargetDependentFunctionAttr(func
, "no-frame-pointer-elim-non-leaf", "true");
582 LLVMRunFunctionPassManager(gallivm
->passmgr
, func
);
583 func
= LLVMGetNextFunction(func
);
585 LLVMFinalizeFunctionPassManager(gallivm
->passmgr
);
587 if (gallivm_debug
& GALLIVM_DEBUG_PERF
) {
588 int64_t time_end
= os_time_get();
589 int time_msec
= (int)(time_end
- time_begin
) / 1000;
590 assert(gallivm
->module_name
);
591 debug_printf("optimizing module %s took %d msec\n",
592 gallivm
->module_name
, time_msec
);
595 /* Dump byte code to a file */
596 if (gallivm_debug
& GALLIVM_DEBUG_DUMP_BC
) {
598 assert(gallivm
->module_name
);
599 util_snprintf(filename
, sizeof(filename
), "ir_%s.bc", gallivm
->module_name
);
600 LLVMWriteBitcodeToFile(gallivm
->module
, filename
);
601 debug_printf("%s written\n", filename
);
602 debug_printf("Invoke as \"llc -o - %s\"\n", filename
);
606 assert(!gallivm
->engine
);
607 if (!init_gallivm_engine(gallivm
)) {
611 assert(gallivm
->engine
);
615 if (gallivm_debug
& GALLIVM_DEBUG_ASM
) {
616 LLVMValueRef llvm_func
= LLVMGetFirstFunction(gallivm
->module
);
620 * Need to filter out functions which don't have an implementation,
621 * such as the intrinsics. May not be sufficient in case of IPO?
622 * LLVMGetPointerToGlobal() will abort otherwise.
624 if (!LLVMIsDeclaration(llvm_func
)) {
625 void *func_code
= LLVMGetPointerToGlobal(gallivm
->engine
, llvm_func
);
626 lp_disassemble(llvm_func
, func_code
);
628 llvm_func
= LLVMGetNextFunction(llvm_func
);
634 LLVMValueRef llvm_func
= LLVMGetFirstFunction(gallivm
->module
);
637 if (!LLVMIsDeclaration(llvm_func
)) {
638 void *func_code
= LLVMGetPointerToGlobal(gallivm
->engine
, llvm_func
);
639 lp_profile(llvm_func
, func_code
);
641 llvm_func
= LLVMGetNextFunction(llvm_func
);
650 gallivm_jit_function(struct gallivm_state
*gallivm
,
654 func_pointer jit_func
;
656 assert(gallivm
->compiled
);
657 assert(gallivm
->engine
);
659 code
= LLVMGetPointerToGlobal(gallivm
->engine
, func
);
661 jit_func
= pointer_to_func(code
);