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/u_simple_list.h"
36 #include "lp_bld_debug.h"
37 #include "lp_bld_misc.h"
38 #include "lp_bld_init.h"
40 #include <llvm-c/Analysis.h>
41 #include <llvm-c/Transforms/Scalar.h>
42 #include <llvm-c/BitWriter.h>
46 * AVX is supported in:
47 * - standard JIT from LLVM 3.2 onwards
48 * - MC-JIT from LLVM 3.1
49 * - MC-JIT supports limited OSes (MacOSX and Linux)
50 * - standard JIT in LLVM 3.1, with backports
52 #if defined(PIPE_ARCH_PPC_64)
55 #elif HAVE_LLVM >= 0x0302 || (HAVE_LLVM == 0x0301 && defined(HAVE_JIT_AVX_SUPPORT))
58 #elif HAVE_LLVM == 0x0301 && (defined(PIPE_OS_LINUX) || defined(PIPE_OS_APPLE))
68 void LLVMLinkInMCJIT();
73 unsigned gallivm_debug
= 0;
75 static const struct debug_named_value lp_bld_debug_flags
[] = {
76 { "tgsi", GALLIVM_DEBUG_TGSI
, NULL
},
77 { "ir", GALLIVM_DEBUG_IR
, NULL
},
78 { "asm", GALLIVM_DEBUG_ASM
, NULL
},
79 { "nopt", GALLIVM_DEBUG_NO_OPT
, NULL
},
80 { "perf", GALLIVM_DEBUG_PERF
, NULL
},
81 { "no_brilinear", GALLIVM_DEBUG_NO_BRILINEAR
, NULL
},
82 { "gc", GALLIVM_DEBUG_GC
, NULL
},
86 DEBUG_GET_ONCE_FLAGS_OPTION(gallivm_debug
, "GALLIVM_DEBUG", lp_bld_debug_flags
, 0)
90 static boolean gallivm_initialized
= FALSE
;
92 unsigned lp_native_vector_width
;
96 * Optimization values are:
99 * - 2: Default (-O2, -Os)
100 * - 3: Aggressive (-O3)
102 * See also CodeGenOpt::Level in llvm/Target/TargetMachine.h
104 enum LLVM_CodeGenOpt_Level
{
105 #if HAVE_LLVM >= 0x207
118 #if HAVE_LLVM <= 0x0206
120 * LLVM 2.6 permits only one ExecutionEngine to be created. So use the
121 * same gallivm state everywhere.
123 static struct gallivm_state
*GlobalGallivm
= NULL
;
128 * Create the LLVM (optimization) pass manager and install
129 * relevant optimization passes.
130 * \return TRUE for success, FALSE for failure
133 create_pass_manager(struct gallivm_state
*gallivm
)
135 assert(!gallivm
->passmgr
);
136 assert(gallivm
->target
);
138 gallivm
->passmgr
= LLVMCreateFunctionPassManager(gallivm
->provider
);
139 if (!gallivm
->passmgr
)
142 LLVMAddTargetData(gallivm
->target
, gallivm
->passmgr
);
144 if ((gallivm_debug
& GALLIVM_DEBUG_NO_OPT
) == 0) {
145 /* These are the passes currently listed in llvm-c/Transforms/Scalar.h,
146 * but there are more on SVN.
147 * TODO: Add more passes.
149 LLVMAddCFGSimplificationPass(gallivm
->passmgr
);
151 if (HAVE_LLVM
>= 0x207 && sizeof(void*) == 4) {
152 /* For LLVM >= 2.7 and 32-bit build, use this order of passes to
153 * avoid generating bad code.
154 * Test with piglit glsl-vs-sqrt-zero test.
156 LLVMAddConstantPropagationPass(gallivm
->passmgr
);
157 LLVMAddPromoteMemoryToRegisterPass(gallivm
->passmgr
);
160 LLVMAddPromoteMemoryToRegisterPass(gallivm
->passmgr
);
161 LLVMAddConstantPropagationPass(gallivm
->passmgr
);
164 if (util_cpu_caps
.has_sse4_1
) {
165 /* FIXME: There is a bug in this pass, whereby the combination
166 * of fptosi and sitofp (necessary for trunc/floor/ceil/round
167 * implementation) somehow becomes invalid code.
169 LLVMAddInstructionCombiningPass(gallivm
->passmgr
);
171 LLVMAddGVNPass(gallivm
->passmgr
);
174 /* We need at least this pass to prevent the backends to fail in
177 LLVMAddPromoteMemoryToRegisterPass(gallivm
->passmgr
);
185 * Free gallivm object's LLVM allocations, but not the gallivm object itself.
188 free_gallivm_state(struct gallivm_state
*gallivm
)
190 #if HAVE_LLVM >= 0x207 /* XXX or 0x208? */
191 /* This leads to crashes w/ some versions of LLVM */
195 if (gallivm
->engine
&& gallivm
->provider
)
196 LLVMRemoveModuleProvider(gallivm
->engine
, gallivm
->provider
,
200 if (gallivm
->passmgr
) {
201 LLVMDisposePassManager(gallivm
->passmgr
);
205 /* XXX this seems to crash with all versions of LLVM */
206 if (gallivm
->provider
)
207 LLVMDisposeModuleProvider(gallivm
->provider
);
210 if (HAVE_LLVM
>= 0x207 && gallivm
->engine
) {
211 /* This will already destroy any associated module */
212 LLVMDisposeExecutionEngine(gallivm
->engine
);
214 LLVMDisposeModule(gallivm
->module
);
218 /* Don't free the TargetData, it's owned by the exec engine */
220 if (gallivm
->target
) {
221 LLVMDisposeTargetData(gallivm
->target
);
225 /* Never free the LLVM context.
228 if (gallivm
->context
)
229 LLVMContextDispose(gallivm
->context
);
232 if (gallivm
->builder
)
233 LLVMDisposeBuilder(gallivm
->builder
);
235 gallivm
->engine
= NULL
;
236 gallivm
->target
= NULL
;
237 gallivm
->module
= NULL
;
238 gallivm
->provider
= NULL
;
239 gallivm
->passmgr
= NULL
;
240 gallivm
->context
= NULL
;
241 gallivm
->builder
= NULL
;
246 init_gallivm_engine(struct gallivm_state
*gallivm
)
249 /* We can only create one LLVMExecutionEngine (w/ LLVM 2.6 anyway) */
250 enum LLVM_CodeGenOpt_Level optlevel
;
254 if (gallivm_debug
& GALLIVM_DEBUG_NO_OPT
) {
262 ret
= lp_build_create_mcjit_compiler_for_module(&gallivm
->engine
,
267 ret
= LLVMCreateJITCompiler(&gallivm
->engine
, gallivm
->provider
,
268 (unsigned) optlevel
, &error
);
271 _debug_printf("%s\n", error
);
272 LLVMDisposeMessage(error
);
276 #if defined(DEBUG) || defined(PROFILE)
277 lp_register_oprofile_jit_event_listener(gallivm
->engine
);
281 LLVMAddModuleProvider(gallivm
->engine
, gallivm
->provider
);//new
284 gallivm
->target
= LLVMGetExecutionEngineTargetData(gallivm
->engine
);
285 if (!gallivm
->target
)
290 * Dump the data layout strings.
293 LLVMTargetDataRef target
= LLVMGetExecutionEngineTargetData(gallivm
->engine
);
295 char *engine_data_layout
;
297 data_layout
= LLVMCopyStringRepOfTargetData(gallivm
->target
);
298 engine_data_layout
= LLVMCopyStringRepOfTargetData(target
);
301 debug_printf("module target data = %s\n", data_layout
);
302 debug_printf("engine target data = %s\n", engine_data_layout
);
306 free(engine_data_layout
);
320 * We must never free LLVM contexts, because LLVM has several global caches
321 * which pointing/derived from objects owned by the context, causing false
322 * memory leaks and false cache hits when these objects are destroyed.
324 * TODO: For thread safety on multi-threaded OpenGL we should use one LLVM
325 * context per thread, and put them in a pool when threads are destroyed.
327 static LLVMContextRef gallivm_context
= NULL
;
331 * Allocate gallivm LLVM objects.
332 * \return TRUE for success, FALSE for failure
335 init_gallivm_state(struct gallivm_state
*gallivm
)
337 assert(!gallivm
->context
);
338 assert(!gallivm
->module
);
339 assert(!gallivm
->provider
);
343 if (!gallivm_context
) {
344 gallivm_context
= LLVMContextCreate();
346 gallivm
->context
= gallivm_context
;
347 if (!gallivm
->context
)
350 gallivm
->module
= LLVMModuleCreateWithNameInContext("gallivm",
352 if (!gallivm
->module
)
356 LLVMCreateModuleProviderForExistingModule(gallivm
->module
);
357 if (!gallivm
->provider
)
360 gallivm
->builder
= LLVMCreateBuilderInContext(gallivm
->context
);
361 if (!gallivm
->builder
)
364 /* FIXME: MC-JIT only allows compiling one module at a time, and it must be
365 * complete when MC-JIT is created. So defer the MC-JIT engine creation for
369 if (!init_gallivm_engine(gallivm
)) {
374 * MC-JIT engine compiles the module immediately on creation, so we can't
375 * obtain the target data from it. Instead we create a target data layout
378 * The produced layout strings are not precisely the same, but should make
379 * no difference for the kind of optimization passes we run.
381 * For reference this is the layout string on x64:
383 * 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
386 * - http://llvm.org/docs/LangRef.html#datalayout
390 const unsigned pointer_size
= 8 * sizeof(void *);
392 util_snprintf(layout
, sizeof layout
, "%c-p:%u:%u:%u-i64:64:64-a0:0:%u-s0:%u:%u",
393 #ifdef PIPE_ARCH_LITTLE_ENDIAN
394 'e', // little endian
398 pointer_size
, pointer_size
, pointer_size
, // pointer size, abi alignment, preferred alignment
399 pointer_size
, // aggregate preferred alignment
400 pointer_size
, pointer_size
); // stack objects abi alignment, preferred alignment
402 gallivm
->target
= LLVMCreateTargetData(layout
);
403 if (!gallivm
->target
) {
409 if (!create_pass_manager(gallivm
))
415 free_gallivm_state(gallivm
);
423 if (gallivm_initialized
)
427 gallivm_debug
= debug_get_option_gallivm_debug();
430 lp_set_target_options();
440 /* AMD Bulldozer AVX's throughput is the same as SSE2; and because using
441 * 8-wide vector needs more floating ops than 4-wide (due to padding), it is
442 * actually more efficient to use 4-wide vectors on this processor.
445 * - http://www.anandtech.com/show/4955/the-bulldozer-review-amd-fx8150-tested/2
448 util_cpu_caps
.has_avx
&&
449 util_cpu_caps
.has_intel
) {
450 lp_native_vector_width
= 256;
452 /* Leave it at 128, even when no SIMD extensions are available.
453 * Really needs to be a multiple of 128 so can fit 4 floats.
455 lp_native_vector_width
= 128;
458 lp_native_vector_width
= debug_get_num_option("LP_NATIVE_VECTOR_WIDTH",
459 lp_native_vector_width
);
461 if (lp_native_vector_width
<= 128) {
462 /* Hide AVX support, as often LLVM AVX instrinsics are only guarded by
463 * "util_cpu_caps.has_avx" predicate, and lack the
464 * "lp_native_vector_width > 128" predicate. And also to ensure a more
465 * consistent behavior, allowing one to test SSE2 on AVX machines.
467 util_cpu_caps
.has_avx
= 0;
470 gallivm_initialized
= TRUE
;
473 /* For simulating less capable machines */
474 util_cpu_caps
.has_sse3
= 0;
475 util_cpu_caps
.has_ssse3
= 0;
476 util_cpu_caps
.has_sse4_1
= 0;
477 util_cpu_caps
.has_avx
= 0;
484 * Create a new gallivm_state object.
485 * Note that we return a singleton.
487 struct gallivm_state
*
490 struct gallivm_state
*gallivm
;
492 #if HAVE_LLVM <= 0x206
494 return GlobalGallivm
;
498 gallivm
= CALLOC_STRUCT(gallivm_state
);
500 if (!init_gallivm_state(gallivm
)) {
506 #if HAVE_LLVM <= 0x206
507 GlobalGallivm
= gallivm
;
515 * Destroy a gallivm_state object.
518 gallivm_destroy(struct gallivm_state
*gallivm
)
520 #if HAVE_LLVM <= 0x0206
521 /* No-op: don't destroy the singleton */
524 free_gallivm_state(gallivm
);
531 * Validate and optimze a function.
534 gallivm_optimize_function(struct gallivm_state
*gallivm
,
538 debug_printf("optimizing %s...\n", LLVMGetValueName(func
));
541 assert(gallivm
->passmgr
);
543 /* Apply optimizations to LLVM IR */
544 LLVMRunFunctionPassManager(gallivm
->passmgr
, func
);
547 if (gallivm_debug
& GALLIVM_DEBUG_IR
) {
548 /* Print the LLVM IR to stderr */
549 lp_debug_dump_value(func
);
557 * Validate a function.
560 gallivm_verify_function(struct gallivm_state
*gallivm
,
563 /* Verify the LLVM IR. If invalid, dump and abort */
565 if (LLVMVerifyFunction(func
, LLVMPrintMessageAction
)) {
566 lp_debug_dump_value(func
);
572 gallivm_optimize_function(gallivm
, func
);
574 if (gallivm_debug
& GALLIVM_DEBUG_IR
) {
575 /* Print the LLVM IR to stderr */
576 lp_debug_dump_value(func
);
583 gallivm_compile_module(struct gallivm_state
*gallivm
)
585 #if HAVE_LLVM > 0x206
586 assert(!gallivm
->compiled
);
589 /* Dump byte code to a file */
591 LLVMWriteBitcodeToFile(gallivm
->module
, "llvmpipe.bc");
592 debug_printf("llvmpipe.bc written\n");
593 debug_printf("Invoke as \"llc -o - llvmpipe.bc\"\n");
597 assert(!gallivm
->engine
);
598 if (!init_gallivm_engine(gallivm
)) {
602 assert(gallivm
->engine
);
609 gallivm_jit_function(struct gallivm_state
*gallivm
,
613 func_pointer jit_func
;
615 assert(gallivm
->compiled
);
616 assert(gallivm
->engine
);
618 code
= LLVMGetPointerToGlobal(gallivm
->engine
, func
);
620 jit_func
= pointer_to_func(code
);
622 if (gallivm_debug
& GALLIVM_DEBUG_ASM
) {
623 lp_disassemble(code
);
626 /* Free the function body to save memory */
627 lp_func_delete_body(func
);
634 * Free the function (and its machine code).
637 gallivm_free_function(struct gallivm_state
*gallivm
,
643 LLVMFreeMachineCodeForFunction(gallivm
->engine
, func
);
646 LLVMDeleteFunction(func
);