blob: bd5249750ddf816d1418c4c4ac4a8f57769de369 [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
Alan Bakerea88c712018-12-06 11:40:49 -0500614
alan-bakerfec0a472018-11-08 18:09:40 -0500615 // Unhide loads from __constant address space. Undoes the action of
616 // HideConstantLoadsPass.
617 pm->add(clspv::createUnhideConstantLoadsPass());
618
619 pm->add(clspv::createFunctionInternalizerPass());
620 pm->add(clspv::createReplaceLLVMIntrinsicsPass());
621 pm->add(clspv::createUndoBoolPass());
622 pm->add(clspv::createUndoTruncatedSwitchConditionPass());
623 pm->add(llvm::createStructurizeCFGPass(false));
alan-baker3fa76d92018-11-12 14:54:40 -0500624 // Must be run after structurize cfg.
alan-bakerfec0a472018-11-08 18:09:40 -0500625 pm->add(clspv::createReorderBasicBlocksPass());
626 pm->add(clspv::createUndoGetElementPtrConstantExprPass());
627 pm->add(clspv::createSplatArgPass());
628 pm->add(clspv::createSimplifyPointerBitcastPass());
629 pm->add(clspv::createReplacePointerBitcastPass());
630
631 pm->add(clspv::createUndoTranslateSamplerFoldPass());
632
633 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
634 pm->add(clspv::createClusterModuleScopeConstantVars());
635 }
636
637 pm->add(clspv::createShareModuleScopeVariablesPass());
alan-bakere9308012019-03-15 10:25:13 -0400638 // This should be run after LLVM and OpenCL intrinsics are replaced.
alan-bakerfec0a472018-11-08 18:09:40 -0500639 pm->add(clspv::createAllocateDescriptorsPass(*SamplerMapEntries));
640 pm->add(llvm::createVerifierPass());
641 pm->add(clspv::createDirectResourceAccessPass());
642 // Replacing pointer bitcasts can leave some trivial GEPs
643 // that are easy to remove. Also replace GEPs of GEPS
644 // left by replacing indirect buffer accesses.
645 pm->add(clspv::createSimplifyPointerBitcastPass());
alan-baker4217b322019-03-06 08:56:12 -0500646 // Run after DRA to clean up parameters and help reduce the need for variable
647 // pointers.
648 pm->add(clspv::createRemoveUnusedArgumentsPass());
alan-bakerfec0a472018-11-08 18:09:40 -0500649
650 pm->add(clspv::createSplatSelectConditionPass());
651 pm->add(clspv::createSignedCompareFixupPass());
652 // This pass generates insertions that need to be rewritten.
653 pm->add(clspv::createScalarizePass());
654 pm->add(clspv::createRewriteInsertsPass());
655 // This pass mucks with types to point where you shouldn't rely on DataLayout
656 // anymore so leave this right before SPIR-V generation.
657 pm->add(clspv::createUBOTypeTransformPass());
658 pm->add(clspv::createSPIRVProducerPass(
alan-bakerf5e5f692018-11-27 08:33:24 -0500659 *binaryStream, descriptor_map_entries, *SamplerMapEntries,
alan-bakerfec0a472018-11-08 18:09:40 -0500660 OutputAssembly.getValue(), OutputFormat == "c"));
alan-bakerf5e5f692018-11-27 08:33:24 -0500661
662 return 0;
alan-bakerfec0a472018-11-08 18:09:40 -0500663}
664} // namespace
665
666namespace clspv {
667int Compile(const int argc, const char *const argv[]) {
668 // We need to change how one of the called passes works by spoofing
669 // ParseCommandLineOptions with the specific option.
670 const int llvmArgc = 2;
671 const char *llvmArgv[llvmArgc] = {
alan-bakerf5e5f692018-11-27 08:33:24 -0500672 argv[0],
673 "-simplifycfg-sink-common=false",
alan-bakerfec0a472018-11-08 18:09:40 -0500674 };
675
676 llvm::cl::ParseCommandLineOptions(llvmArgc, llvmArgv);
677
678 llvm::cl::ParseCommandLineOptions(argc, argv);
679
alan-bakerfec0a472018-11-08 18:09:40 -0500680 llvm::SmallVector<std::pair<unsigned, std::string>, 8> SamplerMapEntries;
alan-bakerf5e5f692018-11-27 08:33:24 -0500681 if (auto error = ParseSamplerMap("", &SamplerMapEntries))
alan-bakerfec0a472018-11-08 18:09:40 -0500682 return error;
683
684 // if no output file was provided, use a default
685 llvm::StringRef overiddenInputFilename = InputFilename.getValue();
686
687 // If we are reading our input file from stdin.
688 if ("-" == InputFilename) {
689 // We need to overwrite the file name we use.
690 overiddenInputFilename = "stdin.cl";
691 }
692
693 clang::CompilerInstance instance;
694 clang::FrontendInputFile kernelFile(overiddenInputFilename,
695 clang::InputKind::OpenCL);
696 std::string log;
697 llvm::raw_string_ostream diagnosticsStream(log);
alan-bakerf5e5f692018-11-27 08:33:24 -0500698 if (auto error = SetCompilerInstanceOptions(
699 instance, overiddenInputFilename, kernelFile, "", &diagnosticsStream))
alan-bakerfec0a472018-11-08 18:09:40 -0500700 return error;
701
702 // Parse.
703 llvm::LLVMContext context;
704 clang::EmitLLVMOnlyAction action(&context);
705
706 // Prepare the action for processing kernelFile
707 const bool success = action.BeginSourceFile(instance, kernelFile);
708 if (!success) {
709 return -1;
710 }
711
712 action.Execute();
713 action.EndSourceFile();
714
715 clang::DiagnosticConsumer *const consumer =
716 instance.getDiagnostics().getClient();
717 consumer->finish();
718
719 auto num_errors = consumer->getNumErrors();
720 if (num_errors > 0) {
721 llvm::errs() << log << "\n";
722 return -1;
723 }
724
725 if (clspv::Option::ConstantArgsInUniformBuffer() &&
726 !clspv::Option::InlineEntryPoints()) {
alan-bakerb39c8262019-03-08 14:03:37 -0500727 llvm::errs() << "clspv restriction: -constant-args-ubo requires "
alan-bakerfec0a472018-11-08 18:09:40 -0500728 "-inline-entry-points\n";
729 return -1;
730 }
731
alan-bakerb39c8262019-03-08 14:03:37 -0500732 // TODO: Remove when #279 is resolved.
733 if (clspv::Option::ConstantArgsInUniformBuffer() &&
734 clspv::Option::Int8Support()) {
735 llvm::errs() << "clspv restriction: -constant-args-ubo is currently "
736 "incompatible with -int8\n";
737 return -1;
738 }
739
alan-bakerfec0a472018-11-08 18:09:40 -0500740 llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry();
741 llvm::initializeCore(Registry);
742 llvm::initializeScalarOpts(Registry);
743
744 std::unique_ptr<llvm::Module> module(action.takeModule());
745
746 // Optimize.
747 // Create a memory buffer for temporarily writing the result.
748 SmallVector<char, 10000> binary;
749 llvm::raw_svector_ostream binaryStream(binary);
750 std::string descriptor_map;
alan-bakerfec0a472018-11-08 18:09:40 -0500751 llvm::legacy::PassManager pm;
alan-bakerf5e5f692018-11-27 08:33:24 -0500752 std::vector<version0::DescriptorMapEntry> descriptor_map_entries;
753 if (auto error =
754 PopulatePassManager(&pm, &binaryStream,
755 &descriptor_map_entries, &SamplerMapEntries))
756 return error;
alan-bakerfec0a472018-11-08 18:09:40 -0500757 pm.run(*module);
758
759 // Write outputs
760
761 // Write the descriptor map, if requested.
762 std::error_code error;
763 if (!DescriptorMapFilename.empty()) {
alan-bakerfec0a472018-11-08 18:09:40 -0500764 llvm::raw_fd_ostream descriptor_map_out_fd(DescriptorMapFilename, error,
765 llvm::sys::fs::F_RW |
766 llvm::sys::fs::F_Text);
767 if (error) {
768 llvm::errs() << "Unable to open descriptor map file '"
769 << DescriptorMapFilename << "': " << error.message() << '\n';
770 return -1;
771 }
alan-bakerf5e5f692018-11-27 08:33:24 -0500772 std::string descriptor_map_string;
773 std::ostringstream str(descriptor_map_string);
774 for (const auto &entry : descriptor_map_entries) {
775 str << entry << "\n";
776 }
777 descriptor_map_out_fd << str.str();
alan-bakerfec0a472018-11-08 18:09:40 -0500778 descriptor_map_out_fd.close();
779 }
780
781 // Write the resulting binary.
782 // Wait until now to try writing the file so that we only write it on
783 // successful compilation.
784 if (OutputFilename.empty()) {
785 // if we've to output assembly
786 if (OutputAssembly) {
787 OutputFilename = "a.spvasm";
788 } else if (OutputFormat == "c") {
789 OutputFilename = "a.spvinc";
790 } else {
791 OutputFilename = "a.spv";
792 }
793 }
794 llvm::raw_fd_ostream outStream(OutputFilename, error, llvm::sys::fs::F_RW);
795
796 if (error) {
797 llvm::errs() << "Unable to open output file '" << OutputFilename
798 << "': " << error.message() << '\n';
799 return -1;
800 }
801 outStream << binaryStream.str();
802
803 return 0;
804}
alan-bakerf5e5f692018-11-27 08:33:24 -0500805
806int CompileFromSourceString(const std::string &program,
807 const std::string &sampler_map,
808 const std::string &options,
809 std::vector<uint32_t> *output_binary,
810 std::vector<clspv::version0::DescriptorMapEntry> *descriptor_map_entries) {
811 // We need to change how one of the called passes works by spoofing
812 // ParseCommandLineOptions with the specific option.
813 const int llvmArgc = 2;
814 const char *llvmArgv[llvmArgc] = {
815 "clspv",
816 "-simplifycfg-sink-common=false",
817 };
818
alan-baker2d606eb2019-03-14 13:16:09 -0400819 llvm::cl::ResetAllOptionOccurrences();
alan-bakerf5e5f692018-11-27 08:33:24 -0500820 llvm::cl::ParseCommandLineOptions(llvmArgc, llvmArgv);
821
822 llvm::SmallVector<const char *, 20> argv;
823 llvm::BumpPtrAllocator A;
824 llvm::StringSaver Saver(A);
825 argv.push_back(Saver.save("clspv").data());
826 llvm::cl::TokenizeGNUCommandLine(options, Saver, argv);
827 int argc = static_cast<int>(argv.size());
828 llvm::cl::ParseCommandLineOptions(argc, &argv[0]);
829
830 llvm::SmallVector<std::pair<unsigned, std::string>, 8> SamplerMapEntries;
831 if (auto error = ParseSamplerMap(sampler_map, &SamplerMapEntries))
832 return error;
833
834 InputFilename = "source.cl";
835 llvm::StringRef overiddenInputFilename = InputFilename.getValue();
836
837 clang::CompilerInstance instance;
838 clang::FrontendInputFile kernelFile(overiddenInputFilename,
839 clang::InputKind::OpenCL);
840 std::string log;
841 llvm::raw_string_ostream diagnosticsStream(log);
842 if (auto error =
843 SetCompilerInstanceOptions(instance, overiddenInputFilename,
844 kernelFile, program, &diagnosticsStream))
845 return error;
846
847 // Parse.
848 llvm::LLVMContext context;
849 clang::EmitLLVMOnlyAction action(&context);
850
851 // Prepare the action for processing kernelFile
852 const bool success = action.BeginSourceFile(instance, kernelFile);
853 if (!success) {
854 return -1;
855 }
856
857 action.Execute();
858 action.EndSourceFile();
859
860 clang::DiagnosticConsumer *const consumer =
861 instance.getDiagnostics().getClient();
862 consumer->finish();
863
864 auto num_errors = consumer->getNumErrors();
865 if (num_errors > 0) {
866 llvm::errs() << log << "\n";
867 return -1;
868 }
869
870 if (clspv::Option::ConstantArgsInUniformBuffer() &&
871 !clspv::Option::InlineEntryPoints()) {
872 llvm::errs() << "clspv restriction: -constant-arg-ubo requires "
873 "-inline-entry-points\n";
874 return -1;
875 }
876
877 llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry();
878 llvm::initializeCore(Registry);
879 llvm::initializeScalarOpts(Registry);
880
881 std::unique_ptr<llvm::Module> module(action.takeModule());
882
883 // Optimize.
884 // Create a memory buffer for temporarily writing the result.
885 SmallVector<char, 10000> binary;
886 llvm::raw_svector_ostream binaryStream(binary);
887 std::string descriptor_map;
888 llvm::legacy::PassManager pm;
889 if (auto error =
890 PopulatePassManager(&pm, &binaryStream,
891 descriptor_map_entries, &SamplerMapEntries))
892 return error;
893 pm.run(*module);
894
895 // Write outputs
896
897 // Write the descriptor map. This is required.
898 assert(descriptor_map_entries && "Valid descriptor map container is required.");
899 if (!DescriptorMapFilename.empty()) {
900 llvm::errs() << "Warning: -descriptormap is ignored descriptor map container is provided.\n";
901 }
902
903 // Write the resulting binary.
904 // Wait until now to try writing the file so that we only write it on
905 // successful compilation.
906 assert(output_binary && "Valid binary container is required.");
907 if (!OutputFilename.empty()) {
908 llvm::outs()
909 << "Warning: -o is ignored when binary container is provided.\n";
910 }
911 output_binary->resize(binary.size() / 4);
912 memcpy(output_binary->data(), binary.data(), binary.size());
913
914 return 0;
915}
alan-bakerfec0a472018-11-08 18:09:40 -0500916} // namespace clspv