a305299f507d846ba352f8a54d12f72c8633cbdc
[mesa.git] / src / gallium / frontends / clover / llvm / invocation.cpp
1 //
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
7 //
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:
14 //
15 // The above copyright notice and this permission notice shall be included in
16 // all copies or substantial portions of the Software.
17 //
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.
25 //
26
27 #include <llvm/IR/DiagnosticPrinter.h>
28 #include <llvm/IR/DiagnosticInfo.h>
29 #include <llvm/IR/LLVMContext.h>
30 #include <llvm/Support/raw_ostream.h>
31 #include <llvm/Transforms/IPO/PassManagerBuilder.h>
32 #include <llvm-c/Target.h>
33 #ifdef HAVE_CLOVER_SPIRV
34 #include <LLVMSPIRVLib/LLVMSPIRVLib.h>
35 #endif
36
37 #include <clang/CodeGen/CodeGenAction.h>
38 #include <clang/Lex/PreprocessorOptions.h>
39 #include <clang/Frontend/TextDiagnosticBuffer.h>
40 #include <clang/Frontend/TextDiagnosticPrinter.h>
41 #include <clang/Basic/TargetInfo.h>
42
43 // We need to include internal headers last, because the internal headers
44 // include CL headers which have #define's like:
45 //
46 //#define cl_khr_gl_sharing 1
47 //#define cl_khr_icd 1
48 //
49 // Which will break the compilation of clang/Basic/OpenCLOptions.h
50
51 #include "core/error.hpp"
52 #include "llvm/codegen.hpp"
53 #include "llvm/compat.hpp"
54 #include "llvm/invocation.hpp"
55 #include "llvm/metadata.hpp"
56 #include "llvm/util.hpp"
57 #ifdef HAVE_CLOVER_SPIRV
58 #include "spirv/invocation.hpp"
59 #endif
60 #include "util/algorithm.hpp"
61
62
63 using namespace clover;
64 using namespace clover::llvm;
65
66 using ::llvm::Function;
67 using ::llvm::LLVMContext;
68 using ::llvm::Module;
69 using ::llvm::raw_string_ostream;
70
71 namespace {
72
73 struct cl_version {
74 std::string version_str; // CL Version
75 unsigned version_number; // Numeric CL Version
76 };
77
78 static const unsigned ANY_VERSION = 999;
79 const cl_version cl_versions[] = {
80 { "1.0", 100},
81 { "1.1", 110},
82 { "1.2", 120},
83 { "2.0", 200},
84 { "2.1", 210},
85 { "2.2", 220},
86 };
87
88 struct clc_version_lang_std {
89 unsigned version_number; // CLC Version
90 clang::LangStandard::Kind clc_lang_standard;
91 };
92
93 const clc_version_lang_std cl_version_lang_stds[] = {
94 { 100, compat::lang_opencl10},
95 { 110, clang::LangStandard::lang_opencl11},
96 { 120, clang::LangStandard::lang_opencl12},
97 { 200, clang::LangStandard::lang_opencl20},
98 };
99
100 void
101 init_targets() {
102 static bool targets_initialized = false;
103 if (!targets_initialized) {
104 LLVMInitializeAllTargets();
105 LLVMInitializeAllTargetInfos();
106 LLVMInitializeAllTargetMCs();
107 LLVMInitializeAllAsmParsers();
108 LLVMInitializeAllAsmPrinters();
109 targets_initialized = true;
110 }
111 }
112
113 void
114 diagnostic_handler(const ::llvm::DiagnosticInfo &di, void *data) {
115 if (di.getSeverity() == ::llvm::DS_Error) {
116 raw_string_ostream os { *reinterpret_cast<std::string *>(data) };
117 ::llvm::DiagnosticPrinterRawOStream printer { os };
118 di.print(printer);
119 throw build_error();
120 }
121 }
122
123 std::unique_ptr<LLVMContext>
124 create_context(std::string &r_log) {
125 init_targets();
126 std::unique_ptr<LLVMContext> ctx { new LLVMContext };
127 compat::set_diagnostic_handler(*ctx, diagnostic_handler, &r_log);
128 return ctx;
129 }
130
131 const struct clc_version_lang_std&
132 get_cl_lang_standard(unsigned requested, unsigned max = ANY_VERSION) {
133 for (const struct clc_version_lang_std &version : cl_version_lang_stds) {
134 if (version.version_number == max ||
135 version.version_number == requested) {
136 return version;
137 }
138 }
139 throw build_error("Unknown/Unsupported language version");
140 }
141
142 const struct cl_version&
143 get_cl_version(const std::string &version_str,
144 unsigned max = ANY_VERSION) {
145 for (const struct cl_version &version : cl_versions) {
146 if (version.version_number == max || version.version_str == version_str) {
147 return version;
148 }
149 }
150 throw build_error("Unknown/Unsupported language version");
151 }
152
153 clang::LangStandard::Kind
154 get_lang_standard_from_version_str(const std::string &version_str,
155 bool is_build_opt = false) {
156
157 //Per CL 2.0 spec, section 5.8.4.5:
158 // If it's an option, use the value directly.
159 // If it's a device version, clamp to max 1.x version, a.k.a. 1.2
160 const cl_version version =
161 get_cl_version(version_str, is_build_opt ? ANY_VERSION : 120);
162
163 const struct clc_version_lang_std standard =
164 get_cl_lang_standard(version.version_number);
165
166 return standard.clc_lang_standard;
167 }
168
169 clang::LangStandard::Kind
170 get_language_version(const std::vector<std::string> &opts,
171 const std::string &device_version) {
172
173 const std::string search = "-cl-std=CL";
174
175 for (auto &opt: opts) {
176 auto pos = opt.find(search);
177 if (pos == 0){
178 const auto ver = opt.substr(pos + search.size());
179 const auto device_ver = get_cl_version(device_version);
180 const auto requested = get_cl_version(ver);
181 if (requested.version_number > device_ver.version_number) {
182 throw build_error();
183 }
184 return get_lang_standard_from_version_str(ver, true);
185 }
186 }
187
188 return get_lang_standard_from_version_str(device_version);
189 }
190
191 std::unique_ptr<clang::CompilerInstance>
192 create_compiler_instance(const device &dev, const std::string& ir_target,
193 const std::vector<std::string> &opts,
194 std::string &r_log) {
195 std::unique_ptr<clang::CompilerInstance> c { new clang::CompilerInstance };
196 clang::TextDiagnosticBuffer *diag_buffer = new clang::TextDiagnosticBuffer;
197 clang::DiagnosticsEngine diag { new clang::DiagnosticIDs,
198 new clang::DiagnosticOptions, diag_buffer };
199
200 // Parse the compiler options. A file name should be present at the end
201 // and must have the .cl extension in order for the CompilerInvocation
202 // class to recognize it as an OpenCL source file.
203 const std::vector<const char *> copts =
204 map(std::mem_fn(&std::string::c_str), opts);
205
206 const target &target = ir_target;
207 const std::string &device_clc_version = dev.device_clc_version();
208
209 if (!compat::create_compiler_invocation_from_args(
210 c->getInvocation(), copts, diag))
211 throw invalid_build_options_error();
212
213 diag_buffer->FlushDiagnostics(diag);
214 if (diag.hasErrorOccurred())
215 throw invalid_build_options_error();
216
217 c->getTargetOpts().CPU = target.cpu;
218 c->getTargetOpts().Triple = target.triple;
219 c->getLangOpts().NoBuiltin = true;
220
221 // This is a workaround for a Clang bug which causes the number
222 // of warnings and errors to be printed to stderr.
223 // http://www.llvm.org/bugs/show_bug.cgi?id=19735
224 c->getDiagnosticOpts().ShowCarets = false;
225
226 c->getInvocation().setLangDefaults(c->getLangOpts(),
227 compat::ik_opencl, ::llvm::Triple(target.triple),
228 c->getPreprocessorOpts(),
229 get_language_version(opts, device_clc_version));
230
231 c->createDiagnostics(new clang::TextDiagnosticPrinter(
232 *new raw_string_ostream(r_log),
233 &c->getDiagnosticOpts(), true));
234
235 c->setTarget(clang::TargetInfo::CreateTargetInfo(
236 c->getDiagnostics(), c->getInvocation().TargetOpts));
237
238 return c;
239 }
240
241 std::unique_ptr<Module>
242 compile(LLVMContext &ctx, clang::CompilerInstance &c,
243 const std::string &name, const std::string &source,
244 const header_map &headers, const device &dev,
245 const std::string &opts, bool use_libclc, std::string &r_log) {
246 c.getFrontendOpts().ProgramAction = clang::frontend::EmitLLVMOnly;
247 c.getHeaderSearchOpts().UseBuiltinIncludes = true;
248 c.getHeaderSearchOpts().UseStandardSystemIncludes = true;
249 c.getHeaderSearchOpts().ResourceDir = CLANG_RESOURCE_DIR;
250
251 if (use_libclc) {
252 // Add libclc generic search path
253 c.getHeaderSearchOpts().AddPath(LIBCLC_INCLUDEDIR,
254 clang::frontend::Angled,
255 false, false);
256
257 // Add libclc include
258 c.getPreprocessorOpts().Includes.push_back("clc/clc.h");
259 } else {
260 // Add opencl-c generic search path
261 c.getHeaderSearchOpts().AddPath(CLANG_RESOURCE_DIR,
262 clang::frontend::Angled,
263 false, false);
264
265 // Add opencl include
266 c.getPreprocessorOpts().Includes.push_back("opencl-c.h");
267 }
268
269 // Add definition for the OpenCL version
270 c.getPreprocessorOpts().addMacroDef("__OPENCL_VERSION__=" +
271 std::to_string(get_cl_version(
272 dev.device_version()).version_number));
273
274 // clc.h requires that this macro be defined:
275 c.getPreprocessorOpts().addMacroDef("cl_clang_storage_class_specifiers");
276 c.getPreprocessorOpts().addRemappedFile(
277 name, ::llvm::MemoryBuffer::getMemBuffer(source).release());
278
279 if (headers.size()) {
280 const std::string tmp_header_path = "/tmp/clover/";
281
282 c.getHeaderSearchOpts().AddPath(tmp_header_path,
283 clang::frontend::Angled,
284 false, false);
285
286 for (const auto &header : headers)
287 c.getPreprocessorOpts().addRemappedFile(
288 tmp_header_path + header.first,
289 ::llvm::MemoryBuffer::getMemBuffer(header.second).release());
290 }
291
292 // Tell clang to link this file before performing any
293 // optimizations. This is required so that we can replace calls
294 // to the OpenCL C barrier() builtin with calls to target
295 // intrinsics that have the noduplicate attribute. This
296 // attribute will prevent Clang from creating illegal uses of
297 // barrier() (e.g. Moving barrier() inside a conditional that is
298 // no executed by all threads) during its optimizaton passes.
299 if (use_libclc)
300 compat::add_link_bitcode_file(c.getCodeGenOpts(),
301 LIBCLC_LIBEXECDIR + dev.ir_target() + ".bc");
302
303 // Compile the code
304 clang::EmitLLVMOnlyAction act(&ctx);
305 if (!c.ExecuteAction(act))
306 throw build_error();
307
308 return act.takeModule();
309 }
310
311 #ifdef HAVE_CLOVER_SPIRV
312 SPIRV::TranslatorOpts
313 get_spirv_translator_options(const device &dev) {
314 const auto supported_versions = spirv::supported_versions();
315 const auto maximum_spirv_version =
316 std::min(static_cast<SPIRV::VersionNumber>(supported_versions.back()),
317 SPIRV::VersionNumber::MaximumVersion);
318
319 SPIRV::TranslatorOpts::ExtensionsStatusMap spirv_extensions;
320 for (auto &ext : spirv::supported_extensions()) {
321 #define EXT(X) if (ext == #X) spirv_extensions.insert({ SPIRV::ExtensionID::X, true });
322 #include <LLVMSPIRVLib/LLVMSPIRVExtensions.inc>
323 #undef EXT
324 }
325
326 return SPIRV::TranslatorOpts(maximum_spirv_version, spirv_extensions);
327 }
328 #endif
329 }
330
331 module
332 clover::llvm::compile_program(const std::string &source,
333 const header_map &headers,
334 const device &dev,
335 const std::string &opts,
336 std::string &r_log) {
337 if (has_flag(debug::clc))
338 debug::log(".cl", "// Options: " + opts + '\n' + source);
339
340 auto ctx = create_context(r_log);
341 auto c = create_compiler_instance(dev, dev.ir_target(),
342 tokenize(opts + " input.cl"), r_log);
343 auto mod = compile(*ctx, *c, "input.cl", source, headers, dev, opts, true,
344 r_log);
345
346 if (has_flag(debug::llvm))
347 debug::log(".ll", print_module_bitcode(*mod));
348
349 return build_module_library(*mod, module::section::text_intermediate);
350 }
351
352 namespace {
353 void
354 optimize(Module &mod, unsigned optimization_level,
355 bool internalize_symbols) {
356 ::llvm::legacy::PassManager pm;
357
358 // By default, the function internalizer pass will look for a function
359 // called "main" and then mark all other functions as internal. Marking
360 // functions as internal enables the optimizer to perform optimizations
361 // like function inlining and global dead-code elimination.
362 //
363 // When there is no "main" function in a module, the internalize pass will
364 // treat the module like a library, and it won't internalize any functions.
365 // Since there is no "main" function in our kernels, we need to tell
366 // the internalizer pass that this module is not a library by passing a
367 // list of kernel functions to the internalizer. The internalizer will
368 // treat the functions in the list as "main" functions and internalize
369 // all of the other functions.
370 if (internalize_symbols) {
371 std::vector<std::string> names =
372 map(std::mem_fn(&Function::getName), get_kernels(mod));
373 pm.add(::llvm::createInternalizePass(
374 [=](const ::llvm::GlobalValue &gv) {
375 return std::find(names.begin(), names.end(),
376 gv.getName()) != names.end();
377 }));
378 }
379
380 ::llvm::PassManagerBuilder pmb;
381 pmb.OptLevel = optimization_level;
382 pmb.LibraryInfo = new ::llvm::TargetLibraryInfoImpl(
383 ::llvm::Triple(mod.getTargetTriple()));
384 pmb.populateModulePassManager(pm);
385 pm.run(mod);
386 }
387
388 std::unique_ptr<Module>
389 link(LLVMContext &ctx, const clang::CompilerInstance &c,
390 const std::vector<module> &modules, std::string &r_log) {
391 std::unique_ptr<Module> mod { new Module("link", ctx) };
392 std::unique_ptr< ::llvm::Linker> linker { new ::llvm::Linker(*mod) };
393
394 for (auto &m : modules) {
395 if (linker->linkInModule(parse_module_library(m, ctx, r_log)))
396 throw build_error();
397 }
398
399 return mod;
400 }
401 }
402
403 module
404 clover::llvm::link_program(const std::vector<module> &modules,
405 const device &dev, const std::string &opts,
406 std::string &r_log) {
407 std::vector<std::string> options = tokenize(opts + " input.cl");
408 const bool create_library = count("-create-library", options);
409 erase_if(equals("-create-library"), options);
410
411 auto ctx = create_context(r_log);
412 auto c = create_compiler_instance(dev, dev.ir_target(), options, r_log);
413 auto mod = link(*ctx, *c, modules, r_log);
414
415 optimize(*mod, c->getCodeGenOpts().OptimizationLevel, !create_library);
416
417 static std::atomic_uint seq(0);
418 const std::string id = "." + mod->getModuleIdentifier() + "-" +
419 std::to_string(seq++);
420
421 if (has_flag(debug::llvm))
422 debug::log(id + ".ll", print_module_bitcode(*mod));
423
424 if (create_library) {
425 return build_module_library(*mod, module::section::text_library);
426
427 } else if (dev.ir_format() == PIPE_SHADER_IR_NATIVE) {
428 if (has_flag(debug::native))
429 debug::log(id + ".asm", print_module_native(*mod, dev.ir_target()));
430
431 return build_module_native(*mod, dev.ir_target(), *c, r_log);
432
433 } else {
434 unreachable("Unsupported IR.");
435 }
436 }
437
438 #ifdef HAVE_CLOVER_SPIRV
439 module
440 clover::llvm::compile_to_spirv(const std::string &source,
441 const header_map &headers,
442 const device &dev,
443 const std::string &opts,
444 std::string &r_log) {
445 if (has_flag(debug::clc))
446 debug::log(".cl", "// Options: " + opts + '\n' + source);
447
448 auto ctx = create_context(r_log);
449 const std::string target = dev.address_bits() == 32u ?
450 "-spir-unknown-unknown" :
451 "-spir64-unknown-unknown";
452 auto c = create_compiler_instance(dev, target,
453 tokenize(opts + " -O0 input.cl"), r_log);
454 auto mod = compile(*ctx, *c, "input.cl", source, headers, dev, opts, false,
455 r_log);
456
457 if (has_flag(debug::llvm))
458 debug::log(".ll", print_module_bitcode(*mod));
459
460 const auto spirv_options = get_spirv_translator_options(dev);
461
462 std::string error_msg;
463 std::ostringstream os;
464 if (!::llvm::writeSpirv(mod.get(), spirv_options, os, error_msg)) {
465 r_log += "Translation from LLVM IR to SPIR-V failed: " + error_msg + ".\n";
466 throw error(CL_INVALID_VALUE);
467 }
468
469 const std::string osContent = os.str();
470 std::vector<char> binary(osContent.begin(), osContent.end());
471 if (binary.empty()) {
472 r_log += "Failed to retrieve SPIR-V binary.\n";
473 throw error(CL_INVALID_VALUE);
474 }
475
476 if (has_flag(debug::spirv))
477 debug::log(".spvasm", spirv::print_module(binary, dev.device_version()));
478
479 return spirv::compile_program(binary, dev, r_log);
480 }
481 #endif