2 // Copyright 2012-2016 Francisco Jerez
3 // Copyright 2012-2016 Advanced Micro Devices, Inc.
4 // Copyright 2014-2016 Jan Vesely
5 // Copyright 2014-2015 Serge Martin
6 // Copyright 2015 Zoltan Gilian
8 // Permission is hereby granted, free of charge, to any person obtaining a
9 // copy of this software and associated documentation files (the "Software"),
10 // to deal in the Software without restriction, including without limitation
11 // the rights to use, copy, modify, merge, publish, distribute, sublicense,
12 // and/or sell copies of the Software, and to permit persons to whom the
13 // Software is furnished to do so, subject to the following conditions:
15 // The above copyright notice and this permission notice shall be included in
16 // all copies or substantial portions of the Software.
18 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21 // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
22 // OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
23 // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
24 // OTHER DEALINGS IN THE SOFTWARE.
27 #include "core/compiler.hpp"
29 #include <clang/Frontend/CompilerInstance.h>
30 #include <clang/Frontend/TextDiagnosticBuffer.h>
31 #include <clang/Frontend/TextDiagnosticPrinter.h>
32 #include <clang/CodeGen/CodeGenAction.h>
33 #include <clang/Basic/TargetInfo.h>
34 #include <llvm/Bitcode/BitstreamWriter.h>
35 #include <llvm/Bitcode/ReaderWriter.h>
36 #include <llvm/Linker/Linker.h>
37 #include <llvm/IR/DiagnosticInfo.h>
38 #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 >= 0x0307
45 #include <llvm/IR/LegacyPassManager.h>
47 #include <llvm/PassManager.h>
49 #include <llvm/Support/CodeGen.h>
50 #include <llvm/Support/TargetSelect.h>
51 #include <llvm/Support/MemoryBuffer.h>
52 #include <llvm/Support/FormattedStream.h>
53 #include <llvm/Support/TargetRegistry.h>
54 #include <llvm/Transforms/IPO.h>
55 #include <llvm/Transforms/IPO/PassManagerBuilder.h>
56 #include <llvm/Transforms/Utils/Cloning.h>
59 #include <llvm/IR/DataLayout.h>
60 #if HAVE_LLVM >= 0x0307
61 #include <llvm/Analysis/TargetLibraryInfo.h>
63 #include <llvm/Target/TargetLibraryInfo.h>
65 #include <llvm/Target/TargetMachine.h>
66 #include <llvm/Target/TargetOptions.h>
68 #include <llvm-c/Target.h>
69 #include <llvm-c/TargetMachine.h>
70 #include <llvm-c/Core.h>
72 #include "pipe/p_state.h"
73 #include "util/u_memory.h"
74 #include "util/u_math.h"
84 using namespace clover
;
89 build_binary(const std::string
&source
, const std::string
&target
,
90 const std::string
&name
) {
91 clang::CompilerInstance c
;
92 clang::EmitObjAction
act(&llvm::getGlobalContext());
94 llvm::raw_string_ostream
s_log(log
);
96 LLVMInitializeTGSITarget();
97 LLVMInitializeTGSITargetInfo();
98 LLVMInitializeTGSITargetMC();
99 LLVMInitializeTGSIAsmPrinter();
101 c
.getFrontendOpts().Inputs
.push_back(
102 std::make_pair(clang::IK_OpenCL
, name
));
103 c
.getHeaderSearchOpts().UseBuiltinIncludes
= false;
104 c
.getHeaderSearchOpts().UseStandardIncludes
= false;
105 c
.getLangOpts().NoBuiltin
= true;
106 c
.getTargetOpts().Triple
= target
;
107 c
.getInvocation().setLangDefaults(clang::IK_OpenCL
);
108 c
.createDiagnostics(0, NULL
, new clang::TextDiagnosticPrinter(
109 s_log
, c
.getDiagnosticOpts()));
111 c
.getPreprocessorOpts().addRemappedFile(
112 name
, llvm::MemoryBuffer::getMemBuffer(source
));
114 if (!c
.ExecuteAction(act
))
115 throw compile_error(log
);
119 load_binary(const char *name
) {
120 std::ifstream
fs((name
));
121 std::vector
<unsigned char> str((std::istreambuf_iterator
<char>(fs
)),
122 (std::istreambuf_iterator
<char>()));
123 compat::istream
cs(str
);
124 return module::deserialize(cs
);
127 void debug_log(const std::string
&msg
, const std::string
&suffix
) {
128 const char *dbg_file
= debug_get_option("CLOVER_DEBUG_FILE", "stderr");
129 if (!strcmp("stderr", dbg_file
)) {
132 std::ofstream
file(dbg_file
+ suffix
, std::ios::app
);
138 compile_llvm(llvm::LLVMContext
&llvm_ctx
, const std::string
&source
,
139 const header_map
&headers
,
140 const std::string
&name
, const std::string
&triple
,
141 const std::string
&processor
, const std::string
&opts
,
142 clang::LangAS::Map
& address_spaces
, unsigned &optimization_level
,
143 std::string
&r_log
) {
145 clang::CompilerInstance c
;
146 clang::EmitLLVMOnlyAction
act(&llvm_ctx
);
148 llvm::raw_string_ostream
s_log(log
);
149 std::string libclc_path
= LIBCLC_LIBEXECDIR
+ processor
+ "-"
152 // Parse the compiler options:
153 std::vector
<std::string
> opts_array
;
154 std::istringstream
ss(opts
);
158 getline(ss
, opt
, ' ');
159 opts_array
.push_back(opt
);
162 opts_array
.push_back(name
);
164 std::vector
<const char *> opts_carray
;
165 for (unsigned i
= 0; i
< opts_array
.size(); i
++) {
166 opts_carray
.push_back(opts_array
.at(i
).c_str());
169 llvm::IntrusiveRefCntPtr
<clang::DiagnosticIDs
> DiagID
;
170 llvm::IntrusiveRefCntPtr
<clang::DiagnosticOptions
> DiagOpts
;
171 clang::TextDiagnosticBuffer
*DiagsBuffer
;
173 DiagID
= new clang::DiagnosticIDs();
174 DiagOpts
= new clang::DiagnosticOptions();
175 DiagsBuffer
= new clang::TextDiagnosticBuffer();
177 clang::DiagnosticsEngine
Diags(DiagID
, &*DiagOpts
, DiagsBuffer
);
180 Success
= clang::CompilerInvocation::CreateFromArgs(c
.getInvocation(),
182 opts_carray
.data() + opts_carray
.size(),
185 throw error(CL_INVALID_COMPILER_OPTIONS
);
187 c
.getFrontendOpts().ProgramAction
= clang::frontend::EmitLLVMOnly
;
188 c
.getHeaderSearchOpts().UseBuiltinIncludes
= true;
189 c
.getHeaderSearchOpts().UseStandardSystemIncludes
= true;
190 c
.getHeaderSearchOpts().ResourceDir
= CLANG_RESOURCE_DIR
;
192 // Add libclc generic search path
193 c
.getHeaderSearchOpts().AddPath(LIBCLC_INCLUDEDIR
,
194 clang::frontend::Angled
,
198 // Add libclc include
199 c
.getPreprocessorOpts().Includes
.push_back("clc/clc.h");
201 // clc.h requires that this macro be defined:
202 c
.getPreprocessorOpts().addMacroDef("cl_clang_storage_class_specifiers");
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 #if HAVE_LLVM >= 0x0309
214 llvm::Triple(triple
), c
.getPreprocessorOpts(),
216 clang::LangStandard::lang_opencl11
);
218 new clang::TextDiagnosticPrinter(
220 &c
.getDiagnosticOpts()));
222 c
.getPreprocessorOpts().addRemappedFile(name
,
223 llvm::MemoryBuffer::getMemBuffer(source
).release());
225 if (headers
.size()) {
226 const std::string tmp_header_path
= "/tmp/clover/";
228 c
.getHeaderSearchOpts().AddPath(tmp_header_path
,
229 clang::frontend::Angled
,
233 for (header_map::const_iterator it
= headers
.begin();
234 it
!= headers
.end(); ++it
) {
235 const std::string path
= tmp_header_path
+ std::string(it
->first
);
236 c
.getPreprocessorOpts().addRemappedFile(path
,
237 llvm::MemoryBuffer::getMemBuffer(it
->second
.c_str()).release());
241 // Setting this attribute tells clang to link this file before
242 // performing any optimizations. This is required so that
243 // we can replace calls to the OpenCL C barrier() builtin
244 // with calls to target intrinsics that have the noduplicate
245 // attribute. This attribute will prevent Clang from creating
246 // illegal uses of barrier() (e.g. Moving barrier() inside a conditional
247 // that is no executed by all threads) during its optimizaton passes.
248 #if HAVE_LLVM >= 0x0308
249 c
.getCodeGenOpts().LinkBitcodeFiles
.emplace_back(llvm::Linker::Flags::None
,
252 c
.getCodeGenOpts().LinkBitcodeFile
= libclc_path
;
254 optimization_level
= c
.getCodeGenOpts().OptimizationLevel
;
257 bool ExecSuccess
= c
.ExecuteAction(act
);
261 throw compile_error();
263 // Get address spaces map to be able to find kernel argument address space
264 memcpy(address_spaces
, c
.getTarget().getAddressSpaceMap(),
265 sizeof(address_spaces
));
267 return act
.takeModule().release();
270 std::vector
<llvm::Function
*>
271 find_kernels(llvm::Module
*mod
) {
272 std::vector
<llvm::Function
*> kernels
;
273 #if HAVE_LLVM >= 0x0309
274 auto &list
= mod
->getFunctionList();
275 for_each(list
.begin(), list
.end(), [&](llvm::Function
&f
){
276 if (f
.getMetadata("kernel_arg_type"))
277 kernels
.push_back(&f
);
281 const llvm::NamedMDNode
*kernel_node
=
282 mod
->getNamedMetadata("opencl.kernels");
283 // This means there are no kernels in the program. The spec does not
284 // require that we return an error here, but there will be an error if
285 // the user tries to pass this program to a clCreateKernel() call.
287 return std::vector
<llvm::Function
*>();
290 kernels
.reserve(kernel_node
->getNumOperands());
291 for (unsigned i
= 0; i
< kernel_node
->getNumOperands(); ++i
) {
292 kernels
.push_back(llvm::mdconst::dyn_extract
<llvm::Function
>(
293 kernel_node
->getOperand(i
)->getOperand(0)));
299 optimize(llvm::Module
*mod
, unsigned optimization_level
) {
301 #if HAVE_LLVM >= 0x0307
302 llvm::legacy::PassManager PM
;
304 llvm::PassManager PM
;
307 const std::vector
<llvm::Function
*> kernels
= find_kernels(mod
);
309 // Add a function internalizer pass.
311 // By default, the function internalizer pass will look for a function
312 // called "main" and then mark all other functions as internal. Marking
313 // functions as internal enables the optimizer to perform optimizations
314 // like function inlining and global dead-code elimination.
316 // When there is no "main" function in a module, the internalize pass will
317 // treat the module like a library, and it won't internalize any functions.
318 // Since there is no "main" function in our kernels, we need to tell
319 // the internalizer pass that this module is not a library by passing a
320 // list of kernel functions to the internalizer. The internalizer will
321 // treat the functions in the list as "main" functions and internalize
322 // all of the other functions.
323 #if HAVE_LLVM >= 0x0309
324 auto preserve_kernels
= [=](const llvm::GlobalValue
&GV
) {
325 for (const auto &kernel
: kernels
) {
326 if (GV
.getName() == kernel
->getName())
332 std::vector
<const char*> export_list
;
333 for (std::vector
<llvm::Function
*>::const_iterator I
= kernels
.begin(),
336 llvm::Function
*kernel
= *I
;
337 export_list
.push_back(kernel
->getName().data());
340 #if HAVE_LLVM < 0x0307
341 PM
.add(new llvm::DataLayoutPass());
343 #if HAVE_LLVM >= 0x0309
344 PM
.add(llvm::createInternalizePass(preserve_kernels
));
346 PM
.add(llvm::createInternalizePass(export_list
));
349 llvm::PassManagerBuilder PMB
;
350 PMB
.OptLevel
= optimization_level
;
351 #if HAVE_LLVM < 0x0307
352 PMB
.LibraryInfo
= new llvm::TargetLibraryInfo(
354 PMB
.LibraryInfo
= new llvm::TargetLibraryInfoImpl(
356 llvm::Triple(mod
->getTargetTriple()));
357 PMB
.populateModulePassManager(PM
);
363 struct kernel_arg_md
{
364 llvm::StringRef type_name
;
365 llvm::StringRef access_qual
;
366 kernel_arg_md(llvm::StringRef type_name_
, llvm::StringRef access_qual_
):
367 type_name(type_name_
), access_qual(access_qual_
) {}
369 #if HAVE_LLVM >= 0x0309
370 std::vector
<kernel_arg_md
>
371 get_kernel_arg_md(const llvm::Function
*kernel_func
) {
373 size_t num_args
= kernel_func
->getArgumentList().size();
375 auto aq
= kernel_func
->getMetadata("kernel_arg_access_qual");
376 auto ty
= kernel_func
->getMetadata("kernel_arg_type");
378 std::vector
<kernel_arg_md
> res
;
379 res
.reserve(num_args
);
380 for (size_t i
= 0; i
< num_args
; ++i
) {
381 res
.push_back(kernel_arg_md(
382 llvm::cast
<llvm::MDString
>(ty
->getOperand(i
))->getString(),
383 llvm::cast
<llvm::MDString
>(aq
->getOperand(i
))->getString()));
392 get_kernel_metadata(const llvm::Function
*kernel_func
) {
393 auto mod
= kernel_func
->getParent();
394 auto kernels_node
= mod
->getNamedMetadata("opencl.kernels");
399 const llvm::MDNode
*kernel_node
= nullptr;
400 for (unsigned i
= 0; i
< kernels_node
->getNumOperands(); ++i
) {
401 auto func
= llvm::mdconst::dyn_extract
<llvm::Function
>(
402 kernels_node
->getOperand(i
)->getOperand(0));
403 if (func
== kernel_func
) {
404 kernel_node
= kernels_node
->getOperand(i
);
413 node_from_op_checked(const llvm::MDOperand
&md_operand
,
414 llvm::StringRef expect_name
,
415 unsigned expect_num_args
)
417 auto node
= llvm::cast
<llvm::MDNode
>(md_operand
);
418 assert(node
->getNumOperands() == expect_num_args
&&
419 "Wrong number of operands.");
421 auto str_node
= llvm::cast
<llvm::MDString
>(node
->getOperand(0));
422 assert(str_node
->getString() == expect_name
&&
423 "Wrong metadata node name.");
428 std::vector
<kernel_arg_md
>
429 get_kernel_arg_md(const llvm::Function
*kernel_func
) {
430 auto num_args
= kernel_func
->getArgumentList().size();
432 auto kernel_node
= get_kernel_metadata(kernel_func
);
433 auto aq
= node_from_op_checked(kernel_node
->getOperand(2),
434 "kernel_arg_access_qual", num_args
+ 1);
435 auto ty
= node_from_op_checked(kernel_node
->getOperand(3),
436 "kernel_arg_type", num_args
+ 1);
438 std::vector
<kernel_arg_md
> res
;
439 res
.reserve(num_args
);
440 for (unsigned i
= 0; i
< num_args
; ++i
) {
441 res
.push_back(kernel_arg_md(
442 llvm::cast
<llvm::MDString
>(ty
->getOperand(i
+1))->getString(),
443 llvm::cast
<llvm::MDString
>(aq
->getOperand(i
+1))->getString()));
450 std::vector
<module::argument
>
451 get_kernel_args(const llvm::Module
*mod
, const std::string
&kernel_name
,
452 const clang::LangAS::Map
&address_spaces
) {
454 std::vector
<module::argument
> args
;
455 llvm::Function
*kernel_func
= mod
->getFunction(kernel_name
);
456 assert(kernel_func
&& "Kernel name not found in module.");
457 auto arg_md
= get_kernel_arg_md(kernel_func
);
459 llvm::DataLayout
TD(mod
);
460 llvm::Type
*size_type
=
461 TD
.getSmallestLegalIntType(mod
->getContext(), sizeof(cl_uint
) * 8);
463 for (const auto &arg
: kernel_func
->args()) {
465 llvm::Type
*arg_type
= arg
.getType();
466 const unsigned arg_store_size
= TD
.getTypeStoreSize(arg_type
);
468 // OpenCL 1.2 specification, Ch. 6.1.5: "A built-in data
469 // type that is not a power of two bytes in size must be
470 // aligned to the next larger power of two". We need this
471 // alignment for three element vectors, which have
472 // non-power-of-2 store size.
473 const unsigned arg_api_size
= util_next_power_of_two(arg_store_size
);
475 llvm::Type
*target_type
= arg_type
->isIntegerTy() ?
476 TD
.getSmallestLegalIntType(mod
->getContext(), arg_store_size
* 8)
478 unsigned target_size
= TD
.getTypeStoreSize(target_type
);
479 unsigned target_align
= TD
.getABITypeAlignment(target_type
);
481 llvm::StringRef type_name
= arg_md
[arg
.getArgNo()].type_name
;
482 llvm::StringRef access_qual
= arg_md
[arg
.getArgNo()].access_qual
;
485 const bool is_image2d
= type_name
== "image2d_t";
486 const bool is_image3d
= type_name
== "image3d_t";
487 if (is_image2d
|| is_image3d
) {
488 const bool is_write_only
= access_qual
== "write_only";
489 const bool is_read_only
= access_qual
== "read_only";
491 enum module::argument::type marg_type
;
492 if (is_image2d
&& is_read_only
) {
493 marg_type
= module::argument::image2d_rd
;
494 } else if (is_image2d
&& is_write_only
) {
495 marg_type
= module::argument::image2d_wr
;
496 } else if (is_image3d
&& is_read_only
) {
497 marg_type
= module::argument::image3d_rd
;
498 } else if (is_image3d
&& is_write_only
) {
499 marg_type
= module::argument::image3d_wr
;
501 assert(0 && "Wrong image access qualifier");
504 args
.push_back(module::argument(marg_type
,
505 arg_store_size
, target_size
,
507 module::argument::zero_ext
));
511 // Image size implicit argument
512 if (type_name
== "__llvm_image_size") {
513 args
.push_back(module::argument(module::argument::scalar
,
515 TD
.getTypeStoreSize(size_type
),
516 TD
.getABITypeAlignment(size_type
),
517 module::argument::zero_ext
,
518 module::argument::image_size
));
522 // Image format implicit argument
523 if (type_name
== "__llvm_image_format") {
524 args
.push_back(module::argument(module::argument::scalar
,
526 TD
.getTypeStoreSize(size_type
),
527 TD
.getABITypeAlignment(size_type
),
528 module::argument::zero_ext
,
529 module::argument::image_format
));
534 if (llvm::isa
<llvm::PointerType
>(arg_type
) && arg
.hasByValAttr()) {
536 llvm::dyn_cast
<llvm::PointerType
>(arg_type
)->getElementType();
539 if (arg_type
->isPointerTy()) {
540 unsigned address_space
= llvm::cast
<llvm::PointerType
>(arg_type
)->getAddressSpace();
541 if (address_space
== address_spaces
[clang::LangAS::opencl_local
542 - clang::LangAS::Offset
]) {
543 args
.push_back(module::argument(module::argument::local
,
544 arg_api_size
, target_size
,
546 module::argument::zero_ext
));
548 // XXX: Correctly handle constant address space. There is no
549 // way for r600g to pass a handle for constant buffers back
550 // to clover like it can for global buffers, so
551 // creating constant arguments will break r600g. For now,
552 // continue treating constant buffers as global buffers
553 // until we can come up with a way to create handles for
555 args
.push_back(module::argument(module::argument::global
,
556 arg_api_size
, target_size
,
558 module::argument::zero_ext
));
562 llvm::AttributeSet attrs
= kernel_func
->getAttributes();
563 enum module::argument::ext_type ext_type
=
564 (attrs
.hasAttribute(arg
.getArgNo() + 1,
565 llvm::Attribute::SExt
) ?
566 module::argument::sign_ext
:
567 module::argument::zero_ext
);
570 module::argument(module::argument::scalar
, arg_api_size
,
571 target_size
, target_align
, ext_type
));
575 // Append implicit arguments. XXX - The types, ordering and
576 // vector size of the implicit arguments should depend on the
577 // target according to the selected calling convention.
579 module::argument(module::argument::scalar
, sizeof(cl_uint
),
580 TD
.getTypeStoreSize(size_type
),
581 TD
.getABITypeAlignment(size_type
),
582 module::argument::zero_ext
,
583 module::argument::grid_dimension
));
586 module::argument(module::argument::scalar
, sizeof(cl_uint
),
587 TD
.getTypeStoreSize(size_type
),
588 TD
.getABITypeAlignment(size_type
),
589 module::argument::zero_ext
,
590 module::argument::grid_offset
));
596 build_module_llvm(llvm::Module
*mod
,
597 clang::LangAS::Map
& address_spaces
) {
600 struct pipe_llvm_program_header header
;
602 llvm::SmallVector
<char, 1024> llvm_bitcode
;
603 llvm::raw_svector_ostream
bitcode_ostream(llvm_bitcode
);
604 llvm::BitstreamWriter
writer(llvm_bitcode
);
605 llvm::WriteBitcodeToFile(mod
, bitcode_ostream
);
606 #if HAVE_LLVM < 0x0308
607 bitcode_ostream
.flush();
610 const std::vector
<llvm::Function
*> kernels
= find_kernels(mod
);
611 for (unsigned i
= 0; i
< kernels
.size(); ++i
) {
612 std::string kernel_name
= kernels
[i
]->getName();
613 std::vector
<module::argument
> args
=
614 get_kernel_args(mod
, kernel_name
, address_spaces
);
616 m
.syms
.push_back(module::symbol(kernel_name
, 0, i
, args
));
619 header
.num_bytes
= llvm_bitcode
.size();
620 std::vector
<char> data
;
621 data
.insert(data
.end(), (char*)(&header
),
622 (char*)(&header
) + sizeof(header
));
623 data
.insert(data
.end(), llvm_bitcode
.begin(),
625 m
.secs
.push_back(module::section(0, module::section::text
,
626 header
.num_bytes
, data
));
632 emit_code(LLVMTargetMachineRef tm
, LLVMModuleRef mod
,
633 LLVMCodeGenFileType file_type
,
634 LLVMMemoryBufferRef
*out_buffer
,
635 std::string
&r_log
) {
637 char *err_message
= NULL
;
639 err
= LLVMTargetMachineEmitToMemoryBuffer(tm
, mod
, file_type
,
640 &err_message
, out_buffer
);
643 r_log
= std::string(err_message
);
646 LLVMDisposeMessage(err_message
);
649 throw compile_error();
654 compile_native(const llvm::Module
*mod
, const std::string
&triple
,
655 const std::string
&processor
, unsigned dump_asm
,
656 std::string
&r_log
) {
659 LLVMTargetRef target
;
661 LLVMMemoryBufferRef out_buffer
;
662 unsigned buffer_size
;
663 const char *buffer_data
;
664 LLVMModuleRef mod_ref
= wrap(mod
);
666 if (LLVMGetTargetFromTriple(triple
.c_str(), &target
, &error_message
)) {
667 r_log
= std::string(error_message
);
668 LLVMDisposeMessage(error_message
);
669 throw compile_error();
672 LLVMTargetMachineRef tm
= LLVMCreateTargetMachine(
673 target
, triple
.c_str(), processor
.c_str(), "",
674 LLVMCodeGenLevelDefault
, LLVMRelocDefault
, LLVMCodeModelDefault
);
677 r_log
= "Could not create TargetMachine: " + triple
;
678 throw compile_error();
682 LLVMSetTargetMachineAsmVerbosity(tm
, true);
683 #if HAVE_LLVM >= 0x0308
684 LLVMModuleRef debug_mod
= wrap(llvm::CloneModule(mod
).release());
686 LLVMModuleRef debug_mod
= wrap(llvm::CloneModule(mod
));
688 emit_code(tm
, debug_mod
, LLVMAssemblyFile
, &out_buffer
, r_log
);
689 buffer_size
= LLVMGetBufferSize(out_buffer
);
690 buffer_data
= LLVMGetBufferStart(out_buffer
);
691 debug_log(std::string(buffer_data
, buffer_size
), ".asm");
693 LLVMSetTargetMachineAsmVerbosity(tm
, false);
694 LLVMDisposeMemoryBuffer(out_buffer
);
695 LLVMDisposeModule(debug_mod
);
698 emit_code(tm
, mod_ref
, LLVMObjectFile
, &out_buffer
, r_log
);
700 buffer_size
= LLVMGetBufferSize(out_buffer
);
701 buffer_data
= LLVMGetBufferStart(out_buffer
);
703 std::vector
<char> code(buffer_data
, buffer_data
+ buffer_size
);
705 LLVMDisposeMemoryBuffer(out_buffer
);
706 LLVMDisposeTargetMachine(tm
);
711 std::map
<std::string
, unsigned>
712 get_kernel_offsets(std::vector
<char> &code
,
713 const std::vector
<llvm::Function
*> &kernels
,
714 std::string
&r_log
) {
716 // One of the libelf implementations
717 // (http://www.mr511.de/software/english.htm) requires calling
718 // elf_version() before elf_memory().
720 elf_version(EV_CURRENT
);
722 Elf
*elf
= elf_memory(&code
[0], code
.size());
723 size_t section_str_index
;
724 elf_getshdrstrndx(elf
, §ion_str_index
);
725 Elf_Scn
*section
= NULL
;
726 Elf_Scn
*symtab
= NULL
;
727 GElf_Shdr symtab_header
;
729 // Find the symbol table
731 while ((section
= elf_nextscn(elf
, section
))) {
733 if (gelf_getshdr(section
, &symtab_header
) != &symtab_header
) {
734 r_log
= "Failed to read ELF section header.";
735 throw compile_error();
737 name
= elf_strptr(elf
, section_str_index
, symtab_header
.sh_name
);
738 if (!strcmp(name
, ".symtab")) {
744 r_log
= "Unable to find symbol table.";
745 throw compile_error();
747 } catch (compile_error
&e
) {
753 // Extract symbol information from the table
754 Elf_Data
*symtab_data
= NULL
;
758 std::map
<std::string
, unsigned> kernel_offsets
;
759 symtab_data
= elf_getdata(symtab
, symtab_data
);
761 // Determine the offsets for each kernel
762 for (int i
= 0; (symbol
= gelf_getsym(symtab_data
, i
, &s
)); i
++) {
763 char *name
= elf_strptr(elf
, symtab_header
.sh_link
, symbol
->st_name
);
764 for (std::vector
<llvm::Function
*>::const_iterator it
= kernels
.begin(),
765 e
= kernels
.end(); it
!= e
; ++it
) {
766 llvm::Function
*f
= *it
;
767 if (f
->getName() == std::string(name
))
768 kernel_offsets
[f
->getName()] = symbol
->st_value
;
772 return kernel_offsets
;
776 build_module_native(std::vector
<char> &code
,
778 const clang::LangAS::Map
&address_spaces
,
779 std::string
&r_log
) {
781 const std::vector
<llvm::Function
*> kernels
= find_kernels(mod
);
783 std::map
<std::string
, unsigned> kernel_offsets
=
784 get_kernel_offsets(code
, kernels
, r_log
);
786 // Begin building the clover module
788 struct pipe_llvm_program_header header
;
790 // Store the generated ELF binary in the module's text section.
791 header
.num_bytes
= code
.size();
792 std::vector
<char> data
;
793 data
.insert(data
.end(), (char*)(&header
),
794 (char*)(&header
) + sizeof(header
));
795 data
.insert(data
.end(), code
.begin(), code
.end());
796 m
.secs
.push_back(module::section(0, module::section::text
,
797 header
.num_bytes
, data
));
799 for (std::map
<std::string
, unsigned>::iterator i
= kernel_offsets
.begin(),
800 e
= kernel_offsets
.end(); i
!= e
; ++i
) {
801 std::vector
<module::argument
> args
=
802 get_kernel_args(mod
, i
->first
, address_spaces
);
803 m
.syms
.push_back(module::symbol(i
->first
, 0, i
->second
, args
));
810 diagnostic_handler(const llvm::DiagnosticInfo
&di
, void *data
) {
811 if (di
.getSeverity() == llvm::DS_Error
) {
812 std::string message
= *(std::string
*)data
;
813 llvm::raw_string_ostream
stream(message
);
814 llvm::DiagnosticPrinterRawOStream
dp(stream
);
817 *(std::string
*)data
= message
;
819 throw compile_error();
825 static bool targets_initialized
= false;
826 if (!targets_initialized
) {
827 LLVMInitializeAllTargets();
828 LLVMInitializeAllTargetInfos();
829 LLVMInitializeAllTargetMCs();
830 LLVMInitializeAllAsmPrinters();
831 targets_initialized
= true;
835 #define DBG_CLC (1 << 0)
836 #define DBG_LLVM (1 << 1)
837 #define DBG_ASM (1 << 2)
841 static const struct debug_named_value debug_options
[] = {
842 {"clc", DBG_CLC
, "Dump the OpenCL C code for all kernels."},
843 {"llvm", DBG_LLVM
, "Dump the generated LLVM IR for all kernels."},
844 {"asm", DBG_ASM
, "Dump kernel assembly code for targets specifying "
845 "PIPE_SHADER_IR_NATIVE"},
846 DEBUG_NAMED_VALUE_END
// must be last
848 static const unsigned debug_flags
=
849 debug_get_flags_option("CLOVER_DEBUG", debug_options
, 0);
854 } // End anonymous namespace
857 clover::compile_program_llvm(const std::string
&source
,
858 const header_map
&headers
,
859 enum pipe_shader_ir ir
,
860 const std::string
&target
,
861 const std::string
&opts
,
862 std::string
&r_log
) {
866 size_t processor_str_len
= std::string(target
).find_first_of("-");
867 std::string
processor(target
, 0, processor_str_len
);
868 std::string
triple(target
, processor_str_len
+ 1,
869 target
.size() - processor_str_len
- 1);
870 clang::LangAS::Map address_spaces
;
871 llvm::LLVMContext llvm_ctx
;
872 unsigned optimization_level
;
874 llvm_ctx
.setDiagnosticHandler(diagnostic_handler
, &r_log
);
876 if (get_debug_flags() & DBG_CLC
)
877 debug_log("// Build options: " + opts
+ '\n' + source
, ".cl");
879 // The input file name must have the .cl extension in order for the
880 // CompilerInvocation class to recognize it as an OpenCL source file.
881 llvm::Module
*mod
= compile_llvm(llvm_ctx
, source
, headers
, "input.cl",
882 triple
, processor
, opts
, address_spaces
,
883 optimization_level
, r_log
);
885 optimize(mod
, optimization_level
);
887 if (get_debug_flags() & DBG_LLVM
) {
889 llvm::raw_string_ostream
s_log(log
);
890 mod
->print(s_log
, NULL
);
892 debug_log(log
, ".ll");
896 // Build the clover::module
898 case PIPE_SHADER_IR_NIR
:
899 case PIPE_SHADER_IR_TGSI
:
900 //XXX: Handle TGSI, NIR
904 case PIPE_SHADER_IR_LLVM
:
905 m
= build_module_llvm(mod
, address_spaces
);
907 case PIPE_SHADER_IR_NATIVE
: {
908 std::vector
<char> code
= compile_native(mod
, triple
, processor
,
909 get_debug_flags() & DBG_ASM
,
911 m
= build_module_native(code
, mod
, address_spaces
, r_log
);
915 // The user takes ownership of the module.