1153411dd5255caf65efc4a42c85e4bb4ffcef2b
[mesa.git] / src / gallium / auxiliary / gallivm / lp_bld_init.c
1 /**************************************************************************
2 *
3 * Copyright 2009 VMware, Inc.
4 * All Rights Reserved.
5 *
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:
13 *
14 * The above copyright notice and this permission notice (including the
15 * next paragraph) shall be included in all copies or substantial portions
16 * of the Software.
17 *
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.
25 *
26 **************************************************************************/
27
28
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"
35 #include "lp_bld.h"
36 #include "lp_bld_debug.h"
37 #include "lp_bld_misc.h"
38 #include "lp_bld_init.h"
39
40 #include <llvm-c/Analysis.h>
41 #include <llvm-c/Transforms/Scalar.h>
42 #include <llvm-c/BitWriter.h>
43
44
45 /**
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
51 */
52 #if defined(PIPE_ARCH_PPC_64)
53 # define USE_MCJIT 1
54 # define HAVE_AVX 0
55 #elif HAVE_LLVM >= 0x0302 || (HAVE_LLVM == 0x0301 && defined(HAVE_JIT_AVX_SUPPORT))
56 # define USE_MCJIT 0
57 # define HAVE_AVX 1
58 #elif HAVE_LLVM == 0x0301 && (defined(PIPE_OS_LINUX) || defined(PIPE_OS_APPLE))
59 # define USE_MCJIT 1
60 # define HAVE_AVX 1
61 #else
62 # define USE_MCJIT 0
63 # define HAVE_AVX 0
64 #endif
65
66
67 #if USE_MCJIT
68 void LLVMLinkInMCJIT();
69 #endif
70
71
72 #ifdef DEBUG
73 unsigned gallivm_debug = 0;
74
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 },
83 DEBUG_NAMED_VALUE_END
84 };
85
86 DEBUG_GET_ONCE_FLAGS_OPTION(gallivm_debug, "GALLIVM_DEBUG", lp_bld_debug_flags, 0)
87 #endif
88
89
90 static boolean gallivm_initialized = FALSE;
91
92 unsigned lp_native_vector_width;
93
94
95 /*
96 * Optimization values are:
97 * - 0: None (-O0)
98 * - 1: Less (-O1)
99 * - 2: Default (-O2, -Os)
100 * - 3: Aggressive (-O3)
101 *
102 * See also CodeGenOpt::Level in llvm/Target/TargetMachine.h
103 */
104 enum LLVM_CodeGenOpt_Level {
105 #if HAVE_LLVM >= 0x207
106 None, // -O0
107 Less, // -O1
108 Default, // -O2, -Os
109 Aggressive // -O3
110 #else
111 Default,
112 None,
113 Aggressive
114 #endif
115 };
116
117
118 #if HAVE_LLVM <= 0x0206
119 /**
120 * LLVM 2.6 permits only one ExecutionEngine to be created. So use the
121 * same gallivm state everywhere.
122 */
123 static struct gallivm_state *GlobalGallivm = NULL;
124 #endif
125
126
127 /**
128 * Create the LLVM (optimization) pass manager and install
129 * relevant optimization passes.
130 * \return TRUE for success, FALSE for failure
131 */
132 static boolean
133 create_pass_manager(struct gallivm_state *gallivm)
134 {
135 assert(!gallivm->passmgr);
136 assert(gallivm->target);
137
138 gallivm->passmgr = LLVMCreateFunctionPassManager(gallivm->provider);
139 if (!gallivm->passmgr)
140 return FALSE;
141
142 LLVMAddTargetData(gallivm->target, gallivm->passmgr);
143
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.
148 */
149 LLVMAddCFGSimplificationPass(gallivm->passmgr);
150
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.
155 */
156 LLVMAddConstantPropagationPass(gallivm->passmgr);
157 LLVMAddPromoteMemoryToRegisterPass(gallivm->passmgr);
158 }
159 else {
160 LLVMAddPromoteMemoryToRegisterPass(gallivm->passmgr);
161 LLVMAddConstantPropagationPass(gallivm->passmgr);
162 }
163
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.
168 */
169 LLVMAddInstructionCombiningPass(gallivm->passmgr);
170 }
171 LLVMAddGVNPass(gallivm->passmgr);
172 }
173 else {
174 /* We need at least this pass to prevent the backends to fail in
175 * unexpected ways.
176 */
177 LLVMAddPromoteMemoryToRegisterPass(gallivm->passmgr);
178 }
179
180 return TRUE;
181 }
182
183
184 /**
185 * Free gallivm object's LLVM allocations, but not the gallivm object itself.
186 */
187 static void
188 free_gallivm_state(struct gallivm_state *gallivm)
189 {
190 #if HAVE_LLVM >= 0x207 /* XXX or 0x208? */
191 /* This leads to crashes w/ some versions of LLVM */
192 LLVMModuleRef mod;
193 char *error;
194
195 if (gallivm->engine && gallivm->provider)
196 LLVMRemoveModuleProvider(gallivm->engine, gallivm->provider,
197 &mod, &error);
198 #endif
199
200 if (gallivm->passmgr) {
201 LLVMDisposePassManager(gallivm->passmgr);
202 }
203
204 #if 0
205 /* XXX this seems to crash with all versions of LLVM */
206 if (gallivm->provider)
207 LLVMDisposeModuleProvider(gallivm->provider);
208 #endif
209
210 if (HAVE_LLVM >= 0x207 && gallivm->engine) {
211 /* This will already destroy any associated module */
212 LLVMDisposeExecutionEngine(gallivm->engine);
213 } else {
214 LLVMDisposeModule(gallivm->module);
215 }
216
217 #if !USE_MCJIT
218 /* Don't free the TargetData, it's owned by the exec engine */
219 #else
220 if (gallivm->target) {
221 LLVMDisposeTargetData(gallivm->target);
222 }
223 #endif
224
225 /* Never free the LLVM context.
226 */
227 #if 0
228 if (gallivm->context)
229 LLVMContextDispose(gallivm->context);
230 #endif
231
232 if (gallivm->builder)
233 LLVMDisposeBuilder(gallivm->builder);
234
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;
242 }
243
244
245 static boolean
246 init_gallivm_engine(struct gallivm_state *gallivm)
247 {
248 if (1) {
249 /* We can only create one LLVMExecutionEngine (w/ LLVM 2.6 anyway) */
250 enum LLVM_CodeGenOpt_Level optlevel;
251 char *error = NULL;
252 int ret;
253
254 if (gallivm_debug & GALLIVM_DEBUG_NO_OPT) {
255 optlevel = None;
256 }
257 else {
258 optlevel = Default;
259 }
260
261 #if HAVE_LLVM >= 0x0301
262 ret = lp_build_create_jit_compiler_for_module(&gallivm->engine,
263 gallivm->module,
264 (unsigned) optlevel,
265 USE_MCJIT,
266 &error);
267 #else
268 ret = LLVMCreateJITCompiler(&gallivm->engine, gallivm->provider,
269 (unsigned) optlevel, &error);
270 #endif
271 if (ret) {
272 _debug_printf("%s\n", error);
273 LLVMDisposeMessage(error);
274 goto fail;
275 }
276 }
277
278 LLVMAddModuleProvider(gallivm->engine, gallivm->provider);//new
279
280 #if !USE_MCJIT
281 gallivm->target = LLVMGetExecutionEngineTargetData(gallivm->engine);
282 if (!gallivm->target)
283 goto fail;
284 #else
285 if (0) {
286 /*
287 * Dump the data layout strings.
288 */
289
290 LLVMTargetDataRef target = LLVMGetExecutionEngineTargetData(gallivm->engine);
291 char *data_layout;
292 char *engine_data_layout;
293
294 data_layout = LLVMCopyStringRepOfTargetData(gallivm->target);
295 engine_data_layout = LLVMCopyStringRepOfTargetData(target);
296
297 if (1) {
298 debug_printf("module target data = %s\n", data_layout);
299 debug_printf("engine target data = %s\n", engine_data_layout);
300 }
301
302 free(data_layout);
303 free(engine_data_layout);
304 }
305 #endif
306
307 return TRUE;
308
309 fail:
310 return FALSE;
311 }
312
313
314 /**
315 * Singleton
316 *
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.
320 *
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.
323 */
324 static LLVMContextRef gallivm_context = NULL;
325
326
327 /**
328 * Allocate gallivm LLVM objects.
329 * \return TRUE for success, FALSE for failure
330 */
331 static boolean
332 init_gallivm_state(struct gallivm_state *gallivm)
333 {
334 assert(!gallivm->context);
335 assert(!gallivm->module);
336 assert(!gallivm->provider);
337
338 lp_build_init();
339
340 if (!gallivm_context) {
341 gallivm_context = LLVMContextCreate();
342 }
343 gallivm->context = gallivm_context;
344 if (!gallivm->context)
345 goto fail;
346
347 gallivm->module = LLVMModuleCreateWithNameInContext("gallivm",
348 gallivm->context);
349 if (!gallivm->module)
350 goto fail;
351
352 gallivm->provider =
353 LLVMCreateModuleProviderForExistingModule(gallivm->module);
354 if (!gallivm->provider)
355 goto fail;
356
357 gallivm->builder = LLVMCreateBuilderInContext(gallivm->context);
358 if (!gallivm->builder)
359 goto fail;
360
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
363 * now.
364 */
365 #if !USE_MCJIT
366 if (!init_gallivm_engine(gallivm)) {
367 goto fail;
368 }
369 #else
370 /*
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
373 * from a string.
374 *
375 * The produced layout strings are not precisely the same, but should make
376 * no difference for the kind of optimization passes we run.
377 *
378 * For reference this is the layout string on x64:
379 *
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
381 *
382 * See also:
383 * - http://llvm.org/docs/LangRef.html#datalayout
384 */
385
386 {
387 const unsigned pointer_size = 8 * sizeof(void *);
388 char layout[512];
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
392 #else
393 'E', // big endian
394 #endif
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
398
399 gallivm->target = LLVMCreateTargetData(layout);
400 if (!gallivm->target) {
401 return FALSE;
402 }
403 }
404 #endif
405
406 if (!create_pass_manager(gallivm))
407 goto fail;
408
409 return TRUE;
410
411 fail:
412 free_gallivm_state(gallivm);
413 return FALSE;
414 }
415
416
417 void
418 lp_build_init(void)
419 {
420 if (gallivm_initialized)
421 return;
422
423 #ifdef DEBUG
424 gallivm_debug = debug_get_option_gallivm_debug();
425 #endif
426
427 lp_set_target_options();
428
429 #if USE_MCJIT
430 LLVMLinkInMCJIT();
431 #else
432 LLVMLinkInJIT();
433 #endif
434
435 util_cpu_detect();
436
437 /* AMD Bulldozer AVX's throughput is the same as SSE2; and because using
438 * 8-wide vector needs more floating ops than 4-wide (due to padding), it is
439 * actually more efficient to use 4-wide vectors on this processor.
440 *
441 * See also:
442 * - http://www.anandtech.com/show/4955/the-bulldozer-review-amd-fx8150-tested/2
443 */
444 if (HAVE_AVX &&
445 util_cpu_caps.has_avx &&
446 util_cpu_caps.has_intel) {
447 lp_native_vector_width = 256;
448 } else {
449 /* Leave it at 128, even when no SIMD extensions are available.
450 * Really needs to be a multiple of 128 so can fit 4 floats.
451 */
452 lp_native_vector_width = 128;
453 }
454
455 lp_native_vector_width = debug_get_num_option("LP_NATIVE_VECTOR_WIDTH",
456 lp_native_vector_width);
457
458 if (lp_native_vector_width <= 128) {
459 /* Hide AVX support, as often LLVM AVX instrinsics are only guarded by
460 * "util_cpu_caps.has_avx" predicate, and lack the
461 * "lp_native_vector_width > 128" predicate. And also to ensure a more
462 * consistent behavior, allowing one to test SSE2 on AVX machines.
463 */
464 util_cpu_caps.has_avx = 0;
465 }
466
467 if (!HAVE_AVX) {
468 /*
469 * note these instructions are VEX-only, so can only emit if we use
470 * avx (don't want to base it on has_avx & has_f16c later as that would
471 * omit it unnecessarily on amd cpus, see above).
472 */
473 util_cpu_caps.has_f16c = 0;
474 }
475
476 #ifdef PIPE_ARCH_PPC_64
477 /* Set the NJ bit in VSCR to 0 so denormalized values are handled as
478 * specified by IEEE standard (PowerISA 2.06 - Section 6.3). This garantees
479 * that some rounding and half-float to float handling does not round
480 * incorrectly to 0.
481 */
482 if (util_cpu_caps.has_altivec) {
483 unsigned short mask[] = { 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF,
484 0xFFFF, 0xFFFF, 0xFFFE, 0xFFFF };
485 __asm (
486 "mfvscr %%v1\n"
487 "vand %0,%%v1,%0\n"
488 "mtvscr %0"
489 :
490 : "r" (*mask)
491 );
492 }
493 #endif
494
495 gallivm_initialized = TRUE;
496
497 #if 0
498 /* For simulating less capable machines */
499 util_cpu_caps.has_sse3 = 0;
500 util_cpu_caps.has_ssse3 = 0;
501 util_cpu_caps.has_sse4_1 = 0;
502 util_cpu_caps.has_avx = 0;
503 util_cpu_caps.has_f16c = 0;
504 #endif
505 }
506
507
508
509 /**
510 * Create a new gallivm_state object.
511 * Note that we return a singleton.
512 */
513 struct gallivm_state *
514 gallivm_create(void)
515 {
516 struct gallivm_state *gallivm;
517
518 #if HAVE_LLVM <= 0x206
519 if (GlobalGallivm) {
520 return GlobalGallivm;
521 }
522 #endif
523
524 gallivm = CALLOC_STRUCT(gallivm_state);
525 if (gallivm) {
526 if (!init_gallivm_state(gallivm)) {
527 FREE(gallivm);
528 gallivm = NULL;
529 }
530 }
531
532 #if HAVE_LLVM <= 0x206
533 GlobalGallivm = gallivm;
534 #endif
535
536 return gallivm;
537 }
538
539
540 /**
541 * Destroy a gallivm_state object.
542 */
543 void
544 gallivm_destroy(struct gallivm_state *gallivm)
545 {
546 #if HAVE_LLVM <= 0x0206
547 /* No-op: don't destroy the singleton */
548 (void) gallivm;
549 #else
550 free_gallivm_state(gallivm);
551 FREE(gallivm);
552 #endif
553 }
554
555
556 /**
557 * Validate and optimze a function.
558 */
559 static void
560 gallivm_optimize_function(struct gallivm_state *gallivm,
561 LLVMValueRef func)
562 {
563 if (0) {
564 debug_printf("optimizing %s...\n", LLVMGetValueName(func));
565 }
566
567 assert(gallivm->passmgr);
568
569 /* Apply optimizations to LLVM IR */
570 LLVMRunFunctionPassManager(gallivm->passmgr, func);
571
572 if (0) {
573 if (gallivm_debug & GALLIVM_DEBUG_IR) {
574 /* Print the LLVM IR to stderr */
575 lp_debug_dump_value(func);
576 debug_printf("\n");
577 }
578 }
579 }
580
581
582 /**
583 * Validate a function.
584 */
585 void
586 gallivm_verify_function(struct gallivm_state *gallivm,
587 LLVMValueRef func)
588 {
589 /* Verify the LLVM IR. If invalid, dump and abort */
590 #ifdef DEBUG
591 if (LLVMVerifyFunction(func, LLVMPrintMessageAction)) {
592 lp_debug_dump_value(func);
593 assert(0);
594 return;
595 }
596 #endif
597
598 gallivm_optimize_function(gallivm, func);
599
600 if (gallivm_debug & GALLIVM_DEBUG_IR) {
601 /* Print the LLVM IR to stderr */
602 lp_debug_dump_value(func);
603 debug_printf("\n");
604 }
605 }
606
607
608 void
609 gallivm_compile_module(struct gallivm_state *gallivm)
610 {
611 #if HAVE_LLVM > 0x206
612 assert(!gallivm->compiled);
613 #endif
614
615 /* Dump byte code to a file */
616 if (0) {
617 LLVMWriteBitcodeToFile(gallivm->module, "llvmpipe.bc");
618 debug_printf("llvmpipe.bc written\n");
619 debug_printf("Invoke as \"llc -o - llvmpipe.bc\"\n");
620 }
621
622 #if USE_MCJIT
623 assert(!gallivm->engine);
624 if (!init_gallivm_engine(gallivm)) {
625 assert(0);
626 }
627 #endif
628 assert(gallivm->engine);
629
630 ++gallivm->compiled;
631 }
632
633
634
635 func_pointer
636 gallivm_jit_function(struct gallivm_state *gallivm,
637 LLVMValueRef func)
638 {
639 void *code;
640 func_pointer jit_func;
641
642 assert(gallivm->compiled);
643 assert(gallivm->engine);
644
645 code = LLVMGetPointerToGlobal(gallivm->engine, func);
646 assert(code);
647 jit_func = pointer_to_func(code);
648
649 if (gallivm_debug & GALLIVM_DEBUG_ASM) {
650 lp_disassemble(func, code);
651 }
652
653 #if defined(PROFILE)
654 lp_profile(func, code);
655 #endif
656
657 /* Free the function body to save memory */
658 lp_func_delete_body(func);
659
660 return jit_func;
661 }
662
663
664 /**
665 * Free the function (and its machine code).
666 */
667 void
668 gallivm_free_function(struct gallivm_state *gallivm,
669 LLVMValueRef func,
670 const void *code)
671 {
672 #if !USE_MCJIT
673 if (code) {
674 LLVMFreeMachineCodeForFunction(gallivm->engine, func);
675 }
676
677 LLVMDeleteFunction(func);
678 #endif
679 }