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 < 0x0306
65 #include <llvm/ExecutionEngine/JITMemoryManager.h>
67 #include <llvm/ExecutionEngine/SectionMemoryManager.h>
69 #include <llvm/Support/CommandLine.h>
70 #include <llvm/Support/Host.h>
71 #include <llvm/Support/PrettyStackTrace.h>
73 #include <llvm/Support/TargetSelect.h>
75 #include <llvm/IR/IRBuilder.h>
76 #include <llvm/IR/Module.h>
77 #include <llvm/Support/CBindingWrapping.h>
79 // Workaround http://llvm.org/PR23628
80 #if HAVE_LLVM >= 0x0307
81 # pragma pop_macro("DEBUG")
84 #include "pipe/p_config.h"
85 #include "util/u_debug.h"
86 #include "util/u_cpu_detect.h"
88 #include "lp_bld_misc.h"
92 class LLVMEnsureMultithreaded
{
94 LLVMEnsureMultithreaded()
96 if (!LLVMIsMultithreaded()) {
97 LLVMStartMultithreaded();
102 static LLVMEnsureMultithreaded lLVMEnsureMultithreaded
;
107 lp_set_target_options(void)
109 #if HAVE_LLVM < 0x0304
111 * By default LLVM adds a signal handler to output a pretty stack trace.
112 * This signal handler is never removed, causing problems when unloading the
113 * shared object where the gallium driver resides.
115 llvm::DisablePrettyStackTrace
= true;
118 // If we have a native target, initialize it to ensure it is linked in and
119 // usable by the JIT.
120 llvm::InitializeNativeTarget();
122 llvm::InitializeNativeTargetAsmPrinter();
124 llvm::InitializeNativeTargetDisassembler();
130 lp_build_load_volatile(LLVMBuilderRef B
, LLVMValueRef PointerVal
,
133 return llvm::wrap(llvm::unwrap(B
)->CreateLoad(llvm::unwrap(PointerVal
), true, Name
));
139 lp_set_load_alignment(LLVMValueRef Inst
,
142 llvm::unwrap
<llvm::LoadInst
>(Inst
)->setAlignment(Align
);
147 lp_set_store_alignment(LLVMValueRef Inst
,
150 llvm::unwrap
<llvm::StoreInst
>(Inst
)->setAlignment(Align
);
154 #if HAVE_LLVM < 0x0306
155 typedef llvm::JITMemoryManager BaseMemoryManager
;
157 typedef llvm::RTDyldMemoryManager BaseMemoryManager
;
162 * Delegating is tedious but the default manager class is hidden in an
163 * anonymous namespace in LLVM, so we cannot just derive from it to change
166 class DelegatingJITMemoryManager
: public BaseMemoryManager
{
169 virtual BaseMemoryManager
*mgr() const = 0;
172 #if HAVE_LLVM < 0x0306
174 * From JITMemoryManager
176 virtual void setMemoryWritable() {
177 mgr()->setMemoryWritable();
179 virtual void setMemoryExecutable() {
180 mgr()->setMemoryExecutable();
182 virtual void setPoisonMemory(bool poison
) {
183 mgr()->setPoisonMemory(poison
);
185 virtual void AllocateGOT() {
186 mgr()->AllocateGOT();
188 * isManagingGOT() is not virtual in base class so we can't delegate.
189 * Instead we mirror the value of HasGOT in our instance.
191 HasGOT
= mgr()->isManagingGOT();
193 virtual uint8_t *getGOTBase() const {
194 return mgr()->getGOTBase();
196 virtual uint8_t *startFunctionBody(const llvm::Function
*F
,
197 uintptr_t &ActualSize
) {
198 return mgr()->startFunctionBody(F
, ActualSize
);
200 virtual uint8_t *allocateStub(const llvm::GlobalValue
*F
,
202 unsigned Alignment
) {
203 return mgr()->allocateStub(F
, StubSize
, Alignment
);
205 virtual void endFunctionBody(const llvm::Function
*F
,
206 uint8_t *FunctionStart
,
207 uint8_t *FunctionEnd
) {
208 mgr()->endFunctionBody(F
, FunctionStart
, FunctionEnd
);
210 virtual uint8_t *allocateSpace(intptr_t Size
, unsigned Alignment
) {
211 return mgr()->allocateSpace(Size
, Alignment
);
213 virtual uint8_t *allocateGlobal(uintptr_t Size
, unsigned Alignment
) {
214 return mgr()->allocateGlobal(Size
, Alignment
);
216 virtual void deallocateFunctionBody(void *Body
) {
217 mgr()->deallocateFunctionBody(Body
);
219 #if HAVE_LLVM < 0x0304
220 virtual uint8_t *startExceptionTable(const llvm::Function
*F
,
221 uintptr_t &ActualSize
) {
222 return mgr()->startExceptionTable(F
, ActualSize
);
224 virtual void endExceptionTable(const llvm::Function
*F
,
227 uint8_t *FrameRegister
) {
228 mgr()->endExceptionTable(F
, TableStart
, TableEnd
,
231 virtual void deallocateExceptionTable(void *ET
) {
232 mgr()->deallocateExceptionTable(ET
);
235 virtual bool CheckInvariants(std::string
&s
) {
236 return mgr()->CheckInvariants(s
);
238 virtual size_t GetDefaultCodeSlabSize() {
239 return mgr()->GetDefaultCodeSlabSize();
241 virtual size_t GetDefaultDataSlabSize() {
242 return mgr()->GetDefaultDataSlabSize();
244 virtual size_t GetDefaultStubSlabSize() {
245 return mgr()->GetDefaultStubSlabSize();
247 virtual unsigned GetNumCodeSlabs() {
248 return mgr()->GetNumCodeSlabs();
250 virtual unsigned GetNumDataSlabs() {
251 return mgr()->GetNumDataSlabs();
253 virtual unsigned GetNumStubSlabs() {
254 return mgr()->GetNumStubSlabs();
259 * From RTDyldMemoryManager
261 #if HAVE_LLVM >= 0x0304
262 virtual uint8_t *allocateCodeSection(uintptr_t Size
,
265 llvm::StringRef SectionName
) {
266 return mgr()->allocateCodeSection(Size
, Alignment
, SectionID
,
270 virtual uint8_t *allocateCodeSection(uintptr_t Size
,
272 unsigned SectionID
) {
273 return mgr()->allocateCodeSection(Size
, Alignment
, SectionID
);
276 virtual uint8_t *allocateDataSection(uintptr_t Size
,
279 #if HAVE_LLVM >= 0x0304
280 llvm::StringRef SectionName
,
283 return mgr()->allocateDataSection(Size
, Alignment
, SectionID
,
284 #if HAVE_LLVM >= 0x0304
289 #if HAVE_LLVM >= 0x0304
290 virtual void registerEHFrames(uint8_t *Addr
, uint64_t LoadAddr
, size_t Size
) {
291 mgr()->registerEHFrames(Addr
, LoadAddr
, Size
);
293 virtual void deregisterEHFrames(uint8_t *Addr
, uint64_t LoadAddr
, size_t Size
) {
294 mgr()->deregisterEHFrames(Addr
, LoadAddr
, Size
);
297 virtual void registerEHFrames(llvm::StringRef SectionData
) {
298 mgr()->registerEHFrames(SectionData
);
301 virtual void *getPointerToNamedFunction(const std::string
&Name
,
302 bool AbortOnFailure
=true) {
303 return mgr()->getPointerToNamedFunction(Name
, AbortOnFailure
);
305 #if HAVE_LLVM <= 0x0303
306 virtual bool applyPermissions(std::string
*ErrMsg
= 0) {
307 return mgr()->applyPermissions(ErrMsg
);
310 virtual bool finalizeMemory(std::string
*ErrMsg
= 0) {
311 return mgr()->finalizeMemory(ErrMsg
);
318 * Delegate memory management to one shared manager for more efficient use
319 * of memory than creating a separate pool for each LLVM engine.
320 * Keep generated code until freeGeneratedCode() is called, instead of when
321 * memory manager is destroyed, which happens during engine destruction.
322 * This allows additional memory savings as we don't have to keep the engine
323 * around in order to use the code.
324 * All methods are delegated to the shared manager except destruction and
325 * deallocating code. For the latter we just remember what needs to be
326 * deallocated later. The shared manager is deleted once it is empty.
328 class ShaderMemoryManager
: public DelegatingJITMemoryManager
{
330 BaseMemoryManager
*TheMM
;
332 struct GeneratedCode
{
333 typedef std::vector
<void *> Vec
;
334 Vec FunctionBody
, ExceptionTable
;
335 BaseMemoryManager
*TheMM
;
337 GeneratedCode(BaseMemoryManager
*MM
) {
343 * Deallocate things as previously requested and
344 * free shared manager when no longer used.
346 #if HAVE_LLVM < 0x0306
350 for ( i
= FunctionBody
.begin(); i
!= FunctionBody
.end(); ++i
)
351 TheMM
->deallocateFunctionBody(*i
);
352 #if HAVE_LLVM < 0x0304
353 for ( i
= ExceptionTable
.begin(); i
!= ExceptionTable
.end(); ++i
)
354 TheMM
->deallocateExceptionTable(*i
);
355 #endif /* HAVE_LLVM < 0x0304 */
356 #endif /* HAVE_LLVM < 0x0306 */
362 BaseMemoryManager
*mgr() const {
368 ShaderMemoryManager(BaseMemoryManager
* MM
) {
370 code
= new GeneratedCode(MM
);
373 virtual ~ShaderMemoryManager() {
375 * 'code' is purposely not deleted. It is the user's responsibility
376 * to call getGeneratedCode() and freeGeneratedCode().
380 struct lp_generated_code
*getGeneratedCode() {
381 return (struct lp_generated_code
*) code
;
384 static void freeGeneratedCode(struct lp_generated_code
*code
) {
385 delete (GeneratedCode
*) code
;
388 #if HAVE_LLVM < 0x0304
389 virtual void deallocateExceptionTable(void *ET
) {
390 // remember for later deallocation
391 code
->ExceptionTable
.push_back(ET
);
395 virtual void deallocateFunctionBody(void *Body
) {
396 // remember for later deallocation
397 code
->FunctionBody
.push_back(Body
);
403 * Same as LLVMCreateJITCompilerForModule, but:
404 * - allows using MCJIT and enabling AVX feature where available.
405 * - set target options
408 * - llvm/lib/ExecutionEngine/ExecutionEngineBindings.cpp
409 * - llvm/tools/lli/lli.cpp
410 * - http://markmail.org/message/ttkuhvgj4cxxy2on#query:+page:1+mid:aju2dggerju3ivd3+state:results
414 lp_build_create_jit_compiler_for_module(LLVMExecutionEngineRef
*OutJIT
,
415 lp_generated_code
**OutCode
,
417 LLVMMCJITMemoryManagerRef CMM
,
422 using namespace llvm
;
425 #if HAVE_LLVM >= 0x0306
426 EngineBuilder
builder(std::unique_ptr
<Module
>(unwrap(M
)));
428 EngineBuilder
builder(unwrap(M
));
432 * LLVM 3.1+ haven't more "extern unsigned llvm::StackAlignmentOverride" and
433 * friends for configuring code generation options, like stack alignment.
435 TargetOptions options
;
436 #if defined(PIPE_ARCH_X86)
437 options
.StackAlignmentOverride
= 4;
438 #if HAVE_LLVM < 0x0304
439 options
.RealignStack
= true;
443 #if defined(DEBUG) && HAVE_LLVM < 0x0307
444 options
.JITEmitDebugInfo
= true;
447 /* XXX: Workaround http://llvm.org/PR21435 */
448 #if defined(DEBUG) || defined(PROFILE) || \
449 (HAVE_LLVM >= 0x0303 && (defined(PIPE_ARCH_X86) || defined(PIPE_ARCH_X86_64)))
450 #if HAVE_LLVM < 0x0304
451 options
.NoFramePointerElimNonLeaf
= true;
453 #if HAVE_LLVM < 0x0307
454 options
.NoFramePointerElim
= true;
458 builder
.setEngineKind(EngineKind::JIT
)
460 .setTargetOptions(options
)
461 .setOptLevel((CodeGenOpt::Level
)OptLevel
);
464 #if HAVE_LLVM < 0x0306
465 builder
.setUseMCJIT(true);
469 * MCJIT works on Windows, but currently only through ELF object format.
471 std::string targetTriple
= llvm::sys::getProcessTriple();
472 targetTriple
.append("-elf");
473 unwrap(M
)->setTargetTriple(targetTriple
);
477 llvm::SmallVector
<std::string
, 1> MAttrs
;
478 if (util_cpu_caps
.has_avx
) {
480 * AVX feature is not automatically detected from CPUID by the X86 target
481 * yet, because the old (yet default) JIT engine is not capable of
482 * emitting the opcodes. On newer llvm versions it is and at least some
483 * versions (tested with 3.3) will emit avx opcodes without this anyway.
485 MAttrs
.push_back("+avx");
486 if (util_cpu_caps
.has_f16c
) {
487 MAttrs
.push_back("+f16c");
489 builder
.setMAttrs(MAttrs
);
492 #if HAVE_LLVM >= 0x0305
493 StringRef MCPU
= llvm::sys::getHostCPUName();
495 * The cpu bits are no longer set automatically, so need to set mcpu manually.
496 * Note that the MAttrs set above will be sort of ignored (since we should
497 * not set any which would not be set by specifying the cpu anyway).
498 * It ought to be safe though since getHostCPUName() should include bits
499 * not only from the cpu but environment as well (for instance if it's safe
500 * to use avx instructions which need OS support). According to
501 * http://llvm.org/bugs/show_bug.cgi?id=19429 however if I understand this
502 * right it may be necessary to specify older cpu (or disable mattrs) though
503 * when not using MCJIT so no instructions are generated which the old JIT
504 * can't handle. Not entirely sure if we really need to do anything yet.
506 builder
.setMCPU(MCPU
);
509 ShaderMemoryManager
*MM
= NULL
;
511 #if HAVE_LLVM > 0x0303
512 BaseMemoryManager
* JMM
= reinterpret_cast<BaseMemoryManager
*>(CMM
);
513 MM
= new ShaderMemoryManager(JMM
);
514 *OutCode
= MM
->getGeneratedCode();
516 #if HAVE_LLVM >= 0x0306
517 builder
.setMCJITMemoryManager(std::unique_ptr
<RTDyldMemoryManager
>(MM
));
518 MM
= NULL
; // ownership taken by std::unique_ptr
520 builder
.setMCJITMemoryManager(MM
);
524 #if HAVE_LLVM < 0x0306
525 BaseMemoryManager
* JMM
= reinterpret_cast<BaseMemoryManager
*>(CMM
);
526 MM
= new ShaderMemoryManager(JMM
);
527 *OutCode
= MM
->getGeneratedCode();
529 builder
.setJITMemoryManager(MM
);
535 ExecutionEngine
*JIT
;
537 JIT
= builder
.create();
542 lp_free_generated_code(*OutCode
);
545 *OutError
= strdup(Error
.c_str());
552 lp_free_generated_code(struct lp_generated_code
*code
)
554 ShaderMemoryManager::freeGeneratedCode(code
);
558 LLVMMCJITMemoryManagerRef
559 lp_get_default_memory_manager()
561 BaseMemoryManager
*mm
;
562 #if HAVE_LLVM < 0x0306
563 mm
= llvm::JITMemoryManager::CreateDefaultMemManager();
565 mm
= new llvm::SectionMemoryManager();
567 return reinterpret_cast<LLVMMCJITMemoryManagerRef
>(mm
);
572 lp_free_memory_manager(LLVMMCJITMemoryManagerRef memorymgr
)
574 delete reinterpret_cast<BaseMemoryManager
*>(memorymgr
);