util/u_endian: set PIPE_ARCH_*_ENDIAN to 1
[mesa.git] / src / gallium / auxiliary / gallivm / lp_bld_misc.cpp
1 /**************************************************************************
2 *
3 * Copyright 2010 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 SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
17 * THE COPYRIGHT HOLDERS, AUTHORS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM,
18 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 * USE OR OTHER DEALINGS IN THE SOFTWARE.
21 *
22 * The above copyright notice and this permission notice (including the
23 * next paragraph) shall be included in all copies or substantial portions
24 * of the Software.
25 *
26 **************************************************************************/
27
28
29 /**
30 * The purpose of this module is to expose LLVM functionality not available
31 * through the C++ bindings.
32 */
33
34
35 // Undef these vars just to silence warnings
36 #undef PACKAGE_BUGREPORT
37 #undef PACKAGE_NAME
38 #undef PACKAGE_STRING
39 #undef PACKAGE_TARNAME
40 #undef PACKAGE_VERSION
41
42
43 #include <stddef.h>
44
45 #include <llvm/Config/llvm-config.h>
46
47 #if LLVM_VERSION_MAJOR < 7
48 // Workaround http://llvm.org/PR23628
49 #pragma push_macro("DEBUG")
50 #undef DEBUG
51 #endif
52
53 #include <llvm/Config/llvm-config.h>
54 #include <llvm-c/Core.h>
55 #include <llvm-c/Support.h>
56 #include <llvm-c/ExecutionEngine.h>
57 #include <llvm/Target/TargetOptions.h>
58 #include <llvm/ExecutionEngine/ExecutionEngine.h>
59 #include <llvm/ADT/Triple.h>
60 #include <llvm/Analysis/TargetLibraryInfo.h>
61 #include <llvm/ExecutionEngine/SectionMemoryManager.h>
62 #include <llvm/Support/CommandLine.h>
63 #include <llvm/Support/Host.h>
64 #include <llvm/Support/PrettyStackTrace.h>
65
66 #include <llvm/Support/TargetSelect.h>
67
68 #include <llvm/IR/CallSite.h>
69 #include <llvm/IR/IRBuilder.h>
70 #include <llvm/IR/Module.h>
71 #include <llvm/Support/CBindingWrapping.h>
72
73 #include <llvm/Config/llvm-config.h>
74 #if LLVM_USE_INTEL_JITEVENTS
75 #include <llvm/ExecutionEngine/JITEventListener.h>
76 #endif
77
78 #if LLVM_VERSION_MAJOR < 7
79 // Workaround http://llvm.org/PR23628
80 #pragma pop_macro("DEBUG")
81 #endif
82
83 #include "c11/threads.h"
84 #include "os/os_thread.h"
85 #include "pipe/p_config.h"
86 #include "util/u_debug.h"
87 #include "util/u_cpu_detect.h"
88
89 #include "lp_bld_misc.h"
90 #include "lp_bld_debug.h"
91
92 namespace {
93
94 class LLVMEnsureMultithreaded {
95 public:
96 LLVMEnsureMultithreaded()
97 {
98 if (!LLVMIsMultithreaded()) {
99 LLVMStartMultithreaded();
100 }
101 }
102 };
103
104 static LLVMEnsureMultithreaded lLVMEnsureMultithreaded;
105
106 }
107
108 static once_flag init_native_targets_once_flag = ONCE_FLAG_INIT;
109
110 static void init_native_targets()
111 {
112 // If we have a native target, initialize it to ensure it is linked in and
113 // usable by the JIT.
114 llvm::InitializeNativeTarget();
115
116 llvm::InitializeNativeTargetAsmPrinter();
117
118 llvm::InitializeNativeTargetDisassembler();
119 #if DEBUG
120 {
121 char *env_llc_options = getenv("GALLIVM_LLC_OPTIONS");
122 if (env_llc_options) {
123 char *option;
124 char *options[64] = {(char *) "llc"}; // Warning without cast
125 int n;
126 for (n = 0, option = strtok(env_llc_options, " "); option; n++, option = strtok(NULL, " ")) {
127 options[n + 1] = option;
128 }
129 if (gallivm_debug & (GALLIVM_DEBUG_IR | GALLIVM_DEBUG_ASM | GALLIVM_DEBUG_DUMP_BC)) {
130 debug_printf("llc additional options (%d):\n", n);
131 for (int i = 1; i <= n; i++)
132 debug_printf("\t%s\n", options[i]);
133 debug_printf("\n");
134 }
135 LLVMParseCommandLineOptions(n + 1, options, NULL);
136 }
137 }
138 #endif
139 }
140
141 extern "C" void
142 lp_set_target_options(void)
143 {
144 /* The llvm target registry is not thread-safe, so drivers and state-trackers
145 * that want to initialize targets should use the lp_set_target_options()
146 * function to safely initialize targets.
147 *
148 * LLVM targets should be initialized before the driver or state-tracker tries
149 * to access the registry.
150 */
151 call_once(&init_native_targets_once_flag, init_native_targets);
152 }
153
154 extern "C"
155 LLVMTargetLibraryInfoRef
156 gallivm_create_target_library_info(const char *triple)
157 {
158 return reinterpret_cast<LLVMTargetLibraryInfoRef>(
159 new llvm::TargetLibraryInfoImpl(
160 llvm::Triple(triple)));
161 }
162
163 extern "C"
164 void
165 gallivm_dispose_target_library_info(LLVMTargetLibraryInfoRef library_info)
166 {
167 delete reinterpret_cast<
168 llvm::TargetLibraryInfoImpl
169 *>(library_info);
170 }
171
172
173 typedef llvm::RTDyldMemoryManager BaseMemoryManager;
174
175
176 /*
177 * Delegating is tedious but the default manager class is hidden in an
178 * anonymous namespace in LLVM, so we cannot just derive from it to change
179 * its behavior.
180 */
181 class DelegatingJITMemoryManager : public BaseMemoryManager {
182
183 protected:
184 virtual BaseMemoryManager *mgr() const = 0;
185
186 public:
187 /*
188 * From RTDyldMemoryManager
189 */
190 virtual uint8_t *allocateCodeSection(uintptr_t Size,
191 unsigned Alignment,
192 unsigned SectionID,
193 llvm::StringRef SectionName) {
194 return mgr()->allocateCodeSection(Size, Alignment, SectionID,
195 SectionName);
196 }
197 virtual uint8_t *allocateDataSection(uintptr_t Size,
198 unsigned Alignment,
199 unsigned SectionID,
200 llvm::StringRef SectionName,
201 bool IsReadOnly) {
202 return mgr()->allocateDataSection(Size, Alignment, SectionID,
203 SectionName,
204 IsReadOnly);
205 }
206 virtual void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr, size_t Size) {
207 mgr()->registerEHFrames(Addr, LoadAddr, Size);
208 }
209 #if LLVM_VERSION_MAJOR >= 5
210 virtual void deregisterEHFrames() {
211 mgr()->deregisterEHFrames();
212 }
213 #else
214 virtual void deregisterEHFrames(uint8_t *Addr, uint64_t LoadAddr, size_t Size) {
215 mgr()->deregisterEHFrames(Addr, LoadAddr, Size);
216 }
217 #endif
218 virtual void *getPointerToNamedFunction(const std::string &Name,
219 bool AbortOnFailure=true) {
220 return mgr()->getPointerToNamedFunction(Name, AbortOnFailure);
221 }
222 virtual bool finalizeMemory(std::string *ErrMsg = 0) {
223 return mgr()->finalizeMemory(ErrMsg);
224 }
225 };
226
227
228 /*
229 * Delegate memory management to one shared manager for more efficient use
230 * of memory than creating a separate pool for each LLVM engine.
231 * Keep generated code until freeGeneratedCode() is called, instead of when
232 * memory manager is destroyed, which happens during engine destruction.
233 * This allows additional memory savings as we don't have to keep the engine
234 * around in order to use the code.
235 * All methods are delegated to the shared manager except destruction and
236 * deallocating code. For the latter we just remember what needs to be
237 * deallocated later. The shared manager is deleted once it is empty.
238 */
239 class ShaderMemoryManager : public DelegatingJITMemoryManager {
240
241 BaseMemoryManager *TheMM;
242
243 struct GeneratedCode {
244 typedef std::vector<void *> Vec;
245 Vec FunctionBody, ExceptionTable;
246 BaseMemoryManager *TheMM;
247
248 GeneratedCode(BaseMemoryManager *MM) {
249 TheMM = MM;
250 }
251
252 ~GeneratedCode() {
253 }
254 };
255
256 GeneratedCode *code;
257
258 BaseMemoryManager *mgr() const {
259 return TheMM;
260 }
261
262 public:
263
264 ShaderMemoryManager(BaseMemoryManager* MM) {
265 TheMM = MM;
266 code = new GeneratedCode(MM);
267 }
268
269 virtual ~ShaderMemoryManager() {
270 /*
271 * 'code' is purposely not deleted. It is the user's responsibility
272 * to call getGeneratedCode() and freeGeneratedCode().
273 */
274 }
275
276 struct lp_generated_code *getGeneratedCode() {
277 return (struct lp_generated_code *) code;
278 }
279
280 static void freeGeneratedCode(struct lp_generated_code *code) {
281 delete (GeneratedCode *) code;
282 }
283
284 virtual void deallocateFunctionBody(void *Body) {
285 // remember for later deallocation
286 code->FunctionBody.push_back(Body);
287 }
288 };
289
290
291 /**
292 * Same as LLVMCreateJITCompilerForModule, but:
293 * - allows using MCJIT and enabling AVX feature where available.
294 * - set target options
295 *
296 * See also:
297 * - llvm/lib/ExecutionEngine/ExecutionEngineBindings.cpp
298 * - llvm/tools/lli/lli.cpp
299 * - http://markmail.org/message/ttkuhvgj4cxxy2on#query:+page:1+mid:aju2dggerju3ivd3+state:results
300 */
301 extern "C"
302 LLVMBool
303 lp_build_create_jit_compiler_for_module(LLVMExecutionEngineRef *OutJIT,
304 lp_generated_code **OutCode,
305 LLVMModuleRef M,
306 LLVMMCJITMemoryManagerRef CMM,
307 unsigned OptLevel,
308 char **OutError)
309 {
310 using namespace llvm;
311
312 std::string Error;
313 EngineBuilder builder(std::unique_ptr<Module>(unwrap(M)));
314
315 /**
316 * LLVM 3.1+ haven't more "extern unsigned llvm::StackAlignmentOverride" and
317 * friends for configuring code generation options, like stack alignment.
318 */
319 TargetOptions options;
320 #if defined(PIPE_ARCH_X86)
321 options.StackAlignmentOverride = 4;
322 #endif
323
324 builder.setEngineKind(EngineKind::JIT)
325 .setErrorStr(&Error)
326 .setTargetOptions(options)
327 .setOptLevel((CodeGenOpt::Level)OptLevel);
328
329 #ifdef _WIN32
330 /*
331 * MCJIT works on Windows, but currently only through ELF object format.
332 *
333 * XXX: We could use `LLVM_HOST_TRIPLE "-elf"` but LLVM_HOST_TRIPLE has
334 * different strings for MinGW/MSVC, so better play it safe and be
335 * explicit.
336 */
337 # ifdef _WIN64
338 LLVMSetTarget(M, "x86_64-pc-win32-elf");
339 # else
340 LLVMSetTarget(M, "i686-pc-win32-elf");
341 # endif
342 #endif
343
344 llvm::SmallVector<std::string, 16> MAttrs;
345
346 #if LLVM_VERSION_MAJOR >= 4 && (defined(PIPE_ARCH_X86) || defined(PIPE_ARCH_X86_64) || defined(PIPE_ARCH_ARM))
347 /* llvm-3.3+ implements sys::getHostCPUFeatures for Arm
348 * and llvm-3.7+ for x86, which allows us to enable/disable
349 * code generation based on the results of cpuid on these
350 * architectures.
351 */
352 llvm::StringMap<bool> features;
353 llvm::sys::getHostCPUFeatures(features);
354
355 for (StringMapIterator<bool> f = features.begin();
356 f != features.end();
357 ++f) {
358 MAttrs.push_back(((*f).second ? "+" : "-") + (*f).first().str());
359 }
360 #elif defined(PIPE_ARCH_X86) || defined(PIPE_ARCH_X86_64)
361 /*
362 * We need to unset attributes because sometimes LLVM mistakenly assumes
363 * certain features are present given the processor name.
364 *
365 * https://bugs.freedesktop.org/show_bug.cgi?id=92214
366 * http://llvm.org/PR25021
367 * http://llvm.org/PR19429
368 * http://llvm.org/PR16721
369 */
370 MAttrs.push_back(util_cpu_caps.has_sse ? "+sse" : "-sse" );
371 MAttrs.push_back(util_cpu_caps.has_sse2 ? "+sse2" : "-sse2" );
372 MAttrs.push_back(util_cpu_caps.has_sse3 ? "+sse3" : "-sse3" );
373 MAttrs.push_back(util_cpu_caps.has_ssse3 ? "+ssse3" : "-ssse3" );
374 MAttrs.push_back(util_cpu_caps.has_sse4_1 ? "+sse4.1" : "-sse4.1");
375 MAttrs.push_back(util_cpu_caps.has_sse4_2 ? "+sse4.2" : "-sse4.2");
376 /*
377 * AVX feature is not automatically detected from CPUID by the X86 target
378 * yet, because the old (yet default) JIT engine is not capable of
379 * emitting the opcodes. On newer llvm versions it is and at least some
380 * versions (tested with 3.3) will emit avx opcodes without this anyway.
381 */
382 MAttrs.push_back(util_cpu_caps.has_avx ? "+avx" : "-avx");
383 MAttrs.push_back(util_cpu_caps.has_f16c ? "+f16c" : "-f16c");
384 MAttrs.push_back(util_cpu_caps.has_fma ? "+fma" : "-fma");
385 MAttrs.push_back(util_cpu_caps.has_avx2 ? "+avx2" : "-avx2");
386 /* disable avx512 and all subvariants */
387 MAttrs.push_back("-avx512cd");
388 MAttrs.push_back("-avx512er");
389 MAttrs.push_back("-avx512f");
390 MAttrs.push_back("-avx512pf");
391 MAttrs.push_back("-avx512bw");
392 MAttrs.push_back("-avx512dq");
393 MAttrs.push_back("-avx512vl");
394 #endif
395 #if defined(PIPE_ARCH_ARM)
396 if (!util_cpu_caps.has_neon) {
397 MAttrs.push_back("-neon");
398 MAttrs.push_back("-crypto");
399 MAttrs.push_back("-vfp2");
400 }
401 #endif
402
403 #if defined(PIPE_ARCH_PPC)
404 MAttrs.push_back(util_cpu_caps.has_altivec ? "+altivec" : "-altivec");
405 #if (LLVM_VERSION_MAJOR < 4)
406 /*
407 * Make sure VSX instructions are disabled
408 * See LLVM bugs:
409 * https://llvm.org/bugs/show_bug.cgi?id=25503#c7 (fixed in 3.8.1)
410 * https://llvm.org/bugs/show_bug.cgi?id=26775 (fixed in 3.8.1)
411 * https://llvm.org/bugs/show_bug.cgi?id=33531 (fixed in 4.0)
412 * https://llvm.org/bugs/show_bug.cgi?id=34647 (llc performance on certain unusual shader IR; intro'd in 4.0, pending as of 5.0)
413 */
414 if (util_cpu_caps.has_altivec) {
415 MAttrs.push_back("-vsx");
416 }
417 #else
418 /*
419 * Bug 25503 is fixed, by the same fix that fixed
420 * bug 26775, in versions of LLVM later than 3.8 (starting with 3.8.1).
421 * BZ 33531 actually comprises more than one bug, all of
422 * which are fixed in LLVM 4.0.
423 *
424 * With LLVM 4.0 or higher:
425 * Make sure VSX instructions are ENABLED (if supported), unless
426 * VSX instructions are explicitly enabled/disabled via GALLIVM_VSX=1 or 0.
427 */
428 if (util_cpu_caps.has_altivec) {
429 MAttrs.push_back(util_cpu_caps.has_vsx ? "+vsx" : "-vsx");
430 }
431 #endif
432 #endif
433
434 builder.setMAttrs(MAttrs);
435
436 if (gallivm_debug & (GALLIVM_DEBUG_IR | GALLIVM_DEBUG_ASM | GALLIVM_DEBUG_DUMP_BC)) {
437 int n = MAttrs.size();
438 if (n > 0) {
439 debug_printf("llc -mattr option(s): ");
440 for (int i = 0; i < n; i++)
441 debug_printf("%s%s", MAttrs[i].c_str(), (i < n - 1) ? "," : "");
442 debug_printf("\n");
443 }
444 }
445
446 StringRef MCPU = llvm::sys::getHostCPUName();
447 /*
448 * The cpu bits are no longer set automatically, so need to set mcpu manually.
449 * Note that the MAttrs set above will be sort of ignored (since we should
450 * not set any which would not be set by specifying the cpu anyway).
451 * It ought to be safe though since getHostCPUName() should include bits
452 * not only from the cpu but environment as well (for instance if it's safe
453 * to use avx instructions which need OS support). According to
454 * http://llvm.org/bugs/show_bug.cgi?id=19429 however if I understand this
455 * right it may be necessary to specify older cpu (or disable mattrs) though
456 * when not using MCJIT so no instructions are generated which the old JIT
457 * can't handle. Not entirely sure if we really need to do anything yet.
458 */
459 #if PIPE_ARCH_LITTLE_ENDIAN && defined(PIPE_ARCH_PPC_64)
460 /*
461 * Versions of LLVM prior to 4.0 lacked a table entry for "POWER8NVL",
462 * resulting in (big-endian) "generic" being returned on
463 * little-endian Power8NVL systems. The result was that code that
464 * attempted to load the least significant 32 bits of a 64-bit quantity
465 * from memory loaded the wrong half. This resulted in failures in some
466 * Piglit tests, e.g.
467 * .../arb_gpu_shader_fp64/execution/conversion/frag-conversion-explicit-double-uint
468 */
469 if (MCPU == "generic")
470 MCPU = "pwr8";
471 #endif
472 builder.setMCPU(MCPU);
473 if (gallivm_debug & (GALLIVM_DEBUG_IR | GALLIVM_DEBUG_ASM | GALLIVM_DEBUG_DUMP_BC)) {
474 debug_printf("llc -mcpu option: %s\n", MCPU.str().c_str());
475 }
476
477 ShaderMemoryManager *MM = NULL;
478 BaseMemoryManager* JMM = reinterpret_cast<BaseMemoryManager*>(CMM);
479 MM = new ShaderMemoryManager(JMM);
480 *OutCode = MM->getGeneratedCode();
481
482 builder.setMCJITMemoryManager(std::unique_ptr<RTDyldMemoryManager>(MM));
483 MM = NULL; // ownership taken by std::unique_ptr
484
485 ExecutionEngine *JIT;
486
487 JIT = builder.create();
488 #if LLVM_USE_INTEL_JITEVENTS
489 JITEventListener *JEL = JITEventListener::createIntelJITEventListener();
490 JIT->RegisterJITEventListener(JEL);
491 #endif
492 if (JIT) {
493 *OutJIT = wrap(JIT);
494 return 0;
495 }
496 lp_free_generated_code(*OutCode);
497 *OutCode = 0;
498 delete MM;
499 *OutError = strdup(Error.c_str());
500 return 1;
501 }
502
503
504 extern "C"
505 void
506 lp_free_generated_code(struct lp_generated_code *code)
507 {
508 ShaderMemoryManager::freeGeneratedCode(code);
509 }
510
511 extern "C"
512 LLVMMCJITMemoryManagerRef
513 lp_get_default_memory_manager()
514 {
515 BaseMemoryManager *mm;
516 mm = new llvm::SectionMemoryManager();
517 return reinterpret_cast<LLVMMCJITMemoryManagerRef>(mm);
518 }
519
520 extern "C"
521 void
522 lp_free_memory_manager(LLVMMCJITMemoryManagerRef memorymgr)
523 {
524 delete reinterpret_cast<BaseMemoryManager*>(memorymgr);
525 }
526
527 extern "C" LLVMValueRef
528 lp_get_called_value(LLVMValueRef call)
529 {
530 return LLVMGetCalledValue(call);
531 }
532
533 extern "C" bool
534 lp_is_function(LLVMValueRef v)
535 {
536 return LLVMGetValueKind(v) == LLVMFunctionValueKind;
537 }