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