blob: e1030079bde0009ee6aaa7fee6d9b9dd8b953abf [file] [log] [blame]
alan-bakerfec0a472018-11-08 18:09:40 -05001// Copyright 2018 The Clspv Authors. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#include "clang/Basic/TargetInfo.h"
16#include "clang/CodeGen/CodeGenAction.h"
17#include "clang/Frontend/CompilerInstance.h"
18#include "clang/Frontend/FrontendPluginRegistry.h"
19#include "clang/Frontend/TextDiagnosticPrinter.h"
20#include "clang/Lex/PreprocessorOptions.h"
21#include "llvm/IR/LLVMContext.h"
22#include "llvm/IR/LegacyPassManager.h"
23#include "llvm/IR/Module.h"
24#include "llvm/IR/Verifier.h"
25#include "llvm/LinkAllPasses.h"
alan-bakerf5e5f692018-11-27 08:33:24 -050026#include "llvm/Support/Allocator.h"
alan-bakerfec0a472018-11-08 18:09:40 -050027#include "llvm/Support/CommandLine.h"
alan-bakerf5e5f692018-11-27 08:33:24 -050028#include "llvm/Support/ErrorOr.h"
alan-bakerfec0a472018-11-08 18:09:40 -050029#include "llvm/Support/MathExtras.h"
alan-bakerf5e5f692018-11-27 08:33:24 -050030#include "llvm/Support/StringSaver.h"
alan-bakerfec0a472018-11-08 18:09:40 -050031#include "llvm/Support/raw_ostream.h"
32#include "llvm/Transforms/IPO/PassManagerBuilder.h"
33
alan-bakerf5e5f692018-11-27 08:33:24 -050034#include "clspv/DescriptorMap.h"
alan-bakerfec0a472018-11-08 18:09:40 -050035#include "clspv/Option.h"
36#include "clspv/Passes.h"
37#include "clspv/opencl_builtins_header.h"
38
39#include "FrontendPlugin.h"
40
alan-bakerf5e5f692018-11-27 08:33:24 -050041#include <cassert>
alan-bakerfec0a472018-11-08 18:09:40 -050042#include <numeric>
43#include <string>
alan-bakerf5e5f692018-11-27 08:33:24 -050044#include <sstream>
alan-bakerfec0a472018-11-08 18:09:40 -050045
46using namespace clang;
47
48namespace {
49// This registration must be located in the same file as the execution of the
50// action.
51static FrontendPluginRegistry::Add<clspv::ExtraValidationASTAction>
52 X("extra-validation",
53 "Perform extra validation on OpenCL C when targeting Vulkan");
54
55static llvm::cl::opt<bool> cl_single_precision_constants(
56 "cl-single-precision-constant", llvm::cl::init(false),
57 llvm::cl::desc("Treat double precision floating-point constant as single "
58 "precision constant."));
59
60static llvm::cl::opt<bool> cl_denorms_are_zero(
61 "cl-denorms-are-zero", llvm::cl::init(false),
62 llvm::cl::desc("If specified, denormalized floating point numbers may be "
63 "flushed to zero."));
64
65static llvm::cl::opt<bool> cl_fp32_correctly_rounded_divide_sqrt(
66 "cl-fp32-correctly-rounded-divide-sqrt", llvm::cl::init(false),
67 llvm::cl::desc("Single precision floating-point divide (x/y and 1/x) and "
68 "sqrt used are correctly rounded."));
69
70static llvm::cl::opt<bool>
71 cl_opt_disable("cl-opt-disable", llvm::cl::init(false),
72 llvm::cl::desc("This option disables all optimizations. The "
73 "default is optimizations are enabled."));
74
75static llvm::cl::opt<bool> cl_mad_enable(
76 "cl-mad-enable", llvm::cl::init(false),
77 llvm::cl::desc("Allow a * b + c to be replaced by a mad. The mad computes "
78 "a * b + c with reduced accuracy."));
79
80static llvm::cl::opt<bool> cl_no_signed_zeros(
81 "cl-no-signed-zeros", llvm::cl::init(false),
82 llvm::cl::desc("Allow optimizations for floating-point arithmetic that "
83 "ignore the signedness of zero."));
84
85static llvm::cl::opt<bool> cl_unsafe_math_optimizations(
86 "cl-unsafe-math-optimizations", llvm::cl::init(false),
87 llvm::cl::desc("Allow optimizations for floating-point arithmetic that (a) "
88 "assume that arguments and results are valid, (b) may "
89 "violate IEEE 754 standard and (c) may violate the OpenCL "
90 "numerical compliance requirements. This option includes "
91 "the -cl-no-signed-zeros and -cl-mad-enable options."));
92
93static llvm::cl::opt<bool> cl_finite_math_only(
94 "cl-finite-math-only", llvm::cl::init(false),
95 llvm::cl::desc("Allow optimizations for floating-point arithmetic that "
96 "assume that arguments and results are not NaNs or INFs."));
97
98static llvm::cl::opt<bool> cl_fast_relaxed_math(
99 "cl-fast-relaxed-math", llvm::cl::init(false),
100 llvm::cl::desc("This option causes the preprocessor macro "
101 "__FAST_RELAXED_MATH__ to be defined. Sets the optimization "
102 "options -cl-finite-math-only and "
103 "-cl-unsafe-math-optimizations."));
104
105static llvm::cl::list<std::string>
106 Includes(llvm::cl::Prefix, "I",
107 llvm::cl::desc("Add a directory to the list of directories "
108 "to be searched for header files."),
109 llvm::cl::ZeroOrMore, llvm::cl::value_desc("include path"));
110
111static llvm::cl::list<std::string>
112 Defines(llvm::cl::Prefix, "D",
113 llvm::cl::desc("Define a #define directive."), llvm::cl::ZeroOrMore,
114 llvm::cl::value_desc("define"));
115
116static llvm::cl::opt<std::string>
117 InputFilename(llvm::cl::Positional, llvm::cl::desc("<input .cl file>"),
118 llvm::cl::init("-"));
119
120static llvm::cl::opt<std::string>
121 OutputFilename("o", llvm::cl::desc("Override output filename"),
122 llvm::cl::value_desc("filename"));
123
124static llvm::cl::opt<std::string>
125 DescriptorMapFilename("descriptormap",
126 llvm::cl::desc("Output file for descriptor map"),
127 llvm::cl::value_desc("filename"));
128
129static llvm::cl::opt<char>
130 OptimizationLevel(llvm::cl::Prefix, "O", llvm::cl::init('2'),
131 llvm::cl::desc("Optimization level to use"),
132 llvm::cl::value_desc("level"));
133
134static llvm::cl::opt<bool>
135 OutputAssembly("S", llvm::cl::init(false),
136 llvm::cl::desc("This option controls output of assembly"));
137
138static llvm::cl::opt<std::string> OutputFormat(
139 "mfmt", llvm::cl::init(""),
140 llvm::cl::desc(
141 "Specify special output format. 'c' is as a C initializer list"),
142 llvm::cl::value_desc("format"));
143
144static llvm::cl::opt<std::string>
145 SamplerMap("samplermap", llvm::cl::desc("Literal sampler map"),
146 llvm::cl::value_desc("filename"));
147
148static llvm::cl::opt<bool> cluster_non_pointer_kernel_args(
149 "cluster-pod-kernel-args", llvm::cl::init(false),
150 llvm::cl::desc("Collect plain-old-data kernel arguments into a struct in "
151 "a single storage buffer, using a binding number after "
152 "other arguments. Use this to reduce storage buffer "
153 "descriptors."));
154
155static llvm::cl::opt<bool> verify("verify", llvm::cl::init(false),
156 llvm::cl::desc("Verify diagnostic outputs"));
157
158// Populates |SamplerMapEntries| with data from the input sampler map. Returns 0
159// if successful.
alan-bakerf5e5f692018-11-27 08:33:24 -0500160int ParseSamplerMap(const std::string &sampler_map,
161 llvm::SmallVectorImpl<std::pair<unsigned, std::string>>
162 *SamplerMapEntries) {
163 std::unique_ptr<llvm::MemoryBuffer> samplerMapBuffer(nullptr);
164 if (!sampler_map.empty()) {
165 // Parse the sampler map from the provided string.
166 samplerMapBuffer = llvm::MemoryBuffer::getMemBuffer(sampler_map);
167
168 if (!SamplerMap.empty()) {
169 llvm::outs() << "Warning: -samplermap is ignored when the sampler map is "
170 "provided through a string.\n";
171 }
172 } else if (!SamplerMap.empty()) {
173 // Parse the sampler map from the option provided file.
alan-bakerfec0a472018-11-08 18:09:40 -0500174 auto errorOrSamplerMapFile =
175 llvm::MemoryBuffer::getFile(SamplerMap.getValue());
176
177 // If there was an error in getting the sampler map file.
178 if (!errorOrSamplerMapFile) {
179 llvm::errs() << "Error: " << errorOrSamplerMapFile.getError().message()
180 << " '" << SamplerMap.getValue() << "'\n";
181 return -1;
182 }
183
alan-bakerf5e5f692018-11-27 08:33:24 -0500184 samplerMapBuffer = std::move(errorOrSamplerMapFile.get());
alan-bakerfec0a472018-11-08 18:09:40 -0500185 if (0 == samplerMapBuffer->getBufferSize()) {
186 llvm::errs() << "Error: Sampler map was an empty file!\n";
187 return -1;
188 }
alan-bakerf5e5f692018-11-27 08:33:24 -0500189 }
alan-bakerfec0a472018-11-08 18:09:40 -0500190
alan-bakerf5e5f692018-11-27 08:33:24 -0500191 // No sampler map to parse.
192 if (!samplerMapBuffer || 0 == samplerMapBuffer->getBufferSize())
193 return 0;
alan-bakerfec0a472018-11-08 18:09:40 -0500194
alan-bakerf5e5f692018-11-27 08:33:24 -0500195 llvm::SmallVector<llvm::StringRef, 3> samplerStrings;
alan-bakerfec0a472018-11-08 18:09:40 -0500196
alan-bakerf5e5f692018-11-27 08:33:24 -0500197 // We need to keep track of the beginning of the current entry.
198 const char *b = samplerMapBuffer->getBufferStart();
199 for (const char *i = b, *e = samplerMapBuffer->getBufferEnd();; i++) {
200 // If we have a separator between declarations.
201 if ((*i == '|') || (*i == ',') || (i == e)) {
202 if (i == b) {
203 llvm::errs() << "Error: Sampler map contained an empty entry!\n";
204 return -1;
alan-bakerfec0a472018-11-08 18:09:40 -0500205 }
206
alan-bakerf5e5f692018-11-27 08:33:24 -0500207 samplerStrings.push_back(llvm::StringRef(b, i - b).trim());
alan-bakerfec0a472018-11-08 18:09:40 -0500208
alan-bakerf5e5f692018-11-27 08:33:24 -0500209 // And set b the next character after i.
210 b = i + 1;
211 }
alan-bakerfec0a472018-11-08 18:09:40 -0500212
alan-bakerf5e5f692018-11-27 08:33:24 -0500213 // If we have a separator between declarations within a single sampler.
214 if ((*i == ',') || (i == e)) {
215 enum NormalizedCoords {
216 CLK_NORMALIZED_COORDS_FALSE = 0x00,
217 CLK_NORMALIZED_COORDS_TRUE = 0x01,
218 CLK_NORMALIZED_COORDS_NOT_SET
219 } NormalizedCoord = CLK_NORMALIZED_COORDS_NOT_SET;
alan-bakerfec0a472018-11-08 18:09:40 -0500220
alan-bakerf5e5f692018-11-27 08:33:24 -0500221 enum AddressingModes {
222 CLK_ADDRESS_NONE = 0x00,
223 CLK_ADDRESS_CLAMP_TO_EDGE = 0x02,
224 CLK_ADDRESS_CLAMP = 0x04,
225 CLK_ADDRESS_MIRRORED_REPEAT = 0x08,
226 CLK_ADDRESS_REPEAT = 0x06,
227 CLK_ADDRESS_NOT_SET
228 } AddressingMode = CLK_ADDRESS_NOT_SET;
229
230 enum FilterModes {
231 CLK_FILTER_NEAREST = 0x10,
232 CLK_FILTER_LINEAR = 0x20,
233 CLK_FILTER_NOT_SET
234 } FilterMode = CLK_FILTER_NOT_SET;
235
236 for (auto str : samplerStrings) {
237 if ("CLK_NORMALIZED_COORDS_FALSE" == str) {
238 if (CLK_NORMALIZED_COORDS_NOT_SET != NormalizedCoord) {
239 llvm::errs() << "Error: Sampler map normalized coordinates was "
240 "previously set!\n";
alan-bakerfec0a472018-11-08 18:09:40 -0500241 return -1;
242 }
alan-bakerf5e5f692018-11-27 08:33:24 -0500243 NormalizedCoord = CLK_NORMALIZED_COORDS_FALSE;
244 } else if ("CLK_NORMALIZED_COORDS_TRUE" == str) {
245 if (CLK_NORMALIZED_COORDS_NOT_SET != NormalizedCoord) {
246 llvm::errs() << "Error: Sampler map normalized coordinates was "
247 "previously set!\n";
248 return -1;
249 }
250 NormalizedCoord = CLK_NORMALIZED_COORDS_TRUE;
251 } else if ("CLK_ADDRESS_NONE" == str) {
252 if (CLK_ADDRESS_NOT_SET != AddressingMode) {
253 llvm::errs()
254 << "Error: Sampler map addressing mode was previously set!\n";
255 return -1;
256 }
257 AddressingMode = CLK_ADDRESS_NONE;
258 } else if ("CLK_ADDRESS_CLAMP_TO_EDGE" == str) {
259 if (CLK_ADDRESS_NOT_SET != AddressingMode) {
260 llvm::errs()
261 << "Error: Sampler map addressing mode was previously set!\n";
262 return -1;
263 }
264 AddressingMode = CLK_ADDRESS_CLAMP_TO_EDGE;
265 } else if ("CLK_ADDRESS_CLAMP" == str) {
266 if (CLK_ADDRESS_NOT_SET != AddressingMode) {
267 llvm::errs()
268 << "Error: Sampler map addressing mode was previously set!\n";
269 return -1;
270 }
271 AddressingMode = CLK_ADDRESS_CLAMP;
272 } else if ("CLK_ADDRESS_MIRRORED_REPEAT" == str) {
273 if (CLK_ADDRESS_NOT_SET != AddressingMode) {
274 llvm::errs()
275 << "Error: Sampler map addressing mode was previously set!\n";
276 return -1;
277 }
278 AddressingMode = CLK_ADDRESS_MIRRORED_REPEAT;
279 } else if ("CLK_ADDRESS_REPEAT" == str) {
280 if (CLK_ADDRESS_NOT_SET != AddressingMode) {
281 llvm::errs()
282 << "Error: Sampler map addressing mode was previously set!\n";
283 return -1;
284 }
285 AddressingMode = CLK_ADDRESS_REPEAT;
286 } else if ("CLK_FILTER_NEAREST" == str) {
287 if (CLK_FILTER_NOT_SET != FilterMode) {
288 llvm::errs()
289 << "Error: Sampler map filtering mode was previously set!\n";
290 return -1;
291 }
292 FilterMode = CLK_FILTER_NEAREST;
293 } else if ("CLK_FILTER_LINEAR" == str) {
294 if (CLK_FILTER_NOT_SET != FilterMode) {
295 llvm::errs()
296 << "Error: Sampler map filtering mode was previously set!\n";
297 return -1;
298 }
299 FilterMode = CLK_FILTER_LINEAR;
300 } else {
301 llvm::errs() << "Error: Unknown sampler string '" << str
302 << "' found!\n";
alan-bakerfec0a472018-11-08 18:09:40 -0500303 return -1;
304 }
alan-bakerfec0a472018-11-08 18:09:40 -0500305 }
306
alan-bakerf5e5f692018-11-27 08:33:24 -0500307 if (CLK_NORMALIZED_COORDS_NOT_SET == NormalizedCoord) {
308 llvm::errs() << "Error: Sampler map entry did not contain normalized "
309 "coordinates entry!\n";
310 return -1;
alan-bakerfec0a472018-11-08 18:09:40 -0500311 }
alan-bakerf5e5f692018-11-27 08:33:24 -0500312
313 if (CLK_ADDRESS_NOT_SET == AddressingMode) {
314 llvm::errs() << "Error: Sampler map entry did not contain addressing "
315 "mode entry!\n";
316 return -1;
317 }
318
319 if (CLK_FILTER_NOT_SET == FilterMode) {
320 llvm::errs()
321 << "Error: Sampler map entry did not contain filer mode entry!\n";
322 return -1;
323 }
324
325 // Generate an equivalent expression in string form. Sort the
326 // strings to get a canonical ordering.
327 std::sort(samplerStrings.begin(), samplerStrings.end(),
328 std::less<StringRef>());
329 const auto samplerExpr = std::accumulate(
330 samplerStrings.begin(), samplerStrings.end(), std::string(),
331 [](std::string left, std::string right) {
332 return left + std::string(left.empty() ? "" : "|") + right;
333 });
334
335 // SamplerMapEntries->push_back(std::make_pair(
336 // NormalizedCoord | AddressingMode | FilterMode, samplerExpr));
337 SamplerMapEntries->emplace_back(
338 NormalizedCoord | AddressingMode | FilterMode, samplerExpr);
339
340 // And reset the sampler strings for the next sampler in the map.
341 samplerStrings.clear();
342 }
343
344 // And lastly, if we are at the end of the file
345 if (i == e) {
346 break;
alan-bakerfec0a472018-11-08 18:09:40 -0500347 }
348 }
349
350 return 0;
351}
352
353// Sets |instance|'s options for compiling. Returns 0 if successful.
354int SetCompilerInstanceOptions(CompilerInstance &instance,
355 const llvm::StringRef &overiddenInputFilename,
356 const clang::FrontendInputFile &kernelFile,
alan-bakerf5e5f692018-11-27 08:33:24 -0500357 const std::string &program,
alan-bakerfec0a472018-11-08 18:09:40 -0500358 llvm::raw_string_ostream *diagnosticsStream) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500359 std::unique_ptr<llvm::MemoryBuffer> memory_buffer(nullptr);
360 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> errorOrInputFile(nullptr);
361 if (program.empty()) {
362 auto errorOrInputFile =
363 llvm::MemoryBuffer::getFileOrSTDIN(InputFilename.getValue());
alan-bakerfec0a472018-11-08 18:09:40 -0500364
alan-bakerf5e5f692018-11-27 08:33:24 -0500365 // If there was an error in getting the input file.
366 if (!errorOrInputFile) {
367 llvm::errs() << "Error: " << errorOrInputFile.getError().message() << " '"
368 << InputFilename.getValue() << "'\n";
369 return -1;
370 }
371 memory_buffer.reset(errorOrInputFile.get().release());
372 } else {
373 memory_buffer = llvm::MemoryBuffer::getMemBuffer(program.c_str(),
374 overiddenInputFilename);
alan-bakerfec0a472018-11-08 18:09:40 -0500375 }
alan-bakerf5e5f692018-11-27 08:33:24 -0500376
alan-bakerfec0a472018-11-08 18:09:40 -0500377 if (verify) {
378 instance.getDiagnosticOpts().VerifyDiagnostics = true;
379 }
380
381 clang::LangStandard::Kind standard = clang::LangStandard::lang_opencl12;
382
383 // We are targeting OpenCL 1.2 only
384 instance.getLangOpts().OpenCLVersion = 120;
385
386 instance.getLangOpts().C99 = true;
387 instance.getLangOpts().RTTI = false;
388 instance.getLangOpts().RTTIData = false;
389 instance.getLangOpts().MathErrno = false;
390 instance.getLangOpts().Optimize = false;
391 instance.getLangOpts().NoBuiltin = true;
392 instance.getLangOpts().ModulesSearchAll = false;
393 instance.getLangOpts().SinglePrecisionConstants = true;
394 instance.getCodeGenOpts().StackRealignment = true;
395 instance.getCodeGenOpts().SimplifyLibCalls = false;
396 instance.getCodeGenOpts().EmitOpenCLArgMetadata = false;
397 instance.getCodeGenOpts().DisableO0ImplyOptNone = true;
398 instance.getDiagnosticOpts().IgnoreWarnings = false;
399
400 instance.getLangOpts().SinglePrecisionConstants =
401 cl_single_precision_constants;
402 // cl_denorms_are_zero ignored for now!
403 // cl_fp32_correctly_rounded_divide_sqrt ignored for now!
404 instance.getCodeGenOpts().LessPreciseFPMAD =
405 cl_mad_enable || cl_unsafe_math_optimizations;
406 // cl_no_signed_zeros ignored for now!
407 instance.getCodeGenOpts().UnsafeFPMath =
408 cl_unsafe_math_optimizations || cl_fast_relaxed_math;
409 instance.getLangOpts().FiniteMathOnly =
410 cl_finite_math_only || cl_fast_relaxed_math;
411 instance.getLangOpts().FastRelaxedMath = cl_fast_relaxed_math;
412
413 // Preprocessor options
414 instance.getPreprocessorOpts().addMacroDef("__IMAGE_SUPPORT__");
415 if (cl_fast_relaxed_math) {
416 instance.getPreprocessorOpts().addMacroDef("__FAST_RELAXED_MATH__");
417 }
418
419 for (auto define : Defines) {
420 instance.getPreprocessorOpts().addMacroDef(define);
421 }
422
423 // Header search options
424 for (auto include : Includes) {
425 instance.getHeaderSearchOpts().AddPath(include, clang::frontend::After,
426 false, false);
427 }
428
429 // We always compile on opt 0 so we preserve as much debug information about
430 // the source as possible. We'll run optimization later, once we've had a
431 // chance to view the unoptimal code first
432 instance.getCodeGenOpts().OptimizationLevel = 0;
433
434// Debug information is disabled temporarily to call instruction.
435#if 0
436 instance.getCodeGenOpts().setDebugInfo(clang::codegenoptions::FullDebugInfo);
437#endif
438
439 // We use the 32-bit pointer-width SPIR triple
440 llvm::Triple triple("spir-unknown-unknown");
441
442 instance.getInvocation().setLangDefaults(
443 instance.getLangOpts(), clang::InputKind::OpenCL, triple,
444 instance.getPreprocessorOpts(), standard);
445
446 // Override the C99 inline semantics to accommodate for more OpenCL C
447 // programs in the wild.
448 instance.getLangOpts().GNUInline = true;
449 instance.createDiagnostics(
450 new clang::TextDiagnosticPrinter(*diagnosticsStream,
451 &instance.getDiagnosticOpts()),
452 true);
453
454 instance.getTargetOpts().Triple = triple.str();
455
456 instance.getCodeGenOpts().MainFileName = overiddenInputFilename;
457 instance.getCodeGenOpts().PreserveVec3Type = true;
458 // Disable generation of lifetime intrinsic.
459 instance.getCodeGenOpts().DisableLifetimeMarkers = true;
460 instance.getFrontendOpts().Inputs.push_back(kernelFile);
alan-bakerf5e5f692018-11-27 08:33:24 -0500461 // instance.getPreprocessorOpts().addRemappedFile(
462 // overiddenInputFilename, errorOrInputFile.get().release());
463 instance.getPreprocessorOpts().addRemappedFile(overiddenInputFilename,
464 memory_buffer.release());
alan-bakerfec0a472018-11-08 18:09:40 -0500465
466 struct OpenCLBuiltinMemoryBuffer final : public llvm::MemoryBuffer {
467 OpenCLBuiltinMemoryBuffer(const void *data, uint64_t data_length) {
468 const char *dataCasted = reinterpret_cast<const char *>(data);
469 init(dataCasted, dataCasted + data_length, true);
470 }
471
472 virtual llvm::MemoryBuffer::BufferKind getBufferKind() const override {
473 return llvm::MemoryBuffer::MemoryBuffer_Malloc;
474 }
475
476 virtual ~OpenCLBuiltinMemoryBuffer() override {}
477 };
478
479 std::unique_ptr<llvm::MemoryBuffer> openCLBuiltinMemoryBuffer(
480 new OpenCLBuiltinMemoryBuffer(opencl_builtins_header_data,
481 opencl_builtins_header_size - 1));
482
483 instance.getPreprocessorOpts().Includes.push_back("openclc.h");
484
485 // Add the VULKAN macro.
486 instance.getPreprocessorOpts().addMacroDef("VULKAN=100");
487
488 // Add the __OPENCL_VERSION__ macro.
489 instance.getPreprocessorOpts().addMacroDef("__OPENCL_VERSION__=120");
490
491 instance.setTarget(clang::TargetInfo::CreateTargetInfo(
492 instance.getDiagnostics(),
493 std::make_shared<clang::TargetOptions>(instance.getTargetOpts())));
494
495 instance.createFileManager();
496 instance.createSourceManager(instance.getFileManager());
497
498#ifdef _MSC_VER
499 std::string includePrefix("include\\");
500#else
501 std::string includePrefix("include/");
502#endif
503
504 auto entry = instance.getFileManager().getVirtualFile(
505 includePrefix + "openclc.h", openCLBuiltinMemoryBuffer->getBufferSize(),
506 0);
507
508 instance.getSourceManager().overrideFileContents(
509 entry, std::move(openCLBuiltinMemoryBuffer));
510
511 return 0;
512}
513
alan-bakerf5e5f692018-11-27 08:33:24 -0500514// Populates |pm| with necessary passes to optimize and legalize the IR.
515int PopulatePassManager(
516 llvm::legacy::PassManager *pm, llvm::raw_svector_ostream *binaryStream,
517 std::vector<clspv::version0::DescriptorMapEntry> *descriptor_map_entries,
518 llvm::SmallVectorImpl<std::pair<unsigned, std::string>>
519 *SamplerMapEntries) {
alan-bakerfec0a472018-11-08 18:09:40 -0500520 llvm::PassManagerBuilder pmBuilder;
521
522 switch (OptimizationLevel) {
523 case '0':
alan-bakerf5e5f692018-11-27 08:33:24 -0500524 case '1':
525 case '2':
526 case '3':
527 case 's':
528 case 'z':
529 break;
530 default:
531 llvm::errs() << "Unknown optimization level -O" << OptimizationLevel
532 << " specified!\n";
533 return -1;
534 }
535
536 switch (OptimizationLevel) {
537 case '0':
alan-bakerfec0a472018-11-08 18:09:40 -0500538 pmBuilder.OptLevel = 0;
539 break;
540 case '1':
541 pmBuilder.OptLevel = 1;
542 break;
543 case '2':
544 pmBuilder.OptLevel = 2;
545 break;
546 case '3':
547 pmBuilder.OptLevel = 3;
548 break;
549 case 's':
550 pmBuilder.SizeLevel = 1;
551 break;
552 case 'z':
553 pmBuilder.SizeLevel = 2;
554 break;
555 default:
556 break;
557 }
558
559 pm->add(clspv::createZeroInitializeAllocasPass());
560 pm->add(clspv::createDefineOpenCLWorkItemBuiltinsPass());
561
562 if (0 < pmBuilder.OptLevel) {
563 pm->add(clspv::createOpenCLInlinerPass());
564 }
565
566 pm->add(clspv::createUndoByvalPass());
567 pm->add(clspv::createUndoSRetPass());
568 if (cluster_non_pointer_kernel_args) {
569 pm->add(clspv::createClusterPodKernelArgumentsPass());
570 }
571 pm->add(clspv::createReplaceOpenCLBuiltinPass());
572
573 // We need to run mem2reg and inst combine early because our
574 // createInlineFuncWithPointerBitCastArgPass pass cannot handle the pattern
575 // %1 = alloca i32 1
576 // store <something> %1
577 // %2 = bitcast float* %1
578 // %3 = load float %2
579 pm->add(llvm::createPromoteMemoryToRegisterPass());
580
581 // Hide loads from __constant address space away from instcombine.
582 // This prevents us from generating select between pointers-to-__constant.
583 // See https://github.com/google/clspv/issues/71
584 pm->add(clspv::createHideConstantLoadsPass());
585
586 pm->add(llvm::createInstructionCombiningPass());
587
588 if (clspv::Option::InlineEntryPoints()) {
589 pm->add(clspv::createInlineEntryPointsPass());
590 } else {
591 pm->add(clspv::createInlineFuncWithPointerBitCastArgPass());
592 pm->add(clspv::createInlineFuncWithPointerToFunctionArgPass());
593 pm->add(clspv::createInlineFuncWithSingleCallSitePass());
594 }
595
596 if (0 == pmBuilder.OptLevel) {
597 // Mem2Reg pass should be run early because O0 level optimization leaves
598 // redundant alloca, load and store instructions from function arguments.
599 // clspv needs to remove them ahead of transformation.
600 pm->add(llvm::createPromoteMemoryToRegisterPass());
601
602 // SROA pass is run because it will fold structs/unions that are problematic
603 // on Vulkan SPIR-V away.
604 pm->add(llvm::createSROAPass());
605
606 // InstructionCombining pass folds bitcast and gep instructions which are
607 // not supported by Vulkan SPIR-V.
608 pm->add(llvm::createInstructionCombiningPass());
609 }
610
611 // Now we add any of the LLVM optimizations we wanted
612 pmBuilder.populateModulePassManager(*pm);
613
614 // Unhide loads from __constant address space. Undoes the action of
615 // HideConstantLoadsPass.
616 pm->add(clspv::createUnhideConstantLoadsPass());
617
618 pm->add(clspv::createFunctionInternalizerPass());
619 pm->add(clspv::createReplaceLLVMIntrinsicsPass());
620 pm->add(clspv::createUndoBoolPass());
621 pm->add(clspv::createUndoTruncatedSwitchConditionPass());
622 pm->add(llvm::createStructurizeCFGPass(false));
alan-baker3fa76d92018-11-12 14:54:40 -0500623 // Must be run after structurize cfg.
alan-bakerfec0a472018-11-08 18:09:40 -0500624 pm->add(clspv::createReorderBasicBlocksPass());
625 pm->add(clspv::createUndoGetElementPtrConstantExprPass());
626 pm->add(clspv::createSplatArgPass());
627 pm->add(clspv::createSimplifyPointerBitcastPass());
628 pm->add(clspv::createReplacePointerBitcastPass());
629
630 pm->add(clspv::createUndoTranslateSamplerFoldPass());
631
632 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
633 pm->add(clspv::createClusterModuleScopeConstantVars());
634 }
635
636 pm->add(clspv::createShareModuleScopeVariablesPass());
637 pm->add(clspv::createAllocateDescriptorsPass(*SamplerMapEntries));
638 pm->add(llvm::createVerifierPass());
639 pm->add(clspv::createDirectResourceAccessPass());
640 // Replacing pointer bitcasts can leave some trivial GEPs
641 // that are easy to remove. Also replace GEPs of GEPS
642 // left by replacing indirect buffer accesses.
643 pm->add(clspv::createSimplifyPointerBitcastPass());
644
645 pm->add(clspv::createSplatSelectConditionPass());
646 pm->add(clspv::createSignedCompareFixupPass());
647 // This pass generates insertions that need to be rewritten.
648 pm->add(clspv::createScalarizePass());
649 pm->add(clspv::createRewriteInsertsPass());
650 // This pass mucks with types to point where you shouldn't rely on DataLayout
651 // anymore so leave this right before SPIR-V generation.
652 pm->add(clspv::createUBOTypeTransformPass());
653 pm->add(clspv::createSPIRVProducerPass(
alan-bakerf5e5f692018-11-27 08:33:24 -0500654 *binaryStream, descriptor_map_entries, *SamplerMapEntries,
alan-bakerfec0a472018-11-08 18:09:40 -0500655 OutputAssembly.getValue(), OutputFormat == "c"));
alan-bakerf5e5f692018-11-27 08:33:24 -0500656
657 return 0;
alan-bakerfec0a472018-11-08 18:09:40 -0500658}
659} // namespace
660
661namespace clspv {
662int Compile(const int argc, const char *const argv[]) {
663 // We need to change how one of the called passes works by spoofing
664 // ParseCommandLineOptions with the specific option.
665 const int llvmArgc = 2;
666 const char *llvmArgv[llvmArgc] = {
alan-bakerf5e5f692018-11-27 08:33:24 -0500667 argv[0],
668 "-simplifycfg-sink-common=false",
alan-bakerfec0a472018-11-08 18:09:40 -0500669 };
670
671 llvm::cl::ParseCommandLineOptions(llvmArgc, llvmArgv);
672
673 llvm::cl::ParseCommandLineOptions(argc, argv);
674
alan-bakerfec0a472018-11-08 18:09:40 -0500675 llvm::SmallVector<std::pair<unsigned, std::string>, 8> SamplerMapEntries;
alan-bakerf5e5f692018-11-27 08:33:24 -0500676 if (auto error = ParseSamplerMap("", &SamplerMapEntries))
alan-bakerfec0a472018-11-08 18:09:40 -0500677 return error;
678
679 // if no output file was provided, use a default
680 llvm::StringRef overiddenInputFilename = InputFilename.getValue();
681
682 // If we are reading our input file from stdin.
683 if ("-" == InputFilename) {
684 // We need to overwrite the file name we use.
685 overiddenInputFilename = "stdin.cl";
686 }
687
688 clang::CompilerInstance instance;
689 clang::FrontendInputFile kernelFile(overiddenInputFilename,
690 clang::InputKind::OpenCL);
691 std::string log;
692 llvm::raw_string_ostream diagnosticsStream(log);
alan-bakerf5e5f692018-11-27 08:33:24 -0500693 if (auto error = SetCompilerInstanceOptions(
694 instance, overiddenInputFilename, kernelFile, "", &diagnosticsStream))
alan-bakerfec0a472018-11-08 18:09:40 -0500695 return error;
696
697 // Parse.
698 llvm::LLVMContext context;
699 clang::EmitLLVMOnlyAction action(&context);
700
701 // Prepare the action for processing kernelFile
702 const bool success = action.BeginSourceFile(instance, kernelFile);
703 if (!success) {
704 return -1;
705 }
706
707 action.Execute();
708 action.EndSourceFile();
709
710 clang::DiagnosticConsumer *const consumer =
711 instance.getDiagnostics().getClient();
712 consumer->finish();
713
714 auto num_errors = consumer->getNumErrors();
715 if (num_errors > 0) {
716 llvm::errs() << log << "\n";
717 return -1;
718 }
719
720 if (clspv::Option::ConstantArgsInUniformBuffer() &&
721 !clspv::Option::InlineEntryPoints()) {
722 llvm::errs() << "clspv restriction: -constant-arg-ubo requires "
723 "-inline-entry-points\n";
724 return -1;
725 }
726
727 llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry();
728 llvm::initializeCore(Registry);
729 llvm::initializeScalarOpts(Registry);
730
731 std::unique_ptr<llvm::Module> module(action.takeModule());
732
733 // Optimize.
734 // Create a memory buffer for temporarily writing the result.
735 SmallVector<char, 10000> binary;
736 llvm::raw_svector_ostream binaryStream(binary);
737 std::string descriptor_map;
alan-bakerfec0a472018-11-08 18:09:40 -0500738 llvm::legacy::PassManager pm;
alan-bakerf5e5f692018-11-27 08:33:24 -0500739 std::vector<version0::DescriptorMapEntry> descriptor_map_entries;
740 if (auto error =
741 PopulatePassManager(&pm, &binaryStream,
742 &descriptor_map_entries, &SamplerMapEntries))
743 return error;
alan-bakerfec0a472018-11-08 18:09:40 -0500744 pm.run(*module);
745
746 // Write outputs
747
748 // Write the descriptor map, if requested.
749 std::error_code error;
750 if (!DescriptorMapFilename.empty()) {
alan-bakerfec0a472018-11-08 18:09:40 -0500751 llvm::raw_fd_ostream descriptor_map_out_fd(DescriptorMapFilename, error,
752 llvm::sys::fs::F_RW |
753 llvm::sys::fs::F_Text);
754 if (error) {
755 llvm::errs() << "Unable to open descriptor map file '"
756 << DescriptorMapFilename << "': " << error.message() << '\n';
757 return -1;
758 }
alan-bakerf5e5f692018-11-27 08:33:24 -0500759 std::string descriptor_map_string;
760 std::ostringstream str(descriptor_map_string);
761 for (const auto &entry : descriptor_map_entries) {
762 str << entry << "\n";
763 }
764 descriptor_map_out_fd << str.str();
alan-bakerfec0a472018-11-08 18:09:40 -0500765 descriptor_map_out_fd.close();
766 }
767
768 // Write the resulting binary.
769 // Wait until now to try writing the file so that we only write it on
770 // successful compilation.
771 if (OutputFilename.empty()) {
772 // if we've to output assembly
773 if (OutputAssembly) {
774 OutputFilename = "a.spvasm";
775 } else if (OutputFormat == "c") {
776 OutputFilename = "a.spvinc";
777 } else {
778 OutputFilename = "a.spv";
779 }
780 }
781 llvm::raw_fd_ostream outStream(OutputFilename, error, llvm::sys::fs::F_RW);
782
783 if (error) {
784 llvm::errs() << "Unable to open output file '" << OutputFilename
785 << "': " << error.message() << '\n';
786 return -1;
787 }
788 outStream << binaryStream.str();
789
790 return 0;
791}
alan-bakerf5e5f692018-11-27 08:33:24 -0500792
793int CompileFromSourceString(const std::string &program,
794 const std::string &sampler_map,
795 const std::string &options,
796 std::vector<uint32_t> *output_binary,
797 std::vector<clspv::version0::DescriptorMapEntry> *descriptor_map_entries) {
798 // We need to change how one of the called passes works by spoofing
799 // ParseCommandLineOptions with the specific option.
800 const int llvmArgc = 2;
801 const char *llvmArgv[llvmArgc] = {
802 "clspv",
803 "-simplifycfg-sink-common=false",
804 };
805
806 llvm::cl::ParseCommandLineOptions(llvmArgc, llvmArgv);
807
808 llvm::SmallVector<const char *, 20> argv;
809 llvm::BumpPtrAllocator A;
810 llvm::StringSaver Saver(A);
811 argv.push_back(Saver.save("clspv").data());
812 llvm::cl::TokenizeGNUCommandLine(options, Saver, argv);
813 int argc = static_cast<int>(argv.size());
814 llvm::cl::ParseCommandLineOptions(argc, &argv[0]);
815
816 llvm::SmallVector<std::pair<unsigned, std::string>, 8> SamplerMapEntries;
817 if (auto error = ParseSamplerMap(sampler_map, &SamplerMapEntries))
818 return error;
819
820 InputFilename = "source.cl";
821 llvm::StringRef overiddenInputFilename = InputFilename.getValue();
822
823 clang::CompilerInstance instance;
824 clang::FrontendInputFile kernelFile(overiddenInputFilename,
825 clang::InputKind::OpenCL);
826 std::string log;
827 llvm::raw_string_ostream diagnosticsStream(log);
828 if (auto error =
829 SetCompilerInstanceOptions(instance, overiddenInputFilename,
830 kernelFile, program, &diagnosticsStream))
831 return error;
832
833 // Parse.
834 llvm::LLVMContext context;
835 clang::EmitLLVMOnlyAction action(&context);
836
837 // Prepare the action for processing kernelFile
838 const bool success = action.BeginSourceFile(instance, kernelFile);
839 if (!success) {
840 return -1;
841 }
842
843 action.Execute();
844 action.EndSourceFile();
845
846 clang::DiagnosticConsumer *const consumer =
847 instance.getDiagnostics().getClient();
848 consumer->finish();
849
850 auto num_errors = consumer->getNumErrors();
851 if (num_errors > 0) {
852 llvm::errs() << log << "\n";
853 return -1;
854 }
855
856 if (clspv::Option::ConstantArgsInUniformBuffer() &&
857 !clspv::Option::InlineEntryPoints()) {
858 llvm::errs() << "clspv restriction: -constant-arg-ubo requires "
859 "-inline-entry-points\n";
860 return -1;
861 }
862
863 llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry();
864 llvm::initializeCore(Registry);
865 llvm::initializeScalarOpts(Registry);
866
867 std::unique_ptr<llvm::Module> module(action.takeModule());
868
869 // Optimize.
870 // Create a memory buffer for temporarily writing the result.
871 SmallVector<char, 10000> binary;
872 llvm::raw_svector_ostream binaryStream(binary);
873 std::string descriptor_map;
874 llvm::legacy::PassManager pm;
875 if (auto error =
876 PopulatePassManager(&pm, &binaryStream,
877 descriptor_map_entries, &SamplerMapEntries))
878 return error;
879 pm.run(*module);
880
881 // Write outputs
882
883 // Write the descriptor map. This is required.
884 assert(descriptor_map_entries && "Valid descriptor map container is required.");
885 if (!DescriptorMapFilename.empty()) {
886 llvm::errs() << "Warning: -descriptormap is ignored descriptor map container is provided.\n";
887 }
888
889 // Write the resulting binary.
890 // Wait until now to try writing the file so that we only write it on
891 // successful compilation.
892 assert(output_binary && "Valid binary container is required.");
893 if (!OutputFilename.empty()) {
894 llvm::outs()
895 << "Warning: -o is ignored when binary container is provided.\n";
896 }
897 output_binary->resize(binary.size() / 4);
898 memcpy(output_binary->data(), binary.data(), binary.size());
899
900 return 0;
901}
alan-bakerfec0a472018-11-08 18:09:40 -0500902} // namespace clspv