draw: hack around weird primitive id input in gs
[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 "os/os_time.h"
36 #include "lp_bld.h"
37 #include "lp_bld_debug.h"
38 #include "lp_bld_misc.h"
39 #include "lp_bld_init.h"
40
41 #include <llvm-c/Analysis.h>
42 #include <llvm-c/Transforms/Scalar.h>
43 #include <llvm-c/BitWriter.h>
44
45
46 /**
47 * AVX is supported in:
48 * - standard JIT from LLVM 3.2 onwards
49 * - MC-JIT from LLVM 3.1
50 * - MC-JIT supports limited OSes (MacOSX and Linux)
51 * - standard JIT in LLVM 3.1, with backports
52 */
53 #if defined(PIPE_ARCH_PPC_64) || defined(PIPE_ARCH_S390) || defined(PIPE_ARCH_ARM) || defined(PIPE_ARCH_AARCH64)
54 # define USE_MCJIT 1
55 # define HAVE_AVX 0
56 #elif HAVE_LLVM >= 0x0302 || (HAVE_LLVM == 0x0301 && defined(HAVE_JIT_AVX_SUPPORT))
57 # define USE_MCJIT 0
58 # define HAVE_AVX 1
59 #elif HAVE_LLVM == 0x0301 && (defined(PIPE_OS_LINUX) || defined(PIPE_OS_APPLE))
60 # define USE_MCJIT 1
61 # define HAVE_AVX 1
62 #else
63 # define USE_MCJIT 0
64 # define HAVE_AVX 0
65 #endif
66
67
68 #if USE_MCJIT
69 void LLVMLinkInMCJIT();
70 #endif
71
72 /*
73 * LLVM has several global caches which pointing/derived from objects
74 * owned by the context, so if we freeing contexts causes
75 * memory leaks and false cache hits when these objects are destroyed.
76 *
77 * TODO: For thread safety on multi-threaded OpenGL we should use one LLVM
78 * context per thread, and put them in a pool when threads are destroyed.
79 */
80 #define USE_GLOBAL_CONTEXT 1
81
82
83 #ifdef DEBUG
84 unsigned gallivm_debug = 0;
85
86 static const struct debug_named_value lp_bld_debug_flags[] = {
87 { "tgsi", GALLIVM_DEBUG_TGSI, NULL },
88 { "ir", GALLIVM_DEBUG_IR, NULL },
89 { "asm", GALLIVM_DEBUG_ASM, NULL },
90 { "nopt", GALLIVM_DEBUG_NO_OPT, NULL },
91 { "perf", GALLIVM_DEBUG_PERF, NULL },
92 { "no_brilinear", GALLIVM_DEBUG_NO_BRILINEAR, NULL },
93 { "no_rho_approx", GALLIVM_DEBUG_NO_RHO_APPROX, NULL },
94 { "no_quad_lod", GALLIVM_DEBUG_NO_QUAD_LOD, NULL },
95 { "gc", GALLIVM_DEBUG_GC, NULL },
96 DEBUG_NAMED_VALUE_END
97 };
98
99 DEBUG_GET_ONCE_FLAGS_OPTION(gallivm_debug, "GALLIVM_DEBUG", lp_bld_debug_flags, 0)
100 #endif
101
102
103 static boolean gallivm_initialized = FALSE;
104
105 unsigned lp_native_vector_width;
106
107
108 /*
109 * Optimization values are:
110 * - 0: None (-O0)
111 * - 1: Less (-O1)
112 * - 2: Default (-O2, -Os)
113 * - 3: Aggressive (-O3)
114 *
115 * See also CodeGenOpt::Level in llvm/Target/TargetMachine.h
116 */
117 enum LLVM_CodeGenOpt_Level {
118 None, // -O0
119 Less, // -O1
120 Default, // -O2, -Os
121 Aggressive // -O3
122 };
123
124
125 /**
126 * Create the LLVM (optimization) pass manager and install
127 * relevant optimization passes.
128 * \return TRUE for success, FALSE for failure
129 */
130 static boolean
131 create_pass_manager(struct gallivm_state *gallivm)
132 {
133 assert(!gallivm->passmgr);
134 assert(gallivm->target);
135
136 gallivm->passmgr = LLVMCreateFunctionPassManagerForModule(gallivm->module);
137 if (!gallivm->passmgr)
138 return FALSE;
139
140 LLVMAddTargetData(gallivm->target, gallivm->passmgr);
141
142 if ((gallivm_debug & GALLIVM_DEBUG_NO_OPT) == 0) {
143 /* These are the passes currently listed in llvm-c/Transforms/Scalar.h,
144 * but there are more on SVN.
145 * TODO: Add more passes.
146 */
147 LLVMAddScalarReplAggregatesPass(gallivm->passmgr);
148 LLVMAddLICMPass(gallivm->passmgr);
149 LLVMAddCFGSimplificationPass(gallivm->passmgr);
150 LLVMAddReassociatePass(gallivm->passmgr);
151 LLVMAddPromoteMemoryToRegisterPass(gallivm->passmgr);
152 LLVMAddConstantPropagationPass(gallivm->passmgr);
153 LLVMAddInstructionCombiningPass(gallivm->passmgr);
154 LLVMAddGVNPass(gallivm->passmgr);
155 }
156 else {
157 /* We need at least this pass to prevent the backends to fail in
158 * unexpected ways.
159 */
160 LLVMAddPromoteMemoryToRegisterPass(gallivm->passmgr);
161 }
162
163 return TRUE;
164 }
165
166
167 /**
168 * Free gallivm object's LLVM allocations, but not any generated code
169 * nor the gallivm object itself.
170 */
171 void
172 gallivm_free_ir(struct gallivm_state *gallivm)
173 {
174 if (gallivm->passmgr) {
175 LLVMDisposePassManager(gallivm->passmgr);
176 }
177
178 if (gallivm->engine) {
179 /* This will already destroy any associated module */
180 LLVMDisposeExecutionEngine(gallivm->engine);
181 } else if (gallivm->module) {
182 LLVMDisposeModule(gallivm->module);
183 }
184
185 #if !USE_MCJIT
186 /* Don't free the TargetData, it's owned by the exec engine */
187 #else
188 if (gallivm->target) {
189 LLVMDisposeTargetData(gallivm->target);
190 }
191 #endif
192
193 if (gallivm->builder)
194 LLVMDisposeBuilder(gallivm->builder);
195
196 if (!USE_GLOBAL_CONTEXT && gallivm->context)
197 LLVMContextDispose(gallivm->context);
198
199 gallivm->engine = NULL;
200 gallivm->target = NULL;
201 gallivm->module = NULL;
202 gallivm->passmgr = NULL;
203 gallivm->context = NULL;
204 gallivm->builder = NULL;
205 }
206
207
208 /**
209 * Free LLVM-generated code. Should be done AFTER gallivm_free_ir().
210 */
211 static void
212 gallivm_free_code(struct gallivm_state *gallivm)
213 {
214 assert(!gallivm->module);
215 assert(!gallivm->engine);
216 lp_free_generated_code(gallivm->code);
217 gallivm->code = NULL;
218 }
219
220
221 static boolean
222 init_gallivm_engine(struct gallivm_state *gallivm)
223 {
224 if (1) {
225 enum LLVM_CodeGenOpt_Level optlevel;
226 char *error = NULL;
227 int ret;
228
229 if (gallivm_debug & GALLIVM_DEBUG_NO_OPT) {
230 optlevel = None;
231 }
232 else {
233 optlevel = Default;
234 }
235
236 ret = lp_build_create_jit_compiler_for_module(&gallivm->engine,
237 &gallivm->code,
238 gallivm->module,
239 (unsigned) optlevel,
240 USE_MCJIT,
241 &error);
242 if (ret) {
243 _debug_printf("%s\n", error);
244 LLVMDisposeMessage(error);
245 goto fail;
246 }
247 }
248
249 #if !USE_MCJIT
250 gallivm->target = LLVMGetExecutionEngineTargetData(gallivm->engine);
251 if (!gallivm->target)
252 goto fail;
253 #else
254 if (0) {
255 /*
256 * Dump the data layout strings.
257 */
258
259 LLVMTargetDataRef target = LLVMGetExecutionEngineTargetData(gallivm->engine);
260 char *data_layout;
261 char *engine_data_layout;
262
263 data_layout = LLVMCopyStringRepOfTargetData(gallivm->target);
264 engine_data_layout = LLVMCopyStringRepOfTargetData(target);
265
266 if (1) {
267 debug_printf("module target data = %s\n", data_layout);
268 debug_printf("engine target data = %s\n", engine_data_layout);
269 }
270
271 free(data_layout);
272 free(engine_data_layout);
273 }
274 #endif
275
276 return TRUE;
277
278 fail:
279 return FALSE;
280 }
281
282
283 /**
284 * Allocate gallivm LLVM objects.
285 * \return TRUE for success, FALSE for failure
286 */
287 static boolean
288 init_gallivm_state(struct gallivm_state *gallivm, const char *name)
289 {
290 assert(!gallivm->context);
291 assert(!gallivm->module);
292
293 lp_build_init();
294
295 if (USE_GLOBAL_CONTEXT) {
296 gallivm->context = LLVMGetGlobalContext();
297 } else {
298 gallivm->context = LLVMContextCreate();
299 }
300 if (!gallivm->context)
301 goto fail;
302
303 gallivm->module = LLVMModuleCreateWithNameInContext(name,
304 gallivm->context);
305 if (!gallivm->module)
306 goto fail;
307
308 gallivm->builder = LLVMCreateBuilderInContext(gallivm->context);
309 if (!gallivm->builder)
310 goto fail;
311
312 /* FIXME: MC-JIT only allows compiling one module at a time, and it must be
313 * complete when MC-JIT is created. So defer the MC-JIT engine creation for
314 * now.
315 */
316 #if !USE_MCJIT
317 if (!init_gallivm_engine(gallivm)) {
318 goto fail;
319 }
320 #else
321 /*
322 * MC-JIT engine compiles the module immediately on creation, so we can't
323 * obtain the target data from it. Instead we create a target data layout
324 * from a string.
325 *
326 * The produced layout strings are not precisely the same, but should make
327 * no difference for the kind of optimization passes we run.
328 *
329 * For reference this is the layout string on x64:
330 *
331 * 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
332 *
333 * See also:
334 * - http://llvm.org/docs/LangRef.html#datalayout
335 */
336
337 {
338 const unsigned pointer_size = 8 * sizeof(void *);
339 char layout[512];
340 util_snprintf(layout, sizeof layout, "%c-p:%u:%u:%u-i64:64:64-a0:0:%u-s0:%u:%u",
341 #ifdef PIPE_ARCH_LITTLE_ENDIAN
342 'e', // little endian
343 #else
344 'E', // big endian
345 #endif
346 pointer_size, pointer_size, pointer_size, // pointer size, abi alignment, preferred alignment
347 pointer_size, // aggregate preferred alignment
348 pointer_size, pointer_size); // stack objects abi alignment, preferred alignment
349
350 gallivm->target = LLVMCreateTargetData(layout);
351 if (!gallivm->target) {
352 return FALSE;
353 }
354 }
355 #endif
356
357 if (!create_pass_manager(gallivm))
358 goto fail;
359
360 return TRUE;
361
362 fail:
363 gallivm_free_ir(gallivm);
364 gallivm_free_code(gallivm);
365 return FALSE;
366 }
367
368
369 void
370 lp_build_init(void)
371 {
372 if (gallivm_initialized)
373 return;
374
375 #ifdef DEBUG
376 gallivm_debug = debug_get_option_gallivm_debug();
377 #endif
378
379 lp_set_target_options();
380
381 #if USE_MCJIT
382 LLVMLinkInMCJIT();
383 #else
384 LLVMLinkInJIT();
385 #endif
386
387 util_cpu_detect();
388
389 /* AMD Bulldozer AVX's throughput is the same as SSE2; and because using
390 * 8-wide vector needs more floating ops than 4-wide (due to padding), it is
391 * actually more efficient to use 4-wide vectors on this processor.
392 *
393 * See also:
394 * - http://www.anandtech.com/show/4955/the-bulldozer-review-amd-fx8150-tested/2
395 */
396 if (HAVE_AVX &&
397 util_cpu_caps.has_avx &&
398 util_cpu_caps.has_intel) {
399 lp_native_vector_width = 256;
400 } else {
401 /* Leave it at 128, even when no SIMD extensions are available.
402 * Really needs to be a multiple of 128 so can fit 4 floats.
403 */
404 lp_native_vector_width = 128;
405 }
406
407 lp_native_vector_width = debug_get_num_option("LP_NATIVE_VECTOR_WIDTH",
408 lp_native_vector_width);
409
410 if (lp_native_vector_width <= 128) {
411 /* Hide AVX support, as often LLVM AVX intrinsics are only guarded by
412 * "util_cpu_caps.has_avx" predicate, and lack the
413 * "lp_native_vector_width > 128" predicate. And also to ensure a more
414 * consistent behavior, allowing one to test SSE2 on AVX machines.
415 * XXX: should not play games with util_cpu_caps directly as it might
416 * get used for other things outside llvm too.
417 */
418 util_cpu_caps.has_avx = 0;
419 util_cpu_caps.has_avx2 = 0;
420 }
421
422 if (!HAVE_AVX) {
423 /*
424 * note these instructions are VEX-only, so can only emit if we use
425 * avx (don't want to base it on has_avx & has_f16c later as that would
426 * omit it unnecessarily on amd cpus, see above).
427 */
428 util_cpu_caps.has_f16c = 0;
429 util_cpu_caps.has_xop = 0;
430 }
431
432 #ifdef PIPE_ARCH_PPC_64
433 /* Set the NJ bit in VSCR to 0 so denormalized values are handled as
434 * specified by IEEE standard (PowerISA 2.06 - Section 6.3). This guarantees
435 * that some rounding and half-float to float handling does not round
436 * incorrectly to 0.
437 * XXX: should eventually follow same logic on all platforms.
438 * Right now denorms get explicitly disabled (but elsewhere) for x86,
439 * whereas ppc64 explicitly enables them...
440 */
441 if (util_cpu_caps.has_altivec) {
442 unsigned short mask[] = { 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF,
443 0xFFFF, 0xFFFF, 0xFFFE, 0xFFFF };
444 __asm (
445 "mfvscr %%v1\n"
446 "vand %0,%%v1,%0\n"
447 "mtvscr %0"
448 :
449 : "r" (*mask)
450 );
451 }
452 #endif
453
454 gallivm_initialized = TRUE;
455
456 #if 0
457 /* For simulating less capable machines */
458 util_cpu_caps.has_sse3 = 0;
459 util_cpu_caps.has_ssse3 = 0;
460 util_cpu_caps.has_sse4_1 = 0;
461 util_cpu_caps.has_avx = 0;
462 util_cpu_caps.has_f16c = 0;
463 #endif
464 }
465
466
467
468 /**
469 * Create a new gallivm_state object.
470 */
471 struct gallivm_state *
472 gallivm_create(const char *name)
473 {
474 struct gallivm_state *gallivm;
475
476 gallivm = CALLOC_STRUCT(gallivm_state);
477 if (gallivm) {
478 if (!init_gallivm_state(gallivm, name)) {
479 FREE(gallivm);
480 gallivm = NULL;
481 }
482 }
483
484 return gallivm;
485 }
486
487
488 /**
489 * Destroy a gallivm_state object.
490 */
491 void
492 gallivm_destroy(struct gallivm_state *gallivm)
493 {
494 gallivm_free_ir(gallivm);
495 gallivm_free_code(gallivm);
496 FREE(gallivm);
497 }
498
499
500 /**
501 * Validate a function.
502 * Verification is only done with debug builds.
503 */
504 void
505 gallivm_verify_function(struct gallivm_state *gallivm,
506 LLVMValueRef func)
507 {
508 /* Verify the LLVM IR. If invalid, dump and abort */
509 #ifdef DEBUG
510 if (LLVMVerifyFunction(func, LLVMPrintMessageAction)) {
511 lp_debug_dump_value(func);
512 assert(0);
513 return;
514 }
515 #endif
516
517 if (gallivm_debug & GALLIVM_DEBUG_IR) {
518 /* Print the LLVM IR to stderr */
519 lp_debug_dump_value(func);
520 debug_printf("\n");
521 }
522 }
523
524
525 /**
526 * Compile a module.
527 * This does IR optimization on all functions in the module.
528 */
529 void
530 gallivm_compile_module(struct gallivm_state *gallivm)
531 {
532 LLVMValueRef func;
533 int64_t time_begin;
534
535 assert(!gallivm->compiled);
536
537 if (gallivm->builder) {
538 LLVMDisposeBuilder(gallivm->builder);
539 gallivm->builder = NULL;
540 }
541
542 if (gallivm_debug & GALLIVM_DEBUG_PERF)
543 time_begin = os_time_get();
544
545 /* Run optimization passes */
546 LLVMInitializeFunctionPassManager(gallivm->passmgr);
547 func = LLVMGetFirstFunction(gallivm->module);
548 while (func) {
549 if (0) {
550 debug_printf("optimizing func %s...\n", LLVMGetValueName(func));
551 }
552 LLVMRunFunctionPassManager(gallivm->passmgr, func);
553 func = LLVMGetNextFunction(func);
554 }
555 LLVMFinalizeFunctionPassManager(gallivm->passmgr);
556
557 if (gallivm_debug & GALLIVM_DEBUG_PERF) {
558 int64_t time_end = os_time_get();
559 int time_msec = (int)(time_end - time_begin) / 1000;
560 debug_printf("optimizing module %s took %d msec\n",
561 lp_get_module_id(gallivm->module), time_msec);
562 }
563
564 /* Dump byte code to a file */
565 if (0) {
566 LLVMWriteBitcodeToFile(gallivm->module, "llvmpipe.bc");
567 debug_printf("llvmpipe.bc written\n");
568 debug_printf("Invoke as \"llc -o - llvmpipe.bc\"\n");
569 }
570
571 #if USE_MCJIT
572 assert(!gallivm->engine);
573 if (!init_gallivm_engine(gallivm)) {
574 assert(0);
575 }
576 #endif
577 assert(gallivm->engine);
578
579 ++gallivm->compiled;
580 }
581
582
583
584 func_pointer
585 gallivm_jit_function(struct gallivm_state *gallivm,
586 LLVMValueRef func)
587 {
588 void *code;
589 func_pointer jit_func;
590
591 assert(gallivm->compiled);
592 assert(gallivm->engine);
593
594 code = LLVMGetPointerToGlobal(gallivm->engine, func);
595 assert(code);
596 jit_func = pointer_to_func(code);
597
598 if (gallivm_debug & GALLIVM_DEBUG_ASM) {
599 lp_disassemble(func, code);
600 }
601
602 #if defined(PROFILE)
603 lp_profile(func, code);
604 #endif
605
606 return jit_func;
607 }