blob: 592b6f9d6f01225fd4e85d0797bfe8bddf9acee0 [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"
alan-baker869cd682021-03-05 11:21:19 -050022#include "llvm/IR/GlobalValue.h"
alan-bakerfec0a472018-11-08 18:09:40 -050023#include "llvm/IR/LLVMContext.h"
24#include "llvm/IR/LegacyPassManager.h"
25#include "llvm/IR/Module.h"
26#include "llvm/IR/Verifier.h"
alan-baker869cd682021-03-05 11:21:19 -050027#include "llvm/IRReader/IRReader.h"
alan-baker0e64a592019-11-18 13:36:25 -050028#include "llvm/InitializePasses.h"
alan-bakerfec0a472018-11-08 18:09:40 -050029#include "llvm/LinkAllPasses.h"
alan-baker869cd682021-03-05 11:21:19 -050030#include "llvm/Linker/Linker.h"
alan-bakerf5e5f692018-11-27 08:33:24 -050031#include "llvm/Support/Allocator.h"
alan-bakerfec0a472018-11-08 18:09:40 -050032#include "llvm/Support/CommandLine.h"
alan-bakerf5e5f692018-11-27 08:33:24 -050033#include "llvm/Support/ErrorOr.h"
alan-bakerfec0a472018-11-08 18:09:40 -050034#include "llvm/Support/MathExtras.h"
alan-bakerf5e5f692018-11-27 08:33:24 -050035#include "llvm/Support/StringSaver.h"
Diego Novillo89500852019-04-15 08:45:10 -040036#include "llvm/Support/ToolOutputFile.h"
alan-bakerfec0a472018-11-08 18:09:40 -050037#include "llvm/Support/raw_ostream.h"
38#include "llvm/Transforms/IPO/PassManagerBuilder.h"
39
Kévin Petit38c52482019-05-07 20:28:00 +080040#include "clspv/AddressSpace.h"
alan-bakerfec0a472018-11-08 18:09:40 -050041#include "clspv/Option.h"
42#include "clspv/Passes.h"
alan-baker86ce19c2020-08-05 13:09:19 -040043#include "clspv/Sampler.h"
alan-baker869cd682021-03-05 11:21:19 -050044#include "clspv/clspv_builtin_library.h"
alan-bakerfec0a472018-11-08 18:09:40 -050045#include "clspv/opencl_builtins_header.h"
46
alan-baker869cd682021-03-05 11:21:19 -050047#include "Builtins.h"
alan-bakerfec0a472018-11-08 18:09:40 -050048#include "FrontendPlugin.h"
Diego Novilloa4c44fa2019-04-11 10:56:15 -040049#include "Passes.h"
alan-bakerfec0a472018-11-08 18:09:40 -050050
alan-bakerf5e5f692018-11-27 08:33:24 -050051#include <cassert>
alan-bakerfec0a472018-11-08 18:09:40 -050052#include <numeric>
alan-bakerf5e5f692018-11-27 08:33:24 -050053#include <sstream>
Diego Novillo3cc8d7a2019-04-10 13:30:34 -040054#include <string>
alan-bakerfec0a472018-11-08 18:09:40 -050055
56using namespace clang;
57
58namespace {
59// This registration must be located in the same file as the execution of the
60// action.
61static FrontendPluginRegistry::Add<clspv::ExtraValidationASTAction>
62 X("extra-validation",
63 "Perform extra validation on OpenCL C when targeting Vulkan");
64
65static llvm::cl::opt<bool> cl_single_precision_constants(
66 "cl-single-precision-constant", llvm::cl::init(false),
67 llvm::cl::desc("Treat double precision floating-point constant as single "
68 "precision constant."));
69
70static llvm::cl::opt<bool> cl_denorms_are_zero(
71 "cl-denorms-are-zero", llvm::cl::init(false),
72 llvm::cl::desc("If specified, denormalized floating point numbers may be "
73 "flushed to zero."));
74
75static llvm::cl::opt<bool> cl_fp32_correctly_rounded_divide_sqrt(
76 "cl-fp32-correctly-rounded-divide-sqrt", llvm::cl::init(false),
77 llvm::cl::desc("Single precision floating-point divide (x/y and 1/x) and "
78 "sqrt used are correctly rounded."));
79
80static llvm::cl::opt<bool>
81 cl_opt_disable("cl-opt-disable", llvm::cl::init(false),
82 llvm::cl::desc("This option disables all optimizations. The "
83 "default is optimizations are enabled."));
84
85static llvm::cl::opt<bool> cl_mad_enable(
86 "cl-mad-enable", llvm::cl::init(false),
87 llvm::cl::desc("Allow a * b + c to be replaced by a mad. The mad computes "
88 "a * b + c with reduced accuracy."));
89
90static llvm::cl::opt<bool> cl_no_signed_zeros(
91 "cl-no-signed-zeros", llvm::cl::init(false),
92 llvm::cl::desc("Allow optimizations for floating-point arithmetic that "
93 "ignore the signedness of zero."));
94
95static llvm::cl::opt<bool> cl_unsafe_math_optimizations(
96 "cl-unsafe-math-optimizations", llvm::cl::init(false),
97 llvm::cl::desc("Allow optimizations for floating-point arithmetic that (a) "
98 "assume that arguments and results are valid, (b) may "
99 "violate IEEE 754 standard and (c) may violate the OpenCL "
100 "numerical compliance requirements. This option includes "
101 "the -cl-no-signed-zeros and -cl-mad-enable options."));
102
103static llvm::cl::opt<bool> cl_finite_math_only(
104 "cl-finite-math-only", llvm::cl::init(false),
105 llvm::cl::desc("Allow optimizations for floating-point arithmetic that "
106 "assume that arguments and results are not NaNs or INFs."));
107
108static llvm::cl::opt<bool> cl_fast_relaxed_math(
109 "cl-fast-relaxed-math", llvm::cl::init(false),
110 llvm::cl::desc("This option causes the preprocessor macro "
111 "__FAST_RELAXED_MATH__ to be defined. Sets the optimization "
112 "options -cl-finite-math-only and "
113 "-cl-unsafe-math-optimizations."));
114
115static llvm::cl::list<std::string>
116 Includes(llvm::cl::Prefix, "I",
117 llvm::cl::desc("Add a directory to the list of directories "
118 "to be searched for header files."),
119 llvm::cl::ZeroOrMore, llvm::cl::value_desc("include path"));
120
121static llvm::cl::list<std::string>
122 Defines(llvm::cl::Prefix, "D",
123 llvm::cl::desc("Define a #define directive."), llvm::cl::ZeroOrMore,
124 llvm::cl::value_desc("define"));
125
126static llvm::cl::opt<std::string>
127 InputFilename(llvm::cl::Positional, llvm::cl::desc("<input .cl file>"),
128 llvm::cl::init("-"));
129
Kévin Petitddad8f42019-09-30 15:12:08 +0100130static llvm::cl::opt<clang::Language> InputLanguage(
131 "x", llvm::cl::desc("Select input type"),
132 llvm::cl::init(clang::Language::OpenCL),
133 llvm::cl::values(clEnumValN(clang::Language::OpenCL, "cl", "OpenCL source"),
134 clEnumValN(clang::Language::LLVM_IR, "ir", "LLVM IR")));
135
alan-bakerfec0a472018-11-08 18:09:40 -0500136static llvm::cl::opt<std::string>
137 OutputFilename("o", llvm::cl::desc("Override output filename"),
138 llvm::cl::value_desc("filename"));
139
alan-bakerfec0a472018-11-08 18:09:40 -0500140static 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-baker869cd682021-03-05 11:21:19 -0500172namespace {
173struct OpenCLBuiltinMemoryBuffer final : public llvm::MemoryBuffer {
174 OpenCLBuiltinMemoryBuffer(const void *data, uint64_t data_length) {
175 const char *dataCasted = reinterpret_cast<const char *>(data);
176 init(dataCasted, dataCasted + data_length, true);
177 }
178
179 virtual llvm::MemoryBuffer::BufferKind getBufferKind() const override {
180 return llvm::MemoryBuffer::MemoryBuffer_Malloc;
181 }
182
183 virtual ~OpenCLBuiltinMemoryBuffer() override {}
184};
185} // namespace
186
alan-bakerfec0a472018-11-08 18:09:40 -0500187// Populates |SamplerMapEntries| with data from the input sampler map. Returns 0
188// if successful.
alan-bakerf5e5f692018-11-27 08:33:24 -0500189int ParseSamplerMap(const std::string &sampler_map,
190 llvm::SmallVectorImpl<std::pair<unsigned, std::string>>
191 *SamplerMapEntries) {
192 std::unique_ptr<llvm::MemoryBuffer> samplerMapBuffer(nullptr);
193 if (!sampler_map.empty()) {
194 // Parse the sampler map from the provided string.
195 samplerMapBuffer = llvm::MemoryBuffer::getMemBuffer(sampler_map);
196
alan-baker09cb9802019-12-10 13:16:27 -0500197 clspv::Option::SetUseSamplerMap(true);
alan-bakerf5e5f692018-11-27 08:33:24 -0500198 if (!SamplerMap.empty()) {
199 llvm::outs() << "Warning: -samplermap is ignored when the sampler map is "
200 "provided through a string.\n";
201 }
202 } else if (!SamplerMap.empty()) {
203 // Parse the sampler map from the option provided file.
alan-bakerfec0a472018-11-08 18:09:40 -0500204 auto errorOrSamplerMapFile =
205 llvm::MemoryBuffer::getFile(SamplerMap.getValue());
206
207 // If there was an error in getting the sampler map file.
208 if (!errorOrSamplerMapFile) {
209 llvm::errs() << "Error: " << errorOrSamplerMapFile.getError().message()
210 << " '" << SamplerMap.getValue() << "'\n";
211 return -1;
212 }
213
alan-baker09cb9802019-12-10 13:16:27 -0500214 clspv::Option::SetUseSamplerMap(true);
alan-bakerf5e5f692018-11-27 08:33:24 -0500215 samplerMapBuffer = std::move(errorOrSamplerMapFile.get());
alan-bakerfec0a472018-11-08 18:09:40 -0500216 if (0 == samplerMapBuffer->getBufferSize()) {
217 llvm::errs() << "Error: Sampler map was an empty file!\n";
218 return -1;
219 }
alan-bakerf5e5f692018-11-27 08:33:24 -0500220 }
alan-bakerfec0a472018-11-08 18:09:40 -0500221
alan-baker09cb9802019-12-10 13:16:27 -0500222 if (clspv::Option::UseSamplerMap()) {
223 llvm::outs()
224 << "Warning: use of the sampler map is deprecated and unnecessary\n";
225 }
226
alan-bakerf5e5f692018-11-27 08:33:24 -0500227 // No sampler map to parse.
228 if (!samplerMapBuffer || 0 == samplerMapBuffer->getBufferSize())
229 return 0;
alan-bakerfec0a472018-11-08 18:09:40 -0500230
alan-bakerf5e5f692018-11-27 08:33:24 -0500231 llvm::SmallVector<llvm::StringRef, 3> samplerStrings;
alan-bakerfec0a472018-11-08 18:09:40 -0500232
alan-bakerf5e5f692018-11-27 08:33:24 -0500233 // We need to keep track of the beginning of the current entry.
234 const char *b = samplerMapBuffer->getBufferStart();
235 for (const char *i = b, *e = samplerMapBuffer->getBufferEnd();; i++) {
236 // If we have a separator between declarations.
237 if ((*i == '|') || (*i == ',') || (i == e)) {
238 if (i == b) {
239 llvm::errs() << "Error: Sampler map contained an empty entry!\n";
240 return -1;
alan-bakerfec0a472018-11-08 18:09:40 -0500241 }
242
alan-bakerf5e5f692018-11-27 08:33:24 -0500243 samplerStrings.push_back(llvm::StringRef(b, i - b).trim());
alan-bakerfec0a472018-11-08 18:09:40 -0500244
alan-bakerf5e5f692018-11-27 08:33:24 -0500245 // And set b the next character after i.
246 b = i + 1;
247 }
alan-bakerfec0a472018-11-08 18:09:40 -0500248
alan-bakerf5e5f692018-11-27 08:33:24 -0500249 // If we have a separator between declarations within a single sampler.
250 if ((*i == ',') || (i == e)) {
alan-bakerfec0a472018-11-08 18:09:40 -0500251
alan-baker86ce19c2020-08-05 13:09:19 -0400252 clspv::SamplerNormalizedCoords NormalizedCoord =
253 clspv::CLK_NORMALIZED_COORDS_NOT_SET;
254 clspv::SamplerAddressingMode AddressingMode = clspv::CLK_ADDRESS_NOT_SET;
255 clspv::SamplerFilterMode FilterMode = clspv::CLK_FILTER_NOT_SET;
alan-bakerf5e5f692018-11-27 08:33:24 -0500256
257 for (auto str : samplerStrings) {
258 if ("CLK_NORMALIZED_COORDS_FALSE" == str) {
alan-baker86ce19c2020-08-05 13:09:19 -0400259 if (clspv::CLK_NORMALIZED_COORDS_NOT_SET != NormalizedCoord) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500260 llvm::errs() << "Error: Sampler map normalized coordinates was "
261 "previously set!\n";
alan-bakerfec0a472018-11-08 18:09:40 -0500262 return -1;
263 }
alan-baker86ce19c2020-08-05 13:09:19 -0400264 NormalizedCoord = clspv::CLK_NORMALIZED_COORDS_FALSE;
alan-bakerf5e5f692018-11-27 08:33:24 -0500265 } else if ("CLK_NORMALIZED_COORDS_TRUE" == str) {
alan-baker86ce19c2020-08-05 13:09:19 -0400266 if (clspv::CLK_NORMALIZED_COORDS_NOT_SET != NormalizedCoord) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500267 llvm::errs() << "Error: Sampler map normalized coordinates was "
268 "previously set!\n";
269 return -1;
270 }
alan-baker86ce19c2020-08-05 13:09:19 -0400271 NormalizedCoord = clspv::CLK_NORMALIZED_COORDS_TRUE;
alan-bakerf5e5f692018-11-27 08:33:24 -0500272 } else if ("CLK_ADDRESS_NONE" == str) {
alan-baker86ce19c2020-08-05 13:09:19 -0400273 if (clspv::CLK_ADDRESS_NOT_SET != AddressingMode) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500274 llvm::errs()
275 << "Error: Sampler map addressing mode was previously set!\n";
276 return -1;
277 }
alan-baker86ce19c2020-08-05 13:09:19 -0400278 AddressingMode = clspv::CLK_ADDRESS_NONE;
alan-bakerf5e5f692018-11-27 08:33:24 -0500279 } else if ("CLK_ADDRESS_CLAMP_TO_EDGE" == str) {
alan-baker86ce19c2020-08-05 13:09:19 -0400280 if (clspv::CLK_ADDRESS_NOT_SET != AddressingMode) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500281 llvm::errs()
282 << "Error: Sampler map addressing mode was previously set!\n";
283 return -1;
284 }
alan-baker86ce19c2020-08-05 13:09:19 -0400285 AddressingMode = clspv::CLK_ADDRESS_CLAMP_TO_EDGE;
alan-bakerf5e5f692018-11-27 08:33:24 -0500286 } else if ("CLK_ADDRESS_CLAMP" == str) {
alan-baker86ce19c2020-08-05 13:09:19 -0400287 if (clspv::CLK_ADDRESS_NOT_SET != AddressingMode) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500288 llvm::errs()
289 << "Error: Sampler map addressing mode was previously set!\n";
290 return -1;
291 }
alan-baker86ce19c2020-08-05 13:09:19 -0400292 AddressingMode = clspv::CLK_ADDRESS_CLAMP;
alan-bakerf5e5f692018-11-27 08:33:24 -0500293 } else if ("CLK_ADDRESS_MIRRORED_REPEAT" == str) {
alan-baker86ce19c2020-08-05 13:09:19 -0400294 if (clspv::CLK_ADDRESS_NOT_SET != AddressingMode) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500295 llvm::errs()
296 << "Error: Sampler map addressing mode was previously set!\n";
297 return -1;
298 }
alan-baker86ce19c2020-08-05 13:09:19 -0400299 AddressingMode = clspv::CLK_ADDRESS_MIRRORED_REPEAT;
alan-bakerf5e5f692018-11-27 08:33:24 -0500300 } else if ("CLK_ADDRESS_REPEAT" == str) {
alan-baker86ce19c2020-08-05 13:09:19 -0400301 if (clspv::CLK_ADDRESS_NOT_SET != AddressingMode) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500302 llvm::errs()
303 << "Error: Sampler map addressing mode was previously set!\n";
304 return -1;
305 }
alan-baker86ce19c2020-08-05 13:09:19 -0400306 AddressingMode = clspv::CLK_ADDRESS_REPEAT;
alan-bakerf5e5f692018-11-27 08:33:24 -0500307 } else if ("CLK_FILTER_NEAREST" == str) {
alan-baker86ce19c2020-08-05 13:09:19 -0400308 if (clspv::CLK_FILTER_NOT_SET != FilterMode) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500309 llvm::errs()
310 << "Error: Sampler map filtering mode was previously set!\n";
311 return -1;
312 }
alan-baker86ce19c2020-08-05 13:09:19 -0400313 FilterMode = clspv::CLK_FILTER_NEAREST;
alan-bakerf5e5f692018-11-27 08:33:24 -0500314 } else if ("CLK_FILTER_LINEAR" == str) {
alan-baker86ce19c2020-08-05 13:09:19 -0400315 if (clspv::CLK_FILTER_NOT_SET != FilterMode) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500316 llvm::errs()
317 << "Error: Sampler map filtering mode was previously set!\n";
318 return -1;
319 }
alan-baker86ce19c2020-08-05 13:09:19 -0400320 FilterMode = clspv::CLK_FILTER_LINEAR;
alan-bakerf5e5f692018-11-27 08:33:24 -0500321 } else {
322 llvm::errs() << "Error: Unknown sampler string '" << str
323 << "' found!\n";
alan-bakerfec0a472018-11-08 18:09:40 -0500324 return -1;
325 }
alan-bakerfec0a472018-11-08 18:09:40 -0500326 }
327
alan-baker86ce19c2020-08-05 13:09:19 -0400328 if (clspv::CLK_NORMALIZED_COORDS_NOT_SET == NormalizedCoord) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500329 llvm::errs() << "Error: Sampler map entry did not contain normalized "
330 "coordinates entry!\n";
331 return -1;
alan-bakerfec0a472018-11-08 18:09:40 -0500332 }
alan-bakerf5e5f692018-11-27 08:33:24 -0500333
alan-baker86ce19c2020-08-05 13:09:19 -0400334 if (clspv::CLK_ADDRESS_NOT_SET == AddressingMode) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500335 llvm::errs() << "Error: Sampler map entry did not contain addressing "
336 "mode entry!\n";
337 return -1;
338 }
339
alan-baker86ce19c2020-08-05 13:09:19 -0400340 if (clspv::CLK_FILTER_NOT_SET == FilterMode) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500341 llvm::errs()
342 << "Error: Sampler map entry did not contain filer mode entry!\n";
343 return -1;
344 }
345
346 // Generate an equivalent expression in string form. Sort the
347 // strings to get a canonical ordering.
348 std::sort(samplerStrings.begin(), samplerStrings.end(),
349 std::less<StringRef>());
350 const auto samplerExpr = std::accumulate(
351 samplerStrings.begin(), samplerStrings.end(), std::string(),
alan-baker21574d32020-01-29 16:00:31 -0500352 [](llvm::StringRef left, llvm::StringRef right) {
353 return left.str() + std::string(left.empty() ? "" : "|") +
354 right.str();
alan-bakerf5e5f692018-11-27 08:33:24 -0500355 });
356
357 // SamplerMapEntries->push_back(std::make_pair(
358 // NormalizedCoord | AddressingMode | FilterMode, samplerExpr));
359 SamplerMapEntries->emplace_back(
360 NormalizedCoord | AddressingMode | FilterMode, samplerExpr);
361
362 // And reset the sampler strings for the next sampler in the map.
363 samplerStrings.clear();
364 }
365
366 // And lastly, if we are at the end of the file
367 if (i == e) {
368 break;
alan-bakerfec0a472018-11-08 18:09:40 -0500369 }
370 }
371
372 return 0;
373}
374
375// Sets |instance|'s options for compiling. Returns 0 if successful.
376int SetCompilerInstanceOptions(CompilerInstance &instance,
377 const llvm::StringRef &overiddenInputFilename,
378 const clang::FrontendInputFile &kernelFile,
alan-bakerf5e5f692018-11-27 08:33:24 -0500379 const std::string &program,
alan-bakerfec0a472018-11-08 18:09:40 -0500380 llvm::raw_string_ostream *diagnosticsStream) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500381 std::unique_ptr<llvm::MemoryBuffer> memory_buffer(nullptr);
382 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> errorOrInputFile(nullptr);
383 if (program.empty()) {
384 auto errorOrInputFile =
385 llvm::MemoryBuffer::getFileOrSTDIN(InputFilename.getValue());
alan-bakerfec0a472018-11-08 18:09:40 -0500386
alan-bakerf5e5f692018-11-27 08:33:24 -0500387 // If there was an error in getting the input file.
388 if (!errorOrInputFile) {
389 llvm::errs() << "Error: " << errorOrInputFile.getError().message() << " '"
390 << InputFilename.getValue() << "'\n";
391 return -1;
392 }
393 memory_buffer.reset(errorOrInputFile.get().release());
394 } else {
395 memory_buffer = llvm::MemoryBuffer::getMemBuffer(program.c_str(),
396 overiddenInputFilename);
alan-bakerfec0a472018-11-08 18:09:40 -0500397 }
alan-bakerf5e5f692018-11-27 08:33:24 -0500398
alan-bakerfec0a472018-11-08 18:09:40 -0500399 if (verify) {
400 instance.getDiagnosticOpts().VerifyDiagnostics = true;
alan-bakerbccf62c2019-03-29 10:32:41 -0400401 instance.getDiagnosticOpts().VerifyPrefixes.push_back("expected");
alan-bakerfec0a472018-11-08 18:09:40 -0500402 }
403
Kévin Petit0fc88042019-04-09 23:25:02 +0100404 clang::LangStandard::Kind standard;
Kévin Petitf0515712020-01-07 18:29:20 +0000405 switch (clspv::Option::Language()) {
406 case clspv::Option::SourceLanguage::OpenCL_C_10:
407 standard = clang::LangStandard::lang_opencl10;
408 break;
409 case clspv::Option::SourceLanguage::OpenCL_C_11:
410 standard = clang::LangStandard::lang_opencl11;
411 break;
412 case clspv::Option::SourceLanguage::OpenCL_C_12:
Kévin Petit0fc88042019-04-09 23:25:02 +0100413 standard = clang::LangStandard::lang_opencl12;
Kévin Petitf0515712020-01-07 18:29:20 +0000414 break;
415 case clspv::Option::SourceLanguage::OpenCL_C_20:
416 standard = clang::LangStandard::lang_opencl20;
417 break;
Kévin Petit77838ff2020-10-19 18:54:51 +0100418 case clspv::Option::SourceLanguage::OpenCL_C_30:
419 standard = clang::LangStandard::lang_opencl30;
alan-bakera1001772021-02-08 16:42:33 -0500420 // TODO: See #705, find a better solution for this.
421 instance.getPreprocessorOpts().addMacroUndef("cl_khr_3d_image_writes");
Kévin Petit77838ff2020-10-19 18:54:51 +0100422 break;
Kévin Petitf0515712020-01-07 18:29:20 +0000423 case clspv::Option::SourceLanguage::OpenCL_CPP:
424 standard = clang::LangStandard::lang_openclcpp;
425 break;
426 default:
427 llvm_unreachable("Unknown source language");
Kévin Petit0fc88042019-04-09 23:25:02 +0100428 }
alan-bakerfec0a472018-11-08 18:09:40 -0500429
alan-bakerfec0a472018-11-08 18:09:40 -0500430 instance.getLangOpts().C99 = true;
431 instance.getLangOpts().RTTI = false;
432 instance.getLangOpts().RTTIData = false;
433 instance.getLangOpts().MathErrno = false;
434 instance.getLangOpts().Optimize = false;
435 instance.getLangOpts().NoBuiltin = true;
436 instance.getLangOpts().ModulesSearchAll = false;
437 instance.getLangOpts().SinglePrecisionConstants = true;
438 instance.getCodeGenOpts().StackRealignment = true;
439 instance.getCodeGenOpts().SimplifyLibCalls = false;
440 instance.getCodeGenOpts().EmitOpenCLArgMetadata = false;
441 instance.getCodeGenOpts().DisableO0ImplyOptNone = true;
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100442 instance.getDiagnosticOpts().IgnoreWarnings = IgnoreWarnings;
alan-bakerfec0a472018-11-08 18:09:40 -0500443
444 instance.getLangOpts().SinglePrecisionConstants =
445 cl_single_precision_constants;
446 // cl_denorms_are_zero ignored for now!
447 // cl_fp32_correctly_rounded_divide_sqrt ignored for now!
448 instance.getCodeGenOpts().LessPreciseFPMAD =
449 cl_mad_enable || cl_unsafe_math_optimizations;
450 // cl_no_signed_zeros ignored for now!
alan-baker869cd682021-03-05 11:21:19 -0500451 instance.getLangOpts().UnsafeFPMath = cl_unsafe_math_optimizations ||
452 cl_fast_relaxed_math ||
453 clspv::Option::NativeMath();
454 instance.getLangOpts().FiniteMathOnly = cl_finite_math_only ||
455 cl_fast_relaxed_math ||
456 clspv::Option::NativeMath();
457 instance.getLangOpts().FastRelaxedMath =
458 cl_fast_relaxed_math || clspv::Option::NativeMath();
alan-bakerfec0a472018-11-08 18:09:40 -0500459
460 // Preprocessor options
Kévin Petita624c0c2019-05-07 20:27:43 +0800461 if (!clspv::Option::ImageSupport()) {
462 instance.getPreprocessorOpts().addMacroUndef("__IMAGE_SUPPORT__");
463 }
alan-baker869cd682021-03-05 11:21:19 -0500464 if (cl_fast_relaxed_math || clspv::Option::NativeMath()) {
alan-bakerfec0a472018-11-08 18:09:40 -0500465 instance.getPreprocessorOpts().addMacroDef("__FAST_RELAXED_MATH__");
466 }
467
468 for (auto define : Defines) {
469 instance.getPreprocessorOpts().addMacroDef(define);
470 }
471
472 // Header search options
473 for (auto include : Includes) {
474 instance.getHeaderSearchOpts().AddPath(include, clang::frontend::After,
475 false, false);
476 }
477
478 // We always compile on opt 0 so we preserve as much debug information about
479 // the source as possible. We'll run optimization later, once we've had a
480 // chance to view the unoptimal code first
481 instance.getCodeGenOpts().OptimizationLevel = 0;
482
483// Debug information is disabled temporarily to call instruction.
484#if 0
485 instance.getCodeGenOpts().setDebugInfo(clang::codegenoptions::FullDebugInfo);
486#endif
487
488 // We use the 32-bit pointer-width SPIR triple
489 llvm::Triple triple("spir-unknown-unknown");
490
James Price40efe7f2021-01-18 09:19:31 -0500491 // We manually include the OpenCL headers below, so this vector is unused.
492 std::vector<std::string> includes;
493
alan-bakerfec0a472018-11-08 18:09:40 -0500494 instance.getInvocation().setLangDefaults(
alan-bakerd354f1a2019-08-06 15:41:55 -0400495 instance.getLangOpts(), clang::InputKind(clang::Language::OpenCL), triple,
James Price40efe7f2021-01-18 09:19:31 -0500496 includes, standard);
alan-bakerfec0a472018-11-08 18:09:40 -0500497
498 // Override the C99 inline semantics to accommodate for more OpenCL C
499 // programs in the wild.
500 instance.getLangOpts().GNUInline = true;
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100501
502 // Set up diagnostics
alan-bakerfec0a472018-11-08 18:09:40 -0500503 instance.createDiagnostics(
504 new clang::TextDiagnosticPrinter(*diagnosticsStream,
505 &instance.getDiagnosticOpts()),
506 true);
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100507 instance.getDiagnostics().setWarningsAsErrors(WarningsAsErrors);
508 instance.getDiagnostics().setEnableAllWarnings(true);
alan-bakerfec0a472018-11-08 18:09:40 -0500509
510 instance.getTargetOpts().Triple = triple.str();
511
alan-baker21574d32020-01-29 16:00:31 -0500512 instance.getCodeGenOpts().MainFileName = overiddenInputFilename.str();
alan-bakerfec0a472018-11-08 18:09:40 -0500513 instance.getCodeGenOpts().PreserveVec3Type = true;
514 // Disable generation of lifetime intrinsic.
515 instance.getCodeGenOpts().DisableLifetimeMarkers = true;
516 instance.getFrontendOpts().Inputs.push_back(kernelFile);
alan-bakerf5e5f692018-11-27 08:33:24 -0500517 instance.getPreprocessorOpts().addRemappedFile(overiddenInputFilename,
518 memory_buffer.release());
alan-bakerfec0a472018-11-08 18:09:40 -0500519
alan-bakerfec0a472018-11-08 18:09:40 -0500520 std::unique_ptr<llvm::MemoryBuffer> openCLBuiltinMemoryBuffer(
521 new OpenCLBuiltinMemoryBuffer(opencl_builtins_header_data,
522 opencl_builtins_header_size - 1));
523
James Price40efe7f2021-01-18 09:19:31 -0500524 instance.getPreprocessorOpts().Includes.push_back("opencl-c.h");
alan-bakerfec0a472018-11-08 18:09:40 -0500525
alan-bakerf3bce4a2019-06-28 16:01:15 -0400526 std::unique_ptr<llvm::MemoryBuffer> openCLBaseBuiltinMemoryBuffer(
527 new OpenCLBuiltinMemoryBuffer(opencl_base_builtins_header_data,
528 opencl_base_builtins_header_size - 1));
529
530 instance.getPreprocessorOpts().Includes.push_back("opencl-c-base.h");
531
alan-bakerfec0a472018-11-08 18:09:40 -0500532 // Add the VULKAN macro.
533 instance.getPreprocessorOpts().addMacroDef("VULKAN=100");
534
535 // Add the __OPENCL_VERSION__ macro.
536 instance.getPreprocessorOpts().addMacroDef("__OPENCL_VERSION__=120");
537
538 instance.setTarget(clang::TargetInfo::CreateTargetInfo(
539 instance.getDiagnostics(),
540 std::make_shared<clang::TargetOptions>(instance.getTargetOpts())));
541
542 instance.createFileManager();
543 instance.createSourceManager(instance.getFileManager());
544
545#ifdef _MSC_VER
546 std::string includePrefix("include\\");
547#else
548 std::string includePrefix("include/");
549#endif
550
551 auto entry = instance.getFileManager().getVirtualFile(
James Price40efe7f2021-01-18 09:19:31 -0500552 includePrefix + "opencl-c.h", openCLBuiltinMemoryBuffer->getBufferSize(),
alan-bakerfec0a472018-11-08 18:09:40 -0500553 0);
554
555 instance.getSourceManager().overrideFileContents(
556 entry, std::move(openCLBuiltinMemoryBuffer));
557
alan-bakerf3bce4a2019-06-28 16:01:15 -0400558 auto base_entry = instance.getFileManager().getVirtualFile(
559 includePrefix + "opencl-c-base.h",
560 openCLBaseBuiltinMemoryBuffer->getBufferSize(), 0);
561
562 instance.getSourceManager().overrideFileContents(
563 base_entry, std::move(openCLBaseBuiltinMemoryBuffer));
564
alan-bakerfec0a472018-11-08 18:09:40 -0500565 return 0;
566}
567
alan-bakerf5e5f692018-11-27 08:33:24 -0500568// Populates |pm| with necessary passes to optimize and legalize the IR.
569int PopulatePassManager(
570 llvm::legacy::PassManager *pm, llvm::raw_svector_ostream *binaryStream,
alan-bakerf5e5f692018-11-27 08:33:24 -0500571 llvm::SmallVectorImpl<std::pair<unsigned, std::string>>
572 *SamplerMapEntries) {
alan-bakerfec0a472018-11-08 18:09:40 -0500573 llvm::PassManagerBuilder pmBuilder;
574
575 switch (OptimizationLevel) {
576 case '0':
alan-bakerf5e5f692018-11-27 08:33:24 -0500577 case '1':
578 case '2':
579 case '3':
580 case 's':
581 case 'z':
582 break;
583 default:
584 llvm::errs() << "Unknown optimization level -O" << OptimizationLevel
585 << " specified!\n";
586 return -1;
587 }
588
589 switch (OptimizationLevel) {
590 case '0':
alan-bakerfec0a472018-11-08 18:09:40 -0500591 pmBuilder.OptLevel = 0;
592 break;
593 case '1':
594 pmBuilder.OptLevel = 1;
595 break;
596 case '2':
597 pmBuilder.OptLevel = 2;
598 break;
599 case '3':
600 pmBuilder.OptLevel = 3;
601 break;
602 case 's':
603 pmBuilder.SizeLevel = 1;
604 break;
605 case 'z':
606 pmBuilder.SizeLevel = 2;
607 break;
608 default:
609 break;
610 }
611
alan-baker869cd682021-03-05 11:21:19 -0500612 pm->add(clspv::createNativeMathPass());
alan-bakerfec0a472018-11-08 18:09:40 -0500613 pm->add(clspv::createZeroInitializeAllocasPass());
alan-baker04f3a952020-03-24 10:39:53 -0400614 pm->add(clspv::createAddFunctionAttributesPass());
alan-bakerc4579bb2020-04-29 14:15:50 -0400615 pm->add(clspv::createAutoPodArgsPass());
Kévin Petitbbbda972020-03-03 19:16:31 +0000616 pm->add(clspv::createDeclarePushConstantsPass());
alan-bakerfec0a472018-11-08 18:09:40 -0500617 pm->add(clspv::createDefineOpenCLWorkItemBuiltinsPass());
618
619 if (0 < pmBuilder.OptLevel) {
620 pm->add(clspv::createOpenCLInlinerPass());
621 }
622
623 pm->add(clspv::createUndoByvalPass());
624 pm->add(clspv::createUndoSRetPass());
alan-baker9b0ec3c2020-04-06 14:45:34 -0400625 if (clspv::Option::ClusterPodKernelArgs()) {
alan-bakerfec0a472018-11-08 18:09:40 -0500626 pm->add(clspv::createClusterPodKernelArgumentsPass());
627 }
628 pm->add(clspv::createReplaceOpenCLBuiltinPass());
629
Marco Antognini535998c2020-09-16 18:48:51 +0100630 // Lower longer vectors when requested. Note that this pass depends on
631 // ReplaceOpenCLBuiltinPass and expects DeadCodeEliminationPass to be run
632 // afterwards.
633 if (clspv::Option::LongVectorSupport()) {
634 pm->add(clspv::createLongVectorLoweringPass());
635 }
636
alan-bakerfec0a472018-11-08 18:09:40 -0500637 // We need to run mem2reg and inst combine early because our
638 // createInlineFuncWithPointerBitCastArgPass pass cannot handle the pattern
639 // %1 = alloca i32 1
640 // store <something> %1
641 // %2 = bitcast float* %1
642 // %3 = load float %2
643 pm->add(llvm::createPromoteMemoryToRegisterPass());
644
alan-baker1b13e8f2019-08-08 17:56:51 -0400645 // Try to deal with pointer bitcasts early. This can prevent problems like
646 // issue #409 where LLVM is looser about access chain addressing than SPIR-V.
647 // This needs to happen before instcombine and after replacing OpenCL
648 // builtins. This run of the pass will not handle all pointer bitcasts that
649 // could be handled. It should be run again after other optimizations (e.g
650 // InlineFuncWithPointerBitCastArgPass).
651 pm->add(clspv::createSimplifyPointerBitcastPass());
652 pm->add(clspv::createReplacePointerBitcastPass());
653 pm->add(llvm::createDeadCodeEliminationPass());
654
alan-bakerfec0a472018-11-08 18:09:40 -0500655 // Hide loads from __constant address space away from instcombine.
656 // This prevents us from generating select between pointers-to-__constant.
657 // See https://github.com/google/clspv/issues/71
658 pm->add(clspv::createHideConstantLoadsPass());
659
660 pm->add(llvm::createInstructionCombiningPass());
661
662 if (clspv::Option::InlineEntryPoints()) {
663 pm->add(clspv::createInlineEntryPointsPass());
664 } else {
665 pm->add(clspv::createInlineFuncWithPointerBitCastArgPass());
666 pm->add(clspv::createInlineFuncWithPointerToFunctionArgPass());
667 pm->add(clspv::createInlineFuncWithSingleCallSitePass());
668 }
669
Kévin Petitf0515712020-01-07 18:29:20 +0000670 if (clspv::Option::LanguageUsesGenericAddressSpace()) {
Kévin Petit38c52482019-05-07 20:28:00 +0800671 pm->add(llvm::createInferAddressSpacesPass(clspv::AddressSpace::Generic));
Kévin Petit0fc88042019-04-09 23:25:02 +0100672 }
673
alan-bakerfec0a472018-11-08 18:09:40 -0500674 if (0 == pmBuilder.OptLevel) {
675 // Mem2Reg pass should be run early because O0 level optimization leaves
676 // redundant alloca, load and store instructions from function arguments.
677 // clspv needs to remove them ahead of transformation.
678 pm->add(llvm::createPromoteMemoryToRegisterPass());
679
680 // SROA pass is run because it will fold structs/unions that are problematic
681 // on Vulkan SPIR-V away.
682 pm->add(llvm::createSROAPass());
683
684 // InstructionCombining pass folds bitcast and gep instructions which are
685 // not supported by Vulkan SPIR-V.
686 pm->add(llvm::createInstructionCombiningPass());
687 }
688
689 // Now we add any of the LLVM optimizations we wanted
690 pmBuilder.populateModulePassManager(*pm);
691
alan-bakerb5e74d62020-04-07 20:38:05 -0400692 // No point attempting to handle freeze currently so strip them from the IR.
693 pm->add(clspv::createStripFreezePass());
694
alan-bakerfec0a472018-11-08 18:09:40 -0500695 // Unhide loads from __constant address space. Undoes the action of
696 // HideConstantLoadsPass.
697 pm->add(clspv::createUnhideConstantLoadsPass());
698
alan-baker13568382020-04-02 17:29:27 -0400699 pm->add(clspv::createUndoInstCombinePass());
alan-bakerfec0a472018-11-08 18:09:40 -0500700 pm->add(clspv::createFunctionInternalizerPass());
701 pm->add(clspv::createReplaceLLVMIntrinsicsPass());
alan-bakerad1a12f2020-08-25 09:18:38 -0400702 // Replace LLVM intrinsics can leave dead code around.
703 pm->add(llvm::createDeadCodeEliminationPass());
alan-bakerfec0a472018-11-08 18:09:40 -0500704 pm->add(clspv::createUndoBoolPass());
alan-bakere711c762020-05-20 17:56:59 -0400705 pm->add(clspv::createUndoTruncateToOddIntegerPass());
alan-bakerfec0a472018-11-08 18:09:40 -0500706 pm->add(llvm::createStructurizeCFGPass(false));
alan-baker3fa76d92018-11-12 14:54:40 -0500707 // Must be run after structurize cfg.
alan-baker9580aef2020-01-07 22:31:48 -0500708 pm->add(clspv::createFixupStructuredCFGPass());
709 // Must be run after structured cfg fixup.
alan-bakerfec0a472018-11-08 18:09:40 -0500710 pm->add(clspv::createReorderBasicBlocksPass());
711 pm->add(clspv::createUndoGetElementPtrConstantExprPass());
712 pm->add(clspv::createSplatArgPass());
713 pm->add(clspv::createSimplifyPointerBitcastPass());
714 pm->add(clspv::createReplacePointerBitcastPass());
715
716 pm->add(clspv::createUndoTranslateSamplerFoldPass());
717
718 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
719 pm->add(clspv::createClusterModuleScopeConstantVars());
720 }
721
722 pm->add(clspv::createShareModuleScopeVariablesPass());
alan-bakerf67468c2019-11-25 15:51:49 -0500723 // Specialize images before assigning descriptors to disambiguate the various
724 // types.
725 pm->add(clspv::createSpecializeImageTypesPass());
alan-bakere9308012019-03-15 10:25:13 -0400726 // This should be run after LLVM and OpenCL intrinsics are replaced.
alan-bakerfec0a472018-11-08 18:09:40 -0500727 pm->add(clspv::createAllocateDescriptorsPass(*SamplerMapEntries));
728 pm->add(llvm::createVerifierPass());
729 pm->add(clspv::createDirectResourceAccessPass());
730 // Replacing pointer bitcasts can leave some trivial GEPs
731 // that are easy to remove. Also replace GEPs of GEPS
732 // left by replacing indirect buffer accesses.
733 pm->add(clspv::createSimplifyPointerBitcastPass());
alan-baker4217b322019-03-06 08:56:12 -0500734 // Run after DRA to clean up parameters and help reduce the need for variable
735 // pointers.
736 pm->add(clspv::createRemoveUnusedArgumentsPass());
alan-bakerfec0a472018-11-08 18:09:40 -0500737
738 pm->add(clspv::createSplatSelectConditionPass());
739 pm->add(clspv::createSignedCompareFixupPass());
740 // This pass generates insertions that need to be rewritten.
741 pm->add(clspv::createScalarizePass());
742 pm->add(clspv::createRewriteInsertsPass());
alan-bakera71f1932019-04-11 11:04:34 -0400743 // UBO Transformations
744 if (clspv::Option::ConstantArgsInUniformBuffer() &&
745 !clspv::Option::InlineEntryPoints()) {
746 // MultiVersionUBOFunctionsPass will examine non-kernel functions with UBO
747 // arguments and either multi-version them as necessary or inline them if
748 // multi-versioning cannot be accomplished.
749 pm->add(clspv::createMultiVersionUBOFunctionsPass());
750 // Cleanup passes.
751 // Specialization can blindly generate GEP chains that are easily cleaned up
752 // by SimplifyPointerBitcastPass.
753 pm->add(clspv::createSimplifyPointerBitcastPass());
754 // RemoveUnusedArgumentsPass removes the actual UBO arguments that were
755 // problematic to begin with now that they have no uses.
756 pm->add(clspv::createRemoveUnusedArgumentsPass());
757 // DCE cleans up callers of the specialized functions.
758 pm->add(llvm::createDeadCodeEliminationPass());
759 }
alan-bakerfec0a472018-11-08 18:09:40 -0500760 // This pass mucks with types to point where you shouldn't rely on DataLayout
761 // anymore so leave this right before SPIR-V generation.
762 pm->add(clspv::createUBOTypeTransformPass());
alan-baker86ce19c2020-08-05 13:09:19 -0400763 pm->add(clspv::createSPIRVProducerPass(*binaryStream, *SamplerMapEntries,
alan-baker00e7a582019-06-07 12:54:21 -0400764 OutputFormat == "c"));
alan-bakerf5e5f692018-11-27 08:33:24 -0500765
766 return 0;
alan-bakerfec0a472018-11-08 18:09:40 -0500767}
alan-bakerfec0a472018-11-08 18:09:40 -0500768
Kévin Petitd5db2d22019-04-04 13:55:14 +0100769int ParseOptions(const int argc, const char *const argv[]) {
alan-baker227e9782020-06-02 15:35:37 -0400770 // We need to change how some of the called passes works by spoofing
771 // ParseCommandLineOptions with the specific options.
772 bool has_pre = false;
773 bool has_load_pre = false;
774 const std::string pre = "-enable-pre";
775 const std::string load_pre = "-enable-load-pre";
776 for (int i = 1; i < argc; ++i) {
777 std::string option(argv[i]);
778 auto pre_pos = option.find(pre);
779 auto load_pos = option.find(load_pre);
780 if (pre_pos == 0 || (pre_pos == 1 && option[0] == '-')) {
781 has_pre = true;
782 } else if (load_pos == 0 || (load_pos == 1 && option[0] == '-')) {
783 has_load_pre = true;
784 }
785 }
786
787 int llvmArgc = 2;
788 const char *llvmArgv[4];
789 llvmArgv[0] = argv[0];
790 llvmArgv[1] = "-simplifycfg-sink-common=false";
791 if (!has_pre) {
792 llvmArgv[llvmArgc++] = "-enable-pre=0";
793 }
794 if (!has_load_pre) {
795 llvmArgv[llvmArgc++] = "-enable-load-pre=0";
796 }
alan-bakerfec0a472018-11-08 18:09:40 -0500797
Kévin Petitd5db2d22019-04-04 13:55:14 +0100798 llvm::cl::ResetAllOptionOccurrences();
alan-bakerfec0a472018-11-08 18:09:40 -0500799 llvm::cl::ParseCommandLineOptions(llvmArgc, llvmArgv);
alan-bakerfec0a472018-11-08 18:09:40 -0500800 llvm::cl::ParseCommandLineOptions(argc, argv);
801
Kévin Petitf0515712020-01-07 18:29:20 +0000802 if (clspv::Option::LanguageUsesGenericAddressSpace() &&
803 !clspv::Option::InlineEntryPoints()) {
804 llvm::errs() << "cannot compile languages that use the generic address "
805 "space (e.g. CLC++, CL2.0) without -inline-entry-points\n";
Kévin Petit0fc88042019-04-09 23:25:02 +0100806 return -1;
807 }
808
Kévin Petitbbbda972020-03-03 19:16:31 +0000809 if (clspv::Option::ScalarBlockLayout()) {
810 llvm::errs() << "scalar block layout support unimplemented\n";
811 return -1;
812 }
813
alan-baker9b0ec3c2020-04-06 14:45:34 -0400814 // Push constant option validation.
815 if (clspv::Option::PodArgsInPushConstants()) {
816 if (clspv::Option::PodArgsInUniformBuffer()) {
817 llvm::errs() << "POD arguments can only be in either uniform buffers or "
818 "push constants\n";
819 return -1;
820 }
821
822 if (!clspv::Option::ClusterPodKernelArgs()) {
823 llvm::errs()
824 << "POD arguments must be clustered to be passed as push constants\n";
825 return -1;
826 }
827
828 // Conservatively error if a module scope push constant could be used.
James Price708cf362020-05-06 19:33:45 -0400829 if (clspv::Option::GlobalOffsetPushConstant() ||
alan-baker9b0ec3c2020-04-06 14:45:34 -0400830 clspv::Option::Language() ==
831 clspv::Option::SourceLanguage::OpenCL_C_20 ||
832 clspv::Option::Language() ==
833 clspv::Option::SourceLanguage::OpenCL_CPP) {
834 llvm::errs() << "POD arguments as push constants are not compatible with "
835 "module scope push constants\n";
836 return -1;
837 }
838 }
839
Kévin Petitd5db2d22019-04-04 13:55:14 +0100840 return 0;
841}
Diego Novillo89500852019-04-15 08:45:10 -0400842
843int GenerateIRFile(llvm::legacy::PassManager *pm, llvm::Module &module,
844 std::string output) {
845 std::error_code ec;
846 std::unique_ptr<llvm::ToolOutputFile> out(
847 new llvm::ToolOutputFile(output, ec, llvm::sys::fs::F_None));
848 if (ec) {
849 llvm::errs() << output << ": " << ec.message() << '\n';
850 return -1;
851 }
852 pm->add(llvm::createPrintModulePass(out->os(), "", false));
853 pm->run(module);
854 out->keep();
855 return 0;
856}
857
alan-baker869cd682021-03-05 11:21:19 -0500858bool LinkBuiltinLibrary(llvm::Module *module) {
859 std::unique_ptr<llvm::MemoryBuffer> buffer(new OpenCLBuiltinMemoryBuffer(
860 clspv_builtin_library_data, clspv_builtin_library_size - 1));
861
862 llvm::SMDiagnostic Err;
863 auto library = llvm::parseIR(*buffer, Err, module->getContext());
864 if (!library) {
865 llvm::errs() << "Failed to parse builtins library\n";
866 return false;
867 }
868
869 // TODO: when clang generates builtins using the generic address space,
870 // different builtins are used for pointer-based builtins. Need to do some
871 // work to ensure they are kept around.
872 // Affects: modf, remquo, lgamma_r, frexp
873
874 llvm::Linker L(*module);
875 L.linkInModule(std::move(library), 0);
876
877 return true;
878}
879
Kévin Petitd5db2d22019-04-04 13:55:14 +0100880} // namespace
881
882namespace clspv {
883int Compile(const int argc, const char *const argv[]) {
884
885 if (auto error = ParseOptions(argc, argv))
886 return error;
887
alan-bakerfec0a472018-11-08 18:09:40 -0500888 llvm::SmallVector<std::pair<unsigned, std::string>, 8> SamplerMapEntries;
alan-bakerf5e5f692018-11-27 08:33:24 -0500889 if (auto error = ParseSamplerMap("", &SamplerMapEntries))
alan-bakerfec0a472018-11-08 18:09:40 -0500890 return error;
891
892 // if no output file was provided, use a default
893 llvm::StringRef overiddenInputFilename = InputFilename.getValue();
894
895 // If we are reading our input file from stdin.
896 if ("-" == InputFilename) {
897 // We need to overwrite the file name we use.
Kévin Petitddad8f42019-09-30 15:12:08 +0100898 switch (InputLanguage) {
899 case clang::Language::OpenCL:
900 overiddenInputFilename = "stdin.cl";
901 break;
902 case clang::Language::LLVM_IR:
903 overiddenInputFilename = "stdin.ll";
904 break;
alan-baker31298a62019-10-07 13:24:30 -0400905 default:
906 // Default to fix compiler warnings/errors. Option parsing will reject a
907 // bad enum value for the option so there is no need for a message.
908 return -1;
Kévin Petitddad8f42019-09-30 15:12:08 +0100909 }
alan-bakerfec0a472018-11-08 18:09:40 -0500910 }
911
912 clang::CompilerInstance instance;
Kévin Petitddad8f42019-09-30 15:12:08 +0100913 clang::FrontendInputFile kernelFile(overiddenInputFilename,
914 clang::InputKind(InputLanguage));
alan-bakerfec0a472018-11-08 18:09:40 -0500915 std::string log;
916 llvm::raw_string_ostream diagnosticsStream(log);
alan-bakerf5e5f692018-11-27 08:33:24 -0500917 if (auto error = SetCompilerInstanceOptions(
918 instance, overiddenInputFilename, kernelFile, "", &diagnosticsStream))
alan-bakerfec0a472018-11-08 18:09:40 -0500919 return error;
920
921 // Parse.
922 llvm::LLVMContext context;
923 clang::EmitLLVMOnlyAction action(&context);
924
925 // Prepare the action for processing kernelFile
926 const bool success = action.BeginSourceFile(instance, kernelFile);
927 if (!success) {
928 return -1;
929 }
930
alan-bakerf3bce4a2019-06-28 16:01:15 -0400931 auto result = action.Execute();
alan-bakerfec0a472018-11-08 18:09:40 -0500932 action.EndSourceFile();
933
934 clang::DiagnosticConsumer *const consumer =
935 instance.getDiagnostics().getClient();
936 consumer->finish();
937
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100938 auto num_warnings = consumer->getNumWarnings();
alan-bakerfec0a472018-11-08 18:09:40 -0500939 auto num_errors = consumer->getNumErrors();
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100940 if ((num_errors > 0) || (num_warnings > 0)) {
941 llvm::errs() << log;
942 }
alan-bakerf3bce4a2019-06-28 16:01:15 -0400943 if (result || num_errors > 0) {
alan-bakerfec0a472018-11-08 18:09:40 -0500944 return -1;
945 }
946
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100947 // Don't run the passes or produce any output in verify mode.
948 // Clang doesn't always produce a valid module.
949 if (verify) {
950 return 0;
951 }
952
alan-bakerfec0a472018-11-08 18:09:40 -0500953 llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry();
954 llvm::initializeCore(Registry);
955 llvm::initializeScalarOpts(Registry);
Diego Novillo1fcff722019-05-07 13:45:53 -0400956 llvm::initializeClspvPasses(Registry);
alan-bakerfec0a472018-11-08 18:09:40 -0500957
958 std::unique_ptr<llvm::Module> module(action.takeModule());
959
960 // Optimize.
961 // Create a memory buffer for temporarily writing the result.
962 SmallVector<char, 10000> binary;
963 llvm::raw_svector_ostream binaryStream(binary);
alan-bakerfec0a472018-11-08 18:09:40 -0500964 llvm::legacy::PassManager pm;
Diego Novillo89500852019-04-15 08:45:10 -0400965
966 // If --emit-ir was requested, emit the initial LLVM IR and stop compilation.
967 if (!IROutputFile.empty()) {
968 return GenerateIRFile(&pm, *module, IROutputFile);
969 }
970
alan-baker869cd682021-03-05 11:21:19 -0500971 if (!LinkBuiltinLibrary(module.get())) {
972 return -1;
973 }
974
Diego Novillo89500852019-04-15 08:45:10 -0400975 // Otherwise, populate the pass manager and run the regular passes.
alan-baker86ce19c2020-08-05 13:09:19 -0400976 if (auto error = PopulatePassManager(&pm, &binaryStream, &SamplerMapEntries))
alan-bakerf5e5f692018-11-27 08:33:24 -0500977 return error;
alan-bakerfec0a472018-11-08 18:09:40 -0500978 pm.run(*module);
979
980 // Write outputs
alan-bakerfec0a472018-11-08 18:09:40 -0500981 std::error_code error;
alan-bakerfec0a472018-11-08 18:09:40 -0500982
983 // Write the resulting binary.
984 // Wait until now to try writing the file so that we only write it on
985 // successful compilation.
986 if (OutputFilename.empty()) {
Kévin Petite4786902019-04-02 21:51:47 +0100987 if (OutputFormat == "c") {
alan-bakerfec0a472018-11-08 18:09:40 -0500988 OutputFilename = "a.spvinc";
989 } else {
990 OutputFilename = "a.spv";
991 }
992 }
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400993 llvm::raw_fd_ostream outStream(OutputFilename, error,
994 llvm::sys::fs::FA_Write);
alan-bakerfec0a472018-11-08 18:09:40 -0500995
996 if (error) {
997 llvm::errs() << "Unable to open output file '" << OutputFilename
998 << "': " << error.message() << '\n';
999 return -1;
1000 }
1001 outStream << binaryStream.str();
1002
1003 return 0;
1004}
alan-bakerf5e5f692018-11-27 08:33:24 -05001005
alan-baker86ce19c2020-08-05 13:09:19 -04001006int CompileFromSourceString(const std::string &program,
1007 const std::string &sampler_map,
1008 const std::string &options,
Kévin Petit899162d2020-09-08 19:16:08 +01001009 std::vector<uint32_t> *output_binary,
1010 std::string *output_log) {
alan-bakerf5e5f692018-11-27 08:33:24 -05001011
1012 llvm::SmallVector<const char *, 20> argv;
1013 llvm::BumpPtrAllocator A;
1014 llvm::StringSaver Saver(A);
1015 argv.push_back(Saver.save("clspv").data());
1016 llvm::cl::TokenizeGNUCommandLine(options, Saver, argv);
1017 int argc = static_cast<int>(argv.size());
Kévin Petitd5db2d22019-04-04 13:55:14 +01001018
1019 if (auto error = ParseOptions(argc, &argv[0]))
1020 return error;
alan-bakerf5e5f692018-11-27 08:33:24 -05001021
1022 llvm::SmallVector<std::pair<unsigned, std::string>, 8> SamplerMapEntries;
1023 if (auto error = ParseSamplerMap(sampler_map, &SamplerMapEntries))
1024 return error;
1025
1026 InputFilename = "source.cl";
1027 llvm::StringRef overiddenInputFilename = InputFilename.getValue();
1028
1029 clang::CompilerInstance instance;
alan-bakerd354f1a2019-08-06 15:41:55 -04001030 clang::FrontendInputFile kernelFile(
1031 overiddenInputFilename, clang::InputKind(clang::Language::OpenCL));
alan-bakerf5e5f692018-11-27 08:33:24 -05001032 std::string log;
1033 llvm::raw_string_ostream diagnosticsStream(log);
1034 if (auto error =
1035 SetCompilerInstanceOptions(instance, overiddenInputFilename,
1036 kernelFile, program, &diagnosticsStream))
1037 return error;
1038
1039 // Parse.
1040 llvm::LLVMContext context;
1041 clang::EmitLLVMOnlyAction action(&context);
1042
1043 // Prepare the action for processing kernelFile
1044 const bool success = action.BeginSourceFile(instance, kernelFile);
1045 if (!success) {
1046 return -1;
1047 }
1048
alan-bakerf3bce4a2019-06-28 16:01:15 -04001049 auto result = action.Execute();
alan-bakerf5e5f692018-11-27 08:33:24 -05001050 action.EndSourceFile();
1051
1052 clang::DiagnosticConsumer *const consumer =
1053 instance.getDiagnostics().getClient();
1054 consumer->finish();
1055
Kévin Petit899162d2020-09-08 19:16:08 +01001056 if (output_log != nullptr) {
1057 *output_log = log;
1058 }
1059
alan-bakerf5e5f692018-11-27 08:33:24 -05001060 auto num_errors = consumer->getNumErrors();
alan-bakerf3bce4a2019-06-28 16:01:15 -04001061 if (result || num_errors > 0) {
alan-bakerf5e5f692018-11-27 08:33:24 -05001062 return -1;
1063 }
1064
alan-bakerf5e5f692018-11-27 08:33:24 -05001065 llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry();
1066 llvm::initializeCore(Registry);
1067 llvm::initializeScalarOpts(Registry);
Diego Novillo1fcff722019-05-07 13:45:53 -04001068 llvm::initializeClspvPasses(Registry);
alan-bakerf5e5f692018-11-27 08:33:24 -05001069
1070 std::unique_ptr<llvm::Module> module(action.takeModule());
1071
alan-baker869cd682021-03-05 11:21:19 -05001072 if (!LinkBuiltinLibrary(module.get())) {
1073 return -1;
1074 }
1075
alan-bakerf5e5f692018-11-27 08:33:24 -05001076 // Optimize.
1077 // Create a memory buffer for temporarily writing the result.
1078 SmallVector<char, 10000> binary;
1079 llvm::raw_svector_ostream binaryStream(binary);
alan-bakerf5e5f692018-11-27 08:33:24 -05001080 llvm::legacy::PassManager pm;
alan-baker86ce19c2020-08-05 13:09:19 -04001081 if (auto error = PopulatePassManager(&pm, &binaryStream, &SamplerMapEntries))
alan-bakerf5e5f692018-11-27 08:33:24 -05001082 return error;
1083 pm.run(*module);
1084
alan-bakerf5e5f692018-11-27 08:33:24 -05001085 // Write the resulting binary.
1086 // Wait until now to try writing the file so that we only write it on
1087 // successful compilation.
1088 assert(output_binary && "Valid binary container is required.");
1089 if (!OutputFilename.empty()) {
1090 llvm::outs()
1091 << "Warning: -o is ignored when binary container is provided.\n";
1092 }
1093 output_binary->resize(binary.size() / 4);
1094 memcpy(output_binary->data(), binary.data(), binary.size());
1095
1096 return 0;
1097}
alan-bakerfec0a472018-11-08 18:09:40 -05001098} // namespace clspv