blob: 2e12d1f3ba5bc0a2e175bb7be0cddb755a31d104 [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-bakerfec0a472018-11-08 18:09:40 -050038#include "clspv/Option.h"
39#include "clspv/Passes.h"
alan-baker86ce19c2020-08-05 13:09:19 -040040#include "clspv/Sampler.h"
alan-bakerfec0a472018-11-08 18:09:40 -050041#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
alan-bakerfec0a472018-11-08 18:09:40 -0500135static llvm::cl::opt<char>
136 OptimizationLevel(llvm::cl::Prefix, "O", llvm::cl::init('2'),
137 llvm::cl::desc("Optimization level to use"),
138 llvm::cl::value_desc("level"));
139
alan-bakerfec0a472018-11-08 18:09:40 -0500140static llvm::cl::opt<std::string> OutputFormat(
141 "mfmt", llvm::cl::init(""),
142 llvm::cl::desc(
143 "Specify special output format. 'c' is as a C initializer list"),
144 llvm::cl::value_desc("format"));
145
146static llvm::cl::opt<std::string>
alan-baker09cb9802019-12-10 13:16:27 -0500147 SamplerMap("samplermap", llvm::cl::desc("DEPRECATED - Literal sampler map"),
alan-bakerfec0a472018-11-08 18:09:40 -0500148 llvm::cl::value_desc("filename"));
149
alan-bakerfec0a472018-11-08 18:09:40 -0500150static llvm::cl::opt<bool> verify("verify", llvm::cl::init(false),
151 llvm::cl::desc("Verify diagnostic outputs"));
152
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100153static llvm::cl::opt<bool>
154 IgnoreWarnings("w", llvm::cl::init(false),
155 llvm::cl::desc("Disable all warnings"));
156
157static llvm::cl::opt<bool>
158 WarningsAsErrors("Werror", llvm::cl::init(false),
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400159 llvm::cl::desc("Turn warnings into errors"));
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100160
Diego Novillo89500852019-04-15 08:45:10 -0400161static llvm::cl::opt<std::string> IROutputFile(
162 "emit-ir",
163 llvm::cl::desc(
164 "Emit LLVM IR to the given file after parsing and stop compilation."),
165 llvm::cl::value_desc("filename"));
166
alan-bakerfec0a472018-11-08 18:09:40 -0500167// Populates |SamplerMapEntries| with data from the input sampler map. Returns 0
168// if successful.
alan-bakerf5e5f692018-11-27 08:33:24 -0500169int ParseSamplerMap(const std::string &sampler_map,
170 llvm::SmallVectorImpl<std::pair<unsigned, std::string>>
171 *SamplerMapEntries) {
172 std::unique_ptr<llvm::MemoryBuffer> samplerMapBuffer(nullptr);
173 if (!sampler_map.empty()) {
174 // Parse the sampler map from the provided string.
175 samplerMapBuffer = llvm::MemoryBuffer::getMemBuffer(sampler_map);
176
alan-baker09cb9802019-12-10 13:16:27 -0500177 clspv::Option::SetUseSamplerMap(true);
alan-bakerf5e5f692018-11-27 08:33:24 -0500178 if (!SamplerMap.empty()) {
179 llvm::outs() << "Warning: -samplermap is ignored when the sampler map is "
180 "provided through a string.\n";
181 }
182 } else if (!SamplerMap.empty()) {
183 // Parse the sampler map from the option provided file.
alan-bakerfec0a472018-11-08 18:09:40 -0500184 auto errorOrSamplerMapFile =
185 llvm::MemoryBuffer::getFile(SamplerMap.getValue());
186
187 // If there was an error in getting the sampler map file.
188 if (!errorOrSamplerMapFile) {
189 llvm::errs() << "Error: " << errorOrSamplerMapFile.getError().message()
190 << " '" << SamplerMap.getValue() << "'\n";
191 return -1;
192 }
193
alan-baker09cb9802019-12-10 13:16:27 -0500194 clspv::Option::SetUseSamplerMap(true);
alan-bakerf5e5f692018-11-27 08:33:24 -0500195 samplerMapBuffer = std::move(errorOrSamplerMapFile.get());
alan-bakerfec0a472018-11-08 18:09:40 -0500196 if (0 == samplerMapBuffer->getBufferSize()) {
197 llvm::errs() << "Error: Sampler map was an empty file!\n";
198 return -1;
199 }
alan-bakerf5e5f692018-11-27 08:33:24 -0500200 }
alan-bakerfec0a472018-11-08 18:09:40 -0500201
alan-baker09cb9802019-12-10 13:16:27 -0500202 if (clspv::Option::UseSamplerMap()) {
203 llvm::outs()
204 << "Warning: use of the sampler map is deprecated and unnecessary\n";
205 }
206
alan-bakerf5e5f692018-11-27 08:33:24 -0500207 // No sampler map to parse.
208 if (!samplerMapBuffer || 0 == samplerMapBuffer->getBufferSize())
209 return 0;
alan-bakerfec0a472018-11-08 18:09:40 -0500210
alan-bakerf5e5f692018-11-27 08:33:24 -0500211 llvm::SmallVector<llvm::StringRef, 3> samplerStrings;
alan-bakerfec0a472018-11-08 18:09:40 -0500212
alan-bakerf5e5f692018-11-27 08:33:24 -0500213 // We need to keep track of the beginning of the current entry.
214 const char *b = samplerMapBuffer->getBufferStart();
215 for (const char *i = b, *e = samplerMapBuffer->getBufferEnd();; i++) {
216 // If we have a separator between declarations.
217 if ((*i == '|') || (*i == ',') || (i == e)) {
218 if (i == b) {
219 llvm::errs() << "Error: Sampler map contained an empty entry!\n";
220 return -1;
alan-bakerfec0a472018-11-08 18:09:40 -0500221 }
222
alan-bakerf5e5f692018-11-27 08:33:24 -0500223 samplerStrings.push_back(llvm::StringRef(b, i - b).trim());
alan-bakerfec0a472018-11-08 18:09:40 -0500224
alan-bakerf5e5f692018-11-27 08:33:24 -0500225 // And set b the next character after i.
226 b = i + 1;
227 }
alan-bakerfec0a472018-11-08 18:09:40 -0500228
alan-bakerf5e5f692018-11-27 08:33:24 -0500229 // If we have a separator between declarations within a single sampler.
230 if ((*i == ',') || (i == e)) {
alan-bakerfec0a472018-11-08 18:09:40 -0500231
alan-baker86ce19c2020-08-05 13:09:19 -0400232 clspv::SamplerNormalizedCoords NormalizedCoord =
233 clspv::CLK_NORMALIZED_COORDS_NOT_SET;
234 clspv::SamplerAddressingMode AddressingMode = clspv::CLK_ADDRESS_NOT_SET;
235 clspv::SamplerFilterMode FilterMode = clspv::CLK_FILTER_NOT_SET;
alan-bakerf5e5f692018-11-27 08:33:24 -0500236
237 for (auto str : samplerStrings) {
238 if ("CLK_NORMALIZED_COORDS_FALSE" == str) {
alan-baker86ce19c2020-08-05 13:09:19 -0400239 if (clspv::CLK_NORMALIZED_COORDS_NOT_SET != NormalizedCoord) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500240 llvm::errs() << "Error: Sampler map normalized coordinates was "
241 "previously set!\n";
alan-bakerfec0a472018-11-08 18:09:40 -0500242 return -1;
243 }
alan-baker86ce19c2020-08-05 13:09:19 -0400244 NormalizedCoord = clspv::CLK_NORMALIZED_COORDS_FALSE;
alan-bakerf5e5f692018-11-27 08:33:24 -0500245 } else if ("CLK_NORMALIZED_COORDS_TRUE" == str) {
alan-baker86ce19c2020-08-05 13:09:19 -0400246 if (clspv::CLK_NORMALIZED_COORDS_NOT_SET != NormalizedCoord) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500247 llvm::errs() << "Error: Sampler map normalized coordinates was "
248 "previously set!\n";
249 return -1;
250 }
alan-baker86ce19c2020-08-05 13:09:19 -0400251 NormalizedCoord = clspv::CLK_NORMALIZED_COORDS_TRUE;
alan-bakerf5e5f692018-11-27 08:33:24 -0500252 } else if ("CLK_ADDRESS_NONE" == str) {
alan-baker86ce19c2020-08-05 13:09:19 -0400253 if (clspv::CLK_ADDRESS_NOT_SET != AddressingMode) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500254 llvm::errs()
255 << "Error: Sampler map addressing mode was previously set!\n";
256 return -1;
257 }
alan-baker86ce19c2020-08-05 13:09:19 -0400258 AddressingMode = clspv::CLK_ADDRESS_NONE;
alan-bakerf5e5f692018-11-27 08:33:24 -0500259 } else if ("CLK_ADDRESS_CLAMP_TO_EDGE" == str) {
alan-baker86ce19c2020-08-05 13:09:19 -0400260 if (clspv::CLK_ADDRESS_NOT_SET != AddressingMode) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500261 llvm::errs()
262 << "Error: Sampler map addressing mode was previously set!\n";
263 return -1;
264 }
alan-baker86ce19c2020-08-05 13:09:19 -0400265 AddressingMode = clspv::CLK_ADDRESS_CLAMP_TO_EDGE;
alan-bakerf5e5f692018-11-27 08:33:24 -0500266 } else if ("CLK_ADDRESS_CLAMP" == str) {
alan-baker86ce19c2020-08-05 13:09:19 -0400267 if (clspv::CLK_ADDRESS_NOT_SET != AddressingMode) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500268 llvm::errs()
269 << "Error: Sampler map addressing mode was previously set!\n";
270 return -1;
271 }
alan-baker86ce19c2020-08-05 13:09:19 -0400272 AddressingMode = clspv::CLK_ADDRESS_CLAMP;
alan-bakerf5e5f692018-11-27 08:33:24 -0500273 } else if ("CLK_ADDRESS_MIRRORED_REPEAT" == str) {
alan-baker86ce19c2020-08-05 13:09:19 -0400274 if (clspv::CLK_ADDRESS_NOT_SET != AddressingMode) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500275 llvm::errs()
276 << "Error: Sampler map addressing mode was previously set!\n";
277 return -1;
278 }
alan-baker86ce19c2020-08-05 13:09:19 -0400279 AddressingMode = clspv::CLK_ADDRESS_MIRRORED_REPEAT;
alan-bakerf5e5f692018-11-27 08:33:24 -0500280 } else if ("CLK_ADDRESS_REPEAT" == str) {
alan-baker86ce19c2020-08-05 13:09:19 -0400281 if (clspv::CLK_ADDRESS_NOT_SET != AddressingMode) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500282 llvm::errs()
283 << "Error: Sampler map addressing mode was previously set!\n";
284 return -1;
285 }
alan-baker86ce19c2020-08-05 13:09:19 -0400286 AddressingMode = clspv::CLK_ADDRESS_REPEAT;
alan-bakerf5e5f692018-11-27 08:33:24 -0500287 } else if ("CLK_FILTER_NEAREST" == str) {
alan-baker86ce19c2020-08-05 13:09:19 -0400288 if (clspv::CLK_FILTER_NOT_SET != FilterMode) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500289 llvm::errs()
290 << "Error: Sampler map filtering mode was previously set!\n";
291 return -1;
292 }
alan-baker86ce19c2020-08-05 13:09:19 -0400293 FilterMode = clspv::CLK_FILTER_NEAREST;
alan-bakerf5e5f692018-11-27 08:33:24 -0500294 } else if ("CLK_FILTER_LINEAR" == str) {
alan-baker86ce19c2020-08-05 13:09:19 -0400295 if (clspv::CLK_FILTER_NOT_SET != FilterMode) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500296 llvm::errs()
297 << "Error: Sampler map filtering mode was previously set!\n";
298 return -1;
299 }
alan-baker86ce19c2020-08-05 13:09:19 -0400300 FilterMode = clspv::CLK_FILTER_LINEAR;
alan-bakerf5e5f692018-11-27 08:33:24 -0500301 } else {
302 llvm::errs() << "Error: Unknown sampler string '" << str
303 << "' found!\n";
alan-bakerfec0a472018-11-08 18:09:40 -0500304 return -1;
305 }
alan-bakerfec0a472018-11-08 18:09:40 -0500306 }
307
alan-baker86ce19c2020-08-05 13:09:19 -0400308 if (clspv::CLK_NORMALIZED_COORDS_NOT_SET == NormalizedCoord) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500309 llvm::errs() << "Error: Sampler map entry did not contain normalized "
310 "coordinates entry!\n";
311 return -1;
alan-bakerfec0a472018-11-08 18:09:40 -0500312 }
alan-bakerf5e5f692018-11-27 08:33:24 -0500313
alan-baker86ce19c2020-08-05 13:09:19 -0400314 if (clspv::CLK_ADDRESS_NOT_SET == AddressingMode) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500315 llvm::errs() << "Error: Sampler map entry did not contain addressing "
316 "mode entry!\n";
317 return -1;
318 }
319
alan-baker86ce19c2020-08-05 13:09:19 -0400320 if (clspv::CLK_FILTER_NOT_SET == FilterMode) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500321 llvm::errs()
322 << "Error: Sampler map entry did not contain filer mode entry!\n";
323 return -1;
324 }
325
326 // Generate an equivalent expression in string form. Sort the
327 // strings to get a canonical ordering.
328 std::sort(samplerStrings.begin(), samplerStrings.end(),
329 std::less<StringRef>());
330 const auto samplerExpr = std::accumulate(
331 samplerStrings.begin(), samplerStrings.end(), std::string(),
alan-baker21574d32020-01-29 16:00:31 -0500332 [](llvm::StringRef left, llvm::StringRef right) {
333 return left.str() + std::string(left.empty() ? "" : "|") +
334 right.str();
alan-bakerf5e5f692018-11-27 08:33:24 -0500335 });
336
337 // SamplerMapEntries->push_back(std::make_pair(
338 // NormalizedCoord | AddressingMode | FilterMode, samplerExpr));
339 SamplerMapEntries->emplace_back(
340 NormalizedCoord | AddressingMode | FilterMode, samplerExpr);
341
342 // And reset the sampler strings for the next sampler in the map.
343 samplerStrings.clear();
344 }
345
346 // And lastly, if we are at the end of the file
347 if (i == e) {
348 break;
alan-bakerfec0a472018-11-08 18:09:40 -0500349 }
350 }
351
352 return 0;
353}
354
355// Sets |instance|'s options for compiling. Returns 0 if successful.
356int SetCompilerInstanceOptions(CompilerInstance &instance,
357 const llvm::StringRef &overiddenInputFilename,
358 const clang::FrontendInputFile &kernelFile,
alan-bakerf5e5f692018-11-27 08:33:24 -0500359 const std::string &program,
alan-bakerfec0a472018-11-08 18:09:40 -0500360 llvm::raw_string_ostream *diagnosticsStream) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500361 std::unique_ptr<llvm::MemoryBuffer> memory_buffer(nullptr);
362 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> errorOrInputFile(nullptr);
363 if (program.empty()) {
364 auto errorOrInputFile =
365 llvm::MemoryBuffer::getFileOrSTDIN(InputFilename.getValue());
alan-bakerfec0a472018-11-08 18:09:40 -0500366
alan-bakerf5e5f692018-11-27 08:33:24 -0500367 // If there was an error in getting the input file.
368 if (!errorOrInputFile) {
369 llvm::errs() << "Error: " << errorOrInputFile.getError().message() << " '"
370 << InputFilename.getValue() << "'\n";
371 return -1;
372 }
373 memory_buffer.reset(errorOrInputFile.get().release());
374 } else {
375 memory_buffer = llvm::MemoryBuffer::getMemBuffer(program.c_str(),
376 overiddenInputFilename);
alan-bakerfec0a472018-11-08 18:09:40 -0500377 }
alan-bakerf5e5f692018-11-27 08:33:24 -0500378
alan-bakerfec0a472018-11-08 18:09:40 -0500379 if (verify) {
380 instance.getDiagnosticOpts().VerifyDiagnostics = true;
alan-bakerbccf62c2019-03-29 10:32:41 -0400381 instance.getDiagnosticOpts().VerifyPrefixes.push_back("expected");
alan-bakerfec0a472018-11-08 18:09:40 -0500382 }
383
Kévin Petit0fc88042019-04-09 23:25:02 +0100384 clang::LangStandard::Kind standard;
Kévin Petitf0515712020-01-07 18:29:20 +0000385 switch (clspv::Option::Language()) {
386 case clspv::Option::SourceLanguage::OpenCL_C_10:
387 standard = clang::LangStandard::lang_opencl10;
388 break;
389 case clspv::Option::SourceLanguage::OpenCL_C_11:
390 standard = clang::LangStandard::lang_opencl11;
391 break;
392 case clspv::Option::SourceLanguage::OpenCL_C_12:
Kévin Petit0fc88042019-04-09 23:25:02 +0100393 standard = clang::LangStandard::lang_opencl12;
Kévin Petitf0515712020-01-07 18:29:20 +0000394 break;
395 case clspv::Option::SourceLanguage::OpenCL_C_20:
396 standard = clang::LangStandard::lang_opencl20;
397 break;
Kévin Petit77838ff2020-10-19 18:54:51 +0100398 case clspv::Option::SourceLanguage::OpenCL_C_30:
399 standard = clang::LangStandard::lang_opencl30;
400 break;
Kévin Petitf0515712020-01-07 18:29:20 +0000401 case clspv::Option::SourceLanguage::OpenCL_CPP:
402 standard = clang::LangStandard::lang_openclcpp;
403 break;
404 default:
405 llvm_unreachable("Unknown source language");
Kévin Petit0fc88042019-04-09 23:25:02 +0100406 }
alan-bakerfec0a472018-11-08 18:09:40 -0500407
alan-bakerfec0a472018-11-08 18:09:40 -0500408 instance.getLangOpts().C99 = true;
409 instance.getLangOpts().RTTI = false;
410 instance.getLangOpts().RTTIData = false;
411 instance.getLangOpts().MathErrno = false;
412 instance.getLangOpts().Optimize = false;
413 instance.getLangOpts().NoBuiltin = true;
414 instance.getLangOpts().ModulesSearchAll = false;
415 instance.getLangOpts().SinglePrecisionConstants = true;
416 instance.getCodeGenOpts().StackRealignment = true;
417 instance.getCodeGenOpts().SimplifyLibCalls = false;
418 instance.getCodeGenOpts().EmitOpenCLArgMetadata = false;
419 instance.getCodeGenOpts().DisableO0ImplyOptNone = true;
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100420 instance.getDiagnosticOpts().IgnoreWarnings = IgnoreWarnings;
alan-bakerfec0a472018-11-08 18:09:40 -0500421
422 instance.getLangOpts().SinglePrecisionConstants =
423 cl_single_precision_constants;
424 // cl_denorms_are_zero ignored for now!
425 // cl_fp32_correctly_rounded_divide_sqrt ignored for now!
426 instance.getCodeGenOpts().LessPreciseFPMAD =
427 cl_mad_enable || cl_unsafe_math_optimizations;
428 // cl_no_signed_zeros ignored for now!
alan-baker0f814cd2020-06-02 15:35:14 -0400429 instance.getLangOpts().UnsafeFPMath =
alan-bakerfec0a472018-11-08 18:09:40 -0500430 cl_unsafe_math_optimizations || cl_fast_relaxed_math;
431 instance.getLangOpts().FiniteMathOnly =
432 cl_finite_math_only || cl_fast_relaxed_math;
433 instance.getLangOpts().FastRelaxedMath = cl_fast_relaxed_math;
434
435 // Preprocessor options
Kévin Petita624c0c2019-05-07 20:27:43 +0800436 if (!clspv::Option::ImageSupport()) {
437 instance.getPreprocessorOpts().addMacroUndef("__IMAGE_SUPPORT__");
438 }
alan-bakerfec0a472018-11-08 18:09:40 -0500439 if (cl_fast_relaxed_math) {
440 instance.getPreprocessorOpts().addMacroDef("__FAST_RELAXED_MATH__");
441 }
442
443 for (auto define : Defines) {
444 instance.getPreprocessorOpts().addMacroDef(define);
445 }
446
447 // Header search options
448 for (auto include : Includes) {
449 instance.getHeaderSearchOpts().AddPath(include, clang::frontend::After,
450 false, false);
451 }
452
453 // We always compile on opt 0 so we preserve as much debug information about
454 // the source as possible. We'll run optimization later, once we've had a
455 // chance to view the unoptimal code first
456 instance.getCodeGenOpts().OptimizationLevel = 0;
457
458// Debug information is disabled temporarily to call instruction.
459#if 0
460 instance.getCodeGenOpts().setDebugInfo(clang::codegenoptions::FullDebugInfo);
461#endif
462
463 // We use the 32-bit pointer-width SPIR triple
464 llvm::Triple triple("spir-unknown-unknown");
465
James Price40efe7f2021-01-18 09:19:31 -0500466 // We manually include the OpenCL headers below, so this vector is unused.
467 std::vector<std::string> includes;
468
alan-bakerfec0a472018-11-08 18:09:40 -0500469 instance.getInvocation().setLangDefaults(
alan-bakerd354f1a2019-08-06 15:41:55 -0400470 instance.getLangOpts(), clang::InputKind(clang::Language::OpenCL), triple,
James Price40efe7f2021-01-18 09:19:31 -0500471 includes, standard);
alan-bakerfec0a472018-11-08 18:09:40 -0500472
473 // Override the C99 inline semantics to accommodate for more OpenCL C
474 // programs in the wild.
475 instance.getLangOpts().GNUInline = true;
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100476
477 // Set up diagnostics
alan-bakerfec0a472018-11-08 18:09:40 -0500478 instance.createDiagnostics(
479 new clang::TextDiagnosticPrinter(*diagnosticsStream,
480 &instance.getDiagnosticOpts()),
481 true);
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100482 instance.getDiagnostics().setWarningsAsErrors(WarningsAsErrors);
483 instance.getDiagnostics().setEnableAllWarnings(true);
alan-bakerfec0a472018-11-08 18:09:40 -0500484
485 instance.getTargetOpts().Triple = triple.str();
486
alan-baker21574d32020-01-29 16:00:31 -0500487 instance.getCodeGenOpts().MainFileName = overiddenInputFilename.str();
alan-bakerfec0a472018-11-08 18:09:40 -0500488 instance.getCodeGenOpts().PreserveVec3Type = true;
489 // Disable generation of lifetime intrinsic.
490 instance.getCodeGenOpts().DisableLifetimeMarkers = true;
491 instance.getFrontendOpts().Inputs.push_back(kernelFile);
alan-bakerf5e5f692018-11-27 08:33:24 -0500492 instance.getPreprocessorOpts().addRemappedFile(overiddenInputFilename,
493 memory_buffer.release());
alan-bakerfec0a472018-11-08 18:09:40 -0500494
495 struct OpenCLBuiltinMemoryBuffer final : public llvm::MemoryBuffer {
496 OpenCLBuiltinMemoryBuffer(const void *data, uint64_t data_length) {
497 const char *dataCasted = reinterpret_cast<const char *>(data);
498 init(dataCasted, dataCasted + data_length, true);
499 }
500
501 virtual llvm::MemoryBuffer::BufferKind getBufferKind() const override {
502 return llvm::MemoryBuffer::MemoryBuffer_Malloc;
503 }
504
505 virtual ~OpenCLBuiltinMemoryBuffer() override {}
506 };
507
508 std::unique_ptr<llvm::MemoryBuffer> openCLBuiltinMemoryBuffer(
509 new OpenCLBuiltinMemoryBuffer(opencl_builtins_header_data,
510 opencl_builtins_header_size - 1));
511
James Price40efe7f2021-01-18 09:19:31 -0500512 instance.getPreprocessorOpts().Includes.push_back("opencl-c.h");
alan-bakerfec0a472018-11-08 18:09:40 -0500513
alan-bakerf3bce4a2019-06-28 16:01:15 -0400514 std::unique_ptr<llvm::MemoryBuffer> openCLBaseBuiltinMemoryBuffer(
515 new OpenCLBuiltinMemoryBuffer(opencl_base_builtins_header_data,
516 opencl_base_builtins_header_size - 1));
517
518 instance.getPreprocessorOpts().Includes.push_back("opencl-c-base.h");
519
alan-bakerfec0a472018-11-08 18:09:40 -0500520 // Add the VULKAN macro.
521 instance.getPreprocessorOpts().addMacroDef("VULKAN=100");
522
523 // Add the __OPENCL_VERSION__ macro.
524 instance.getPreprocessorOpts().addMacroDef("__OPENCL_VERSION__=120");
525
526 instance.setTarget(clang::TargetInfo::CreateTargetInfo(
527 instance.getDiagnostics(),
528 std::make_shared<clang::TargetOptions>(instance.getTargetOpts())));
529
530 instance.createFileManager();
531 instance.createSourceManager(instance.getFileManager());
532
533#ifdef _MSC_VER
534 std::string includePrefix("include\\");
535#else
536 std::string includePrefix("include/");
537#endif
538
539 auto entry = instance.getFileManager().getVirtualFile(
James Price40efe7f2021-01-18 09:19:31 -0500540 includePrefix + "opencl-c.h", openCLBuiltinMemoryBuffer->getBufferSize(),
alan-bakerfec0a472018-11-08 18:09:40 -0500541 0);
542
543 instance.getSourceManager().overrideFileContents(
544 entry, std::move(openCLBuiltinMemoryBuffer));
545
alan-bakerf3bce4a2019-06-28 16:01:15 -0400546 auto base_entry = instance.getFileManager().getVirtualFile(
547 includePrefix + "opencl-c-base.h",
548 openCLBaseBuiltinMemoryBuffer->getBufferSize(), 0);
549
550 instance.getSourceManager().overrideFileContents(
551 base_entry, std::move(openCLBaseBuiltinMemoryBuffer));
552
alan-bakerfec0a472018-11-08 18:09:40 -0500553 return 0;
554}
555
alan-bakerf5e5f692018-11-27 08:33:24 -0500556// Populates |pm| with necessary passes to optimize and legalize the IR.
557int PopulatePassManager(
558 llvm::legacy::PassManager *pm, llvm::raw_svector_ostream *binaryStream,
alan-bakerf5e5f692018-11-27 08:33:24 -0500559 llvm::SmallVectorImpl<std::pair<unsigned, std::string>>
560 *SamplerMapEntries) {
alan-bakerfec0a472018-11-08 18:09:40 -0500561 llvm::PassManagerBuilder pmBuilder;
562
563 switch (OptimizationLevel) {
564 case '0':
alan-bakerf5e5f692018-11-27 08:33:24 -0500565 case '1':
566 case '2':
567 case '3':
568 case 's':
569 case 'z':
570 break;
571 default:
572 llvm::errs() << "Unknown optimization level -O" << OptimizationLevel
573 << " specified!\n";
574 return -1;
575 }
576
577 switch (OptimizationLevel) {
578 case '0':
alan-bakerfec0a472018-11-08 18:09:40 -0500579 pmBuilder.OptLevel = 0;
580 break;
581 case '1':
582 pmBuilder.OptLevel = 1;
583 break;
584 case '2':
585 pmBuilder.OptLevel = 2;
586 break;
587 case '3':
588 pmBuilder.OptLevel = 3;
589 break;
590 case 's':
591 pmBuilder.SizeLevel = 1;
592 break;
593 case 'z':
594 pmBuilder.SizeLevel = 2;
595 break;
596 default:
597 break;
598 }
599
600 pm->add(clspv::createZeroInitializeAllocasPass());
alan-baker04f3a952020-03-24 10:39:53 -0400601 pm->add(clspv::createAddFunctionAttributesPass());
alan-bakerc4579bb2020-04-29 14:15:50 -0400602 pm->add(clspv::createAutoPodArgsPass());
Kévin Petitbbbda972020-03-03 19:16:31 +0000603 pm->add(clspv::createDeclarePushConstantsPass());
alan-bakerfec0a472018-11-08 18:09:40 -0500604 pm->add(clspv::createDefineOpenCLWorkItemBuiltinsPass());
605
606 if (0 < pmBuilder.OptLevel) {
607 pm->add(clspv::createOpenCLInlinerPass());
608 }
609
610 pm->add(clspv::createUndoByvalPass());
611 pm->add(clspv::createUndoSRetPass());
alan-baker9b0ec3c2020-04-06 14:45:34 -0400612 if (clspv::Option::ClusterPodKernelArgs()) {
alan-bakerfec0a472018-11-08 18:09:40 -0500613 pm->add(clspv::createClusterPodKernelArgumentsPass());
614 }
615 pm->add(clspv::createReplaceOpenCLBuiltinPass());
616
Marco Antognini535998c2020-09-16 18:48:51 +0100617 // Lower longer vectors when requested. Note that this pass depends on
618 // ReplaceOpenCLBuiltinPass and expects DeadCodeEliminationPass to be run
619 // afterwards.
620 if (clspv::Option::LongVectorSupport()) {
621 pm->add(clspv::createLongVectorLoweringPass());
622 }
623
alan-bakerfec0a472018-11-08 18:09:40 -0500624 // We need to run mem2reg and inst combine early because our
625 // createInlineFuncWithPointerBitCastArgPass pass cannot handle the pattern
626 // %1 = alloca i32 1
627 // store <something> %1
628 // %2 = bitcast float* %1
629 // %3 = load float %2
630 pm->add(llvm::createPromoteMemoryToRegisterPass());
631
alan-baker1b13e8f2019-08-08 17:56:51 -0400632 // Try to deal with pointer bitcasts early. This can prevent problems like
633 // issue #409 where LLVM is looser about access chain addressing than SPIR-V.
634 // This needs to happen before instcombine and after replacing OpenCL
635 // builtins. This run of the pass will not handle all pointer bitcasts that
636 // could be handled. It should be run again after other optimizations (e.g
637 // InlineFuncWithPointerBitCastArgPass).
638 pm->add(clspv::createSimplifyPointerBitcastPass());
639 pm->add(clspv::createReplacePointerBitcastPass());
640 pm->add(llvm::createDeadCodeEliminationPass());
641
alan-bakerfec0a472018-11-08 18:09:40 -0500642 // Hide loads from __constant address space away from instcombine.
643 // This prevents us from generating select between pointers-to-__constant.
644 // See https://github.com/google/clspv/issues/71
645 pm->add(clspv::createHideConstantLoadsPass());
646
647 pm->add(llvm::createInstructionCombiningPass());
648
649 if (clspv::Option::InlineEntryPoints()) {
650 pm->add(clspv::createInlineEntryPointsPass());
651 } else {
652 pm->add(clspv::createInlineFuncWithPointerBitCastArgPass());
653 pm->add(clspv::createInlineFuncWithPointerToFunctionArgPass());
654 pm->add(clspv::createInlineFuncWithSingleCallSitePass());
655 }
656
Kévin Petitf0515712020-01-07 18:29:20 +0000657 if (clspv::Option::LanguageUsesGenericAddressSpace()) {
Kévin Petit38c52482019-05-07 20:28:00 +0800658 pm->add(llvm::createInferAddressSpacesPass(clspv::AddressSpace::Generic));
Kévin Petit0fc88042019-04-09 23:25:02 +0100659 }
660
alan-bakerfec0a472018-11-08 18:09:40 -0500661 if (0 == pmBuilder.OptLevel) {
662 // Mem2Reg pass should be run early because O0 level optimization leaves
663 // redundant alloca, load and store instructions from function arguments.
664 // clspv needs to remove them ahead of transformation.
665 pm->add(llvm::createPromoteMemoryToRegisterPass());
666
667 // SROA pass is run because it will fold structs/unions that are problematic
668 // on Vulkan SPIR-V away.
669 pm->add(llvm::createSROAPass());
670
671 // InstructionCombining pass folds bitcast and gep instructions which are
672 // not supported by Vulkan SPIR-V.
673 pm->add(llvm::createInstructionCombiningPass());
674 }
675
676 // Now we add any of the LLVM optimizations we wanted
677 pmBuilder.populateModulePassManager(*pm);
678
alan-bakerb5e74d62020-04-07 20:38:05 -0400679 // No point attempting to handle freeze currently so strip them from the IR.
680 pm->add(clspv::createStripFreezePass());
681
alan-bakerfec0a472018-11-08 18:09:40 -0500682 // Unhide loads from __constant address space. Undoes the action of
683 // HideConstantLoadsPass.
684 pm->add(clspv::createUnhideConstantLoadsPass());
685
alan-baker13568382020-04-02 17:29:27 -0400686 pm->add(clspv::createUndoInstCombinePass());
alan-bakerfec0a472018-11-08 18:09:40 -0500687 pm->add(clspv::createFunctionInternalizerPass());
688 pm->add(clspv::createReplaceLLVMIntrinsicsPass());
alan-bakerad1a12f2020-08-25 09:18:38 -0400689 // Replace LLVM intrinsics can leave dead code around.
690 pm->add(llvm::createDeadCodeEliminationPass());
alan-bakerfec0a472018-11-08 18:09:40 -0500691 pm->add(clspv::createUndoBoolPass());
alan-bakere711c762020-05-20 17:56:59 -0400692 pm->add(clspv::createUndoTruncateToOddIntegerPass());
alan-bakerfec0a472018-11-08 18:09:40 -0500693 pm->add(llvm::createStructurizeCFGPass(false));
alan-baker3fa76d92018-11-12 14:54:40 -0500694 // Must be run after structurize cfg.
alan-baker9580aef2020-01-07 22:31:48 -0500695 pm->add(clspv::createFixupStructuredCFGPass());
696 // Must be run after structured cfg fixup.
alan-bakerfec0a472018-11-08 18:09:40 -0500697 pm->add(clspv::createReorderBasicBlocksPass());
698 pm->add(clspv::createUndoGetElementPtrConstantExprPass());
699 pm->add(clspv::createSplatArgPass());
700 pm->add(clspv::createSimplifyPointerBitcastPass());
701 pm->add(clspv::createReplacePointerBitcastPass());
702
703 pm->add(clspv::createUndoTranslateSamplerFoldPass());
704
705 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
706 pm->add(clspv::createClusterModuleScopeConstantVars());
707 }
708
709 pm->add(clspv::createShareModuleScopeVariablesPass());
alan-bakerf67468c2019-11-25 15:51:49 -0500710 // Specialize images before assigning descriptors to disambiguate the various
711 // types.
712 pm->add(clspv::createSpecializeImageTypesPass());
alan-bakere9308012019-03-15 10:25:13 -0400713 // This should be run after LLVM and OpenCL intrinsics are replaced.
alan-bakerfec0a472018-11-08 18:09:40 -0500714 pm->add(clspv::createAllocateDescriptorsPass(*SamplerMapEntries));
715 pm->add(llvm::createVerifierPass());
716 pm->add(clspv::createDirectResourceAccessPass());
717 // Replacing pointer bitcasts can leave some trivial GEPs
718 // that are easy to remove. Also replace GEPs of GEPS
719 // left by replacing indirect buffer accesses.
720 pm->add(clspv::createSimplifyPointerBitcastPass());
alan-baker4217b322019-03-06 08:56:12 -0500721 // Run after DRA to clean up parameters and help reduce the need for variable
722 // pointers.
723 pm->add(clspv::createRemoveUnusedArgumentsPass());
alan-bakerfec0a472018-11-08 18:09:40 -0500724
725 pm->add(clspv::createSplatSelectConditionPass());
726 pm->add(clspv::createSignedCompareFixupPass());
727 // This pass generates insertions that need to be rewritten.
728 pm->add(clspv::createScalarizePass());
729 pm->add(clspv::createRewriteInsertsPass());
alan-bakera71f1932019-04-11 11:04:34 -0400730 // UBO Transformations
731 if (clspv::Option::ConstantArgsInUniformBuffer() &&
732 !clspv::Option::InlineEntryPoints()) {
733 // MultiVersionUBOFunctionsPass will examine non-kernel functions with UBO
734 // arguments and either multi-version them as necessary or inline them if
735 // multi-versioning cannot be accomplished.
736 pm->add(clspv::createMultiVersionUBOFunctionsPass());
737 // Cleanup passes.
738 // Specialization can blindly generate GEP chains that are easily cleaned up
739 // by SimplifyPointerBitcastPass.
740 pm->add(clspv::createSimplifyPointerBitcastPass());
741 // RemoveUnusedArgumentsPass removes the actual UBO arguments that were
742 // problematic to begin with now that they have no uses.
743 pm->add(clspv::createRemoveUnusedArgumentsPass());
744 // DCE cleans up callers of the specialized functions.
745 pm->add(llvm::createDeadCodeEliminationPass());
746 }
alan-bakerfec0a472018-11-08 18:09:40 -0500747 // This pass mucks with types to point where you shouldn't rely on DataLayout
748 // anymore so leave this right before SPIR-V generation.
749 pm->add(clspv::createUBOTypeTransformPass());
alan-baker86ce19c2020-08-05 13:09:19 -0400750 pm->add(clspv::createSPIRVProducerPass(*binaryStream, *SamplerMapEntries,
alan-baker00e7a582019-06-07 12:54:21 -0400751 OutputFormat == "c"));
alan-bakerf5e5f692018-11-27 08:33:24 -0500752
753 return 0;
alan-bakerfec0a472018-11-08 18:09:40 -0500754}
alan-bakerfec0a472018-11-08 18:09:40 -0500755
Kévin Petitd5db2d22019-04-04 13:55:14 +0100756int ParseOptions(const int argc, const char *const argv[]) {
alan-baker227e9782020-06-02 15:35:37 -0400757 // We need to change how some of the called passes works by spoofing
758 // ParseCommandLineOptions with the specific options.
759 bool has_pre = false;
760 bool has_load_pre = false;
761 const std::string pre = "-enable-pre";
762 const std::string load_pre = "-enable-load-pre";
763 for (int i = 1; i < argc; ++i) {
764 std::string option(argv[i]);
765 auto pre_pos = option.find(pre);
766 auto load_pos = option.find(load_pre);
767 if (pre_pos == 0 || (pre_pos == 1 && option[0] == '-')) {
768 has_pre = true;
769 } else if (load_pos == 0 || (load_pos == 1 && option[0] == '-')) {
770 has_load_pre = true;
771 }
772 }
773
774 int llvmArgc = 2;
775 const char *llvmArgv[4];
776 llvmArgv[0] = argv[0];
777 llvmArgv[1] = "-simplifycfg-sink-common=false";
778 if (!has_pre) {
779 llvmArgv[llvmArgc++] = "-enable-pre=0";
780 }
781 if (!has_load_pre) {
782 llvmArgv[llvmArgc++] = "-enable-load-pre=0";
783 }
alan-bakerfec0a472018-11-08 18:09:40 -0500784
Kévin Petitd5db2d22019-04-04 13:55:14 +0100785 llvm::cl::ResetAllOptionOccurrences();
alan-bakerfec0a472018-11-08 18:09:40 -0500786 llvm::cl::ParseCommandLineOptions(llvmArgc, llvmArgv);
alan-bakerfec0a472018-11-08 18:09:40 -0500787 llvm::cl::ParseCommandLineOptions(argc, argv);
788
Kévin Petitf0515712020-01-07 18:29:20 +0000789 if (clspv::Option::LanguageUsesGenericAddressSpace() &&
790 !clspv::Option::InlineEntryPoints()) {
791 llvm::errs() << "cannot compile languages that use the generic address "
792 "space (e.g. CLC++, CL2.0) without -inline-entry-points\n";
Kévin Petit0fc88042019-04-09 23:25:02 +0100793 return -1;
794 }
795
Kévin Petitbbbda972020-03-03 19:16:31 +0000796 if (clspv::Option::ScalarBlockLayout()) {
797 llvm::errs() << "scalar block layout support unimplemented\n";
798 return -1;
799 }
800
alan-baker9b0ec3c2020-04-06 14:45:34 -0400801 // Push constant option validation.
802 if (clspv::Option::PodArgsInPushConstants()) {
803 if (clspv::Option::PodArgsInUniformBuffer()) {
804 llvm::errs() << "POD arguments can only be in either uniform buffers or "
805 "push constants\n";
806 return -1;
807 }
808
809 if (!clspv::Option::ClusterPodKernelArgs()) {
810 llvm::errs()
811 << "POD arguments must be clustered to be passed as push constants\n";
812 return -1;
813 }
814
815 // Conservatively error if a module scope push constant could be used.
James Price708cf362020-05-06 19:33:45 -0400816 if (clspv::Option::GlobalOffsetPushConstant() ||
alan-baker9b0ec3c2020-04-06 14:45:34 -0400817 clspv::Option::Language() ==
818 clspv::Option::SourceLanguage::OpenCL_C_20 ||
819 clspv::Option::Language() ==
820 clspv::Option::SourceLanguage::OpenCL_CPP) {
821 llvm::errs() << "POD arguments as push constants are not compatible with "
822 "module scope push constants\n";
823 return -1;
824 }
825 }
826
Kévin Petitd5db2d22019-04-04 13:55:14 +0100827 return 0;
828}
Diego Novillo89500852019-04-15 08:45:10 -0400829
830int GenerateIRFile(llvm::legacy::PassManager *pm, llvm::Module &module,
831 std::string output) {
832 std::error_code ec;
833 std::unique_ptr<llvm::ToolOutputFile> out(
834 new llvm::ToolOutputFile(output, ec, llvm::sys::fs::F_None));
835 if (ec) {
836 llvm::errs() << output << ": " << ec.message() << '\n';
837 return -1;
838 }
839 pm->add(llvm::createPrintModulePass(out->os(), "", false));
840 pm->run(module);
841 out->keep();
842 return 0;
843}
844
Kévin Petitd5db2d22019-04-04 13:55:14 +0100845} // namespace
846
847namespace clspv {
848int Compile(const int argc, const char *const argv[]) {
849
850 if (auto error = ParseOptions(argc, argv))
851 return error;
852
alan-bakerfec0a472018-11-08 18:09:40 -0500853 llvm::SmallVector<std::pair<unsigned, std::string>, 8> SamplerMapEntries;
alan-bakerf5e5f692018-11-27 08:33:24 -0500854 if (auto error = ParseSamplerMap("", &SamplerMapEntries))
alan-bakerfec0a472018-11-08 18:09:40 -0500855 return error;
856
857 // if no output file was provided, use a default
858 llvm::StringRef overiddenInputFilename = InputFilename.getValue();
859
860 // If we are reading our input file from stdin.
861 if ("-" == InputFilename) {
862 // We need to overwrite the file name we use.
Kévin Petitddad8f42019-09-30 15:12:08 +0100863 switch (InputLanguage) {
864 case clang::Language::OpenCL:
865 overiddenInputFilename = "stdin.cl";
866 break;
867 case clang::Language::LLVM_IR:
868 overiddenInputFilename = "stdin.ll";
869 break;
alan-baker31298a62019-10-07 13:24:30 -0400870 default:
871 // Default to fix compiler warnings/errors. Option parsing will reject a
872 // bad enum value for the option so there is no need for a message.
873 return -1;
Kévin Petitddad8f42019-09-30 15:12:08 +0100874 }
alan-bakerfec0a472018-11-08 18:09:40 -0500875 }
876
877 clang::CompilerInstance instance;
Kévin Petitddad8f42019-09-30 15:12:08 +0100878 clang::FrontendInputFile kernelFile(overiddenInputFilename,
879 clang::InputKind(InputLanguage));
alan-bakerfec0a472018-11-08 18:09:40 -0500880 std::string log;
881 llvm::raw_string_ostream diagnosticsStream(log);
alan-bakerf5e5f692018-11-27 08:33:24 -0500882 if (auto error = SetCompilerInstanceOptions(
883 instance, overiddenInputFilename, kernelFile, "", &diagnosticsStream))
alan-bakerfec0a472018-11-08 18:09:40 -0500884 return error;
885
886 // Parse.
887 llvm::LLVMContext context;
888 clang::EmitLLVMOnlyAction action(&context);
889
890 // Prepare the action for processing kernelFile
891 const bool success = action.BeginSourceFile(instance, kernelFile);
892 if (!success) {
893 return -1;
894 }
895
alan-bakerf3bce4a2019-06-28 16:01:15 -0400896 auto result = action.Execute();
alan-bakerfec0a472018-11-08 18:09:40 -0500897 action.EndSourceFile();
898
899 clang::DiagnosticConsumer *const consumer =
900 instance.getDiagnostics().getClient();
901 consumer->finish();
902
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100903 auto num_warnings = consumer->getNumWarnings();
alan-bakerfec0a472018-11-08 18:09:40 -0500904 auto num_errors = consumer->getNumErrors();
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100905 if ((num_errors > 0) || (num_warnings > 0)) {
906 llvm::errs() << log;
907 }
alan-bakerf3bce4a2019-06-28 16:01:15 -0400908 if (result || num_errors > 0) {
alan-bakerfec0a472018-11-08 18:09:40 -0500909 return -1;
910 }
911
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100912 // Don't run the passes or produce any output in verify mode.
913 // Clang doesn't always produce a valid module.
914 if (verify) {
915 return 0;
916 }
917
alan-bakerfec0a472018-11-08 18:09:40 -0500918 llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry();
919 llvm::initializeCore(Registry);
920 llvm::initializeScalarOpts(Registry);
Diego Novillo1fcff722019-05-07 13:45:53 -0400921 llvm::initializeClspvPasses(Registry);
alan-bakerfec0a472018-11-08 18:09:40 -0500922
923 std::unique_ptr<llvm::Module> module(action.takeModule());
924
925 // Optimize.
926 // Create a memory buffer for temporarily writing the result.
927 SmallVector<char, 10000> binary;
928 llvm::raw_svector_ostream binaryStream(binary);
alan-bakerfec0a472018-11-08 18:09:40 -0500929 llvm::legacy::PassManager pm;
Diego Novillo89500852019-04-15 08:45:10 -0400930
931 // If --emit-ir was requested, emit the initial LLVM IR and stop compilation.
932 if (!IROutputFile.empty()) {
933 return GenerateIRFile(&pm, *module, IROutputFile);
934 }
935
936 // Otherwise, populate the pass manager and run the regular passes.
alan-baker86ce19c2020-08-05 13:09:19 -0400937 if (auto error = PopulatePassManager(&pm, &binaryStream, &SamplerMapEntries))
alan-bakerf5e5f692018-11-27 08:33:24 -0500938 return error;
alan-bakerfec0a472018-11-08 18:09:40 -0500939 pm.run(*module);
940
941 // Write outputs
alan-bakerfec0a472018-11-08 18:09:40 -0500942 std::error_code error;
alan-bakerfec0a472018-11-08 18:09:40 -0500943
944 // Write the resulting binary.
945 // Wait until now to try writing the file so that we only write it on
946 // successful compilation.
947 if (OutputFilename.empty()) {
Kévin Petite4786902019-04-02 21:51:47 +0100948 if (OutputFormat == "c") {
alan-bakerfec0a472018-11-08 18:09:40 -0500949 OutputFilename = "a.spvinc";
950 } else {
951 OutputFilename = "a.spv";
952 }
953 }
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400954 llvm::raw_fd_ostream outStream(OutputFilename, error,
955 llvm::sys::fs::FA_Write);
alan-bakerfec0a472018-11-08 18:09:40 -0500956
957 if (error) {
958 llvm::errs() << "Unable to open output file '" << OutputFilename
959 << "': " << error.message() << '\n';
960 return -1;
961 }
962 outStream << binaryStream.str();
963
964 return 0;
965}
alan-bakerf5e5f692018-11-27 08:33:24 -0500966
alan-baker86ce19c2020-08-05 13:09:19 -0400967int CompileFromSourceString(const std::string &program,
968 const std::string &sampler_map,
969 const std::string &options,
Kévin Petit899162d2020-09-08 19:16:08 +0100970 std::vector<uint32_t> *output_binary,
971 std::string *output_log) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500972
973 llvm::SmallVector<const char *, 20> argv;
974 llvm::BumpPtrAllocator A;
975 llvm::StringSaver Saver(A);
976 argv.push_back(Saver.save("clspv").data());
977 llvm::cl::TokenizeGNUCommandLine(options, Saver, argv);
978 int argc = static_cast<int>(argv.size());
Kévin Petitd5db2d22019-04-04 13:55:14 +0100979
980 if (auto error = ParseOptions(argc, &argv[0]))
981 return error;
alan-bakerf5e5f692018-11-27 08:33:24 -0500982
983 llvm::SmallVector<std::pair<unsigned, std::string>, 8> SamplerMapEntries;
984 if (auto error = ParseSamplerMap(sampler_map, &SamplerMapEntries))
985 return error;
986
987 InputFilename = "source.cl";
988 llvm::StringRef overiddenInputFilename = InputFilename.getValue();
989
990 clang::CompilerInstance instance;
alan-bakerd354f1a2019-08-06 15:41:55 -0400991 clang::FrontendInputFile kernelFile(
992 overiddenInputFilename, clang::InputKind(clang::Language::OpenCL));
alan-bakerf5e5f692018-11-27 08:33:24 -0500993 std::string log;
994 llvm::raw_string_ostream diagnosticsStream(log);
995 if (auto error =
996 SetCompilerInstanceOptions(instance, overiddenInputFilename,
997 kernelFile, program, &diagnosticsStream))
998 return error;
999
1000 // Parse.
1001 llvm::LLVMContext context;
1002 clang::EmitLLVMOnlyAction action(&context);
1003
1004 // Prepare the action for processing kernelFile
1005 const bool success = action.BeginSourceFile(instance, kernelFile);
1006 if (!success) {
1007 return -1;
1008 }
1009
alan-bakerf3bce4a2019-06-28 16:01:15 -04001010 auto result = action.Execute();
alan-bakerf5e5f692018-11-27 08:33:24 -05001011 action.EndSourceFile();
1012
1013 clang::DiagnosticConsumer *const consumer =
1014 instance.getDiagnostics().getClient();
1015 consumer->finish();
1016
Kévin Petit899162d2020-09-08 19:16:08 +01001017 if (output_log != nullptr) {
1018 *output_log = log;
1019 }
1020
alan-bakerf5e5f692018-11-27 08:33:24 -05001021 auto num_errors = consumer->getNumErrors();
alan-bakerf3bce4a2019-06-28 16:01:15 -04001022 if (result || num_errors > 0) {
alan-bakerf5e5f692018-11-27 08:33:24 -05001023 return -1;
1024 }
1025
alan-bakerf5e5f692018-11-27 08:33:24 -05001026 llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry();
1027 llvm::initializeCore(Registry);
1028 llvm::initializeScalarOpts(Registry);
Diego Novillo1fcff722019-05-07 13:45:53 -04001029 llvm::initializeClspvPasses(Registry);
alan-bakerf5e5f692018-11-27 08:33:24 -05001030
1031 std::unique_ptr<llvm::Module> module(action.takeModule());
1032
1033 // Optimize.
1034 // Create a memory buffer for temporarily writing the result.
1035 SmallVector<char, 10000> binary;
1036 llvm::raw_svector_ostream binaryStream(binary);
alan-bakerf5e5f692018-11-27 08:33:24 -05001037 llvm::legacy::PassManager pm;
alan-baker86ce19c2020-08-05 13:09:19 -04001038 if (auto error = PopulatePassManager(&pm, &binaryStream, &SamplerMapEntries))
alan-bakerf5e5f692018-11-27 08:33:24 -05001039 return error;
1040 pm.run(*module);
1041
alan-bakerf5e5f692018-11-27 08:33:24 -05001042 // Write the resulting binary.
1043 // Wait until now to try writing the file so that we only write it on
1044 // successful compilation.
1045 assert(output_binary && "Valid binary container is required.");
1046 if (!OutputFilename.empty()) {
1047 llvm::outs()
1048 << "Warning: -o is ignored when binary container is provided.\n";
1049 }
1050 output_binary->resize(binary.size() / 4);
1051 memcpy(output_binary->data(), binary.data(), binary.size());
1052
1053 return 0;
1054}
alan-bakerfec0a472018-11-08 18:09:40 -05001055} // namespace clspv