xref: /aosp_15_r20/external/mesa3d/src/gallium/auxiliary/gallivm/lp_bld_init.c (revision 6104692788411f58d303aa86923a9ff6ecaded22)
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 "util/detect.h"
30 #include "util/compiler.h"
31 #include "util/macros.h"
32 #include "util/u_cpu_detect.h"
33 #include "util/u_debug.h"
34 #include "util/u_memory.h"
35 #include "util/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 #include "lp_bld_coro.h"
41 #include "lp_bld_printf.h"
42 
43 #include <llvm/Config/llvm-config.h>
44 #include <llvm-c/Analysis.h>
45 #include <llvm-c/BitWriter.h>
46 
47 static bool gallivm_initialized = false;
48 
49 /*
50  * Optimization values are:
51  * - 0: None (-O0)
52  * - 1: Less (-O1)
53  * - 2: Default (-O2, -Os)
54  * - 3: Aggressive (-O3)
55  *
56  * See also CodeGenOpt::Level in llvm/Target/TargetMachine.h
57  */
58 enum LLVM_CodeGenOpt_Level {
59    None,        // -O0
60    Less,        // -O1
61    Default,     // -O2, -Os
62    Aggressive   // -O3
63 };
64 
65 
66 /**
67  * Create the LLVM (optimization) pass manager and install
68  * relevant optimization passes.
69  * \return  TRUE for success, FALSE for failure
70  */
71 static bool
create_pass_manager(struct gallivm_state * gallivm)72 create_pass_manager(struct gallivm_state *gallivm)
73 {
74    {
75       char *td_str;
76       // New ones from the Module.
77       td_str = LLVMCopyStringRepOfTargetData(gallivm->target);
78       LLVMSetDataLayout(gallivm->module, td_str);
79       free(td_str);
80    }
81 
82    return lp_passmgr_create(gallivm->module, &gallivm->passmgr);
83 }
84 
85 /**
86  * Free gallivm object's LLVM allocations, but not any generated code
87  * nor the gallivm object itself.
88  */
89 void
gallivm_free_ir(struct gallivm_state * gallivm)90 gallivm_free_ir(struct gallivm_state *gallivm)
91 {
92    lp_passmgr_dispose(gallivm->passmgr);
93 
94    if (gallivm->engine) {
95       /* This will already destroy any associated module */
96       LLVMDisposeExecutionEngine(gallivm->engine);
97    } else if (gallivm->module) {
98       LLVMDisposeModule(gallivm->module);
99    }
100 
101    if (gallivm->cache) {
102       lp_free_objcache(gallivm->cache->jit_obj_cache);
103       free(gallivm->cache->data);
104    }
105    FREE(gallivm->module_name);
106 
107    if (gallivm->target) {
108       LLVMDisposeTargetData(gallivm->target);
109    }
110 
111    if (gallivm->builder)
112       LLVMDisposeBuilder(gallivm->builder);
113 
114    /* The LLVMContext should be owned by the parent of gallivm. */
115 
116    gallivm->engine = NULL;
117    gallivm->target = NULL;
118    gallivm->module = NULL;
119    gallivm->module_name = NULL;
120    gallivm->passmgr = NULL;
121    gallivm->context = NULL;
122    gallivm->builder = NULL;
123    gallivm->cache = NULL;
124 }
125 
126 
127 /**
128  * Free LLVM-generated code.  Should be done AFTER gallivm_free_ir().
129  */
130 static void
gallivm_free_code(struct gallivm_state * gallivm)131 gallivm_free_code(struct gallivm_state *gallivm)
132 {
133    assert(!gallivm->module);
134    assert(!gallivm->engine);
135    lp_free_generated_code(gallivm->code);
136    gallivm->code = NULL;
137    lp_free_memory_manager(gallivm->memorymgr);
138    gallivm->memorymgr = NULL;
139 }
140 
141 
142 static bool
init_gallivm_engine(struct gallivm_state * gallivm)143 init_gallivm_engine(struct gallivm_state *gallivm)
144 {
145    if (1) {
146       enum LLVM_CodeGenOpt_Level optlevel;
147       char *error = NULL;
148       int ret;
149 
150       if (gallivm_perf & GALLIVM_PERF_NO_OPT) {
151          optlevel = None;
152       }
153       else {
154          optlevel = Default;
155       }
156 
157       ret = lp_build_create_jit_compiler_for_module(&gallivm->engine,
158                                                     &gallivm->code,
159                                                     gallivm->cache,
160                                                     gallivm->module,
161                                                     gallivm->memorymgr,
162                                                     (unsigned) optlevel,
163                                                     &error);
164       if (ret) {
165          _debug_printf("%s\n", error);
166          LLVMDisposeMessage(error);
167          goto fail;
168       }
169    }
170 
171    if (0) {
172        /*
173         * Dump the data layout strings.
174         */
175 
176        LLVMTargetDataRef target = LLVMGetExecutionEngineTargetData(gallivm->engine);
177        char *data_layout;
178        char *engine_data_layout;
179 
180        data_layout = LLVMCopyStringRepOfTargetData(gallivm->target);
181        engine_data_layout = LLVMCopyStringRepOfTargetData(target);
182 
183        if (1) {
184           debug_printf("module target data = %s\n", data_layout);
185           debug_printf("engine target data = %s\n", engine_data_layout);
186        }
187 
188        free(data_layout);
189        free(engine_data_layout);
190    }
191 
192    return true;
193 
194 fail:
195    return false;
196 }
197 
198 
199 /**
200  * Allocate gallivm LLVM objects.
201  * \return  TRUE for success, FALSE for failure
202  */
203 static bool
init_gallivm_state(struct gallivm_state * gallivm,const char * name,lp_context_ref * context,struct lp_cached_code * cache)204 init_gallivm_state(struct gallivm_state *gallivm, const char *name,
205                    lp_context_ref *context, struct lp_cached_code *cache)
206 {
207    assert(!gallivm->context);
208    assert(!gallivm->module);
209 
210    if (!lp_build_init())
211       return false;
212 
213    gallivm->context = context->ref;
214    gallivm->cache = cache;
215    if (!gallivm->context)
216       goto fail;
217 
218    gallivm->module_name = NULL;
219    if (name) {
220       size_t size = strlen(name) + 1;
221       gallivm->module_name = MALLOC(size);
222       if (gallivm->module_name) {
223          memcpy(gallivm->module_name, name, size);
224       }
225    }
226 
227    gallivm->module = LLVMModuleCreateWithNameInContext(name,
228                                                        gallivm->context);
229    if (!gallivm->module)
230       goto fail;
231 
232 #if DETECT_ARCH_X86
233    lp_set_module_stack_alignment_override(gallivm->module, 4);
234 #endif
235 
236    gallivm->builder = LLVMCreateBuilderInContext(gallivm->context);
237    if (!gallivm->builder)
238       goto fail;
239 
240    gallivm->memorymgr = lp_get_default_memory_manager();
241    if (!gallivm->memorymgr)
242       goto fail;
243 
244    /* FIXME: MC-JIT only allows compiling one module at a time, and it must be
245     * complete when MC-JIT is created. So defer the MC-JIT engine creation for
246     * now.
247     */
248 
249    /*
250     * MC-JIT engine compiles the module immediately on creation, so we can't
251     * obtain the target data from it.  Instead we create a target data layout
252     * from a string.
253     *
254     * The produced layout strings are not precisely the same, but should make
255     * no difference for the kind of optimization passes we run.
256     *
257     * For reference this is the layout string on x64:
258     *
259     *   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
260     *
261     * See also:
262     * - http://llvm.org/docs/LangRef.html#datalayout
263     */
264 
265    {
266       const unsigned pointer_size = 8 * sizeof(void *);
267       char layout[512];
268       snprintf(layout, sizeof layout, "%c-p:%u:%u:%u-i64:64:64-a0:0:%u-s0:%u:%u",
269 #if UTIL_ARCH_LITTLE_ENDIAN
270                     'e', // little endian
271 #else
272                     'E', // big endian
273 #endif
274                     pointer_size, pointer_size, pointer_size, // pointer size, abi alignment, preferred alignment
275                     pointer_size, // aggregate preferred alignment
276                     pointer_size, pointer_size); // stack objects abi alignment, preferred alignment
277 
278       gallivm->target = LLVMCreateTargetData(layout);
279       if (!gallivm->target) {
280          return false;
281       }
282    }
283 
284    if (!create_pass_manager(gallivm))
285       goto fail;
286 
287    lp_build_coro_declare_malloc_hooks(gallivm);
288    return true;
289 
290 fail:
291    gallivm_free_ir(gallivm);
292    gallivm_free_code(gallivm);
293    return false;
294 }
295 
296 bool
lp_build_init(void)297 lp_build_init(void)
298 {
299    lp_build_init_native_width();
300    if (gallivm_initialized)
301       return true;
302 
303 
304    /* LLVMLinkIn* are no-ops at runtime.  They just ensure the respective
305     * component is linked at buildtime, which is sufficient for its static
306     * constructors to be called at load time.
307     */
308    LLVMLinkInMCJIT();
309 
310    lp_init_env_options();
311 
312    lp_set_target_options();
313 
314    lp_bld_ppc_disable_denorms();
315 
316    gallivm_initialized = true;
317 
318    return true;
319 }
320 
321 
322 
323 /**
324  * Create a new gallivm_state object.
325  */
326 struct gallivm_state *
gallivm_create(const char * name,lp_context_ref * context,struct lp_cached_code * cache)327 gallivm_create(const char *name, lp_context_ref *context,
328                struct lp_cached_code *cache)
329 {
330    struct gallivm_state *gallivm;
331 
332    gallivm = CALLOC_STRUCT(gallivm_state);
333    if (gallivm) {
334       if (!init_gallivm_state(gallivm, name, context, cache)) {
335          FREE(gallivm);
336          gallivm = NULL;
337       }
338    }
339 
340    assert(gallivm != NULL);
341    return gallivm;
342 }
343 
344 
345 /**
346  * Destroy a gallivm_state object.
347  */
348 void
gallivm_destroy(struct gallivm_state * gallivm)349 gallivm_destroy(struct gallivm_state *gallivm)
350 {
351    gallivm_free_ir(gallivm);
352    gallivm_free_code(gallivm);
353    FREE(gallivm);
354 }
355 
356 void
gallivm_add_global_mapping(struct gallivm_state * gallivm,LLVMValueRef sym,void * addr)357 gallivm_add_global_mapping(struct gallivm_state *gallivm, LLVMValueRef sym, void* addr)
358 {
359    LLVMAddGlobalMapping(gallivm->engine, sym, addr);
360 }
361 
362 /**
363  * Compile a module.
364  * This does IR optimization on all functions in the module.
365  */
366 void
gallivm_compile_module(struct gallivm_state * gallivm)367 gallivm_compile_module(struct gallivm_state *gallivm)
368 {
369    assert(!gallivm->compiled);
370 
371    if (gallivm->builder) {
372       LLVMDisposeBuilder(gallivm->builder);
373       gallivm->builder = NULL;
374    }
375 
376    LLVMSetDataLayout(gallivm->module, "");
377    assert(!gallivm->engine);
378    if (!init_gallivm_engine(gallivm)) {
379       assert(0);
380    }
381    assert(gallivm->engine);
382 
383    if (gallivm->cache && gallivm->cache->data_size) {
384       goto skip_cached;
385    }
386 
387    /* Dump bitcode to a file */
388    if (gallivm_debug & GALLIVM_DEBUG_DUMP_BC) {
389       char filename[256];
390       assert(gallivm->module_name);
391       snprintf(filename, sizeof(filename), "ir_%s.bc", gallivm->module_name);
392       LLVMWriteBitcodeToFile(gallivm->module, filename);
393       debug_printf("%s written\n", filename);
394       debug_printf("Invoke as \"opt %s %s | llc -O%d %s%s\"\n",
395                    gallivm_perf & GALLIVM_PERF_NO_OPT ? "-mem2reg" :
396                    "-sroa -early-cse -simplifycfg -reassociate "
397                    "-mem2reg -constprop -instcombine -gvn",
398                    filename, gallivm_perf & GALLIVM_PERF_NO_OPT ? 0 : 2,
399                    "[-mcpu=<-mcpu option>] ",
400                    "[-mattr=<-mattr option(s)>]");
401    }
402 
403    lp_passmgr_run(gallivm->passmgr,
404                   gallivm->module,
405                   LLVMGetExecutionEngineTargetMachine(gallivm->engine),
406                   gallivm->module_name);
407 
408    /* Setting the module's DataLayout to an empty string will cause the
409     * ExecutionEngine to copy to the DataLayout string from its target machine
410     * to the module.  As of LLVM 3.8 the module and the execution engine are
411     * required to have the same DataLayout.
412     *
413     * We must make sure we do this after running the optimization passes,
414     * because those passes need a correct datalayout string.  For example, if
415     * those optimization passes see an empty datalayout, they will assume this
416     * is a little endian target and will do optimizations that break big endian
417     * machines.
418     *
419     * TODO: This is just a temporary work-around.  The correct solution is for
420     * gallivm_init_state() to create a TargetMachine and pull the DataLayout
421     * from there.  Currently, the TargetMachine used by llvmpipe is being
422     * implicitly created by the EngineBuilder in
423     * lp_build_create_jit_compiler_for_module()
424     */
425  skip_cached:
426 
427    ++gallivm->compiled;
428 
429    lp_init_printf_hook(gallivm);
430    gallivm_add_global_mapping(gallivm, gallivm->debug_printf_hook, debug_printf);
431 
432    lp_init_clock_hook(gallivm);
433    gallivm_add_global_mapping(gallivm, gallivm->get_time_hook, os_time_get_nano);
434 
435    lp_build_coro_add_malloc_hooks(gallivm);
436 
437    if (gallivm_debug & GALLIVM_DEBUG_ASM) {
438       LLVMValueRef llvm_func = LLVMGetFirstFunction(gallivm->module);
439 
440       while (llvm_func) {
441          /*
442           * Need to filter out functions which don't have an implementation,
443           * such as the intrinsics. May not be sufficient in case of IPO?
444           * LLVMGetPointerToGlobal() will abort otherwise.
445           */
446          if (!LLVMIsDeclaration(llvm_func)) {
447             void *func_code = LLVMGetPointerToGlobal(gallivm->engine, llvm_func);
448             lp_disassemble(llvm_func, func_code);
449          }
450          llvm_func = LLVMGetNextFunction(llvm_func);
451       }
452    }
453 
454 #if defined(PROFILE)
455    {
456       LLVMValueRef llvm_func = LLVMGetFirstFunction(gallivm->module);
457 
458       while (llvm_func) {
459          if (!LLVMIsDeclaration(llvm_func)) {
460             void *func_code = LLVMGetPointerToGlobal(gallivm->engine, llvm_func);
461             lp_profile(llvm_func, func_code);
462          }
463          llvm_func = LLVMGetNextFunction(llvm_func);
464       }
465    }
466 #endif
467 }
468 
469 
470 
471 func_pointer
gallivm_jit_function(struct gallivm_state * gallivm,LLVMValueRef func,const char * func_name)472 gallivm_jit_function(struct gallivm_state *gallivm,
473                      LLVMValueRef func, const char *func_name)
474 {
475    void *code;
476    func_pointer jit_func;
477    int64_t time_begin = 0;
478 
479    assert(gallivm->compiled);
480    assert(gallivm->engine);
481 
482    if (gallivm_debug & GALLIVM_DEBUG_PERF)
483       time_begin = os_time_get();
484 
485    code = LLVMGetPointerToGlobal(gallivm->engine, func);
486    assert(code);
487    jit_func = pointer_to_func(code);
488 
489    if (gallivm_debug & GALLIVM_DEBUG_PERF) {
490       int64_t time_end = os_time_get();
491       int time_msec = (int)(time_end - time_begin) / 1000;
492       debug_printf("   jitting func %s took %d msec\n",
493                    LLVMGetValueName(func), time_msec);
494    }
495 
496    return jit_func;
497 }
498 
499 void
gallivm_stub_func(struct gallivm_state * gallivm,LLVMValueRef func)500 gallivm_stub_func(struct gallivm_state *gallivm, LLVMValueRef func)
501 {
502    /*
503     * MCJIT can accept an empty function, nothing is needed here.
504     * The only code is to silence unused var warning.
505     */
506    (void) gallivm;
507    (void) func;
508 }
509