blob: 705b2a6c52a996a1f0b6b8a0c841d26125cf5753 [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;
398 case clspv::Option::SourceLanguage::OpenCL_CPP:
399 standard = clang::LangStandard::lang_openclcpp;
400 break;
401 default:
402 llvm_unreachable("Unknown source language");
Kévin Petit0fc88042019-04-09 23:25:02 +0100403 }
alan-bakerfec0a472018-11-08 18:09:40 -0500404
alan-bakerfec0a472018-11-08 18:09:40 -0500405 instance.getLangOpts().C99 = true;
406 instance.getLangOpts().RTTI = false;
407 instance.getLangOpts().RTTIData = false;
408 instance.getLangOpts().MathErrno = false;
409 instance.getLangOpts().Optimize = false;
410 instance.getLangOpts().NoBuiltin = true;
411 instance.getLangOpts().ModulesSearchAll = false;
412 instance.getLangOpts().SinglePrecisionConstants = true;
413 instance.getCodeGenOpts().StackRealignment = true;
414 instance.getCodeGenOpts().SimplifyLibCalls = false;
415 instance.getCodeGenOpts().EmitOpenCLArgMetadata = false;
416 instance.getCodeGenOpts().DisableO0ImplyOptNone = true;
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100417 instance.getDiagnosticOpts().IgnoreWarnings = IgnoreWarnings;
alan-bakerfec0a472018-11-08 18:09:40 -0500418
419 instance.getLangOpts().SinglePrecisionConstants =
420 cl_single_precision_constants;
421 // cl_denorms_are_zero ignored for now!
422 // cl_fp32_correctly_rounded_divide_sqrt ignored for now!
423 instance.getCodeGenOpts().LessPreciseFPMAD =
424 cl_mad_enable || cl_unsafe_math_optimizations;
425 // cl_no_signed_zeros ignored for now!
alan-baker0f814cd2020-06-02 15:35:14 -0400426 instance.getLangOpts().UnsafeFPMath =
alan-bakerfec0a472018-11-08 18:09:40 -0500427 cl_unsafe_math_optimizations || cl_fast_relaxed_math;
428 instance.getLangOpts().FiniteMathOnly =
429 cl_finite_math_only || cl_fast_relaxed_math;
430 instance.getLangOpts().FastRelaxedMath = cl_fast_relaxed_math;
431
432 // Preprocessor options
Kévin Petita624c0c2019-05-07 20:27:43 +0800433 if (!clspv::Option::ImageSupport()) {
434 instance.getPreprocessorOpts().addMacroUndef("__IMAGE_SUPPORT__");
435 }
alan-bakerfec0a472018-11-08 18:09:40 -0500436 if (cl_fast_relaxed_math) {
437 instance.getPreprocessorOpts().addMacroDef("__FAST_RELAXED_MATH__");
438 }
439
440 for (auto define : Defines) {
441 instance.getPreprocessorOpts().addMacroDef(define);
442 }
443
444 // Header search options
445 for (auto include : Includes) {
446 instance.getHeaderSearchOpts().AddPath(include, clang::frontend::After,
447 false, false);
448 }
449
450 // We always compile on opt 0 so we preserve as much debug information about
451 // the source as possible. We'll run optimization later, once we've had a
452 // chance to view the unoptimal code first
453 instance.getCodeGenOpts().OptimizationLevel = 0;
454
455// Debug information is disabled temporarily to call instruction.
456#if 0
457 instance.getCodeGenOpts().setDebugInfo(clang::codegenoptions::FullDebugInfo);
458#endif
459
460 // We use the 32-bit pointer-width SPIR triple
461 llvm::Triple triple("spir-unknown-unknown");
462
463 instance.getInvocation().setLangDefaults(
alan-bakerd354f1a2019-08-06 15:41:55 -0400464 instance.getLangOpts(), clang::InputKind(clang::Language::OpenCL), triple,
alan-bakerfec0a472018-11-08 18:09:40 -0500465 instance.getPreprocessorOpts(), standard);
466
467 // Override the C99 inline semantics to accommodate for more OpenCL C
468 // programs in the wild.
469 instance.getLangOpts().GNUInline = true;
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100470
471 // Set up diagnostics
alan-bakerfec0a472018-11-08 18:09:40 -0500472 instance.createDiagnostics(
473 new clang::TextDiagnosticPrinter(*diagnosticsStream,
474 &instance.getDiagnosticOpts()),
475 true);
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100476 instance.getDiagnostics().setWarningsAsErrors(WarningsAsErrors);
477 instance.getDiagnostics().setEnableAllWarnings(true);
alan-bakerfec0a472018-11-08 18:09:40 -0500478
479 instance.getTargetOpts().Triple = triple.str();
480
alan-baker21574d32020-01-29 16:00:31 -0500481 instance.getCodeGenOpts().MainFileName = overiddenInputFilename.str();
alan-bakerfec0a472018-11-08 18:09:40 -0500482 instance.getCodeGenOpts().PreserveVec3Type = true;
483 // Disable generation of lifetime intrinsic.
484 instance.getCodeGenOpts().DisableLifetimeMarkers = true;
485 instance.getFrontendOpts().Inputs.push_back(kernelFile);
alan-bakerf5e5f692018-11-27 08:33:24 -0500486 instance.getPreprocessorOpts().addRemappedFile(overiddenInputFilename,
487 memory_buffer.release());
alan-bakerfec0a472018-11-08 18:09:40 -0500488
489 struct OpenCLBuiltinMemoryBuffer final : public llvm::MemoryBuffer {
490 OpenCLBuiltinMemoryBuffer(const void *data, uint64_t data_length) {
491 const char *dataCasted = reinterpret_cast<const char *>(data);
492 init(dataCasted, dataCasted + data_length, true);
493 }
494
495 virtual llvm::MemoryBuffer::BufferKind getBufferKind() const override {
496 return llvm::MemoryBuffer::MemoryBuffer_Malloc;
497 }
498
499 virtual ~OpenCLBuiltinMemoryBuffer() override {}
500 };
501
502 std::unique_ptr<llvm::MemoryBuffer> openCLBuiltinMemoryBuffer(
503 new OpenCLBuiltinMemoryBuffer(opencl_builtins_header_data,
504 opencl_builtins_header_size - 1));
505
506 instance.getPreprocessorOpts().Includes.push_back("openclc.h");
507
alan-bakerf3bce4a2019-06-28 16:01:15 -0400508 std::unique_ptr<llvm::MemoryBuffer> openCLBaseBuiltinMemoryBuffer(
509 new OpenCLBuiltinMemoryBuffer(opencl_base_builtins_header_data,
510 opencl_base_builtins_header_size - 1));
511
512 instance.getPreprocessorOpts().Includes.push_back("opencl-c-base.h");
513
alan-bakerfec0a472018-11-08 18:09:40 -0500514 // Add the VULKAN macro.
515 instance.getPreprocessorOpts().addMacroDef("VULKAN=100");
516
517 // Add the __OPENCL_VERSION__ macro.
518 instance.getPreprocessorOpts().addMacroDef("__OPENCL_VERSION__=120");
519
520 instance.setTarget(clang::TargetInfo::CreateTargetInfo(
521 instance.getDiagnostics(),
522 std::make_shared<clang::TargetOptions>(instance.getTargetOpts())));
523
524 instance.createFileManager();
525 instance.createSourceManager(instance.getFileManager());
526
527#ifdef _MSC_VER
528 std::string includePrefix("include\\");
529#else
530 std::string includePrefix("include/");
531#endif
532
533 auto entry = instance.getFileManager().getVirtualFile(
534 includePrefix + "openclc.h", openCLBuiltinMemoryBuffer->getBufferSize(),
535 0);
536
537 instance.getSourceManager().overrideFileContents(
538 entry, std::move(openCLBuiltinMemoryBuffer));
539
alan-bakerf3bce4a2019-06-28 16:01:15 -0400540 auto base_entry = instance.getFileManager().getVirtualFile(
541 includePrefix + "opencl-c-base.h",
542 openCLBaseBuiltinMemoryBuffer->getBufferSize(), 0);
543
544 instance.getSourceManager().overrideFileContents(
545 base_entry, std::move(openCLBaseBuiltinMemoryBuffer));
546
alan-bakerfec0a472018-11-08 18:09:40 -0500547 return 0;
548}
549
alan-bakerf5e5f692018-11-27 08:33:24 -0500550// Populates |pm| with necessary passes to optimize and legalize the IR.
551int PopulatePassManager(
552 llvm::legacy::PassManager *pm, llvm::raw_svector_ostream *binaryStream,
alan-bakerf5e5f692018-11-27 08:33:24 -0500553 llvm::SmallVectorImpl<std::pair<unsigned, std::string>>
554 *SamplerMapEntries) {
alan-bakerfec0a472018-11-08 18:09:40 -0500555 llvm::PassManagerBuilder pmBuilder;
556
557 switch (OptimizationLevel) {
558 case '0':
alan-bakerf5e5f692018-11-27 08:33:24 -0500559 case '1':
560 case '2':
561 case '3':
562 case 's':
563 case 'z':
564 break;
565 default:
566 llvm::errs() << "Unknown optimization level -O" << OptimizationLevel
567 << " specified!\n";
568 return -1;
569 }
570
571 switch (OptimizationLevel) {
572 case '0':
alan-bakerfec0a472018-11-08 18:09:40 -0500573 pmBuilder.OptLevel = 0;
574 break;
575 case '1':
576 pmBuilder.OptLevel = 1;
577 break;
578 case '2':
579 pmBuilder.OptLevel = 2;
580 break;
581 case '3':
582 pmBuilder.OptLevel = 3;
583 break;
584 case 's':
585 pmBuilder.SizeLevel = 1;
586 break;
587 case 'z':
588 pmBuilder.SizeLevel = 2;
589 break;
590 default:
591 break;
592 }
593
594 pm->add(clspv::createZeroInitializeAllocasPass());
alan-baker04f3a952020-03-24 10:39:53 -0400595 pm->add(clspv::createAddFunctionAttributesPass());
alan-bakerc4579bb2020-04-29 14:15:50 -0400596 pm->add(clspv::createAutoPodArgsPass());
Kévin Petitbbbda972020-03-03 19:16:31 +0000597 pm->add(clspv::createDeclarePushConstantsPass());
alan-bakerfec0a472018-11-08 18:09:40 -0500598 pm->add(clspv::createDefineOpenCLWorkItemBuiltinsPass());
599
600 if (0 < pmBuilder.OptLevel) {
601 pm->add(clspv::createOpenCLInlinerPass());
602 }
603
604 pm->add(clspv::createUndoByvalPass());
605 pm->add(clspv::createUndoSRetPass());
alan-baker9b0ec3c2020-04-06 14:45:34 -0400606 if (clspv::Option::ClusterPodKernelArgs()) {
alan-bakerfec0a472018-11-08 18:09:40 -0500607 pm->add(clspv::createClusterPodKernelArgumentsPass());
608 }
609 pm->add(clspv::createReplaceOpenCLBuiltinPass());
610
Marco Antognini535998c2020-09-16 18:48:51 +0100611 // Lower longer vectors when requested. Note that this pass depends on
612 // ReplaceOpenCLBuiltinPass and expects DeadCodeEliminationPass to be run
613 // afterwards.
614 if (clspv::Option::LongVectorSupport()) {
615 pm->add(clspv::createLongVectorLoweringPass());
616 }
617
alan-bakerfec0a472018-11-08 18:09:40 -0500618 // We need to run mem2reg and inst combine early because our
619 // createInlineFuncWithPointerBitCastArgPass pass cannot handle the pattern
620 // %1 = alloca i32 1
621 // store <something> %1
622 // %2 = bitcast float* %1
623 // %3 = load float %2
624 pm->add(llvm::createPromoteMemoryToRegisterPass());
625
alan-baker1b13e8f2019-08-08 17:56:51 -0400626 // Try to deal with pointer bitcasts early. This can prevent problems like
627 // issue #409 where LLVM is looser about access chain addressing than SPIR-V.
628 // This needs to happen before instcombine and after replacing OpenCL
629 // builtins. This run of the pass will not handle all pointer bitcasts that
630 // could be handled. It should be run again after other optimizations (e.g
631 // InlineFuncWithPointerBitCastArgPass).
632 pm->add(clspv::createSimplifyPointerBitcastPass());
633 pm->add(clspv::createReplacePointerBitcastPass());
634 pm->add(llvm::createDeadCodeEliminationPass());
635
alan-bakerfec0a472018-11-08 18:09:40 -0500636 // Hide loads from __constant address space away from instcombine.
637 // This prevents us from generating select between pointers-to-__constant.
638 // See https://github.com/google/clspv/issues/71
639 pm->add(clspv::createHideConstantLoadsPass());
640
641 pm->add(llvm::createInstructionCombiningPass());
642
643 if (clspv::Option::InlineEntryPoints()) {
644 pm->add(clspv::createInlineEntryPointsPass());
645 } else {
646 pm->add(clspv::createInlineFuncWithPointerBitCastArgPass());
647 pm->add(clspv::createInlineFuncWithPointerToFunctionArgPass());
648 pm->add(clspv::createInlineFuncWithSingleCallSitePass());
649 }
650
Kévin Petitf0515712020-01-07 18:29:20 +0000651 if (clspv::Option::LanguageUsesGenericAddressSpace()) {
Kévin Petit38c52482019-05-07 20:28:00 +0800652 pm->add(llvm::createInferAddressSpacesPass(clspv::AddressSpace::Generic));
Kévin Petit0fc88042019-04-09 23:25:02 +0100653 }
654
alan-bakerfec0a472018-11-08 18:09:40 -0500655 if (0 == pmBuilder.OptLevel) {
656 // Mem2Reg pass should be run early because O0 level optimization leaves
657 // redundant alloca, load and store instructions from function arguments.
658 // clspv needs to remove them ahead of transformation.
659 pm->add(llvm::createPromoteMemoryToRegisterPass());
660
661 // SROA pass is run because it will fold structs/unions that are problematic
662 // on Vulkan SPIR-V away.
663 pm->add(llvm::createSROAPass());
664
665 // InstructionCombining pass folds bitcast and gep instructions which are
666 // not supported by Vulkan SPIR-V.
667 pm->add(llvm::createInstructionCombiningPass());
668 }
669
670 // Now we add any of the LLVM optimizations we wanted
671 pmBuilder.populateModulePassManager(*pm);
672
alan-bakerb5e74d62020-04-07 20:38:05 -0400673 // No point attempting to handle freeze currently so strip them from the IR.
674 pm->add(clspv::createStripFreezePass());
675
alan-bakerfec0a472018-11-08 18:09:40 -0500676 // Unhide loads from __constant address space. Undoes the action of
677 // HideConstantLoadsPass.
678 pm->add(clspv::createUnhideConstantLoadsPass());
679
alan-baker13568382020-04-02 17:29:27 -0400680 pm->add(clspv::createUndoInstCombinePass());
alan-bakerfec0a472018-11-08 18:09:40 -0500681 pm->add(clspv::createFunctionInternalizerPass());
682 pm->add(clspv::createReplaceLLVMIntrinsicsPass());
alan-bakerad1a12f2020-08-25 09:18:38 -0400683 // Replace LLVM intrinsics can leave dead code around.
684 pm->add(llvm::createDeadCodeEliminationPass());
alan-bakerfec0a472018-11-08 18:09:40 -0500685 pm->add(clspv::createUndoBoolPass());
alan-bakere711c762020-05-20 17:56:59 -0400686 pm->add(clspv::createUndoTruncateToOddIntegerPass());
alan-bakerfec0a472018-11-08 18:09:40 -0500687 pm->add(llvm::createStructurizeCFGPass(false));
alan-baker3fa76d92018-11-12 14:54:40 -0500688 // Must be run after structurize cfg.
alan-baker9580aef2020-01-07 22:31:48 -0500689 pm->add(clspv::createFixupStructuredCFGPass());
690 // Must be run after structured cfg fixup.
alan-bakerfec0a472018-11-08 18:09:40 -0500691 pm->add(clspv::createReorderBasicBlocksPass());
692 pm->add(clspv::createUndoGetElementPtrConstantExprPass());
693 pm->add(clspv::createSplatArgPass());
694 pm->add(clspv::createSimplifyPointerBitcastPass());
695 pm->add(clspv::createReplacePointerBitcastPass());
696
697 pm->add(clspv::createUndoTranslateSamplerFoldPass());
698
699 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
700 pm->add(clspv::createClusterModuleScopeConstantVars());
701 }
702
703 pm->add(clspv::createShareModuleScopeVariablesPass());
alan-bakerf67468c2019-11-25 15:51:49 -0500704 // Specialize images before assigning descriptors to disambiguate the various
705 // types.
706 pm->add(clspv::createSpecializeImageTypesPass());
alan-bakere9308012019-03-15 10:25:13 -0400707 // This should be run after LLVM and OpenCL intrinsics are replaced.
alan-bakerfec0a472018-11-08 18:09:40 -0500708 pm->add(clspv::createAllocateDescriptorsPass(*SamplerMapEntries));
709 pm->add(llvm::createVerifierPass());
710 pm->add(clspv::createDirectResourceAccessPass());
711 // Replacing pointer bitcasts can leave some trivial GEPs
712 // that are easy to remove. Also replace GEPs of GEPS
713 // left by replacing indirect buffer accesses.
714 pm->add(clspv::createSimplifyPointerBitcastPass());
alan-baker4217b322019-03-06 08:56:12 -0500715 // Run after DRA to clean up parameters and help reduce the need for variable
716 // pointers.
717 pm->add(clspv::createRemoveUnusedArgumentsPass());
alan-bakerfec0a472018-11-08 18:09:40 -0500718
719 pm->add(clspv::createSplatSelectConditionPass());
720 pm->add(clspv::createSignedCompareFixupPass());
721 // This pass generates insertions that need to be rewritten.
722 pm->add(clspv::createScalarizePass());
723 pm->add(clspv::createRewriteInsertsPass());
alan-bakera71f1932019-04-11 11:04:34 -0400724 // UBO Transformations
725 if (clspv::Option::ConstantArgsInUniformBuffer() &&
726 !clspv::Option::InlineEntryPoints()) {
727 // MultiVersionUBOFunctionsPass will examine non-kernel functions with UBO
728 // arguments and either multi-version them as necessary or inline them if
729 // multi-versioning cannot be accomplished.
730 pm->add(clspv::createMultiVersionUBOFunctionsPass());
731 // Cleanup passes.
732 // Specialization can blindly generate GEP chains that are easily cleaned up
733 // by SimplifyPointerBitcastPass.
734 pm->add(clspv::createSimplifyPointerBitcastPass());
735 // RemoveUnusedArgumentsPass removes the actual UBO arguments that were
736 // problematic to begin with now that they have no uses.
737 pm->add(clspv::createRemoveUnusedArgumentsPass());
738 // DCE cleans up callers of the specialized functions.
739 pm->add(llvm::createDeadCodeEliminationPass());
740 }
alan-bakerfec0a472018-11-08 18:09:40 -0500741 // This pass mucks with types to point where you shouldn't rely on DataLayout
742 // anymore so leave this right before SPIR-V generation.
743 pm->add(clspv::createUBOTypeTransformPass());
alan-baker86ce19c2020-08-05 13:09:19 -0400744 pm->add(clspv::createSPIRVProducerPass(*binaryStream, *SamplerMapEntries,
alan-baker00e7a582019-06-07 12:54:21 -0400745 OutputFormat == "c"));
alan-bakerf5e5f692018-11-27 08:33:24 -0500746
747 return 0;
alan-bakerfec0a472018-11-08 18:09:40 -0500748}
alan-bakerfec0a472018-11-08 18:09:40 -0500749
Kévin Petitd5db2d22019-04-04 13:55:14 +0100750int ParseOptions(const int argc, const char *const argv[]) {
alan-baker227e9782020-06-02 15:35:37 -0400751 // We need to change how some of the called passes works by spoofing
752 // ParseCommandLineOptions with the specific options.
753 bool has_pre = false;
754 bool has_load_pre = false;
755 const std::string pre = "-enable-pre";
756 const std::string load_pre = "-enable-load-pre";
757 for (int i = 1; i < argc; ++i) {
758 std::string option(argv[i]);
759 auto pre_pos = option.find(pre);
760 auto load_pos = option.find(load_pre);
761 if (pre_pos == 0 || (pre_pos == 1 && option[0] == '-')) {
762 has_pre = true;
763 } else if (load_pos == 0 || (load_pos == 1 && option[0] == '-')) {
764 has_load_pre = true;
765 }
766 }
767
768 int llvmArgc = 2;
769 const char *llvmArgv[4];
770 llvmArgv[0] = argv[0];
771 llvmArgv[1] = "-simplifycfg-sink-common=false";
772 if (!has_pre) {
773 llvmArgv[llvmArgc++] = "-enable-pre=0";
774 }
775 if (!has_load_pre) {
776 llvmArgv[llvmArgc++] = "-enable-load-pre=0";
777 }
alan-bakerfec0a472018-11-08 18:09:40 -0500778
Kévin Petitd5db2d22019-04-04 13:55:14 +0100779 llvm::cl::ResetAllOptionOccurrences();
alan-bakerfec0a472018-11-08 18:09:40 -0500780 llvm::cl::ParseCommandLineOptions(llvmArgc, llvmArgv);
alan-bakerfec0a472018-11-08 18:09:40 -0500781 llvm::cl::ParseCommandLineOptions(argc, argv);
782
Kévin Petitf0515712020-01-07 18:29:20 +0000783 if (clspv::Option::LanguageUsesGenericAddressSpace() &&
784 !clspv::Option::InlineEntryPoints()) {
785 llvm::errs() << "cannot compile languages that use the generic address "
786 "space (e.g. CLC++, CL2.0) without -inline-entry-points\n";
Kévin Petit0fc88042019-04-09 23:25:02 +0100787 return -1;
788 }
789
Kévin Petitbbbda972020-03-03 19:16:31 +0000790 if (clspv::Option::ScalarBlockLayout()) {
791 llvm::errs() << "scalar block layout support unimplemented\n";
792 return -1;
793 }
794
alan-baker9b0ec3c2020-04-06 14:45:34 -0400795 // Push constant option validation.
796 if (clspv::Option::PodArgsInPushConstants()) {
797 if (clspv::Option::PodArgsInUniformBuffer()) {
798 llvm::errs() << "POD arguments can only be in either uniform buffers or "
799 "push constants\n";
800 return -1;
801 }
802
803 if (!clspv::Option::ClusterPodKernelArgs()) {
804 llvm::errs()
805 << "POD arguments must be clustered to be passed as push constants\n";
806 return -1;
807 }
808
809 // Conservatively error if a module scope push constant could be used.
James Price708cf362020-05-06 19:33:45 -0400810 if (clspv::Option::GlobalOffsetPushConstant() ||
alan-baker9b0ec3c2020-04-06 14:45:34 -0400811 clspv::Option::Language() ==
812 clspv::Option::SourceLanguage::OpenCL_C_20 ||
813 clspv::Option::Language() ==
814 clspv::Option::SourceLanguage::OpenCL_CPP) {
815 llvm::errs() << "POD arguments as push constants are not compatible with "
816 "module scope push constants\n";
817 return -1;
818 }
819 }
820
Kévin Petitd5db2d22019-04-04 13:55:14 +0100821 return 0;
822}
Diego Novillo89500852019-04-15 08:45:10 -0400823
824int GenerateIRFile(llvm::legacy::PassManager *pm, llvm::Module &module,
825 std::string output) {
826 std::error_code ec;
827 std::unique_ptr<llvm::ToolOutputFile> out(
828 new llvm::ToolOutputFile(output, ec, llvm::sys::fs::F_None));
829 if (ec) {
830 llvm::errs() << output << ": " << ec.message() << '\n';
831 return -1;
832 }
833 pm->add(llvm::createPrintModulePass(out->os(), "", false));
834 pm->run(module);
835 out->keep();
836 return 0;
837}
838
Kévin Petitd5db2d22019-04-04 13:55:14 +0100839} // namespace
840
841namespace clspv {
842int Compile(const int argc, const char *const argv[]) {
843
844 if (auto error = ParseOptions(argc, argv))
845 return error;
846
alan-bakerfec0a472018-11-08 18:09:40 -0500847 llvm::SmallVector<std::pair<unsigned, std::string>, 8> SamplerMapEntries;
alan-bakerf5e5f692018-11-27 08:33:24 -0500848 if (auto error = ParseSamplerMap("", &SamplerMapEntries))
alan-bakerfec0a472018-11-08 18:09:40 -0500849 return error;
850
851 // if no output file was provided, use a default
852 llvm::StringRef overiddenInputFilename = InputFilename.getValue();
853
854 // If we are reading our input file from stdin.
855 if ("-" == InputFilename) {
856 // We need to overwrite the file name we use.
Kévin Petitddad8f42019-09-30 15:12:08 +0100857 switch (InputLanguage) {
858 case clang::Language::OpenCL:
859 overiddenInputFilename = "stdin.cl";
860 break;
861 case clang::Language::LLVM_IR:
862 overiddenInputFilename = "stdin.ll";
863 break;
alan-baker31298a62019-10-07 13:24:30 -0400864 default:
865 // Default to fix compiler warnings/errors. Option parsing will reject a
866 // bad enum value for the option so there is no need for a message.
867 return -1;
Kévin Petitddad8f42019-09-30 15:12:08 +0100868 }
alan-bakerfec0a472018-11-08 18:09:40 -0500869 }
870
871 clang::CompilerInstance instance;
Kévin Petitddad8f42019-09-30 15:12:08 +0100872 clang::FrontendInputFile kernelFile(overiddenInputFilename,
873 clang::InputKind(InputLanguage));
alan-bakerfec0a472018-11-08 18:09:40 -0500874 std::string log;
875 llvm::raw_string_ostream diagnosticsStream(log);
alan-bakerf5e5f692018-11-27 08:33:24 -0500876 if (auto error = SetCompilerInstanceOptions(
877 instance, overiddenInputFilename, kernelFile, "", &diagnosticsStream))
alan-bakerfec0a472018-11-08 18:09:40 -0500878 return error;
879
880 // Parse.
881 llvm::LLVMContext context;
882 clang::EmitLLVMOnlyAction action(&context);
883
884 // Prepare the action for processing kernelFile
885 const bool success = action.BeginSourceFile(instance, kernelFile);
886 if (!success) {
887 return -1;
888 }
889
alan-bakerf3bce4a2019-06-28 16:01:15 -0400890 auto result = action.Execute();
alan-bakerfec0a472018-11-08 18:09:40 -0500891 action.EndSourceFile();
892
893 clang::DiagnosticConsumer *const consumer =
894 instance.getDiagnostics().getClient();
895 consumer->finish();
896
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100897 auto num_warnings = consumer->getNumWarnings();
alan-bakerfec0a472018-11-08 18:09:40 -0500898 auto num_errors = consumer->getNumErrors();
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100899 if ((num_errors > 0) || (num_warnings > 0)) {
900 llvm::errs() << log;
901 }
alan-bakerf3bce4a2019-06-28 16:01:15 -0400902 if (result || num_errors > 0) {
alan-bakerfec0a472018-11-08 18:09:40 -0500903 return -1;
904 }
905
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100906 // Don't run the passes or produce any output in verify mode.
907 // Clang doesn't always produce a valid module.
908 if (verify) {
909 return 0;
910 }
911
alan-bakerfec0a472018-11-08 18:09:40 -0500912 llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry();
913 llvm::initializeCore(Registry);
914 llvm::initializeScalarOpts(Registry);
Diego Novillo1fcff722019-05-07 13:45:53 -0400915 llvm::initializeClspvPasses(Registry);
alan-bakerfec0a472018-11-08 18:09:40 -0500916
917 std::unique_ptr<llvm::Module> module(action.takeModule());
918
919 // Optimize.
920 // Create a memory buffer for temporarily writing the result.
921 SmallVector<char, 10000> binary;
922 llvm::raw_svector_ostream binaryStream(binary);
alan-bakerfec0a472018-11-08 18:09:40 -0500923 llvm::legacy::PassManager pm;
Diego Novillo89500852019-04-15 08:45:10 -0400924
925 // If --emit-ir was requested, emit the initial LLVM IR and stop compilation.
926 if (!IROutputFile.empty()) {
927 return GenerateIRFile(&pm, *module, IROutputFile);
928 }
929
930 // Otherwise, populate the pass manager and run the regular passes.
alan-baker86ce19c2020-08-05 13:09:19 -0400931 if (auto error = PopulatePassManager(&pm, &binaryStream, &SamplerMapEntries))
alan-bakerf5e5f692018-11-27 08:33:24 -0500932 return error;
alan-bakerfec0a472018-11-08 18:09:40 -0500933 pm.run(*module);
934
935 // Write outputs
alan-bakerfec0a472018-11-08 18:09:40 -0500936 std::error_code error;
alan-bakerfec0a472018-11-08 18:09:40 -0500937
938 // Write the resulting binary.
939 // Wait until now to try writing the file so that we only write it on
940 // successful compilation.
941 if (OutputFilename.empty()) {
Kévin Petite4786902019-04-02 21:51:47 +0100942 if (OutputFormat == "c") {
alan-bakerfec0a472018-11-08 18:09:40 -0500943 OutputFilename = "a.spvinc";
944 } else {
945 OutputFilename = "a.spv";
946 }
947 }
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400948 llvm::raw_fd_ostream outStream(OutputFilename, error,
949 llvm::sys::fs::FA_Write);
alan-bakerfec0a472018-11-08 18:09:40 -0500950
951 if (error) {
952 llvm::errs() << "Unable to open output file '" << OutputFilename
953 << "': " << error.message() << '\n';
954 return -1;
955 }
956 outStream << binaryStream.str();
957
958 return 0;
959}
alan-bakerf5e5f692018-11-27 08:33:24 -0500960
alan-baker86ce19c2020-08-05 13:09:19 -0400961int CompileFromSourceString(const std::string &program,
962 const std::string &sampler_map,
963 const std::string &options,
Kévin Petit899162d2020-09-08 19:16:08 +0100964 std::vector<uint32_t> *output_binary,
965 std::string *output_log) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500966
967 llvm::SmallVector<const char *, 20> argv;
968 llvm::BumpPtrAllocator A;
969 llvm::StringSaver Saver(A);
970 argv.push_back(Saver.save("clspv").data());
971 llvm::cl::TokenizeGNUCommandLine(options, Saver, argv);
972 int argc = static_cast<int>(argv.size());
Kévin Petitd5db2d22019-04-04 13:55:14 +0100973
974 if (auto error = ParseOptions(argc, &argv[0]))
975 return error;
alan-bakerf5e5f692018-11-27 08:33:24 -0500976
977 llvm::SmallVector<std::pair<unsigned, std::string>, 8> SamplerMapEntries;
978 if (auto error = ParseSamplerMap(sampler_map, &SamplerMapEntries))
979 return error;
980
981 InputFilename = "source.cl";
982 llvm::StringRef overiddenInputFilename = InputFilename.getValue();
983
984 clang::CompilerInstance instance;
alan-bakerd354f1a2019-08-06 15:41:55 -0400985 clang::FrontendInputFile kernelFile(
986 overiddenInputFilename, clang::InputKind(clang::Language::OpenCL));
alan-bakerf5e5f692018-11-27 08:33:24 -0500987 std::string log;
988 llvm::raw_string_ostream diagnosticsStream(log);
989 if (auto error =
990 SetCompilerInstanceOptions(instance, overiddenInputFilename,
991 kernelFile, program, &diagnosticsStream))
992 return error;
993
994 // Parse.
995 llvm::LLVMContext context;
996 clang::EmitLLVMOnlyAction action(&context);
997
998 // Prepare the action for processing kernelFile
999 const bool success = action.BeginSourceFile(instance, kernelFile);
1000 if (!success) {
1001 return -1;
1002 }
1003
alan-bakerf3bce4a2019-06-28 16:01:15 -04001004 auto result = action.Execute();
alan-bakerf5e5f692018-11-27 08:33:24 -05001005 action.EndSourceFile();
1006
1007 clang::DiagnosticConsumer *const consumer =
1008 instance.getDiagnostics().getClient();
1009 consumer->finish();
1010
Kévin Petit899162d2020-09-08 19:16:08 +01001011 if (output_log != nullptr) {
1012 *output_log = log;
1013 }
1014
alan-bakerf5e5f692018-11-27 08:33:24 -05001015 auto num_errors = consumer->getNumErrors();
alan-bakerf3bce4a2019-06-28 16:01:15 -04001016 if (result || num_errors > 0) {
alan-bakerf5e5f692018-11-27 08:33:24 -05001017 return -1;
1018 }
1019
alan-bakerf5e5f692018-11-27 08:33:24 -05001020 llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry();
1021 llvm::initializeCore(Registry);
1022 llvm::initializeScalarOpts(Registry);
Diego Novillo1fcff722019-05-07 13:45:53 -04001023 llvm::initializeClspvPasses(Registry);
alan-bakerf5e5f692018-11-27 08:33:24 -05001024
1025 std::unique_ptr<llvm::Module> module(action.takeModule());
1026
1027 // Optimize.
1028 // Create a memory buffer for temporarily writing the result.
1029 SmallVector<char, 10000> binary;
1030 llvm::raw_svector_ostream binaryStream(binary);
alan-bakerf5e5f692018-11-27 08:33:24 -05001031 llvm::legacy::PassManager pm;
alan-baker86ce19c2020-08-05 13:09:19 -04001032 if (auto error = PopulatePassManager(&pm, &binaryStream, &SamplerMapEntries))
alan-bakerf5e5f692018-11-27 08:33:24 -05001033 return error;
1034 pm.run(*module);
1035
alan-bakerf5e5f692018-11-27 08:33:24 -05001036 // Write the resulting binary.
1037 // Wait until now to try writing the file so that we only write it on
1038 // successful compilation.
1039 assert(output_binary && "Valid binary container is required.");
1040 if (!OutputFilename.empty()) {
1041 llvm::outs()
1042 << "Warning: -o is ignored when binary container is provided.\n";
1043 }
1044 output_binary->resize(binary.size() / 4);
1045 memcpy(output_binary->data(), binary.data(), binary.size());
1046
1047 return 0;
1048}
alan-bakerfec0a472018-11-08 18:09:40 -05001049} // namespace clspv