Introduce .editorconfig
[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/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 /* Only MCJIT is available as of LLVM SVN r216982 */
47 #if HAVE_LLVM >= 0x0306
48 # define USE_MCJIT 1
49 #elif defined(PIPE_ARCH_PPC_64) || defined(PIPE_ARCH_S390) || defined(PIPE_ARCH_ARM) || defined(PIPE_ARCH_AARCH64)
50 # define USE_MCJIT 1
51 #else
52 static bool USE_MCJIT = 0;
53 #endif
54
55
56 #ifdef DEBUG
57 unsigned gallivm_debug = 0;
58
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 },
70 DEBUG_NAMED_VALUE_END
71 };
72
73 DEBUG_GET_ONCE_FLAGS_OPTION(gallivm_debug, "GALLIVM_DEBUG", lp_bld_debug_flags, 0)
74 #endif
75
76
77 static boolean gallivm_initialized = FALSE;
78
79 unsigned lp_native_vector_width;
80
81
82 /*
83 * Optimization values are:
84 * - 0: None (-O0)
85 * - 1: Less (-O1)
86 * - 2: Default (-O2, -Os)
87 * - 3: Aggressive (-O3)
88 *
89 * See also CodeGenOpt::Level in llvm/Target/TargetMachine.h
90 */
91 enum LLVM_CodeGenOpt_Level {
92 None, // -O0
93 Less, // -O1
94 Default, // -O2, -Os
95 Aggressive // -O3
96 };
97
98
99 /**
100 * Create the LLVM (optimization) pass manager and install
101 * relevant optimization passes.
102 * \return TRUE for success, FALSE for failure
103 */
104 static boolean
105 create_pass_manager(struct gallivm_state *gallivm)
106 {
107 assert(!gallivm->passmgr);
108 assert(gallivm->target);
109
110 gallivm->passmgr = LLVMCreateFunctionPassManagerForModule(gallivm->module);
111 if (!gallivm->passmgr)
112 return FALSE;
113 /*
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.
117 */
118
119 #if HAVE_LLVM < 0x0309
120 // Old versions of LLVM get the DataLayout from the pass manager.
121 LLVMAddTargetData(gallivm->target, gallivm->passmgr);
122 #endif
123
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.
128 *
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()
134 */
135
136 #if HAVE_LLVM < 0x0308
137 {
138 char *td_str;
139 // New ones from the Module.
140 td_str = LLVMCopyStringRepOfTargetData(gallivm->target);
141 LLVMSetDataLayout(gallivm->module, td_str);
142 free(td_str);
143 }
144 #else
145 LLVMSetDataLayout(gallivm->module, "");
146 #endif
147
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.
152 */
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);
161 }
162 else {
163 /* We need at least this pass to prevent the backends to fail in
164 * unexpected ways.
165 */
166 LLVMAddPromoteMemoryToRegisterPass(gallivm->passmgr);
167 }
168
169 return TRUE;
170 }
171
172
173 /**
174 * Free gallivm object's LLVM allocations, but not any generated code
175 * nor the gallivm object itself.
176 */
177 void
178 gallivm_free_ir(struct gallivm_state *gallivm)
179 {
180 if (gallivm->passmgr) {
181 LLVMDisposePassManager(gallivm->passmgr);
182 }
183
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);
189 }
190
191 FREE(gallivm->module_name);
192
193 if (!USE_MCJIT) {
194 /* Don't free the TargetData, it's owned by the exec engine */
195 } else {
196 if (gallivm->target) {
197 LLVMDisposeTargetData(gallivm->target);
198 }
199 }
200
201 if (gallivm->builder)
202 LLVMDisposeBuilder(gallivm->builder);
203
204 /* The LLVMContext should be owned by the parent of gallivm. */
205
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;
213 }
214
215
216 /**
217 * Free LLVM-generated code. Should be done AFTER gallivm_free_ir().
218 */
219 static void
220 gallivm_free_code(struct gallivm_state *gallivm)
221 {
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;
228 }
229
230
231 static boolean
232 init_gallivm_engine(struct gallivm_state *gallivm)
233 {
234 if (1) {
235 enum LLVM_CodeGenOpt_Level optlevel;
236 char *error = NULL;
237 int ret;
238
239 if (gallivm_debug & GALLIVM_DEBUG_NO_OPT) {
240 optlevel = None;
241 }
242 else {
243 optlevel = Default;
244 }
245
246 ret = lp_build_create_jit_compiler_for_module(&gallivm->engine,
247 &gallivm->code,
248 gallivm->module,
249 gallivm->memorymgr,
250 (unsigned) optlevel,
251 USE_MCJIT,
252 &error);
253 if (ret) {
254 _debug_printf("%s\n", error);
255 LLVMDisposeMessage(error);
256 goto fail;
257 }
258 }
259
260 if (!USE_MCJIT) {
261 gallivm->target = LLVMGetExecutionEngineTargetData(gallivm->engine);
262 if (!gallivm->target)
263 goto fail;
264 } else {
265 if (0) {
266 /*
267 * Dump the data layout strings.
268 */
269
270 LLVMTargetDataRef target = LLVMGetExecutionEngineTargetData(gallivm->engine);
271 char *data_layout;
272 char *engine_data_layout;
273
274 data_layout = LLVMCopyStringRepOfTargetData(gallivm->target);
275 engine_data_layout = LLVMCopyStringRepOfTargetData(target);
276
277 if (1) {
278 debug_printf("module target data = %s\n", data_layout);
279 debug_printf("engine target data = %s\n", engine_data_layout);
280 }
281
282 free(data_layout);
283 free(engine_data_layout);
284 }
285 }
286
287 return TRUE;
288
289 fail:
290 return FALSE;
291 }
292
293
294 /**
295 * Allocate gallivm LLVM objects.
296 * \return TRUE for success, FALSE for failure
297 */
298 static boolean
299 init_gallivm_state(struct gallivm_state *gallivm, const char *name,
300 LLVMContextRef context)
301 {
302 assert(!gallivm->context);
303 assert(!gallivm->module);
304
305 if (!lp_build_init())
306 return FALSE;
307
308 gallivm->context = context;
309
310 if (!gallivm->context)
311 goto fail;
312
313 gallivm->module_name = NULL;
314 if (name) {
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);
319 }
320 }
321
322 gallivm->module = LLVMModuleCreateWithNameInContext(name,
323 gallivm->context);
324 if (!gallivm->module)
325 goto fail;
326
327 gallivm->builder = LLVMCreateBuilderInContext(gallivm->context);
328 if (!gallivm->builder)
329 goto fail;
330
331 gallivm->memorymgr = lp_get_default_memory_manager();
332 if (!gallivm->memorymgr)
333 goto fail;
334
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
337 * now.
338 */
339 if (!USE_MCJIT) {
340 if (!init_gallivm_engine(gallivm)) {
341 goto fail;
342 }
343 } else {
344 /*
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
347 * from a string.
348 *
349 * The produced layout strings are not precisely the same, but should make
350 * no difference for the kind of optimization passes we run.
351 *
352 * For reference this is the layout string on x64:
353 *
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
355 *
356 * See also:
357 * - http://llvm.org/docs/LangRef.html#datalayout
358 */
359
360 {
361 const unsigned pointer_size = 8 * sizeof(void *);
362 char layout[512];
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
366 #else
367 'E', // big endian
368 #endif
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
372
373 gallivm->target = LLVMCreateTargetData(layout);
374 if (!gallivm->target) {
375 return FALSE;
376 }
377 }
378 }
379
380 if (!create_pass_manager(gallivm))
381 goto fail;
382
383 return TRUE;
384
385 fail:
386 gallivm_free_ir(gallivm);
387 gallivm_free_code(gallivm);
388 return FALSE;
389 }
390
391
392 boolean
393 lp_build_init(void)
394 {
395 if (gallivm_initialized)
396 return TRUE;
397
398 LLVMLinkInMCJIT();
399 #if !defined(USE_MCJIT)
400 USE_MCJIT = debug_get_bool_option("GALLIVM_MCJIT", 0);
401 LLVMLinkInJIT();
402 #endif
403
404 #ifdef DEBUG
405 gallivm_debug = debug_get_option_gallivm_debug();
406 #endif
407
408 lp_set_target_options();
409
410 util_cpu_detect();
411
412 /* For simulating less capable machines */
413 #ifdef DEBUG
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;
423 util_cpu_caps.has_fma = 0;
424 }
425 #endif
426
427 /* AMD Bulldozer AVX's throughput is the same as SSE2; and because using
428 * 8-wide vector needs more floating ops than 4-wide (due to padding), it is
429 * actually more efficient to use 4-wide vectors on this processor.
430 *
431 * See also:
432 * - http://www.anandtech.com/show/4955/the-bulldozer-review-amd-fx8150-tested/2
433 */
434 if (util_cpu_caps.has_avx &&
435 util_cpu_caps.has_intel) {
436 lp_native_vector_width = 256;
437 } else {
438 /* Leave it at 128, even when no SIMD extensions are available.
439 * Really needs to be a multiple of 128 so can fit 4 floats.
440 */
441 lp_native_vector_width = 128;
442 }
443
444 lp_native_vector_width = debug_get_num_option("LP_NATIVE_VECTOR_WIDTH",
445 lp_native_vector_width);
446
447 if (lp_native_vector_width <= 128) {
448 /* Hide AVX support, as often LLVM AVX intrinsics are only guarded by
449 * "util_cpu_caps.has_avx" predicate, and lack the
450 * "lp_native_vector_width > 128" predicate. And also to ensure a more
451 * consistent behavior, allowing one to test SSE2 on AVX machines.
452 * XXX: should not play games with util_cpu_caps directly as it might
453 * get used for other things outside llvm too.
454 */
455 util_cpu_caps.has_avx = 0;
456 util_cpu_caps.has_avx2 = 0;
457 util_cpu_caps.has_f16c = 0;
458 util_cpu_caps.has_fma = 0;
459 }
460
461 #ifdef PIPE_ARCH_PPC_64
462 /* Set the NJ bit in VSCR to 0 so denormalized values are handled as
463 * specified by IEEE standard (PowerISA 2.06 - Section 6.3). This guarantees
464 * that some rounding and half-float to float handling does not round
465 * incorrectly to 0.
466 * XXX: should eventually follow same logic on all platforms.
467 * Right now denorms get explicitly disabled (but elsewhere) for x86,
468 * whereas ppc64 explicitly enables them...
469 */
470 if (util_cpu_caps.has_altivec) {
471 unsigned short mask[] = { 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF,
472 0xFFFF, 0xFFFF, 0xFFFE, 0xFFFF };
473 __asm (
474 "mfvscr %%v1\n"
475 "vand %0,%%v1,%0\n"
476 "mtvscr %0"
477 :
478 : "r" (*mask)
479 );
480 }
481 #endif
482
483 gallivm_initialized = TRUE;
484
485 return TRUE;
486 }
487
488
489
490 /**
491 * Create a new gallivm_state object.
492 */
493 struct gallivm_state *
494 gallivm_create(const char *name, LLVMContextRef context)
495 {
496 struct gallivm_state *gallivm;
497
498 gallivm = CALLOC_STRUCT(gallivm_state);
499 if (gallivm) {
500 if (!init_gallivm_state(gallivm, name, context)) {
501 FREE(gallivm);
502 gallivm = NULL;
503 }
504 }
505
506 return gallivm;
507 }
508
509
510 /**
511 * Destroy a gallivm_state object.
512 */
513 void
514 gallivm_destroy(struct gallivm_state *gallivm)
515 {
516 gallivm_free_ir(gallivm);
517 gallivm_free_code(gallivm);
518 FREE(gallivm);
519 }
520
521
522 /**
523 * Validate a function.
524 * Verification is only done with debug builds.
525 */
526 void
527 gallivm_verify_function(struct gallivm_state *gallivm,
528 LLVMValueRef func)
529 {
530 /* Verify the LLVM IR. If invalid, dump and abort */
531 #ifdef DEBUG
532 if (LLVMVerifyFunction(func, LLVMPrintMessageAction)) {
533 lp_debug_dump_value(func);
534 assert(0);
535 return;
536 }
537 #endif
538
539 if (gallivm_debug & GALLIVM_DEBUG_IR) {
540 /* Print the LLVM IR to stderr */
541 lp_debug_dump_value(func);
542 debug_printf("\n");
543 }
544 }
545
546
547 /**
548 * Compile a module.
549 * This does IR optimization on all functions in the module.
550 */
551 void
552 gallivm_compile_module(struct gallivm_state *gallivm)
553 {
554 LLVMValueRef func;
555 int64_t time_begin = 0;
556
557 assert(!gallivm->compiled);
558
559 if (gallivm->builder) {
560 LLVMDisposeBuilder(gallivm->builder);
561 gallivm->builder = NULL;
562 }
563
564 if (gallivm_debug & GALLIVM_DEBUG_PERF)
565 time_begin = os_time_get();
566
567 /* Run optimization passes */
568 LLVMInitializeFunctionPassManager(gallivm->passmgr);
569 func = LLVMGetFirstFunction(gallivm->module);
570 while (func) {
571 if (0) {
572 debug_printf("optimizing func %s...\n", LLVMGetValueName(func));
573 }
574
575 /* Disable frame pointer omission on debug/profile builds */
576 /* XXX: And workaround http://llvm.org/PR21435 */
577 #if HAVE_LLVM >= 0x0307 && \
578 (defined(DEBUG) || defined(PROFILE) || \
579 defined(PIPE_ARCH_X86) || defined(PIPE_ARCH_X86_64))
580 LLVMAddTargetDependentFunctionAttr(func, "no-frame-pointer-elim", "true");
581 LLVMAddTargetDependentFunctionAttr(func, "no-frame-pointer-elim-non-leaf", "true");
582 #endif
583
584 LLVMRunFunctionPassManager(gallivm->passmgr, func);
585 func = LLVMGetNextFunction(func);
586 }
587 LLVMFinalizeFunctionPassManager(gallivm->passmgr);
588
589 if (gallivm_debug & GALLIVM_DEBUG_PERF) {
590 int64_t time_end = os_time_get();
591 int time_msec = (int)(time_end - time_begin) / 1000;
592 assert(gallivm->module_name);
593 debug_printf("optimizing module %s took %d msec\n",
594 gallivm->module_name, time_msec);
595 }
596
597 /* Dump byte code to a file */
598 if (gallivm_debug & GALLIVM_DEBUG_DUMP_BC) {
599 char filename[256];
600 assert(gallivm->module_name);
601 util_snprintf(filename, sizeof(filename), "ir_%s.bc", gallivm->module_name);
602 LLVMWriteBitcodeToFile(gallivm->module, filename);
603 debug_printf("%s written\n", filename);
604 debug_printf("Invoke as \"llc -o - %s\"\n", filename);
605 }
606
607 if (USE_MCJIT) {
608 assert(!gallivm->engine);
609 if (!init_gallivm_engine(gallivm)) {
610 assert(0);
611 }
612 }
613 assert(gallivm->engine);
614
615 ++gallivm->compiled;
616
617 if (gallivm_debug & GALLIVM_DEBUG_ASM) {
618 LLVMValueRef llvm_func = LLVMGetFirstFunction(gallivm->module);
619
620 while (llvm_func) {
621 /*
622 * Need to filter out functions which don't have an implementation,
623 * such as the intrinsics. May not be sufficient in case of IPO?
624 * LLVMGetPointerToGlobal() will abort otherwise.
625 */
626 if (!LLVMIsDeclaration(llvm_func)) {
627 void *func_code = LLVMGetPointerToGlobal(gallivm->engine, llvm_func);
628 lp_disassemble(llvm_func, func_code);
629 }
630 llvm_func = LLVMGetNextFunction(llvm_func);
631 }
632 }
633
634 #if defined(PROFILE)
635 {
636 LLVMValueRef llvm_func = LLVMGetFirstFunction(gallivm->module);
637
638 while (llvm_func) {
639 if (!LLVMIsDeclaration(llvm_func)) {
640 void *func_code = LLVMGetPointerToGlobal(gallivm->engine, llvm_func);
641 lp_profile(llvm_func, func_code);
642 }
643 llvm_func = LLVMGetNextFunction(llvm_func);
644 }
645 }
646 #endif
647 }
648
649
650
651 func_pointer
652 gallivm_jit_function(struct gallivm_state *gallivm,
653 LLVMValueRef func)
654 {
655 void *code;
656 func_pointer jit_func;
657
658 assert(gallivm->compiled);
659 assert(gallivm->engine);
660
661 code = LLVMGetPointerToGlobal(gallivm->engine, func);
662 assert(code);
663 jit_func = pointer_to_func(code);
664
665 return jit_func;
666 }