1 /**************************************************************************
3 * Copyright 2010 VMware, Inc.
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:
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.
22 * The above copyright notice and this permission notice (including the
23 * next paragraph) shall be included in all copies or substantial portions
26 **************************************************************************/
30 * The purpose of this module is to expose LLVM functionality not available
31 * through the C++ bindings.
35 #ifndef __STDC_LIMIT_MACROS
36 #define __STDC_LIMIT_MACROS
39 #ifndef __STDC_CONSTANT_MACROS
40 #define __STDC_CONSTANT_MACROS
43 // Undef these vars just to silence warnings
44 #undef PACKAGE_BUGREPORT
47 #undef PACKAGE_TARNAME
48 #undef PACKAGE_VERSION
53 // Workaround http://llvm.org/PR23628
54 #if HAVE_LLVM >= 0x0307
55 # pragma push_macro("DEBUG")
59 #include <llvm-c/Core.h>
60 #include <llvm-c/ExecutionEngine.h>
61 #include <llvm/Target/TargetOptions.h>
62 #include <llvm/ExecutionEngine/ExecutionEngine.h>
63 #include <llvm/ADT/Triple.h>
64 #if HAVE_LLVM >= 0x0307
65 #include <llvm/Analysis/TargetLibraryInfo.h>
67 #include <llvm/Target/TargetLibraryInfo.h>
69 #if HAVE_LLVM < 0x0306
70 #include <llvm/ExecutionEngine/JITMemoryManager.h>
72 #include <llvm/ExecutionEngine/SectionMemoryManager.h>
74 #include <llvm/Support/CommandLine.h>
75 #include <llvm/Support/Host.h>
76 #include <llvm/Support/PrettyStackTrace.h>
78 #include <llvm/Support/TargetSelect.h>
80 #include <llvm/IR/CallSite.h>
81 #include <llvm/IR/IRBuilder.h>
82 #include <llvm/IR/Module.h>
83 #include <llvm/Support/CBindingWrapping.h>
85 #include <llvm/Config/llvm-config.h>
86 #if LLVM_USE_INTEL_JITEVENTS
87 #include <llvm/ExecutionEngine/JITEventListener.h>
90 // Workaround http://llvm.org/PR23628
91 #if HAVE_LLVM >= 0x0307
92 # pragma pop_macro("DEBUG")
95 #include "c11/threads.h"
96 #include "os/os_thread.h"
97 #include "pipe/p_config.h"
98 #include "util/u_debug.h"
99 #include "util/u_cpu_detect.h"
101 #include "lp_bld_misc.h"
105 class LLVMEnsureMultithreaded
{
107 LLVMEnsureMultithreaded()
109 if (!LLVMIsMultithreaded()) {
110 LLVMStartMultithreaded();
115 static LLVMEnsureMultithreaded lLVMEnsureMultithreaded
;
119 static once_flag init_native_targets_once_flag
= ONCE_FLAG_INIT
;
121 static void init_native_targets()
123 // If we have a native target, initialize it to ensure it is linked in and
124 // usable by the JIT.
125 llvm::InitializeNativeTarget();
127 llvm::InitializeNativeTargetAsmPrinter();
129 llvm::InitializeNativeTargetDisassembler();
133 * The llvm target registry is not thread-safe, so drivers and state-trackers
134 * that want to initialize targets should use the gallivm_init_llvm_targets()
135 * function to safely initialize targets.
137 * LLVM targets should be initialized before the driver or state-tracker tries
138 * to access the registry.
141 gallivm_init_llvm_targets(void)
143 call_once(&init_native_targets_once_flag
, init_native_targets
);
147 lp_set_target_options(void)
149 #if HAVE_LLVM < 0x0304
151 * By default LLVM adds a signal handler to output a pretty stack trace.
152 * This signal handler is never removed, causing problems when unloading the
153 * shared object where the gallium driver resides.
155 llvm::DisablePrettyStackTrace
= true;
158 gallivm_init_llvm_targets();
162 LLVMTargetLibraryInfoRef
163 gallivm_create_target_library_info(const char *triple
)
165 return reinterpret_cast<LLVMTargetLibraryInfoRef
>(
166 #if HAVE_LLVM < 0x0307
167 new llvm::TargetLibraryInfo(
169 new llvm::TargetLibraryInfoImpl(
171 llvm::Triple(triple
)));
176 gallivm_dispose_target_library_info(LLVMTargetLibraryInfoRef library_info
)
178 delete reinterpret_cast<
179 #if HAVE_LLVM < 0x0307
180 llvm::TargetLibraryInfo
182 llvm::TargetLibraryInfoImpl
188 #if HAVE_LLVM < 0x0304
192 LLVMSetAlignmentBackport(LLVMValueRef V
,
195 switch (LLVMGetInstructionOpcode(V
)) {
197 llvm::unwrap
<llvm::LoadInst
>(V
)->setAlignment(Bytes
);
200 llvm::unwrap
<llvm::StoreInst
>(V
)->setAlignment(Bytes
);
211 #if HAVE_LLVM < 0x0306
212 typedef llvm::JITMemoryManager BaseMemoryManager
;
214 typedef llvm::RTDyldMemoryManager BaseMemoryManager
;
219 * Delegating is tedious but the default manager class is hidden in an
220 * anonymous namespace in LLVM, so we cannot just derive from it to change
223 class DelegatingJITMemoryManager
: public BaseMemoryManager
{
226 virtual BaseMemoryManager
*mgr() const = 0;
229 #if HAVE_LLVM < 0x0306
231 * From JITMemoryManager
233 virtual void setMemoryWritable() {
234 mgr()->setMemoryWritable();
236 virtual void setMemoryExecutable() {
237 mgr()->setMemoryExecutable();
239 virtual void setPoisonMemory(bool poison
) {
240 mgr()->setPoisonMemory(poison
);
242 virtual void AllocateGOT() {
243 mgr()->AllocateGOT();
245 * isManagingGOT() is not virtual in base class so we can't delegate.
246 * Instead we mirror the value of HasGOT in our instance.
248 HasGOT
= mgr()->isManagingGOT();
250 virtual uint8_t *getGOTBase() const {
251 return mgr()->getGOTBase();
253 virtual uint8_t *startFunctionBody(const llvm::Function
*F
,
254 uintptr_t &ActualSize
) {
255 return mgr()->startFunctionBody(F
, ActualSize
);
257 virtual uint8_t *allocateStub(const llvm::GlobalValue
*F
,
259 unsigned Alignment
) {
260 return mgr()->allocateStub(F
, StubSize
, Alignment
);
262 virtual void endFunctionBody(const llvm::Function
*F
,
263 uint8_t *FunctionStart
,
264 uint8_t *FunctionEnd
) {
265 mgr()->endFunctionBody(F
, FunctionStart
, FunctionEnd
);
267 virtual uint8_t *allocateSpace(intptr_t Size
, unsigned Alignment
) {
268 return mgr()->allocateSpace(Size
, Alignment
);
270 virtual uint8_t *allocateGlobal(uintptr_t Size
, unsigned Alignment
) {
271 return mgr()->allocateGlobal(Size
, Alignment
);
273 virtual void deallocateFunctionBody(void *Body
) {
274 mgr()->deallocateFunctionBody(Body
);
276 #if HAVE_LLVM < 0x0304
277 virtual uint8_t *startExceptionTable(const llvm::Function
*F
,
278 uintptr_t &ActualSize
) {
279 return mgr()->startExceptionTable(F
, ActualSize
);
281 virtual void endExceptionTable(const llvm::Function
*F
,
284 uint8_t *FrameRegister
) {
285 mgr()->endExceptionTable(F
, TableStart
, TableEnd
,
288 virtual void deallocateExceptionTable(void *ET
) {
289 mgr()->deallocateExceptionTable(ET
);
292 virtual bool CheckInvariants(std::string
&s
) {
293 return mgr()->CheckInvariants(s
);
295 virtual size_t GetDefaultCodeSlabSize() {
296 return mgr()->GetDefaultCodeSlabSize();
298 virtual size_t GetDefaultDataSlabSize() {
299 return mgr()->GetDefaultDataSlabSize();
301 virtual size_t GetDefaultStubSlabSize() {
302 return mgr()->GetDefaultStubSlabSize();
304 virtual unsigned GetNumCodeSlabs() {
305 return mgr()->GetNumCodeSlabs();
307 virtual unsigned GetNumDataSlabs() {
308 return mgr()->GetNumDataSlabs();
310 virtual unsigned GetNumStubSlabs() {
311 return mgr()->GetNumStubSlabs();
316 * From RTDyldMemoryManager
318 #if HAVE_LLVM >= 0x0304
319 virtual uint8_t *allocateCodeSection(uintptr_t Size
,
322 llvm::StringRef SectionName
) {
323 return mgr()->allocateCodeSection(Size
, Alignment
, SectionID
,
327 virtual uint8_t *allocateCodeSection(uintptr_t Size
,
329 unsigned SectionID
) {
330 return mgr()->allocateCodeSection(Size
, Alignment
, SectionID
);
333 virtual uint8_t *allocateDataSection(uintptr_t Size
,
336 #if HAVE_LLVM >= 0x0304
337 llvm::StringRef SectionName
,
340 return mgr()->allocateDataSection(Size
, Alignment
, SectionID
,
341 #if HAVE_LLVM >= 0x0304
346 #if HAVE_LLVM >= 0x0304
347 virtual void registerEHFrames(uint8_t *Addr
, uint64_t LoadAddr
, size_t Size
) {
348 mgr()->registerEHFrames(Addr
, LoadAddr
, Size
);
350 virtual void deregisterEHFrames(uint8_t *Addr
, uint64_t LoadAddr
, size_t Size
) {
351 mgr()->deregisterEHFrames(Addr
, LoadAddr
, Size
);
354 virtual void registerEHFrames(llvm::StringRef SectionData
) {
355 mgr()->registerEHFrames(SectionData
);
358 virtual void *getPointerToNamedFunction(const std::string
&Name
,
359 bool AbortOnFailure
=true) {
360 return mgr()->getPointerToNamedFunction(Name
, AbortOnFailure
);
362 #if HAVE_LLVM <= 0x0303
363 virtual bool applyPermissions(std::string
*ErrMsg
= 0) {
364 return mgr()->applyPermissions(ErrMsg
);
367 virtual bool finalizeMemory(std::string
*ErrMsg
= 0) {
368 return mgr()->finalizeMemory(ErrMsg
);
375 * Delegate memory management to one shared manager for more efficient use
376 * of memory than creating a separate pool for each LLVM engine.
377 * Keep generated code until freeGeneratedCode() is called, instead of when
378 * memory manager is destroyed, which happens during engine destruction.
379 * This allows additional memory savings as we don't have to keep the engine
380 * around in order to use the code.
381 * All methods are delegated to the shared manager except destruction and
382 * deallocating code. For the latter we just remember what needs to be
383 * deallocated later. The shared manager is deleted once it is empty.
385 class ShaderMemoryManager
: public DelegatingJITMemoryManager
{
387 BaseMemoryManager
*TheMM
;
389 struct GeneratedCode
{
390 typedef std::vector
<void *> Vec
;
391 Vec FunctionBody
, ExceptionTable
;
392 BaseMemoryManager
*TheMM
;
394 GeneratedCode(BaseMemoryManager
*MM
) {
400 * Deallocate things as previously requested and
401 * free shared manager when no longer used.
403 #if HAVE_LLVM < 0x0306
407 for ( i
= FunctionBody
.begin(); i
!= FunctionBody
.end(); ++i
)
408 TheMM
->deallocateFunctionBody(*i
);
409 #if HAVE_LLVM < 0x0304
410 for ( i
= ExceptionTable
.begin(); i
!= ExceptionTable
.end(); ++i
)
411 TheMM
->deallocateExceptionTable(*i
);
412 #endif /* HAVE_LLVM < 0x0304 */
413 #endif /* HAVE_LLVM < 0x0306 */
419 BaseMemoryManager
*mgr() const {
425 ShaderMemoryManager(BaseMemoryManager
* MM
) {
427 code
= new GeneratedCode(MM
);
430 virtual ~ShaderMemoryManager() {
432 * 'code' is purposely not deleted. It is the user's responsibility
433 * to call getGeneratedCode() and freeGeneratedCode().
437 struct lp_generated_code
*getGeneratedCode() {
438 return (struct lp_generated_code
*) code
;
441 static void freeGeneratedCode(struct lp_generated_code
*code
) {
442 delete (GeneratedCode
*) code
;
445 #if HAVE_LLVM < 0x0304
446 virtual void deallocateExceptionTable(void *ET
) {
447 // remember for later deallocation
448 code
->ExceptionTable
.push_back(ET
);
452 virtual void deallocateFunctionBody(void *Body
) {
453 // remember for later deallocation
454 code
->FunctionBody
.push_back(Body
);
460 * Same as LLVMCreateJITCompilerForModule, but:
461 * - allows using MCJIT and enabling AVX feature where available.
462 * - set target options
465 * - llvm/lib/ExecutionEngine/ExecutionEngineBindings.cpp
466 * - llvm/tools/lli/lli.cpp
467 * - http://markmail.org/message/ttkuhvgj4cxxy2on#query:+page:1+mid:aju2dggerju3ivd3+state:results
471 lp_build_create_jit_compiler_for_module(LLVMExecutionEngineRef
*OutJIT
,
472 lp_generated_code
**OutCode
,
474 LLVMMCJITMemoryManagerRef CMM
,
479 using namespace llvm
;
482 #if HAVE_LLVM >= 0x0306
483 EngineBuilder
builder(std::unique_ptr
<Module
>(unwrap(M
)));
485 EngineBuilder
builder(unwrap(M
));
489 * LLVM 3.1+ haven't more "extern unsigned llvm::StackAlignmentOverride" and
490 * friends for configuring code generation options, like stack alignment.
492 TargetOptions options
;
493 #if defined(PIPE_ARCH_X86)
494 options
.StackAlignmentOverride
= 4;
495 #if HAVE_LLVM < 0x0304
496 options
.RealignStack
= true;
500 #if defined(DEBUG) && HAVE_LLVM < 0x0307
501 options
.JITEmitDebugInfo
= true;
504 /* XXX: Workaround http://llvm.org/PR21435 */
505 #if defined(DEBUG) || defined(PROFILE) || \
506 (HAVE_LLVM >= 0x0303 && (defined(PIPE_ARCH_X86) || defined(PIPE_ARCH_X86_64)))
507 #if HAVE_LLVM < 0x0304
508 options
.NoFramePointerElimNonLeaf
= true;
510 #if HAVE_LLVM < 0x0307
511 options
.NoFramePointerElim
= true;
515 builder
.setEngineKind(EngineKind::JIT
)
517 .setTargetOptions(options
)
518 .setOptLevel((CodeGenOpt::Level
)OptLevel
);
521 #if HAVE_LLVM < 0x0306
522 builder
.setUseMCJIT(true);
526 * MCJIT works on Windows, but currently only through ELF object format.
528 * XXX: We could use `LLVM_HOST_TRIPLE "-elf"` but LLVM_HOST_TRIPLE has
529 * different strings for MinGW/MSVC, so better play it safe and be
533 LLVMSetTarget(M
, "x86_64-pc-win32-elf");
535 LLVMSetTarget(M
, "i686-pc-win32-elf");
540 llvm::SmallVector
<std::string
, 16> MAttrs
;
542 #if defined(PIPE_ARCH_X86) || defined(PIPE_ARCH_X86_64)
544 * We need to unset attributes because sometimes LLVM mistakenly assumes
545 * certain features are present given the processor name.
547 * https://bugs.freedesktop.org/show_bug.cgi?id=92214
548 * http://llvm.org/PR25021
549 * http://llvm.org/PR19429
550 * http://llvm.org/PR16721
552 MAttrs
.push_back(util_cpu_caps
.has_sse
? "+sse" : "-sse" );
553 MAttrs
.push_back(util_cpu_caps
.has_sse2
? "+sse2" : "-sse2" );
554 MAttrs
.push_back(util_cpu_caps
.has_sse3
? "+sse3" : "-sse3" );
555 MAttrs
.push_back(util_cpu_caps
.has_ssse3
? "+ssse3" : "-ssse3" );
556 #if HAVE_LLVM >= 0x0304
557 MAttrs
.push_back(util_cpu_caps
.has_sse4_1
? "+sse4.1" : "-sse4.1");
559 MAttrs
.push_back(util_cpu_caps
.has_sse4_1
? "+sse41" : "-sse41" );
561 #if HAVE_LLVM >= 0x0304
562 MAttrs
.push_back(util_cpu_caps
.has_sse4_2
? "+sse4.2" : "-sse4.2");
564 MAttrs
.push_back(util_cpu_caps
.has_sse4_2
? "+sse42" : "-sse42" );
567 * AVX feature is not automatically detected from CPUID by the X86 target
568 * yet, because the old (yet default) JIT engine is not capable of
569 * emitting the opcodes. On newer llvm versions it is and at least some
570 * versions (tested with 3.3) will emit avx opcodes without this anyway.
572 MAttrs
.push_back(util_cpu_caps
.has_avx
? "+avx" : "-avx");
573 MAttrs
.push_back(util_cpu_caps
.has_f16c
? "+f16c" : "-f16c");
574 if (HAVE_LLVM
>= 0x0304) {
575 MAttrs
.push_back(util_cpu_caps
.has_fma
? "+fma" : "-fma");
578 * The old JIT in LLVM 3.3 has a bug encoding llvm.fmuladd.f32 and
579 * llvm.fmuladd.v2f32 intrinsics when FMA is available.
581 MAttrs
.push_back("-fma");
583 MAttrs
.push_back(util_cpu_caps
.has_avx2
? "+avx2" : "-avx2");
584 /* disable avx512 and all subvariants */
585 #if HAVE_LLVM >= 0x0304
586 MAttrs
.push_back("-avx512cd");
587 MAttrs
.push_back("-avx512er");
588 MAttrs
.push_back("-avx512f");
589 MAttrs
.push_back("-avx512pf");
591 #if HAVE_LLVM >= 0x0305
592 MAttrs
.push_back("-avx512bw");
593 MAttrs
.push_back("-avx512dq");
594 MAttrs
.push_back("-avx512vl");
598 #if defined(PIPE_ARCH_PPC)
599 MAttrs
.push_back(util_cpu_caps
.has_altivec
? "+altivec" : "-altivec");
600 #if HAVE_LLVM >= 0x0304
602 * Make sure VSX instructions are disabled
603 * See LLVM bug https://llvm.org/bugs/show_bug.cgi?id=25503#c7
605 if (util_cpu_caps
.has_altivec
) {
606 MAttrs
.push_back("-vsx");
611 builder
.setMAttrs(MAttrs
);
613 #if HAVE_LLVM >= 0x0305
614 StringRef MCPU
= llvm::sys::getHostCPUName();
616 * The cpu bits are no longer set automatically, so need to set mcpu manually.
617 * Note that the MAttrs set above will be sort of ignored (since we should
618 * not set any which would not be set by specifying the cpu anyway).
619 * It ought to be safe though since getHostCPUName() should include bits
620 * not only from the cpu but environment as well (for instance if it's safe
621 * to use avx instructions which need OS support). According to
622 * http://llvm.org/bugs/show_bug.cgi?id=19429 however if I understand this
623 * right it may be necessary to specify older cpu (or disable mattrs) though
624 * when not using MCJIT so no instructions are generated which the old JIT
625 * can't handle. Not entirely sure if we really need to do anything yet.
627 builder
.setMCPU(MCPU
);
630 ShaderMemoryManager
*MM
= NULL
;
632 BaseMemoryManager
* JMM
= reinterpret_cast<BaseMemoryManager
*>(CMM
);
633 MM
= new ShaderMemoryManager(JMM
);
634 *OutCode
= MM
->getGeneratedCode();
636 #if HAVE_LLVM >= 0x0306
637 builder
.setMCJITMemoryManager(std::unique_ptr
<RTDyldMemoryManager
>(MM
));
638 MM
= NULL
; // ownership taken by std::unique_ptr
639 #elif HAVE_LLVM > 0x0303
640 builder
.setMCJITMemoryManager(MM
);
642 builder
.setJITMemoryManager(MM
);
645 #if HAVE_LLVM < 0x0306
646 BaseMemoryManager
* JMM
= reinterpret_cast<BaseMemoryManager
*>(CMM
);
647 MM
= new ShaderMemoryManager(JMM
);
648 *OutCode
= MM
->getGeneratedCode();
650 builder
.setJITMemoryManager(MM
);
656 ExecutionEngine
*JIT
;
658 JIT
= builder
.create();
659 #if LLVM_USE_INTEL_JITEVENTS
660 JITEventListener
*JEL
= JITEventListener::createIntelJITEventListener();
661 JIT
->RegisterJITEventListener(JEL
);
667 lp_free_generated_code(*OutCode
);
670 *OutError
= strdup(Error
.c_str());
677 lp_free_generated_code(struct lp_generated_code
*code
)
679 ShaderMemoryManager::freeGeneratedCode(code
);
683 LLVMMCJITMemoryManagerRef
684 lp_get_default_memory_manager()
686 BaseMemoryManager
*mm
;
687 #if HAVE_LLVM < 0x0306
688 mm
= llvm::JITMemoryManager::CreateDefaultMemManager();
690 mm
= new llvm::SectionMemoryManager();
692 return reinterpret_cast<LLVMMCJITMemoryManagerRef
>(mm
);
697 lp_free_memory_manager(LLVMMCJITMemoryManagerRef memorymgr
)
699 delete reinterpret_cast<BaseMemoryManager
*>(memorymgr
);
703 lp_add_attr_dereferenceable(LLVMValueRef val
, uint64_t bytes
)
705 #if HAVE_LLVM >= 0x0306
706 llvm::Argument
*A
= llvm::unwrap
<llvm::Argument
>(val
);
708 B
.addDereferenceableAttr(bytes
);
709 A
->addAttr(llvm::AttributeSet::get(A
->getContext(), A
->getArgNo() + 1, B
));
713 extern "C" LLVMValueRef
714 lp_get_called_value(LLVMValueRef call
)
716 #if HAVE_LLVM >= 0x0309
717 return LLVMGetCalledValue(call
);
719 return llvm::wrap(llvm::CallSite(llvm::unwrap
<llvm::Instruction
>(call
)).getCalledValue());
724 lp_is_function(LLVMValueRef v
)
726 #if HAVE_LLVM >= 0x0309
727 return LLVMGetValueKind(v
) == LLVMFunctionValueKind
;
729 return llvm::isa
<llvm::Function
>(llvm::unwrap(v
));