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 HAVE_LLVM >= 0x0301 && (defined(PIPE_OS_LINUX) || defined(PIPE_OS_APPLE))
55 #elif HAVE_LLVM >= 0x0302 || (HAVE_LLVM == 0x0301 && defined(HAVE_JIT_AVX_SUPPORT))
65 void LLVMLinkInMCJIT();
70 unsigned gallivm_debug
= 0;
72 static const struct debug_named_value lp_bld_debug_flags
[] = {
73 { "tgsi", GALLIVM_DEBUG_TGSI
, NULL
},
74 { "ir", GALLIVM_DEBUG_IR
, NULL
},
75 { "asm", GALLIVM_DEBUG_ASM
, NULL
},
76 { "nopt", GALLIVM_DEBUG_NO_OPT
, NULL
},
77 { "perf", GALLIVM_DEBUG_PERF
, NULL
},
78 { "no_brilinear", GALLIVM_DEBUG_NO_BRILINEAR
, NULL
},
79 { "gc", GALLIVM_DEBUG_GC
, NULL
},
83 DEBUG_GET_ONCE_FLAGS_OPTION(gallivm_debug
, "GALLIVM_DEBUG", lp_bld_debug_flags
, 0)
87 static boolean gallivm_initialized
= FALSE
;
89 unsigned lp_native_vector_width
;
93 * Optimization values are:
96 * - 2: Default (-O2, -Os)
97 * - 3: Aggressive (-O3)
99 * See also CodeGenOpt::Level in llvm/Target/TargetMachine.h
101 enum LLVM_CodeGenOpt_Level
{
102 #if HAVE_LLVM >= 0x207
115 #if HAVE_LLVM <= 0x0206
117 * LLVM 2.6 permits only one ExecutionEngine to be created. So use the
118 * same gallivm state everywhere.
120 static struct gallivm_state
*GlobalGallivm
= NULL
;
125 * Create the LLVM (optimization) pass manager and install
126 * relevant optimization passes.
127 * \return TRUE for success, FALSE for failure
130 create_pass_manager(struct gallivm_state
*gallivm
)
132 assert(!gallivm
->passmgr
);
133 assert(gallivm
->target
);
135 gallivm
->passmgr
= LLVMCreateFunctionPassManager(gallivm
->provider
);
136 if (!gallivm
->passmgr
)
139 LLVMAddTargetData(gallivm
->target
, gallivm
->passmgr
);
141 if ((gallivm_debug
& GALLIVM_DEBUG_NO_OPT
) == 0) {
142 /* These are the passes currently listed in llvm-c/Transforms/Scalar.h,
143 * but there are more on SVN.
144 * TODO: Add more passes.
146 LLVMAddCFGSimplificationPass(gallivm
->passmgr
);
148 if (HAVE_LLVM
>= 0x207 && sizeof(void*) == 4) {
149 /* For LLVM >= 2.7 and 32-bit build, use this order of passes to
150 * avoid generating bad code.
151 * Test with piglit glsl-vs-sqrt-zero test.
153 LLVMAddConstantPropagationPass(gallivm
->passmgr
);
154 LLVMAddPromoteMemoryToRegisterPass(gallivm
->passmgr
);
157 LLVMAddPromoteMemoryToRegisterPass(gallivm
->passmgr
);
158 LLVMAddConstantPropagationPass(gallivm
->passmgr
);
161 if (util_cpu_caps
.has_sse4_1
) {
162 /* FIXME: There is a bug in this pass, whereby the combination
163 * of fptosi and sitofp (necessary for trunc/floor/ceil/round
164 * implementation) somehow becomes invalid code.
166 LLVMAddInstructionCombiningPass(gallivm
->passmgr
);
168 LLVMAddGVNPass(gallivm
->passmgr
);
171 /* We need at least this pass to prevent the backends to fail in
174 LLVMAddPromoteMemoryToRegisterPass(gallivm
->passmgr
);
182 * Free gallivm object's LLVM allocations, but not the gallivm object itself.
185 free_gallivm_state(struct gallivm_state
*gallivm
)
187 #if HAVE_LLVM >= 0x207 /* XXX or 0x208? */
188 /* This leads to crashes w/ some versions of LLVM */
192 if (gallivm
->engine
&& gallivm
->provider
)
193 LLVMRemoveModuleProvider(gallivm
->engine
, gallivm
->provider
,
197 if (gallivm
->passmgr
) {
198 LLVMDisposePassManager(gallivm
->passmgr
);
202 /* XXX this seems to crash with all versions of LLVM */
203 if (gallivm
->provider
)
204 LLVMDisposeModuleProvider(gallivm
->provider
);
207 if (HAVE_LLVM
>= 0x207 && gallivm
->engine
) {
208 /* This will already destroy any associated module */
209 LLVMDisposeExecutionEngine(gallivm
->engine
);
211 LLVMDisposeModule(gallivm
->module
);
215 /* Don't free the TargetData, it's owned by the exec engine */
217 if (gallivm
->target
) {
218 LLVMDisposeTargetData(gallivm
->target
);
222 /* Never free the LLVM context.
225 if (gallivm
->context
)
226 LLVMContextDispose(gallivm
->context
);
229 if (gallivm
->builder
)
230 LLVMDisposeBuilder(gallivm
->builder
);
232 gallivm
->engine
= NULL
;
233 gallivm
->target
= NULL
;
234 gallivm
->module
= NULL
;
235 gallivm
->provider
= NULL
;
236 gallivm
->passmgr
= NULL
;
237 gallivm
->context
= NULL
;
238 gallivm
->builder
= NULL
;
243 init_gallivm_engine(struct gallivm_state
*gallivm
)
246 /* We can only create one LLVMExecutionEngine (w/ LLVM 2.6 anyway) */
247 enum LLVM_CodeGenOpt_Level optlevel
;
251 if (gallivm_debug
& GALLIVM_DEBUG_NO_OPT
) {
259 ret
= lp_build_create_mcjit_compiler_for_module(&gallivm
->engine
,
264 ret
= LLVMCreateJITCompiler(&gallivm
->engine
, gallivm
->provider
,
265 (unsigned) optlevel
, &error
);
268 _debug_printf("%s\n", error
);
269 LLVMDisposeMessage(error
);
273 #if defined(DEBUG) || defined(PROFILE)
274 lp_register_oprofile_jit_event_listener(gallivm
->engine
);
278 LLVMAddModuleProvider(gallivm
->engine
, gallivm
->provider
);//new
281 gallivm
->target
= LLVMGetExecutionEngineTargetData(gallivm
->engine
);
282 if (!gallivm
->target
)
287 * Dump the data layout strings.
290 LLVMTargetDataRef target
= LLVMGetExecutionEngineTargetData(gallivm
->engine
);
292 char *engine_data_layout
;
294 data_layout
= LLVMCopyStringRepOfTargetData(gallivm
->target
);
295 engine_data_layout
= LLVMCopyStringRepOfTargetData(target
);
298 debug_printf("module target data = %s\n", data_layout
);
299 debug_printf("engine target data = %s\n", engine_data_layout
);
303 free(engine_data_layout
);
317 * We must never free LLVM contexts, because LLVM has several global caches
318 * which pointing/derived from objects owned by the context, causing false
319 * memory leaks and false cache hits when these objects are destroyed.
321 * TODO: For thread safety on multi-threaded OpenGL we should use one LLVM
322 * context per thread, and put them in a pool when threads are destroyed.
324 static LLVMContextRef gallivm_context
= NULL
;
328 * Allocate gallivm LLVM objects.
329 * \return TRUE for success, FALSE for failure
332 init_gallivm_state(struct gallivm_state
*gallivm
)
334 assert(!gallivm
->context
);
335 assert(!gallivm
->module
);
336 assert(!gallivm
->provider
);
340 if (!gallivm_context
) {
341 gallivm_context
= LLVMContextCreate();
343 gallivm
->context
= gallivm_context
;
344 if (!gallivm
->context
)
347 gallivm
->module
= LLVMModuleCreateWithNameInContext("gallivm",
349 if (!gallivm
->module
)
353 LLVMCreateModuleProviderForExistingModule(gallivm
->module
);
354 if (!gallivm
->provider
)
357 gallivm
->builder
= LLVMCreateBuilderInContext(gallivm
->context
);
358 if (!gallivm
->builder
)
361 /* FIXME: MC-JIT only allows compiling one module at a time, and it must be
362 * complete when MC-JIT is created. So defer the MC-JIT engine creation for
366 if (!init_gallivm_engine(gallivm
)) {
371 * MC-JIT engine compiles the module immediately on creation, so we can't
372 * obtain the target data from it. Instead we create a target data layout
375 * The produced layout strings are not precisely the same, but should make
376 * no difference for the kind of optimization passes we run.
378 * For reference this is the layout string on x64:
380 * 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
383 * - http://llvm.org/docs/LangRef.html#datalayout
387 const unsigned pointer_size
= 8 * sizeof(void *);
389 util_snprintf(layout
, sizeof layout
, "%c-p:%u:%u:%u-i64:64:64-a0:0:%u-s0:%u:%u",
390 #ifdef PIPE_ARCH_LITTLE_ENDIAN
391 'e', // little endian
395 pointer_size
, pointer_size
, pointer_size
, // pointer size, abi alignment, preferred alignment
396 pointer_size
, // aggregate preferred alignment
397 pointer_size
, pointer_size
); // stack objects abi alignment, preferred alignment
399 gallivm
->target
= LLVMCreateTargetData(layout
);
400 if (!gallivm
->target
) {
406 if (!create_pass_manager(gallivm
))
412 free_gallivm_state(gallivm
);
420 if (gallivm_initialized
)
424 gallivm_debug
= debug_get_option_gallivm_debug();
427 lp_set_target_options();
438 util_cpu_caps
.has_avx
) {
439 lp_native_vector_width
= 256;
441 /* Leave it at 128, even when no SIMD extensions are available.
442 * Really needs to be a multiple of 128 so can fit 4 floats.
444 lp_native_vector_width
= 128;
447 lp_native_vector_width
= debug_get_num_option("LP_NATIVE_VECTOR_WIDTH",
448 lp_native_vector_width
);
450 gallivm_initialized
= TRUE
;
453 /* For simulating less capable machines */
454 util_cpu_caps
.has_sse3
= 0;
455 util_cpu_caps
.has_ssse3
= 0;
456 util_cpu_caps
.has_sse4_1
= 0;
463 * Create a new gallivm_state object.
464 * Note that we return a singleton.
466 struct gallivm_state
*
469 struct gallivm_state
*gallivm
;
471 #if HAVE_LLVM <= 0x206
473 return GlobalGallivm
;
477 gallivm
= CALLOC_STRUCT(gallivm_state
);
479 if (!init_gallivm_state(gallivm
)) {
485 #if HAVE_LLVM <= 0x206
486 GlobalGallivm
= gallivm
;
494 * Destroy a gallivm_state object.
497 gallivm_destroy(struct gallivm_state
*gallivm
)
499 #if HAVE_LLVM <= 0x0206
500 /* No-op: don't destroy the singleton */
503 free_gallivm_state(gallivm
);
510 * Validate and optimze a function.
513 gallivm_optimize_function(struct gallivm_state
*gallivm
,
517 debug_printf("optimizing %s...\n", LLVMGetValueName(func
));
520 assert(gallivm
->passmgr
);
522 /* Apply optimizations to LLVM IR */
523 LLVMRunFunctionPassManager(gallivm
->passmgr
, func
);
526 if (gallivm_debug
& GALLIVM_DEBUG_IR
) {
527 /* Print the LLVM IR to stderr */
528 lp_debug_dump_value(func
);
536 * Validate a function.
539 gallivm_verify_function(struct gallivm_state
*gallivm
,
542 /* Verify the LLVM IR. If invalid, dump and abort */
544 if (LLVMVerifyFunction(func
, LLVMPrintMessageAction
)) {
545 lp_debug_dump_value(func
);
551 gallivm_optimize_function(gallivm
, func
);
553 if (gallivm_debug
& GALLIVM_DEBUG_IR
) {
554 /* Print the LLVM IR to stderr */
555 lp_debug_dump_value(func
);
562 gallivm_compile_module(struct gallivm_state
*gallivm
)
564 #if HAVE_LLVM > 0x206
565 assert(!gallivm
->compiled
);
568 /* Dump byte code to a file */
570 LLVMWriteBitcodeToFile(gallivm
->module
, "llvmpipe.bc");
571 debug_printf("llvmpipe.bc written\n");
572 debug_printf("Invoke as \"llc -o - llvmpipe.bc\"\n");
576 assert(!gallivm
->engine
);
577 if (!init_gallivm_engine(gallivm
)) {
581 assert(gallivm
->engine
);
588 gallivm_jit_function(struct gallivm_state
*gallivm
,
592 func_pointer jit_func
;
594 assert(gallivm
->compiled
);
595 assert(gallivm
->engine
);
597 code
= LLVMGetPointerToGlobal(gallivm
->engine
, func
);
599 jit_func
= pointer_to_func(code
);
601 if (gallivm_debug
& GALLIVM_DEBUG_ASM
) {
602 lp_disassemble(code
);
605 /* Free the function body to save memory */
606 lp_func_delete_body(func
);
613 * Free the function (and its machine code).
616 gallivm_free_function(struct gallivm_state
*gallivm
,
622 LLVMFreeMachineCodeForFunction(gallivm
->engine
, func
);
625 LLVMDeleteFunction(func
);