2 // Copyright 2012 Francisco Jerez
4 // Permission is hereby granted, free of charge, to any person obtaining a
5 // copy of this software and associated documentation files (the "Software"),
6 // to deal in the Software without restriction, including without limitation
7 // the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 // and/or sell copies of the Software, and to permit persons to whom the
9 // Software is furnished to do so, subject to the following conditions:
11 // The above copyright notice and this permission notice shall be included in
12 // all copies or substantial portions of the Software.
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 NONINFRINGEMENT. IN NO EVENT SHALL
17 // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
18 // OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
19 // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
20 // OTHER DEALINGS IN THE SOFTWARE.
23 #include "core/compiler.hpp"
25 #include <clang/Frontend/CompilerInstance.h>
26 #include <clang/Frontend/TextDiagnosticBuffer.h>
27 #include <clang/Frontend/TextDiagnosticPrinter.h>
28 #include <clang/CodeGen/CodeGenAction.h>
29 #include <clang/Basic/TargetInfo.h>
30 #include <llvm/Bitcode/BitstreamWriter.h>
31 #include <llvm/Bitcode/ReaderWriter.h>
32 #if HAVE_LLVM < 0x0305
33 #include <llvm/Linker.h>
35 #include <llvm/Linker/Linker.h>
36 #include <llvm/IR/DiagnosticInfo.h>
37 #include <llvm/IR/DiagnosticPrinter.h>
39 #include <llvm/IR/DerivedTypes.h>
40 #include <llvm/IR/LLVMContext.h>
41 #include <llvm/IR/Module.h>
42 #include <llvm/Support/SourceMgr.h>
43 #include <llvm/IRReader/IRReader.h>
44 #if HAVE_LLVM < 0x0305
45 #include <llvm/ADT/OwningPtr.h>
47 #include <llvm/PassManager.h>
48 #include <llvm/Support/CodeGen.h>
49 #include <llvm/Support/TargetSelect.h>
50 #include <llvm/Support/MemoryBuffer.h>
51 #include <llvm/Support/FormattedStream.h>
52 #include <llvm/Support/TargetRegistry.h>
53 #include <llvm/Transforms/IPO.h>
54 #include <llvm/Transforms/IPO/PassManagerBuilder.h>
55 #include <llvm/Transforms/Utils/Cloning.h>
58 #include <llvm/IR/DataLayout.h>
59 #if HAVE_LLVM >= 0x0307
60 #include <llvm/Analysis/TargetLibraryInfo.h>
62 #include <llvm/Target/TargetLibraryInfo.h>
64 #include <llvm/Target/TargetMachine.h>
65 #include <llvm/Target/TargetOptions.h>
67 #include <llvm-c/Target.h>
68 #include <llvm-c/TargetMachine.h>
69 #include <llvm-c/Core.h>
71 #include "pipe/p_state.h"
72 #include "util/u_memory.h"
73 #include "util/u_math.h"
83 using namespace clover
;
88 build_binary(const std::string
&source
, const std::string
&target
,
89 const std::string
&name
) {
90 clang::CompilerInstance c
;
91 clang::EmitObjAction
act(&llvm::getGlobalContext());
93 llvm::raw_string_ostream
s_log(log
);
95 LLVMInitializeTGSITarget();
96 LLVMInitializeTGSITargetInfo();
97 LLVMInitializeTGSITargetMC();
98 LLVMInitializeTGSIAsmPrinter();
100 c
.getFrontendOpts().Inputs
.push_back(
101 std::make_pair(clang::IK_OpenCL
, name
));
102 c
.getHeaderSearchOpts().UseBuiltinIncludes
= false;
103 c
.getHeaderSearchOpts().UseStandardIncludes
= false;
104 c
.getLangOpts().NoBuiltin
= true;
105 c
.getTargetOpts().Triple
= target
;
106 c
.getInvocation().setLangDefaults(clang::IK_OpenCL
);
107 c
.createDiagnostics(0, NULL
, new clang::TextDiagnosticPrinter(
108 s_log
, c
.getDiagnosticOpts()));
110 c
.getPreprocessorOpts().addRemappedFile(
111 name
, llvm::MemoryBuffer::getMemBuffer(source
));
113 if (!c
.ExecuteAction(act
))
114 throw build_error(log
);
118 load_binary(const char *name
) {
119 std::ifstream
fs((name
));
120 std::vector
<unsigned char> str((std::istreambuf_iterator
<char>(fs
)),
121 (std::istreambuf_iterator
<char>()));
122 compat::istream
cs(str
);
123 return module::deserialize(cs
);
126 void debug_log(const std::string
&msg
, const std::string
&suffix
) {
127 const char *dbg_file
= debug_get_option("CLOVER_DEBUG_FILE", "stderr");
128 if (!strcmp("stderr", dbg_file
)) {
131 std::ofstream
file(dbg_file
+ suffix
, std::ios::app
);
137 compile_llvm(llvm::LLVMContext
&llvm_ctx
, const std::string
&source
,
138 const header_map
&headers
,
139 const std::string
&name
, const std::string
&triple
,
140 const std::string
&processor
, const std::string
&opts
,
141 clang::LangAS::Map
& address_spaces
, unsigned &optimization_level
,
142 compat::string
&r_log
) {
144 clang::CompilerInstance c
;
145 clang::EmitLLVMOnlyAction
act(&llvm_ctx
);
147 llvm::raw_string_ostream
s_log(log
);
148 std::string libclc_path
= LIBCLC_LIBEXECDIR
+ processor
+ "-"
151 // Parse the compiler options:
152 std::vector
<std::string
> opts_array
;
153 std::istringstream
ss(opts
);
157 getline(ss
, opt
, ' ');
158 opts_array
.push_back(opt
);
161 opts_array
.push_back(name
);
163 std::vector
<const char *> opts_carray
;
164 for (unsigned i
= 0; i
< opts_array
.size(); i
++) {
165 opts_carray
.push_back(opts_array
.at(i
).c_str());
168 llvm::IntrusiveRefCntPtr
<clang::DiagnosticIDs
> DiagID
;
169 llvm::IntrusiveRefCntPtr
<clang::DiagnosticOptions
> DiagOpts
;
170 clang::TextDiagnosticBuffer
*DiagsBuffer
;
172 DiagID
= new clang::DiagnosticIDs();
173 DiagOpts
= new clang::DiagnosticOptions();
174 DiagsBuffer
= new clang::TextDiagnosticBuffer();
176 clang::DiagnosticsEngine
Diags(DiagID
, &*DiagOpts
, DiagsBuffer
);
179 Success
= clang::CompilerInvocation::CreateFromArgs(c
.getInvocation(),
181 opts_carray
.data() + opts_carray
.size(),
184 throw error(CL_INVALID_COMPILER_OPTIONS
);
186 c
.getFrontendOpts().ProgramAction
= clang::frontend::EmitLLVMOnly
;
187 c
.getHeaderSearchOpts().UseBuiltinIncludes
= true;
188 c
.getHeaderSearchOpts().UseStandardSystemIncludes
= true;
189 c
.getHeaderSearchOpts().ResourceDir
= CLANG_RESOURCE_DIR
;
191 // Add libclc generic search path
192 c
.getHeaderSearchOpts().AddPath(LIBCLC_INCLUDEDIR
,
193 clang::frontend::Angled
,
197 // Add libclc include
198 c
.getPreprocessorOpts().Includes
.push_back("clc/clc.h");
200 // clc.h requires that this macro be defined:
201 c
.getPreprocessorOpts().addMacroDef("cl_clang_storage_class_specifiers");
202 c
.getPreprocessorOpts().addMacroDef("cl_khr_fp64");
204 c
.getLangOpts().NoBuiltin
= true;
205 c
.getTargetOpts().Triple
= triple
;
206 c
.getTargetOpts().CPU
= processor
;
208 // This is a workaround for a Clang bug which causes the number
209 // of warnings and errors to be printed to stderr.
210 // http://www.llvm.org/bugs/show_bug.cgi?id=19735
211 c
.getDiagnosticOpts().ShowCarets
= false;
212 c
.getInvocation().setLangDefaults(c
.getLangOpts(), clang::IK_OpenCL
,
213 clang::LangStandard::lang_opencl11
);
215 new clang::TextDiagnosticPrinter(
217 &c
.getDiagnosticOpts()));
219 #if HAVE_LLVM >= 0x0306
220 c
.getPreprocessorOpts().addRemappedFile(name
,
221 llvm::MemoryBuffer::getMemBuffer(source
).release());
223 c
.getPreprocessorOpts().addRemappedFile(name
,
224 llvm::MemoryBuffer::getMemBuffer(source
));
227 if (headers
.size()) {
228 const std::string tmp_header_path
= "/tmp/clover/";
230 c
.getHeaderSearchOpts().AddPath(tmp_header_path
,
231 clang::frontend::Angled
,
235 for (header_map::const_iterator it
= headers
.begin();
236 it
!= headers
.end(); ++it
) {
237 const std::string path
= tmp_header_path
+ std::string(it
->first
);
238 c
.getPreprocessorOpts().addRemappedFile(path
,
239 #if HAVE_LLVM >= 0x0306
240 llvm::MemoryBuffer::getMemBuffer(it
->second
.c_str()).release());
242 llvm::MemoryBuffer::getMemBuffer(it
->second
.c_str()));
247 // Setting this attribute tells clang to link this file before
248 // performing any optimizations. This is required so that
249 // we can replace calls to the OpenCL C barrier() builtin
250 // with calls to target intrinsics that have the noduplicate
251 // attribute. This attribute will prevent Clang from creating
252 // illegal uses of barrier() (e.g. Moving barrier() inside a conditional
253 // that is no executed by all threads) during its optimizaton passes.
254 c
.getCodeGenOpts().LinkBitcodeFile
= libclc_path
;
256 optimization_level
= c
.getCodeGenOpts().OptimizationLevel
;
259 bool ExecSuccess
= c
.ExecuteAction(act
);
265 // Get address spaces map to be able to find kernel argument address space
266 memcpy(address_spaces
, c
.getTarget().getAddressSpaceMap(),
267 sizeof(address_spaces
));
269 #if HAVE_LLVM >= 0x0306
270 return act
.takeModule().release();
272 return act
.takeModule();
277 find_kernels(llvm::Module
*mod
, std::vector
<llvm::Function
*> &kernels
) {
278 const llvm::NamedMDNode
*kernel_node
=
279 mod
->getNamedMetadata("opencl.kernels");
280 // This means there are no kernels in the program. The spec does not
281 // require that we return an error here, but there will be an error if
282 // the user tries to pass this program to a clCreateKernel() call.
287 for (unsigned i
= 0; i
< kernel_node
->getNumOperands(); ++i
) {
288 #if HAVE_LLVM >= 0x0306
289 kernels
.push_back(llvm::mdconst::dyn_extract
<llvm::Function
>(
291 kernels
.push_back(llvm::dyn_cast
<llvm::Function
>(
293 kernel_node
->getOperand(i
)->getOperand(0)));
298 optimize(llvm::Module
*mod
, unsigned optimization_level
,
299 const std::vector
<llvm::Function
*> &kernels
) {
301 llvm::PassManager PM
;
302 // Add a function internalizer pass.
304 // By default, the function internalizer pass will look for a function
305 // called "main" and then mark all other functions as internal. Marking
306 // functions as internal enables the optimizer to perform optimizations
307 // like function inlining and global dead-code elimination.
309 // When there is no "main" function in a module, the internalize pass will
310 // treat the module like a library, and it won't internalize any functions.
311 // Since there is no "main" function in our kernels, we need to tell
312 // the internalizer pass that this module is not a library by passing a
313 // list of kernel functions to the internalizer. The internalizer will
314 // treat the functions in the list as "main" functions and internalize
315 // all of the other functions.
316 std::vector
<const char*> export_list
;
317 for (std::vector
<llvm::Function
*>::const_iterator I
= kernels
.begin(),
320 llvm::Function
*kernel
= *I
;
321 export_list
.push_back(kernel
->getName().data());
323 #if HAVE_LLVM < 0x0305
324 PM
.add(new llvm::DataLayout(mod
));
325 #elif HAVE_LLVM < 0x0306
326 PM
.add(new llvm::DataLayoutPass(mod
));
328 PM
.add(new llvm::DataLayoutPass());
330 PM
.add(llvm::createInternalizePass(export_list
));
332 llvm::PassManagerBuilder PMB
;
333 PMB
.OptLevel
= optimization_level
;
334 PMB
.LibraryInfo
= new llvm::TargetLibraryInfo(
335 llvm::Triple(mod
->getTargetTriple()));
336 PMB
.populateModulePassManager(PM
);
340 compat::vector
<module::argument
>
341 get_kernel_args(const llvm::Module
*mod
, const std::string
&kernel_name
,
342 const clang::LangAS::Map
&address_spaces
) {
344 compat::vector
<module::argument
> args
;
345 llvm::Function
*kernel_func
= mod
->getFunction(kernel_name
);
347 #if HAVE_LLVM < 0x0305
348 llvm::DataLayout
TD(kernel_func
->getParent()->getDataLayout());
350 llvm::DataLayout
TD(mod
);
353 for (llvm::Function::const_arg_iterator I
= kernel_func
->arg_begin(),
354 E
= kernel_func
->arg_end(); I
!= E
; ++I
) {
355 const llvm::Argument
&arg
= *I
;
357 llvm::Type
*arg_type
= arg
.getType();
358 const unsigned arg_store_size
= TD
.getTypeStoreSize(arg_type
);
360 // OpenCL 1.2 specification, Ch. 6.1.5: "A built-in data
361 // type that is not a power of two bytes in size must be
362 // aligned to the next larger power of two". We need this
363 // alignment for three element vectors, which have
364 // non-power-of-2 store size.
365 const unsigned arg_api_size
= util_next_power_of_two(arg_store_size
);
367 llvm::Type
*target_type
= arg_type
->isIntegerTy() ?
368 TD
.getSmallestLegalIntType(mod
->getContext(), arg_store_size
* 8)
370 unsigned target_size
= TD
.getTypeStoreSize(target_type
);
371 unsigned target_align
= TD
.getABITypeAlignment(target_type
);
373 if (llvm::isa
<llvm::PointerType
>(arg_type
) && arg
.hasByValAttr()) {
375 llvm::dyn_cast
<llvm::PointerType
>(arg_type
)->getElementType();
378 if (arg_type
->isPointerTy()) {
379 unsigned address_space
= llvm::cast
<llvm::PointerType
>(arg_type
)->getAddressSpace();
380 if (address_space
== address_spaces
[clang::LangAS::opencl_local
381 - clang::LangAS::Offset
]) {
382 args
.push_back(module::argument(module::argument::local
,
383 arg_api_size
, target_size
,
385 module::argument::zero_ext
));
387 // XXX: Correctly handle constant address space. There is no
388 // way for r600g to pass a handle for constant buffers back
389 // to clover like it can for global buffers, so
390 // creating constant arguments will break r600g. For now,
391 // continue treating constant buffers as global buffers
392 // until we can come up with a way to create handles for
394 args
.push_back(module::argument(module::argument::global
,
395 arg_api_size
, target_size
,
397 module::argument::zero_ext
));
401 llvm::AttributeSet attrs
= kernel_func
->getAttributes();
402 enum module::argument::ext_type ext_type
=
403 (attrs
.hasAttribute(arg
.getArgNo() + 1,
404 llvm::Attribute::SExt
) ?
405 module::argument::sign_ext
:
406 module::argument::zero_ext
);
409 module::argument(module::argument::scalar
, arg_api_size
,
410 target_size
, target_align
, ext_type
));
414 // Append implicit arguments. XXX - The types, ordering and
415 // vector size of the implicit arguments should depend on the
416 // target according to the selected calling convention.
417 llvm::Type
*size_type
=
418 TD
.getSmallestLegalIntType(mod
->getContext(), sizeof(cl_uint
) * 8);
421 module::argument(module::argument::scalar
, sizeof(cl_uint
),
422 TD
.getTypeStoreSize(size_type
),
423 TD
.getABITypeAlignment(size_type
),
424 module::argument::zero_ext
,
425 module::argument::grid_dimension
));
428 module::argument(module::argument::scalar
, sizeof(cl_uint
),
429 TD
.getTypeStoreSize(size_type
),
430 TD
.getABITypeAlignment(size_type
),
431 module::argument::zero_ext
,
432 module::argument::grid_offset
));
438 build_module_llvm(llvm::Module
*mod
,
439 const std::vector
<llvm::Function
*> &kernels
,
440 clang::LangAS::Map
& address_spaces
) {
443 struct pipe_llvm_program_header header
;
445 llvm::SmallVector
<char, 1024> llvm_bitcode
;
446 llvm::raw_svector_ostream
bitcode_ostream(llvm_bitcode
);
447 llvm::BitstreamWriter
writer(llvm_bitcode
);
448 llvm::WriteBitcodeToFile(mod
, bitcode_ostream
);
449 bitcode_ostream
.flush();
451 for (unsigned i
= 0; i
< kernels
.size(); ++i
) {
452 std::string kernel_name
= kernels
[i
]->getName();
453 compat::vector
<module::argument
> args
=
454 get_kernel_args(mod
, kernel_name
, address_spaces
);
456 m
.syms
.push_back(module::symbol(kernel_name
, 0, i
, args
));
459 header
.num_bytes
= llvm_bitcode
.size();
461 data
.insert(0, (char*)(&header
), sizeof(header
));
462 data
.insert(data
.end(), llvm_bitcode
.begin(),
464 m
.secs
.push_back(module::section(0, module::section::text
,
465 header
.num_bytes
, data
));
471 emit_code(LLVMTargetMachineRef tm
, LLVMModuleRef mod
,
472 LLVMCodeGenFileType file_type
,
473 LLVMMemoryBufferRef
*out_buffer
,
474 compat::string
&r_log
) {
476 char *err_message
= NULL
;
478 err
= LLVMTargetMachineEmitToMemoryBuffer(tm
, mod
, file_type
,
479 &err_message
, out_buffer
);
482 r_log
= std::string(err_message
);
485 LLVMDisposeMessage(err_message
);
493 compile_native(const llvm::Module
*mod
, const std::string
&triple
,
494 const std::string
&processor
, unsigned dump_asm
,
495 compat::string
&r_log
) {
498 LLVMTargetRef target
;
500 LLVMMemoryBufferRef out_buffer
;
501 unsigned buffer_size
;
502 const char *buffer_data
;
503 LLVMModuleRef mod_ref
= wrap(mod
);
505 if (LLVMGetTargetFromTriple(triple
.c_str(), &target
, &error_message
)) {
506 r_log
= std::string(error_message
);
507 LLVMDisposeMessage(error_message
);
511 LLVMTargetMachineRef tm
= LLVMCreateTargetMachine(
512 target
, triple
.c_str(), processor
.c_str(), "",
513 LLVMCodeGenLevelDefault
, LLVMRelocDefault
, LLVMCodeModelDefault
);
516 r_log
= "Could not create TargetMachine: " + triple
;
521 LLVMSetTargetMachineAsmVerbosity(tm
, true);
522 LLVMModuleRef debug_mod
= wrap(llvm::CloneModule(mod
));
523 emit_code(tm
, debug_mod
, LLVMAssemblyFile
, &out_buffer
, r_log
);
524 buffer_size
= LLVMGetBufferSize(out_buffer
);
525 buffer_data
= LLVMGetBufferStart(out_buffer
);
526 debug_log(std::string(buffer_data
, buffer_size
), ".asm");
528 LLVMSetTargetMachineAsmVerbosity(tm
, false);
529 LLVMDisposeMemoryBuffer(out_buffer
);
530 LLVMDisposeModule(debug_mod
);
533 emit_code(tm
, mod_ref
, LLVMObjectFile
, &out_buffer
, r_log
);
535 buffer_size
= LLVMGetBufferSize(out_buffer
);
536 buffer_data
= LLVMGetBufferStart(out_buffer
);
538 std::vector
<char> code(buffer_data
, buffer_data
+ buffer_size
);
540 LLVMDisposeMemoryBuffer(out_buffer
);
541 LLVMDisposeTargetMachine(tm
);
546 std::map
<std::string
, unsigned>
547 get_kernel_offsets(std::vector
<char> &code
,
548 const std::vector
<llvm::Function
*> &kernels
,
549 compat::string
&r_log
) {
551 // One of the libelf implementations
552 // (http://www.mr511.de/software/english.htm) requires calling
553 // elf_version() before elf_memory().
555 elf_version(EV_CURRENT
);
557 Elf
*elf
= elf_memory(&code
[0], code
.size());
558 size_t section_str_index
;
559 elf_getshdrstrndx(elf
, §ion_str_index
);
560 Elf_Scn
*section
= NULL
;
561 Elf_Scn
*symtab
= NULL
;
562 GElf_Shdr symtab_header
;
564 // Find the symbol table
566 while ((section
= elf_nextscn(elf
, section
))) {
568 if (gelf_getshdr(section
, &symtab_header
) != &symtab_header
) {
569 r_log
= "Failed to read ELF section header.";
572 name
= elf_strptr(elf
, section_str_index
, symtab_header
.sh_name
);
573 if (!strcmp(name
, ".symtab")) {
579 r_log
= "Unable to find symbol table.";
582 } catch (build_error
&e
) {
588 // Extract symbol information from the table
589 Elf_Data
*symtab_data
= NULL
;
593 std::map
<std::string
, unsigned> kernel_offsets
;
594 symtab_data
= elf_getdata(symtab
, symtab_data
);
596 // Determine the offsets for each kernel
597 for (int i
= 0; (symbol
= gelf_getsym(symtab_data
, i
, &s
)); i
++) {
598 char *name
= elf_strptr(elf
, symtab_header
.sh_link
, symbol
->st_name
);
599 for (std::vector
<llvm::Function
*>::const_iterator it
= kernels
.begin(),
600 e
= kernels
.end(); it
!= e
; ++it
) {
601 llvm::Function
*f
= *it
;
602 if (f
->getName() == std::string(name
))
603 kernel_offsets
[f
->getName()] = symbol
->st_value
;
607 return kernel_offsets
;
611 build_module_native(std::vector
<char> &code
,
612 const llvm::Module
*mod
,
613 const std::vector
<llvm::Function
*> &kernels
,
614 const clang::LangAS::Map
&address_spaces
,
615 compat::string
&r_log
) {
617 std::map
<std::string
, unsigned> kernel_offsets
=
618 get_kernel_offsets(code
, kernels
, r_log
);
620 // Begin building the clover module
622 struct pipe_llvm_program_header header
;
624 // Store the generated ELF binary in the module's text section.
625 header
.num_bytes
= code
.size();
627 data
.append((char*)(&header
), sizeof(header
));
628 data
.append(code
.begin(), code
.end());
629 m
.secs
.push_back(module::section(0, module::section::text
,
630 header
.num_bytes
, data
));
632 for (std::map
<std::string
, unsigned>::iterator i
= kernel_offsets
.begin(),
633 e
= kernel_offsets
.end(); i
!= e
; ++i
) {
634 compat::vector
<module::argument
> args
=
635 get_kernel_args(mod
, i
->first
, address_spaces
);
636 m
.syms
.push_back(module::symbol(i
->first
, 0, i
->second
, args
));
642 #if HAVE_LLVM >= 0x0305
645 diagnostic_handler(const llvm::DiagnosticInfo
&di
, void *data
) {
646 if (di
.getSeverity() == llvm::DS_Error
) {
647 std::string message
= *(compat::string
*)data
;
648 llvm::raw_string_ostream
stream(message
);
649 llvm::DiagnosticPrinterRawOStream
dp(stream
);
652 *(compat::string
*)data
= message
;
662 static bool targets_initialized
= false;
663 if (!targets_initialized
) {
664 LLVMInitializeAllTargets();
665 LLVMInitializeAllTargetInfos();
666 LLVMInitializeAllTargetMCs();
667 LLVMInitializeAllAsmPrinters();
668 targets_initialized
= true;
671 } // End anonymous namespace
673 #define DBG_CLC (1 << 0)
674 #define DBG_LLVM (1 << 1)
675 #define DBG_ASM (1 << 2)
677 static const struct debug_named_value debug_options
[] = {
678 {"clc", DBG_CLC
, "Dump the OpenCL C code for all kernels."},
679 {"llvm", DBG_LLVM
, "Dump the generated LLVM IR for all kernels."},
680 {"asm", DBG_ASM
, "Dump kernel assembly code for targets specifying "
681 "PIPE_SHADER_IR_NATIVE"},
682 DEBUG_NAMED_VALUE_END
// must be last
686 clover::compile_program_llvm(const compat::string
&source
,
687 const header_map
&headers
,
688 enum pipe_shader_ir ir
,
689 const compat::string
&target
,
690 const compat::string
&opts
,
691 compat::string
&r_log
) {
694 static unsigned debug_flags
= debug_get_flags_option("CLOVER_DEBUG",
697 std::vector
<llvm::Function
*> kernels
;
698 size_t processor_str_len
= std::string(target
.begin()).find_first_of("-");
699 std::string
processor(target
.begin(), 0, processor_str_len
);
700 std::string
triple(target
.begin(), processor_str_len
+ 1,
701 target
.size() - processor_str_len
- 1);
702 clang::LangAS::Map address_spaces
;
703 llvm::LLVMContext llvm_ctx
;
704 unsigned optimization_level
;
706 #if HAVE_LLVM >= 0x0305
707 llvm_ctx
.setDiagnosticHandler(diagnostic_handler
, &r_log
);
710 // The input file name must have the .cl extension in order for the
711 // CompilerInvocation class to recognize it as an OpenCL source file.
712 llvm::Module
*mod
= compile_llvm(llvm_ctx
, source
, headers
, "input.cl",
713 triple
, processor
, opts
, address_spaces
,
714 optimization_level
, r_log
);
716 find_kernels(mod
, kernels
);
718 optimize(mod
, optimization_level
, kernels
);
720 if (debug_flags
& DBG_CLC
)
721 debug_log(source
, ".cl");
723 if (debug_flags
& DBG_LLVM
) {
725 llvm::raw_string_ostream
s_log(log
);
726 mod
->print(s_log
, NULL
);
728 debug_log(log
, ".ll");
732 // Build the clover::module
734 case PIPE_SHADER_IR_TGSI
:
739 case PIPE_SHADER_IR_LLVM
:
740 m
= build_module_llvm(mod
, kernels
, address_spaces
);
742 case PIPE_SHADER_IR_NATIVE
: {
743 std::vector
<char> code
= compile_native(mod
, triple
, processor
,
744 debug_flags
& DBG_ASM
, r_log
);
745 m
= build_module_native(code
, mod
, kernels
, address_spaces
, r_log
);
749 #if HAVE_LLVM >= 0x0306
750 // LLVM 3.6 and newer, the user takes ownership of the module.