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