gallivm: Use mcjit for ppc_64 architecture
[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 USE_MCJIT
262 ret = lp_build_create_mcjit_compiler_for_module(&gallivm->engine,
263 gallivm->module,
264 (unsigned) optlevel,
265 &error);
266 #else
267 ret = LLVMCreateJITCompiler(&gallivm->engine, gallivm->provider,
268 (unsigned) optlevel, &error);
269 #endif
270 if (ret) {
271 _debug_printf("%s\n", error);
272 LLVMDisposeMessage(error);
273 goto fail;
274 }
275
276 #if defined(DEBUG) || defined(PROFILE)
277 lp_register_oprofile_jit_event_listener(gallivm->engine);
278 #endif
279 }
280
281 LLVMAddModuleProvider(gallivm->engine, gallivm->provider);//new
282
283 #if !USE_MCJIT
284 gallivm->target = LLVMGetExecutionEngineTargetData(gallivm->engine);
285 if (!gallivm->target)
286 goto fail;
287 #else
288 if (0) {
289 /*
290 * Dump the data layout strings.
291 */
292
293 LLVMTargetDataRef target = LLVMGetExecutionEngineTargetData(gallivm->engine);
294 char *data_layout;
295 char *engine_data_layout;
296
297 data_layout = LLVMCopyStringRepOfTargetData(gallivm->target);
298 engine_data_layout = LLVMCopyStringRepOfTargetData(target);
299
300 if (1) {
301 debug_printf("module target data = %s\n", data_layout);
302 debug_printf("engine target data = %s\n", engine_data_layout);
303 }
304
305 free(data_layout);
306 free(engine_data_layout);
307 }
308 #endif
309
310 return TRUE;
311
312 fail:
313 return FALSE;
314 }
315
316
317 /**
318 * Singleton
319 *
320 * We must never free LLVM contexts, because LLVM has several global caches
321 * which pointing/derived from objects owned by the context, causing false
322 * memory leaks and false cache hits when these objects are destroyed.
323 *
324 * TODO: For thread safety on multi-threaded OpenGL we should use one LLVM
325 * context per thread, and put them in a pool when threads are destroyed.
326 */
327 static LLVMContextRef gallivm_context = NULL;
328
329
330 /**
331 * Allocate gallivm LLVM objects.
332 * \return TRUE for success, FALSE for failure
333 */
334 static boolean
335 init_gallivm_state(struct gallivm_state *gallivm)
336 {
337 assert(!gallivm->context);
338 assert(!gallivm->module);
339 assert(!gallivm->provider);
340
341 lp_build_init();
342
343 if (!gallivm_context) {
344 gallivm_context = LLVMContextCreate();
345 }
346 gallivm->context = gallivm_context;
347 if (!gallivm->context)
348 goto fail;
349
350 gallivm->module = LLVMModuleCreateWithNameInContext("gallivm",
351 gallivm->context);
352 if (!gallivm->module)
353 goto fail;
354
355 gallivm->provider =
356 LLVMCreateModuleProviderForExistingModule(gallivm->module);
357 if (!gallivm->provider)
358 goto fail;
359
360 gallivm->builder = LLVMCreateBuilderInContext(gallivm->context);
361 if (!gallivm->builder)
362 goto fail;
363
364 /* FIXME: MC-JIT only allows compiling one module at a time, and it must be
365 * complete when MC-JIT is created. So defer the MC-JIT engine creation for
366 * now.
367 */
368 #if !USE_MCJIT
369 if (!init_gallivm_engine(gallivm)) {
370 goto fail;
371 }
372 #else
373 /*
374 * MC-JIT engine compiles the module immediately on creation, so we can't
375 * obtain the target data from it. Instead we create a target data layout
376 * from a string.
377 *
378 * The produced layout strings are not precisely the same, but should make
379 * no difference for the kind of optimization passes we run.
380 *
381 * For reference this is the layout string on x64:
382 *
383 * 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
384 *
385 * See also:
386 * - http://llvm.org/docs/LangRef.html#datalayout
387 */
388
389 {
390 const unsigned pointer_size = 8 * sizeof(void *);
391 char layout[512];
392 util_snprintf(layout, sizeof layout, "%c-p:%u:%u:%u-i64:64:64-a0:0:%u-s0:%u:%u",
393 #ifdef PIPE_ARCH_LITTLE_ENDIAN
394 'e', // little endian
395 #else
396 'E', // big endian
397 #endif
398 pointer_size, pointer_size, pointer_size, // pointer size, abi alignment, preferred alignment
399 pointer_size, // aggregate preferred alignment
400 pointer_size, pointer_size); // stack objects abi alignment, preferred alignment
401
402 gallivm->target = LLVMCreateTargetData(layout);
403 if (!gallivm->target) {
404 return FALSE;
405 }
406 }
407 #endif
408
409 if (!create_pass_manager(gallivm))
410 goto fail;
411
412 return TRUE;
413
414 fail:
415 free_gallivm_state(gallivm);
416 return FALSE;
417 }
418
419
420 void
421 lp_build_init(void)
422 {
423 if (gallivm_initialized)
424 return;
425
426 #ifdef DEBUG
427 gallivm_debug = debug_get_option_gallivm_debug();
428 #endif
429
430 lp_set_target_options();
431
432 #if USE_MCJIT
433 LLVMLinkInMCJIT();
434 #else
435 LLVMLinkInJIT();
436 #endif
437
438 util_cpu_detect();
439
440 /* AMD Bulldozer AVX's throughput is the same as SSE2; and because using
441 * 8-wide vector needs more floating ops than 4-wide (due to padding), it is
442 * actually more efficient to use 4-wide vectors on this processor.
443 *
444 * See also:
445 * - http://www.anandtech.com/show/4955/the-bulldozer-review-amd-fx8150-tested/2
446 */
447 if (HAVE_AVX &&
448 util_cpu_caps.has_avx &&
449 util_cpu_caps.has_intel) {
450 lp_native_vector_width = 256;
451 } else {
452 /* Leave it at 128, even when no SIMD extensions are available.
453 * Really needs to be a multiple of 128 so can fit 4 floats.
454 */
455 lp_native_vector_width = 128;
456 }
457
458 lp_native_vector_width = debug_get_num_option("LP_NATIVE_VECTOR_WIDTH",
459 lp_native_vector_width);
460
461 gallivm_initialized = TRUE;
462
463 #if 0
464 /* For simulating less capable machines */
465 util_cpu_caps.has_sse3 = 0;
466 util_cpu_caps.has_ssse3 = 0;
467 util_cpu_caps.has_sse4_1 = 0;
468 #endif
469 }
470
471
472
473 /**
474 * Create a new gallivm_state object.
475 * Note that we return a singleton.
476 */
477 struct gallivm_state *
478 gallivm_create(void)
479 {
480 struct gallivm_state *gallivm;
481
482 #if HAVE_LLVM <= 0x206
483 if (GlobalGallivm) {
484 return GlobalGallivm;
485 }
486 #endif
487
488 gallivm = CALLOC_STRUCT(gallivm_state);
489 if (gallivm) {
490 if (!init_gallivm_state(gallivm)) {
491 FREE(gallivm);
492 gallivm = NULL;
493 }
494 }
495
496 #if HAVE_LLVM <= 0x206
497 GlobalGallivm = gallivm;
498 #endif
499
500 return gallivm;
501 }
502
503
504 /**
505 * Destroy a gallivm_state object.
506 */
507 void
508 gallivm_destroy(struct gallivm_state *gallivm)
509 {
510 #if HAVE_LLVM <= 0x0206
511 /* No-op: don't destroy the singleton */
512 (void) gallivm;
513 #else
514 free_gallivm_state(gallivm);
515 FREE(gallivm);
516 #endif
517 }
518
519
520 /**
521 * Validate and optimze a function.
522 */
523 static void
524 gallivm_optimize_function(struct gallivm_state *gallivm,
525 LLVMValueRef func)
526 {
527 if (0) {
528 debug_printf("optimizing %s...\n", LLVMGetValueName(func));
529 }
530
531 assert(gallivm->passmgr);
532
533 /* Apply optimizations to LLVM IR */
534 LLVMRunFunctionPassManager(gallivm->passmgr, func);
535
536 if (0) {
537 if (gallivm_debug & GALLIVM_DEBUG_IR) {
538 /* Print the LLVM IR to stderr */
539 lp_debug_dump_value(func);
540 debug_printf("\n");
541 }
542 }
543 }
544
545
546 /**
547 * Validate a function.
548 */
549 void
550 gallivm_verify_function(struct gallivm_state *gallivm,
551 LLVMValueRef func)
552 {
553 /* Verify the LLVM IR. If invalid, dump and abort */
554 #ifdef DEBUG
555 if (LLVMVerifyFunction(func, LLVMPrintMessageAction)) {
556 lp_debug_dump_value(func);
557 assert(0);
558 return;
559 }
560 #endif
561
562 gallivm_optimize_function(gallivm, func);
563
564 if (gallivm_debug & GALLIVM_DEBUG_IR) {
565 /* Print the LLVM IR to stderr */
566 lp_debug_dump_value(func);
567 debug_printf("\n");
568 }
569 }
570
571
572 void
573 gallivm_compile_module(struct gallivm_state *gallivm)
574 {
575 #if HAVE_LLVM > 0x206
576 assert(!gallivm->compiled);
577 #endif
578
579 /* Dump byte code to a file */
580 if (0) {
581 LLVMWriteBitcodeToFile(gallivm->module, "llvmpipe.bc");
582 debug_printf("llvmpipe.bc written\n");
583 debug_printf("Invoke as \"llc -o - llvmpipe.bc\"\n");
584 }
585
586 #if USE_MCJIT
587 assert(!gallivm->engine);
588 if (!init_gallivm_engine(gallivm)) {
589 assert(0);
590 }
591 #endif
592 assert(gallivm->engine);
593
594 ++gallivm->compiled;
595 }
596
597
598 func_pointer
599 gallivm_jit_function(struct gallivm_state *gallivm,
600 LLVMValueRef func)
601 {
602 void *code;
603 func_pointer jit_func;
604
605 assert(gallivm->compiled);
606 assert(gallivm->engine);
607
608 code = LLVMGetPointerToGlobal(gallivm->engine, func);
609 assert(code);
610 jit_func = pointer_to_func(code);
611
612 if (gallivm_debug & GALLIVM_DEBUG_ASM) {
613 lp_disassemble(code);
614 }
615
616 /* Free the function body to save memory */
617 lp_func_delete_body(func);
618
619 return jit_func;
620 }
621
622
623 /**
624 * Free the function (and its machine code).
625 */
626 void
627 gallivm_free_function(struct gallivm_state *gallivm,
628 LLVMValueRef func,
629 const void *code)
630 {
631 #if !USE_MCJIT
632 if (code) {
633 LLVMFreeMachineCodeForFunction(gallivm->engine, func);
634 }
635
636 LLVMDeleteFunction(func);
637 #endif
638 }