blob: 0b1a6ce0c1c73f6bc92215b924c805275dcfebb6 [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
alan-baker0d095d62020-03-12 14:59:47 -040015#include "clang/Basic/FileManager.h"
alan-bakerfec0a472018-11-08 18:09:40 -050016#include "clang/Basic/TargetInfo.h"
17#include "clang/CodeGen/CodeGenAction.h"
18#include "clang/Frontend/CompilerInstance.h"
19#include "clang/Frontend/FrontendPluginRegistry.h"
20#include "clang/Frontend/TextDiagnosticPrinter.h"
21#include "clang/Lex/PreprocessorOptions.h"
22#include "llvm/IR/LLVMContext.h"
23#include "llvm/IR/LegacyPassManager.h"
24#include "llvm/IR/Module.h"
25#include "llvm/IR/Verifier.h"
alan-baker0e64a592019-11-18 13:36:25 -050026#include "llvm/InitializePasses.h"
alan-bakerfec0a472018-11-08 18:09:40 -050027#include "llvm/LinkAllPasses.h"
alan-bakerf5e5f692018-11-27 08:33:24 -050028#include "llvm/Support/Allocator.h"
alan-bakerfec0a472018-11-08 18:09:40 -050029#include "llvm/Support/CommandLine.h"
alan-bakerf5e5f692018-11-27 08:33:24 -050030#include "llvm/Support/ErrorOr.h"
alan-bakerfec0a472018-11-08 18:09:40 -050031#include "llvm/Support/MathExtras.h"
alan-bakerf5e5f692018-11-27 08:33:24 -050032#include "llvm/Support/StringSaver.h"
Diego Novillo89500852019-04-15 08:45:10 -040033#include "llvm/Support/ToolOutputFile.h"
alan-bakerfec0a472018-11-08 18:09:40 -050034#include "llvm/Support/raw_ostream.h"
35#include "llvm/Transforms/IPO/PassManagerBuilder.h"
36
Kévin Petit38c52482019-05-07 20:28:00 +080037#include "clspv/AddressSpace.h"
alan-bakerf5e5f692018-11-27 08:33:24 -050038#include "clspv/DescriptorMap.h"
alan-bakerfec0a472018-11-08 18:09:40 -050039#include "clspv/Option.h"
40#include "clspv/Passes.h"
41#include "clspv/opencl_builtins_header.h"
42
43#include "FrontendPlugin.h"
Diego Novilloa4c44fa2019-04-11 10:56:15 -040044#include "Passes.h"
alan-bakerfec0a472018-11-08 18:09:40 -050045
alan-bakerf5e5f692018-11-27 08:33:24 -050046#include <cassert>
alan-bakerfec0a472018-11-08 18:09:40 -050047#include <numeric>
alan-bakerf5e5f692018-11-27 08:33:24 -050048#include <sstream>
Diego Novillo3cc8d7a2019-04-10 13:30:34 -040049#include <string>
alan-bakerfec0a472018-11-08 18:09:40 -050050
51using namespace clang;
52
53namespace {
54// This registration must be located in the same file as the execution of the
55// action.
56static FrontendPluginRegistry::Add<clspv::ExtraValidationASTAction>
57 X("extra-validation",
58 "Perform extra validation on OpenCL C when targeting Vulkan");
59
60static llvm::cl::opt<bool> cl_single_precision_constants(
61 "cl-single-precision-constant", llvm::cl::init(false),
62 llvm::cl::desc("Treat double precision floating-point constant as single "
63 "precision constant."));
64
65static llvm::cl::opt<bool> cl_denorms_are_zero(
66 "cl-denorms-are-zero", llvm::cl::init(false),
67 llvm::cl::desc("If specified, denormalized floating point numbers may be "
68 "flushed to zero."));
69
70static llvm::cl::opt<bool> cl_fp32_correctly_rounded_divide_sqrt(
71 "cl-fp32-correctly-rounded-divide-sqrt", llvm::cl::init(false),
72 llvm::cl::desc("Single precision floating-point divide (x/y and 1/x) and "
73 "sqrt used are correctly rounded."));
74
75static llvm::cl::opt<bool>
76 cl_opt_disable("cl-opt-disable", llvm::cl::init(false),
77 llvm::cl::desc("This option disables all optimizations. The "
78 "default is optimizations are enabled."));
79
80static llvm::cl::opt<bool> cl_mad_enable(
81 "cl-mad-enable", llvm::cl::init(false),
82 llvm::cl::desc("Allow a * b + c to be replaced by a mad. The mad computes "
83 "a * b + c with reduced accuracy."));
84
85static llvm::cl::opt<bool> cl_no_signed_zeros(
86 "cl-no-signed-zeros", llvm::cl::init(false),
87 llvm::cl::desc("Allow optimizations for floating-point arithmetic that "
88 "ignore the signedness of zero."));
89
90static llvm::cl::opt<bool> cl_unsafe_math_optimizations(
91 "cl-unsafe-math-optimizations", llvm::cl::init(false),
92 llvm::cl::desc("Allow optimizations for floating-point arithmetic that (a) "
93 "assume that arguments and results are valid, (b) may "
94 "violate IEEE 754 standard and (c) may violate the OpenCL "
95 "numerical compliance requirements. This option includes "
96 "the -cl-no-signed-zeros and -cl-mad-enable options."));
97
98static llvm::cl::opt<bool> cl_finite_math_only(
99 "cl-finite-math-only", llvm::cl::init(false),
100 llvm::cl::desc("Allow optimizations for floating-point arithmetic that "
101 "assume that arguments and results are not NaNs or INFs."));
102
103static llvm::cl::opt<bool> cl_fast_relaxed_math(
104 "cl-fast-relaxed-math", llvm::cl::init(false),
105 llvm::cl::desc("This option causes the preprocessor macro "
106 "__FAST_RELAXED_MATH__ to be defined. Sets the optimization "
107 "options -cl-finite-math-only and "
108 "-cl-unsafe-math-optimizations."));
109
110static llvm::cl::list<std::string>
111 Includes(llvm::cl::Prefix, "I",
112 llvm::cl::desc("Add a directory to the list of directories "
113 "to be searched for header files."),
114 llvm::cl::ZeroOrMore, llvm::cl::value_desc("include path"));
115
116static llvm::cl::list<std::string>
117 Defines(llvm::cl::Prefix, "D",
118 llvm::cl::desc("Define a #define directive."), llvm::cl::ZeroOrMore,
119 llvm::cl::value_desc("define"));
120
121static llvm::cl::opt<std::string>
122 InputFilename(llvm::cl::Positional, llvm::cl::desc("<input .cl file>"),
123 llvm::cl::init("-"));
124
Kévin Petitddad8f42019-09-30 15:12:08 +0100125static llvm::cl::opt<clang::Language> InputLanguage(
126 "x", llvm::cl::desc("Select input type"),
127 llvm::cl::init(clang::Language::OpenCL),
128 llvm::cl::values(clEnumValN(clang::Language::OpenCL, "cl", "OpenCL source"),
129 clEnumValN(clang::Language::LLVM_IR, "ir", "LLVM IR")));
130
alan-bakerfec0a472018-11-08 18:09:40 -0500131static llvm::cl::opt<std::string>
132 OutputFilename("o", llvm::cl::desc("Override output filename"),
133 llvm::cl::value_desc("filename"));
134
135static llvm::cl::opt<std::string>
136 DescriptorMapFilename("descriptormap",
137 llvm::cl::desc("Output file for descriptor map"),
138 llvm::cl::value_desc("filename"));
139
140static llvm::cl::opt<char>
141 OptimizationLevel(llvm::cl::Prefix, "O", llvm::cl::init('2'),
142 llvm::cl::desc("Optimization level to use"),
143 llvm::cl::value_desc("level"));
144
alan-bakerfec0a472018-11-08 18:09:40 -0500145static llvm::cl::opt<std::string> OutputFormat(
146 "mfmt", llvm::cl::init(""),
147 llvm::cl::desc(
148 "Specify special output format. 'c' is as a C initializer list"),
149 llvm::cl::value_desc("format"));
150
151static llvm::cl::opt<std::string>
alan-baker09cb9802019-12-10 13:16:27 -0500152 SamplerMap("samplermap", llvm::cl::desc("DEPRECATED - Literal sampler map"),
alan-bakerfec0a472018-11-08 18:09:40 -0500153 llvm::cl::value_desc("filename"));
154
alan-bakerfec0a472018-11-08 18:09:40 -0500155static llvm::cl::opt<bool> verify("verify", llvm::cl::init(false),
156 llvm::cl::desc("Verify diagnostic outputs"));
157
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100158static llvm::cl::opt<bool>
159 IgnoreWarnings("w", llvm::cl::init(false),
160 llvm::cl::desc("Disable all warnings"));
161
162static llvm::cl::opt<bool>
163 WarningsAsErrors("Werror", llvm::cl::init(false),
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400164 llvm::cl::desc("Turn warnings into errors"));
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100165
Diego Novillo89500852019-04-15 08:45:10 -0400166static llvm::cl::opt<std::string> IROutputFile(
167 "emit-ir",
168 llvm::cl::desc(
169 "Emit LLVM IR to the given file after parsing and stop compilation."),
170 llvm::cl::value_desc("filename"));
171
alan-bakerfec0a472018-11-08 18:09:40 -0500172// Populates |SamplerMapEntries| with data from the input sampler map. Returns 0
173// if successful.
alan-bakerf5e5f692018-11-27 08:33:24 -0500174int ParseSamplerMap(const std::string &sampler_map,
175 llvm::SmallVectorImpl<std::pair<unsigned, std::string>>
176 *SamplerMapEntries) {
177 std::unique_ptr<llvm::MemoryBuffer> samplerMapBuffer(nullptr);
178 if (!sampler_map.empty()) {
179 // Parse the sampler map from the provided string.
180 samplerMapBuffer = llvm::MemoryBuffer::getMemBuffer(sampler_map);
181
alan-baker09cb9802019-12-10 13:16:27 -0500182 clspv::Option::SetUseSamplerMap(true);
alan-bakerf5e5f692018-11-27 08:33:24 -0500183 if (!SamplerMap.empty()) {
184 llvm::outs() << "Warning: -samplermap is ignored when the sampler map is "
185 "provided through a string.\n";
186 }
187 } else if (!SamplerMap.empty()) {
188 // Parse the sampler map from the option provided file.
alan-bakerfec0a472018-11-08 18:09:40 -0500189 auto errorOrSamplerMapFile =
190 llvm::MemoryBuffer::getFile(SamplerMap.getValue());
191
192 // If there was an error in getting the sampler map file.
193 if (!errorOrSamplerMapFile) {
194 llvm::errs() << "Error: " << errorOrSamplerMapFile.getError().message()
195 << " '" << SamplerMap.getValue() << "'\n";
196 return -1;
197 }
198
alan-baker09cb9802019-12-10 13:16:27 -0500199 clspv::Option::SetUseSamplerMap(true);
alan-bakerf5e5f692018-11-27 08:33:24 -0500200 samplerMapBuffer = std::move(errorOrSamplerMapFile.get());
alan-bakerfec0a472018-11-08 18:09:40 -0500201 if (0 == samplerMapBuffer->getBufferSize()) {
202 llvm::errs() << "Error: Sampler map was an empty file!\n";
203 return -1;
204 }
alan-bakerf5e5f692018-11-27 08:33:24 -0500205 }
alan-bakerfec0a472018-11-08 18:09:40 -0500206
alan-baker09cb9802019-12-10 13:16:27 -0500207 if (clspv::Option::UseSamplerMap()) {
208 llvm::outs()
209 << "Warning: use of the sampler map is deprecated and unnecessary\n";
210 }
211
alan-bakerf5e5f692018-11-27 08:33:24 -0500212 // No sampler map to parse.
213 if (!samplerMapBuffer || 0 == samplerMapBuffer->getBufferSize())
214 return 0;
alan-bakerfec0a472018-11-08 18:09:40 -0500215
alan-bakerf5e5f692018-11-27 08:33:24 -0500216 llvm::SmallVector<llvm::StringRef, 3> samplerStrings;
alan-bakerfec0a472018-11-08 18:09:40 -0500217
alan-bakerf5e5f692018-11-27 08:33:24 -0500218 // We need to keep track of the beginning of the current entry.
219 const char *b = samplerMapBuffer->getBufferStart();
220 for (const char *i = b, *e = samplerMapBuffer->getBufferEnd();; i++) {
221 // If we have a separator between declarations.
222 if ((*i == '|') || (*i == ',') || (i == e)) {
223 if (i == b) {
224 llvm::errs() << "Error: Sampler map contained an empty entry!\n";
225 return -1;
alan-bakerfec0a472018-11-08 18:09:40 -0500226 }
227
alan-bakerf5e5f692018-11-27 08:33:24 -0500228 samplerStrings.push_back(llvm::StringRef(b, i - b).trim());
alan-bakerfec0a472018-11-08 18:09:40 -0500229
alan-bakerf5e5f692018-11-27 08:33:24 -0500230 // And set b the next character after i.
231 b = i + 1;
232 }
alan-bakerfec0a472018-11-08 18:09:40 -0500233
alan-bakerf5e5f692018-11-27 08:33:24 -0500234 // If we have a separator between declarations within a single sampler.
235 if ((*i == ',') || (i == e)) {
alan-bakerfec0a472018-11-08 18:09:40 -0500236
James Pricec05f6052020-01-14 13:37:20 -0500237 clspv::version0::SamplerNormalizedCoords NormalizedCoord =
238 clspv::version0::CLK_NORMALIZED_COORDS_NOT_SET;
239 clspv::version0::SamplerAddressingMode AddressingMode =
240 clspv::version0::CLK_ADDRESS_NOT_SET;
241 clspv::version0::SamplerFilterMode FilterMode =
242 clspv::version0::CLK_FILTER_NOT_SET;
alan-bakerf5e5f692018-11-27 08:33:24 -0500243
244 for (auto str : samplerStrings) {
245 if ("CLK_NORMALIZED_COORDS_FALSE" == str) {
James Pricec05f6052020-01-14 13:37:20 -0500246 if (clspv::version0::CLK_NORMALIZED_COORDS_NOT_SET !=
247 NormalizedCoord) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500248 llvm::errs() << "Error: Sampler map normalized coordinates was "
249 "previously set!\n";
alan-bakerfec0a472018-11-08 18:09:40 -0500250 return -1;
251 }
James Pricec05f6052020-01-14 13:37:20 -0500252 NormalizedCoord = clspv::version0::CLK_NORMALIZED_COORDS_FALSE;
alan-bakerf5e5f692018-11-27 08:33:24 -0500253 } else if ("CLK_NORMALIZED_COORDS_TRUE" == str) {
James Pricec05f6052020-01-14 13:37:20 -0500254 if (clspv::version0::CLK_NORMALIZED_COORDS_NOT_SET !=
255 NormalizedCoord) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500256 llvm::errs() << "Error: Sampler map normalized coordinates was "
257 "previously set!\n";
258 return -1;
259 }
James Pricec05f6052020-01-14 13:37:20 -0500260 NormalizedCoord = clspv::version0::CLK_NORMALIZED_COORDS_TRUE;
alan-bakerf5e5f692018-11-27 08:33:24 -0500261 } else if ("CLK_ADDRESS_NONE" == str) {
James Pricec05f6052020-01-14 13:37:20 -0500262 if (clspv::version0::CLK_ADDRESS_NOT_SET != AddressingMode) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500263 llvm::errs()
264 << "Error: Sampler map addressing mode was previously set!\n";
265 return -1;
266 }
James Pricec05f6052020-01-14 13:37:20 -0500267 AddressingMode = clspv::version0::CLK_ADDRESS_NONE;
alan-bakerf5e5f692018-11-27 08:33:24 -0500268 } else if ("CLK_ADDRESS_CLAMP_TO_EDGE" == str) {
James Pricec05f6052020-01-14 13:37:20 -0500269 if (clspv::version0::CLK_ADDRESS_NOT_SET != AddressingMode) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500270 llvm::errs()
271 << "Error: Sampler map addressing mode was previously set!\n";
272 return -1;
273 }
James Pricec05f6052020-01-14 13:37:20 -0500274 AddressingMode = clspv::version0::CLK_ADDRESS_CLAMP_TO_EDGE;
alan-bakerf5e5f692018-11-27 08:33:24 -0500275 } else if ("CLK_ADDRESS_CLAMP" == str) {
James Pricec05f6052020-01-14 13:37:20 -0500276 if (clspv::version0::CLK_ADDRESS_NOT_SET != AddressingMode) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500277 llvm::errs()
278 << "Error: Sampler map addressing mode was previously set!\n";
279 return -1;
280 }
James Pricec05f6052020-01-14 13:37:20 -0500281 AddressingMode = clspv::version0::CLK_ADDRESS_CLAMP;
alan-bakerf5e5f692018-11-27 08:33:24 -0500282 } else if ("CLK_ADDRESS_MIRRORED_REPEAT" == str) {
James Pricec05f6052020-01-14 13:37:20 -0500283 if (clspv::version0::CLK_ADDRESS_NOT_SET != AddressingMode) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500284 llvm::errs()
285 << "Error: Sampler map addressing mode was previously set!\n";
286 return -1;
287 }
James Pricec05f6052020-01-14 13:37:20 -0500288 AddressingMode = clspv::version0::CLK_ADDRESS_MIRRORED_REPEAT;
alan-bakerf5e5f692018-11-27 08:33:24 -0500289 } else if ("CLK_ADDRESS_REPEAT" == str) {
James Pricec05f6052020-01-14 13:37:20 -0500290 if (clspv::version0::CLK_ADDRESS_NOT_SET != AddressingMode) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500291 llvm::errs()
292 << "Error: Sampler map addressing mode was previously set!\n";
293 return -1;
294 }
James Pricec05f6052020-01-14 13:37:20 -0500295 AddressingMode = clspv::version0::CLK_ADDRESS_REPEAT;
alan-bakerf5e5f692018-11-27 08:33:24 -0500296 } else if ("CLK_FILTER_NEAREST" == str) {
James Pricec05f6052020-01-14 13:37:20 -0500297 if (clspv::version0::CLK_FILTER_NOT_SET != FilterMode) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500298 llvm::errs()
299 << "Error: Sampler map filtering mode was previously set!\n";
300 return -1;
301 }
James Pricec05f6052020-01-14 13:37:20 -0500302 FilterMode = clspv::version0::CLK_FILTER_NEAREST;
alan-bakerf5e5f692018-11-27 08:33:24 -0500303 } else if ("CLK_FILTER_LINEAR" == str) {
James Pricec05f6052020-01-14 13:37:20 -0500304 if (clspv::version0::CLK_FILTER_NOT_SET != FilterMode) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500305 llvm::errs()
306 << "Error: Sampler map filtering mode was previously set!\n";
307 return -1;
308 }
James Pricec05f6052020-01-14 13:37:20 -0500309 FilterMode = clspv::version0::CLK_FILTER_LINEAR;
alan-bakerf5e5f692018-11-27 08:33:24 -0500310 } else {
311 llvm::errs() << "Error: Unknown sampler string '" << str
312 << "' found!\n";
alan-bakerfec0a472018-11-08 18:09:40 -0500313 return -1;
314 }
alan-bakerfec0a472018-11-08 18:09:40 -0500315 }
316
James Pricec05f6052020-01-14 13:37:20 -0500317 if (clspv::version0::CLK_NORMALIZED_COORDS_NOT_SET == NormalizedCoord) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500318 llvm::errs() << "Error: Sampler map entry did not contain normalized "
319 "coordinates entry!\n";
320 return -1;
alan-bakerfec0a472018-11-08 18:09:40 -0500321 }
alan-bakerf5e5f692018-11-27 08:33:24 -0500322
James Pricec05f6052020-01-14 13:37:20 -0500323 if (clspv::version0::CLK_ADDRESS_NOT_SET == AddressingMode) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500324 llvm::errs() << "Error: Sampler map entry did not contain addressing "
325 "mode entry!\n";
326 return -1;
327 }
328
James Pricec05f6052020-01-14 13:37:20 -0500329 if (clspv::version0::CLK_FILTER_NOT_SET == FilterMode) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500330 llvm::errs()
331 << "Error: Sampler map entry did not contain filer mode entry!\n";
332 return -1;
333 }
334
335 // Generate an equivalent expression in string form. Sort the
336 // strings to get a canonical ordering.
337 std::sort(samplerStrings.begin(), samplerStrings.end(),
338 std::less<StringRef>());
339 const auto samplerExpr = std::accumulate(
340 samplerStrings.begin(), samplerStrings.end(), std::string(),
alan-baker21574d32020-01-29 16:00:31 -0500341 [](llvm::StringRef left, llvm::StringRef right) {
342 return left.str() + std::string(left.empty() ? "" : "|") +
343 right.str();
alan-bakerf5e5f692018-11-27 08:33:24 -0500344 });
345
346 // SamplerMapEntries->push_back(std::make_pair(
347 // NormalizedCoord | AddressingMode | FilterMode, samplerExpr));
348 SamplerMapEntries->emplace_back(
349 NormalizedCoord | AddressingMode | FilterMode, samplerExpr);
350
351 // And reset the sampler strings for the next sampler in the map.
352 samplerStrings.clear();
353 }
354
355 // And lastly, if we are at the end of the file
356 if (i == e) {
357 break;
alan-bakerfec0a472018-11-08 18:09:40 -0500358 }
359 }
360
361 return 0;
362}
363
364// Sets |instance|'s options for compiling. Returns 0 if successful.
365int SetCompilerInstanceOptions(CompilerInstance &instance,
366 const llvm::StringRef &overiddenInputFilename,
367 const clang::FrontendInputFile &kernelFile,
alan-bakerf5e5f692018-11-27 08:33:24 -0500368 const std::string &program,
alan-bakerfec0a472018-11-08 18:09:40 -0500369 llvm::raw_string_ostream *diagnosticsStream) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500370 std::unique_ptr<llvm::MemoryBuffer> memory_buffer(nullptr);
371 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> errorOrInputFile(nullptr);
372 if (program.empty()) {
373 auto errorOrInputFile =
374 llvm::MemoryBuffer::getFileOrSTDIN(InputFilename.getValue());
alan-bakerfec0a472018-11-08 18:09:40 -0500375
alan-bakerf5e5f692018-11-27 08:33:24 -0500376 // If there was an error in getting the input file.
377 if (!errorOrInputFile) {
378 llvm::errs() << "Error: " << errorOrInputFile.getError().message() << " '"
379 << InputFilename.getValue() << "'\n";
380 return -1;
381 }
382 memory_buffer.reset(errorOrInputFile.get().release());
383 } else {
384 memory_buffer = llvm::MemoryBuffer::getMemBuffer(program.c_str(),
385 overiddenInputFilename);
alan-bakerfec0a472018-11-08 18:09:40 -0500386 }
alan-bakerf5e5f692018-11-27 08:33:24 -0500387
alan-bakerfec0a472018-11-08 18:09:40 -0500388 if (verify) {
389 instance.getDiagnosticOpts().VerifyDiagnostics = true;
alan-bakerbccf62c2019-03-29 10:32:41 -0400390 instance.getDiagnosticOpts().VerifyPrefixes.push_back("expected");
alan-bakerfec0a472018-11-08 18:09:40 -0500391 }
392
Kévin Petit0fc88042019-04-09 23:25:02 +0100393 clang::LangStandard::Kind standard;
Kévin Petitf0515712020-01-07 18:29:20 +0000394 switch (clspv::Option::Language()) {
395 case clspv::Option::SourceLanguage::OpenCL_C_10:
396 standard = clang::LangStandard::lang_opencl10;
397 break;
398 case clspv::Option::SourceLanguage::OpenCL_C_11:
399 standard = clang::LangStandard::lang_opencl11;
400 break;
401 case clspv::Option::SourceLanguage::OpenCL_C_12:
Kévin Petit0fc88042019-04-09 23:25:02 +0100402 standard = clang::LangStandard::lang_opencl12;
Kévin Petitf0515712020-01-07 18:29:20 +0000403 break;
404 case clspv::Option::SourceLanguage::OpenCL_C_20:
405 standard = clang::LangStandard::lang_opencl20;
406 break;
407 case clspv::Option::SourceLanguage::OpenCL_CPP:
408 standard = clang::LangStandard::lang_openclcpp;
409 break;
410 default:
411 llvm_unreachable("Unknown source language");
Kévin Petit0fc88042019-04-09 23:25:02 +0100412 }
alan-bakerfec0a472018-11-08 18:09:40 -0500413
alan-bakerfec0a472018-11-08 18:09:40 -0500414 instance.getLangOpts().C99 = true;
415 instance.getLangOpts().RTTI = false;
416 instance.getLangOpts().RTTIData = false;
417 instance.getLangOpts().MathErrno = false;
418 instance.getLangOpts().Optimize = false;
419 instance.getLangOpts().NoBuiltin = true;
420 instance.getLangOpts().ModulesSearchAll = false;
421 instance.getLangOpts().SinglePrecisionConstants = true;
422 instance.getCodeGenOpts().StackRealignment = true;
423 instance.getCodeGenOpts().SimplifyLibCalls = false;
424 instance.getCodeGenOpts().EmitOpenCLArgMetadata = false;
425 instance.getCodeGenOpts().DisableO0ImplyOptNone = true;
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100426 instance.getDiagnosticOpts().IgnoreWarnings = IgnoreWarnings;
alan-bakerfec0a472018-11-08 18:09:40 -0500427
428 instance.getLangOpts().SinglePrecisionConstants =
429 cl_single_precision_constants;
430 // cl_denorms_are_zero ignored for now!
431 // cl_fp32_correctly_rounded_divide_sqrt ignored for now!
432 instance.getCodeGenOpts().LessPreciseFPMAD =
433 cl_mad_enable || cl_unsafe_math_optimizations;
434 // cl_no_signed_zeros ignored for now!
435 instance.getCodeGenOpts().UnsafeFPMath =
436 cl_unsafe_math_optimizations || cl_fast_relaxed_math;
437 instance.getLangOpts().FiniteMathOnly =
438 cl_finite_math_only || cl_fast_relaxed_math;
439 instance.getLangOpts().FastRelaxedMath = cl_fast_relaxed_math;
440
441 // Preprocessor options
Kévin Petita624c0c2019-05-07 20:27:43 +0800442 if (!clspv::Option::ImageSupport()) {
443 instance.getPreprocessorOpts().addMacroUndef("__IMAGE_SUPPORT__");
444 }
alan-bakerfec0a472018-11-08 18:09:40 -0500445 if (cl_fast_relaxed_math) {
446 instance.getPreprocessorOpts().addMacroDef("__FAST_RELAXED_MATH__");
447 }
448
449 for (auto define : Defines) {
450 instance.getPreprocessorOpts().addMacroDef(define);
451 }
452
453 // Header search options
454 for (auto include : Includes) {
455 instance.getHeaderSearchOpts().AddPath(include, clang::frontend::After,
456 false, false);
457 }
458
459 // We always compile on opt 0 so we preserve as much debug information about
460 // the source as possible. We'll run optimization later, once we've had a
461 // chance to view the unoptimal code first
462 instance.getCodeGenOpts().OptimizationLevel = 0;
463
464// Debug information is disabled temporarily to call instruction.
465#if 0
466 instance.getCodeGenOpts().setDebugInfo(clang::codegenoptions::FullDebugInfo);
467#endif
468
469 // We use the 32-bit pointer-width SPIR triple
470 llvm::Triple triple("spir-unknown-unknown");
471
472 instance.getInvocation().setLangDefaults(
alan-bakerd354f1a2019-08-06 15:41:55 -0400473 instance.getLangOpts(), clang::InputKind(clang::Language::OpenCL), triple,
alan-bakerfec0a472018-11-08 18:09:40 -0500474 instance.getPreprocessorOpts(), standard);
475
476 // Override the C99 inline semantics to accommodate for more OpenCL C
477 // programs in the wild.
478 instance.getLangOpts().GNUInline = true;
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100479
480 // Set up diagnostics
alan-bakerfec0a472018-11-08 18:09:40 -0500481 instance.createDiagnostics(
482 new clang::TextDiagnosticPrinter(*diagnosticsStream,
483 &instance.getDiagnosticOpts()),
484 true);
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100485 instance.getDiagnostics().setWarningsAsErrors(WarningsAsErrors);
486 instance.getDiagnostics().setEnableAllWarnings(true);
alan-bakerfec0a472018-11-08 18:09:40 -0500487
488 instance.getTargetOpts().Triple = triple.str();
489
alan-baker21574d32020-01-29 16:00:31 -0500490 instance.getCodeGenOpts().MainFileName = overiddenInputFilename.str();
alan-bakerfec0a472018-11-08 18:09:40 -0500491 instance.getCodeGenOpts().PreserveVec3Type = true;
492 // Disable generation of lifetime intrinsic.
493 instance.getCodeGenOpts().DisableLifetimeMarkers = true;
494 instance.getFrontendOpts().Inputs.push_back(kernelFile);
alan-bakerf5e5f692018-11-27 08:33:24 -0500495 instance.getPreprocessorOpts().addRemappedFile(overiddenInputFilename,
496 memory_buffer.release());
alan-bakerfec0a472018-11-08 18:09:40 -0500497
498 struct OpenCLBuiltinMemoryBuffer final : public llvm::MemoryBuffer {
499 OpenCLBuiltinMemoryBuffer(const void *data, uint64_t data_length) {
500 const char *dataCasted = reinterpret_cast<const char *>(data);
501 init(dataCasted, dataCasted + data_length, true);
502 }
503
504 virtual llvm::MemoryBuffer::BufferKind getBufferKind() const override {
505 return llvm::MemoryBuffer::MemoryBuffer_Malloc;
506 }
507
508 virtual ~OpenCLBuiltinMemoryBuffer() override {}
509 };
510
511 std::unique_ptr<llvm::MemoryBuffer> openCLBuiltinMemoryBuffer(
512 new OpenCLBuiltinMemoryBuffer(opencl_builtins_header_data,
513 opencl_builtins_header_size - 1));
514
515 instance.getPreprocessorOpts().Includes.push_back("openclc.h");
516
alan-bakerf3bce4a2019-06-28 16:01:15 -0400517 std::unique_ptr<llvm::MemoryBuffer> openCLBaseBuiltinMemoryBuffer(
518 new OpenCLBuiltinMemoryBuffer(opencl_base_builtins_header_data,
519 opencl_base_builtins_header_size - 1));
520
521 instance.getPreprocessorOpts().Includes.push_back("opencl-c-base.h");
522
alan-bakerfec0a472018-11-08 18:09:40 -0500523 // Add the VULKAN macro.
524 instance.getPreprocessorOpts().addMacroDef("VULKAN=100");
525
526 // Add the __OPENCL_VERSION__ macro.
527 instance.getPreprocessorOpts().addMacroDef("__OPENCL_VERSION__=120");
528
529 instance.setTarget(clang::TargetInfo::CreateTargetInfo(
530 instance.getDiagnostics(),
531 std::make_shared<clang::TargetOptions>(instance.getTargetOpts())));
532
533 instance.createFileManager();
534 instance.createSourceManager(instance.getFileManager());
535
536#ifdef _MSC_VER
537 std::string includePrefix("include\\");
538#else
539 std::string includePrefix("include/");
540#endif
541
542 auto entry = instance.getFileManager().getVirtualFile(
543 includePrefix + "openclc.h", openCLBuiltinMemoryBuffer->getBufferSize(),
544 0);
545
546 instance.getSourceManager().overrideFileContents(
547 entry, std::move(openCLBuiltinMemoryBuffer));
548
alan-bakerf3bce4a2019-06-28 16:01:15 -0400549 auto base_entry = instance.getFileManager().getVirtualFile(
550 includePrefix + "opencl-c-base.h",
551 openCLBaseBuiltinMemoryBuffer->getBufferSize(), 0);
552
553 instance.getSourceManager().overrideFileContents(
554 base_entry, std::move(openCLBaseBuiltinMemoryBuffer));
555
alan-bakerfec0a472018-11-08 18:09:40 -0500556 return 0;
557}
558
alan-bakerf5e5f692018-11-27 08:33:24 -0500559// Populates |pm| with necessary passes to optimize and legalize the IR.
560int PopulatePassManager(
561 llvm::legacy::PassManager *pm, llvm::raw_svector_ostream *binaryStream,
562 std::vector<clspv::version0::DescriptorMapEntry> *descriptor_map_entries,
563 llvm::SmallVectorImpl<std::pair<unsigned, std::string>>
564 *SamplerMapEntries) {
alan-bakerfec0a472018-11-08 18:09:40 -0500565 llvm::PassManagerBuilder pmBuilder;
566
567 switch (OptimizationLevel) {
568 case '0':
alan-bakerf5e5f692018-11-27 08:33:24 -0500569 case '1':
570 case '2':
571 case '3':
572 case 's':
573 case 'z':
574 break;
575 default:
576 llvm::errs() << "Unknown optimization level -O" << OptimizationLevel
577 << " specified!\n";
578 return -1;
579 }
580
581 switch (OptimizationLevel) {
582 case '0':
alan-bakerfec0a472018-11-08 18:09:40 -0500583 pmBuilder.OptLevel = 0;
584 break;
585 case '1':
586 pmBuilder.OptLevel = 1;
587 break;
588 case '2':
589 pmBuilder.OptLevel = 2;
590 break;
591 case '3':
592 pmBuilder.OptLevel = 3;
593 break;
594 case 's':
595 pmBuilder.SizeLevel = 1;
596 break;
597 case 'z':
598 pmBuilder.SizeLevel = 2;
599 break;
600 default:
601 break;
602 }
603
604 pm->add(clspv::createZeroInitializeAllocasPass());
alan-baker04f3a952020-03-24 10:39:53 -0400605 pm->add(clspv::createAddFunctionAttributesPass());
Kévin Petitbbbda972020-03-03 19:16:31 +0000606 pm->add(clspv::createDeclarePushConstantsPass());
alan-bakerfec0a472018-11-08 18:09:40 -0500607 pm->add(clspv::createDefineOpenCLWorkItemBuiltinsPass());
608
609 if (0 < pmBuilder.OptLevel) {
610 pm->add(clspv::createOpenCLInlinerPass());
611 }
612
613 pm->add(clspv::createUndoByvalPass());
614 pm->add(clspv::createUndoSRetPass());
alan-baker9b0ec3c2020-04-06 14:45:34 -0400615 if (clspv::Option::ClusterPodKernelArgs()) {
alan-bakerfec0a472018-11-08 18:09:40 -0500616 pm->add(clspv::createClusterPodKernelArgumentsPass());
617 }
618 pm->add(clspv::createReplaceOpenCLBuiltinPass());
619
620 // We need to run mem2reg and inst combine early because our
621 // createInlineFuncWithPointerBitCastArgPass pass cannot handle the pattern
622 // %1 = alloca i32 1
623 // store <something> %1
624 // %2 = bitcast float* %1
625 // %3 = load float %2
626 pm->add(llvm::createPromoteMemoryToRegisterPass());
627
alan-baker1b13e8f2019-08-08 17:56:51 -0400628 // Try to deal with pointer bitcasts early. This can prevent problems like
629 // issue #409 where LLVM is looser about access chain addressing than SPIR-V.
630 // This needs to happen before instcombine and after replacing OpenCL
631 // builtins. This run of the pass will not handle all pointer bitcasts that
632 // could be handled. It should be run again after other optimizations (e.g
633 // InlineFuncWithPointerBitCastArgPass).
634 pm->add(clspv::createSimplifyPointerBitcastPass());
635 pm->add(clspv::createReplacePointerBitcastPass());
636 pm->add(llvm::createDeadCodeEliminationPass());
637
alan-bakerfec0a472018-11-08 18:09:40 -0500638 // Hide loads from __constant address space away from instcombine.
639 // This prevents us from generating select between pointers-to-__constant.
640 // See https://github.com/google/clspv/issues/71
641 pm->add(clspv::createHideConstantLoadsPass());
642
643 pm->add(llvm::createInstructionCombiningPass());
644
645 if (clspv::Option::InlineEntryPoints()) {
646 pm->add(clspv::createInlineEntryPointsPass());
647 } else {
648 pm->add(clspv::createInlineFuncWithPointerBitCastArgPass());
649 pm->add(clspv::createInlineFuncWithPointerToFunctionArgPass());
650 pm->add(clspv::createInlineFuncWithSingleCallSitePass());
651 }
652
Kévin Petitf0515712020-01-07 18:29:20 +0000653 if (clspv::Option::LanguageUsesGenericAddressSpace()) {
Kévin Petit38c52482019-05-07 20:28:00 +0800654 pm->add(llvm::createInferAddressSpacesPass(clspv::AddressSpace::Generic));
Kévin Petit0fc88042019-04-09 23:25:02 +0100655 }
656
alan-bakerfec0a472018-11-08 18:09:40 -0500657 if (0 == pmBuilder.OptLevel) {
658 // Mem2Reg pass should be run early because O0 level optimization leaves
659 // redundant alloca, load and store instructions from function arguments.
660 // clspv needs to remove them ahead of transformation.
661 pm->add(llvm::createPromoteMemoryToRegisterPass());
662
663 // SROA pass is run because it will fold structs/unions that are problematic
664 // on Vulkan SPIR-V away.
665 pm->add(llvm::createSROAPass());
666
667 // InstructionCombining pass folds bitcast and gep instructions which are
668 // not supported by Vulkan SPIR-V.
669 pm->add(llvm::createInstructionCombiningPass());
670 }
671
672 // Now we add any of the LLVM optimizations we wanted
673 pmBuilder.populateModulePassManager(*pm);
674
alan-bakerb5e74d62020-04-07 20:38:05 -0400675 // No point attempting to handle freeze currently so strip them from the IR.
676 pm->add(clspv::createStripFreezePass());
677
alan-bakerfec0a472018-11-08 18:09:40 -0500678 // Unhide loads from __constant address space. Undoes the action of
679 // HideConstantLoadsPass.
680 pm->add(clspv::createUnhideConstantLoadsPass());
681
alan-baker13568382020-04-02 17:29:27 -0400682 pm->add(clspv::createUndoInstCombinePass());
alan-bakerfec0a472018-11-08 18:09:40 -0500683 pm->add(clspv::createFunctionInternalizerPass());
684 pm->add(clspv::createReplaceLLVMIntrinsicsPass());
685 pm->add(clspv::createUndoBoolPass());
686 pm->add(clspv::createUndoTruncatedSwitchConditionPass());
687 pm->add(llvm::createStructurizeCFGPass(false));
alan-baker3fa76d92018-11-12 14:54:40 -0500688 // Must be run after structurize cfg.
alan-baker9580aef2020-01-07 22:31:48 -0500689 pm->add(clspv::createFixupStructuredCFGPass());
690 // Must be run after structured cfg fixup.
alan-bakerfec0a472018-11-08 18:09:40 -0500691 pm->add(clspv::createReorderBasicBlocksPass());
692 pm->add(clspv::createUndoGetElementPtrConstantExprPass());
693 pm->add(clspv::createSplatArgPass());
694 pm->add(clspv::createSimplifyPointerBitcastPass());
695 pm->add(clspv::createReplacePointerBitcastPass());
696
697 pm->add(clspv::createUndoTranslateSamplerFoldPass());
698
699 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
700 pm->add(clspv::createClusterModuleScopeConstantVars());
701 }
702
703 pm->add(clspv::createShareModuleScopeVariablesPass());
alan-bakerf67468c2019-11-25 15:51:49 -0500704 // Specialize images before assigning descriptors to disambiguate the various
705 // types.
706 pm->add(clspv::createSpecializeImageTypesPass());
alan-bakere9308012019-03-15 10:25:13 -0400707 // This should be run after LLVM and OpenCL intrinsics are replaced.
alan-bakerfec0a472018-11-08 18:09:40 -0500708 pm->add(clspv::createAllocateDescriptorsPass(*SamplerMapEntries));
709 pm->add(llvm::createVerifierPass());
710 pm->add(clspv::createDirectResourceAccessPass());
711 // Replacing pointer bitcasts can leave some trivial GEPs
712 // that are easy to remove. Also replace GEPs of GEPS
713 // left by replacing indirect buffer accesses.
714 pm->add(clspv::createSimplifyPointerBitcastPass());
alan-baker4217b322019-03-06 08:56:12 -0500715 // Run after DRA to clean up parameters and help reduce the need for variable
716 // pointers.
717 pm->add(clspv::createRemoveUnusedArgumentsPass());
alan-bakerfec0a472018-11-08 18:09:40 -0500718
719 pm->add(clspv::createSplatSelectConditionPass());
720 pm->add(clspv::createSignedCompareFixupPass());
721 // This pass generates insertions that need to be rewritten.
722 pm->add(clspv::createScalarizePass());
723 pm->add(clspv::createRewriteInsertsPass());
alan-bakera71f1932019-04-11 11:04:34 -0400724 // UBO Transformations
725 if (clspv::Option::ConstantArgsInUniformBuffer() &&
726 !clspv::Option::InlineEntryPoints()) {
727 // MultiVersionUBOFunctionsPass will examine non-kernel functions with UBO
728 // arguments and either multi-version them as necessary or inline them if
729 // multi-versioning cannot be accomplished.
730 pm->add(clspv::createMultiVersionUBOFunctionsPass());
731 // Cleanup passes.
732 // Specialization can blindly generate GEP chains that are easily cleaned up
733 // by SimplifyPointerBitcastPass.
734 pm->add(clspv::createSimplifyPointerBitcastPass());
735 // RemoveUnusedArgumentsPass removes the actual UBO arguments that were
736 // problematic to begin with now that they have no uses.
737 pm->add(clspv::createRemoveUnusedArgumentsPass());
738 // DCE cleans up callers of the specialized functions.
739 pm->add(llvm::createDeadCodeEliminationPass());
740 }
alan-bakerfec0a472018-11-08 18:09:40 -0500741 // This pass mucks with types to point where you shouldn't rely on DataLayout
742 // anymore so leave this right before SPIR-V generation.
743 pm->add(clspv::createUBOTypeTransformPass());
alan-baker00e7a582019-06-07 12:54:21 -0400744 pm->add(clspv::createSPIRVProducerPass(*binaryStream, descriptor_map_entries,
745 *SamplerMapEntries,
746 OutputFormat == "c"));
alan-bakerf5e5f692018-11-27 08:33:24 -0500747
748 return 0;
alan-bakerfec0a472018-11-08 18:09:40 -0500749}
alan-bakerfec0a472018-11-08 18:09:40 -0500750
Kévin Petitd5db2d22019-04-04 13:55:14 +0100751int ParseOptions(const int argc, const char *const argv[]) {
alan-bakerfec0a472018-11-08 18:09:40 -0500752 // We need to change how one of the called passes works by spoofing
753 // ParseCommandLineOptions with the specific option.
754 const int llvmArgc = 2;
755 const char *llvmArgv[llvmArgc] = {
alan-bakerf5e5f692018-11-27 08:33:24 -0500756 argv[0],
757 "-simplifycfg-sink-common=false",
alan-bakerfec0a472018-11-08 18:09:40 -0500758 };
759
Kévin Petitd5db2d22019-04-04 13:55:14 +0100760 llvm::cl::ResetAllOptionOccurrences();
alan-bakerfec0a472018-11-08 18:09:40 -0500761 llvm::cl::ParseCommandLineOptions(llvmArgc, llvmArgv);
alan-bakerfec0a472018-11-08 18:09:40 -0500762 llvm::cl::ParseCommandLineOptions(argc, argv);
763
Kévin Petitf0515712020-01-07 18:29:20 +0000764 if (clspv::Option::LanguageUsesGenericAddressSpace() &&
765 !clspv::Option::InlineEntryPoints()) {
766 llvm::errs() << "cannot compile languages that use the generic address "
767 "space (e.g. CLC++, CL2.0) without -inline-entry-points\n";
Kévin Petit0fc88042019-04-09 23:25:02 +0100768 return -1;
769 }
770
Kévin Petitbbbda972020-03-03 19:16:31 +0000771 if (clspv::Option::ScalarBlockLayout()) {
772 llvm::errs() << "scalar block layout support unimplemented\n";
773 return -1;
774 }
775
alan-baker9b0ec3c2020-04-06 14:45:34 -0400776 // Push constant option validation.
777 if (clspv::Option::PodArgsInPushConstants()) {
778 if (clspv::Option::PodArgsInUniformBuffer()) {
779 llvm::errs() << "POD arguments can only be in either uniform buffers or "
780 "push constants\n";
781 return -1;
782 }
783
784 if (!clspv::Option::ClusterPodKernelArgs()) {
785 llvm::errs()
786 << "POD arguments must be clustered to be passed as push constants\n";
787 return -1;
788 }
789
790 // Conservatively error if a module scope push constant could be used.
alan-bakerbed3a882020-04-21 14:42:41 -0400791 if (clspv::Option::GlobalOffset() ||
alan-baker9b0ec3c2020-04-06 14:45:34 -0400792 clspv::Option::Language() ==
793 clspv::Option::SourceLanguage::OpenCL_C_20 ||
794 clspv::Option::Language() ==
795 clspv::Option::SourceLanguage::OpenCL_CPP) {
796 llvm::errs() << "POD arguments as push constants are not compatible with "
797 "module scope push constants\n";
798 return -1;
799 }
800 }
801
Kévin Petitd5db2d22019-04-04 13:55:14 +0100802 return 0;
803}
Diego Novillo89500852019-04-15 08:45:10 -0400804
805int GenerateIRFile(llvm::legacy::PassManager *pm, llvm::Module &module,
806 std::string output) {
807 std::error_code ec;
808 std::unique_ptr<llvm::ToolOutputFile> out(
809 new llvm::ToolOutputFile(output, ec, llvm::sys::fs::F_None));
810 if (ec) {
811 llvm::errs() << output << ": " << ec.message() << '\n';
812 return -1;
813 }
814 pm->add(llvm::createPrintModulePass(out->os(), "", false));
815 pm->run(module);
816 out->keep();
817 return 0;
818}
819
Kévin Petitd5db2d22019-04-04 13:55:14 +0100820} // namespace
821
822namespace clspv {
823int Compile(const int argc, const char *const argv[]) {
824
825 if (auto error = ParseOptions(argc, argv))
826 return error;
827
alan-bakerfec0a472018-11-08 18:09:40 -0500828 llvm::SmallVector<std::pair<unsigned, std::string>, 8> SamplerMapEntries;
alan-bakerf5e5f692018-11-27 08:33:24 -0500829 if (auto error = ParseSamplerMap("", &SamplerMapEntries))
alan-bakerfec0a472018-11-08 18:09:40 -0500830 return error;
831
832 // if no output file was provided, use a default
833 llvm::StringRef overiddenInputFilename = InputFilename.getValue();
834
835 // If we are reading our input file from stdin.
836 if ("-" == InputFilename) {
837 // We need to overwrite the file name we use.
Kévin Petitddad8f42019-09-30 15:12:08 +0100838 switch (InputLanguage) {
839 case clang::Language::OpenCL:
840 overiddenInputFilename = "stdin.cl";
841 break;
842 case clang::Language::LLVM_IR:
843 overiddenInputFilename = "stdin.ll";
844 break;
alan-baker31298a62019-10-07 13:24:30 -0400845 default:
846 // Default to fix compiler warnings/errors. Option parsing will reject a
847 // bad enum value for the option so there is no need for a message.
848 return -1;
Kévin Petitddad8f42019-09-30 15:12:08 +0100849 }
alan-bakerfec0a472018-11-08 18:09:40 -0500850 }
851
852 clang::CompilerInstance instance;
Kévin Petitddad8f42019-09-30 15:12:08 +0100853 clang::FrontendInputFile kernelFile(overiddenInputFilename,
854 clang::InputKind(InputLanguage));
alan-bakerfec0a472018-11-08 18:09:40 -0500855 std::string log;
856 llvm::raw_string_ostream diagnosticsStream(log);
alan-bakerf5e5f692018-11-27 08:33:24 -0500857 if (auto error = SetCompilerInstanceOptions(
858 instance, overiddenInputFilename, kernelFile, "", &diagnosticsStream))
alan-bakerfec0a472018-11-08 18:09:40 -0500859 return error;
860
861 // Parse.
862 llvm::LLVMContext context;
863 clang::EmitLLVMOnlyAction action(&context);
864
865 // Prepare the action for processing kernelFile
866 const bool success = action.BeginSourceFile(instance, kernelFile);
867 if (!success) {
868 return -1;
869 }
870
alan-bakerf3bce4a2019-06-28 16:01:15 -0400871 auto result = action.Execute();
alan-bakerfec0a472018-11-08 18:09:40 -0500872 action.EndSourceFile();
873
874 clang::DiagnosticConsumer *const consumer =
875 instance.getDiagnostics().getClient();
876 consumer->finish();
877
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100878 auto num_warnings = consumer->getNumWarnings();
alan-bakerfec0a472018-11-08 18:09:40 -0500879 auto num_errors = consumer->getNumErrors();
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100880 if ((num_errors > 0) || (num_warnings > 0)) {
881 llvm::errs() << log;
882 }
alan-bakerf3bce4a2019-06-28 16:01:15 -0400883 if (result || num_errors > 0) {
alan-bakerfec0a472018-11-08 18:09:40 -0500884 return -1;
885 }
886
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100887 // Don't run the passes or produce any output in verify mode.
888 // Clang doesn't always produce a valid module.
889 if (verify) {
890 return 0;
891 }
892
alan-bakerfec0a472018-11-08 18:09:40 -0500893 llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry();
894 llvm::initializeCore(Registry);
895 llvm::initializeScalarOpts(Registry);
Diego Novillo1fcff722019-05-07 13:45:53 -0400896 llvm::initializeClspvPasses(Registry);
alan-bakerfec0a472018-11-08 18:09:40 -0500897
898 std::unique_ptr<llvm::Module> module(action.takeModule());
899
900 // Optimize.
901 // Create a memory buffer for temporarily writing the result.
902 SmallVector<char, 10000> binary;
903 llvm::raw_svector_ostream binaryStream(binary);
904 std::string descriptor_map;
alan-bakerfec0a472018-11-08 18:09:40 -0500905 llvm::legacy::PassManager pm;
alan-bakerf5e5f692018-11-27 08:33:24 -0500906 std::vector<version0::DescriptorMapEntry> descriptor_map_entries;
Diego Novillo89500852019-04-15 08:45:10 -0400907
908 // If --emit-ir was requested, emit the initial LLVM IR and stop compilation.
909 if (!IROutputFile.empty()) {
910 return GenerateIRFile(&pm, *module, IROutputFile);
911 }
912
913 // Otherwise, populate the pass manager and run the regular passes.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400914 if (auto error = PopulatePassManager(
915 &pm, &binaryStream, &descriptor_map_entries, &SamplerMapEntries))
alan-bakerf5e5f692018-11-27 08:33:24 -0500916 return error;
alan-bakerfec0a472018-11-08 18:09:40 -0500917 pm.run(*module);
918
919 // Write outputs
920
921 // Write the descriptor map, if requested.
922 std::error_code error;
923 if (!DescriptorMapFilename.empty()) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400924 llvm::raw_fd_ostream descriptor_map_out_fd(
925 DescriptorMapFilename, error, llvm::sys::fs::CD_CreateAlways,
926 llvm::sys::fs::FA_Write, llvm::sys::fs::F_Text);
alan-bakerfec0a472018-11-08 18:09:40 -0500927 if (error) {
928 llvm::errs() << "Unable to open descriptor map file '"
929 << DescriptorMapFilename << "': " << error.message() << '\n';
930 return -1;
931 }
alan-bakerf5e5f692018-11-27 08:33:24 -0500932 std::string descriptor_map_string;
933 std::ostringstream str(descriptor_map_string);
934 for (const auto &entry : descriptor_map_entries) {
935 str << entry << "\n";
936 }
937 descriptor_map_out_fd << str.str();
alan-bakerfec0a472018-11-08 18:09:40 -0500938 descriptor_map_out_fd.close();
939 }
940
941 // Write the resulting binary.
942 // Wait until now to try writing the file so that we only write it on
943 // successful compilation.
944 if (OutputFilename.empty()) {
Kévin Petite4786902019-04-02 21:51:47 +0100945 if (OutputFormat == "c") {
alan-bakerfec0a472018-11-08 18:09:40 -0500946 OutputFilename = "a.spvinc";
947 } else {
948 OutputFilename = "a.spv";
949 }
950 }
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400951 llvm::raw_fd_ostream outStream(OutputFilename, error,
952 llvm::sys::fs::FA_Write);
alan-bakerfec0a472018-11-08 18:09:40 -0500953
954 if (error) {
955 llvm::errs() << "Unable to open output file '" << OutputFilename
956 << "': " << error.message() << '\n';
957 return -1;
958 }
959 outStream << binaryStream.str();
960
961 return 0;
962}
alan-bakerf5e5f692018-11-27 08:33:24 -0500963
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400964int CompileFromSourceString(
965 const std::string &program, const std::string &sampler_map,
966 const std::string &options, std::vector<uint32_t> *output_binary,
967 std::vector<clspv::version0::DescriptorMapEntry> *descriptor_map_entries) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500968
969 llvm::SmallVector<const char *, 20> argv;
970 llvm::BumpPtrAllocator A;
971 llvm::StringSaver Saver(A);
972 argv.push_back(Saver.save("clspv").data());
973 llvm::cl::TokenizeGNUCommandLine(options, Saver, argv);
974 int argc = static_cast<int>(argv.size());
Kévin Petitd5db2d22019-04-04 13:55:14 +0100975
976 if (auto error = ParseOptions(argc, &argv[0]))
977 return error;
alan-bakerf5e5f692018-11-27 08:33:24 -0500978
979 llvm::SmallVector<std::pair<unsigned, std::string>, 8> SamplerMapEntries;
980 if (auto error = ParseSamplerMap(sampler_map, &SamplerMapEntries))
981 return error;
982
983 InputFilename = "source.cl";
984 llvm::StringRef overiddenInputFilename = InputFilename.getValue();
985
986 clang::CompilerInstance instance;
alan-bakerd354f1a2019-08-06 15:41:55 -0400987 clang::FrontendInputFile kernelFile(
988 overiddenInputFilename, clang::InputKind(clang::Language::OpenCL));
alan-bakerf5e5f692018-11-27 08:33:24 -0500989 std::string log;
990 llvm::raw_string_ostream diagnosticsStream(log);
991 if (auto error =
992 SetCompilerInstanceOptions(instance, overiddenInputFilename,
993 kernelFile, program, &diagnosticsStream))
994 return error;
995
996 // Parse.
997 llvm::LLVMContext context;
998 clang::EmitLLVMOnlyAction action(&context);
999
1000 // Prepare the action for processing kernelFile
1001 const bool success = action.BeginSourceFile(instance, kernelFile);
1002 if (!success) {
1003 return -1;
1004 }
1005
alan-bakerf3bce4a2019-06-28 16:01:15 -04001006 auto result = action.Execute();
alan-bakerf5e5f692018-11-27 08:33:24 -05001007 action.EndSourceFile();
1008
1009 clang::DiagnosticConsumer *const consumer =
1010 instance.getDiagnostics().getClient();
1011 consumer->finish();
1012
1013 auto num_errors = consumer->getNumErrors();
alan-bakerf3bce4a2019-06-28 16:01:15 -04001014 if (result || num_errors > 0) {
alan-bakerf5e5f692018-11-27 08:33:24 -05001015 llvm::errs() << log << "\n";
1016 return -1;
1017 }
1018
alan-bakerf5e5f692018-11-27 08:33:24 -05001019 llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry();
1020 llvm::initializeCore(Registry);
1021 llvm::initializeScalarOpts(Registry);
Diego Novillo1fcff722019-05-07 13:45:53 -04001022 llvm::initializeClspvPasses(Registry);
alan-bakerf5e5f692018-11-27 08:33:24 -05001023
1024 std::unique_ptr<llvm::Module> module(action.takeModule());
1025
1026 // Optimize.
1027 // Create a memory buffer for temporarily writing the result.
1028 SmallVector<char, 10000> binary;
1029 llvm::raw_svector_ostream binaryStream(binary);
1030 std::string descriptor_map;
1031 llvm::legacy::PassManager pm;
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001032 if (auto error = PopulatePassManager(
1033 &pm, &binaryStream, descriptor_map_entries, &SamplerMapEntries))
alan-bakerf5e5f692018-11-27 08:33:24 -05001034 return error;
1035 pm.run(*module);
1036
1037 // Write outputs
1038
1039 // Write the descriptor map. This is required.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001040 assert(descriptor_map_entries &&
1041 "Valid descriptor map container is required.");
alan-bakerf5e5f692018-11-27 08:33:24 -05001042 if (!DescriptorMapFilename.empty()) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001043 llvm::errs() << "Warning: -descriptormap is ignored descriptor map "
1044 "container is provided.\n";
alan-bakerf5e5f692018-11-27 08:33:24 -05001045 }
1046
1047 // Write the resulting binary.
1048 // Wait until now to try writing the file so that we only write it on
1049 // successful compilation.
1050 assert(output_binary && "Valid binary container is required.");
1051 if (!OutputFilename.empty()) {
1052 llvm::outs()
1053 << "Warning: -o is ignored when binary container is provided.\n";
1054 }
1055 output_binary->resize(binary.size() / 4);
1056 memcpy(output_binary->data(), binary.data(), binary.size());
1057
1058 return 0;
1059}
alan-bakerfec0a472018-11-08 18:09:40 -05001060} // namespace clspv