blob: 4e805d751e5fe936963ec61cfd7d11c3fdaaff0c [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
611 // We need to run mem2reg and inst combine early because our
612 // createInlineFuncWithPointerBitCastArgPass pass cannot handle the pattern
613 // %1 = alloca i32 1
614 // store <something> %1
615 // %2 = bitcast float* %1
616 // %3 = load float %2
617 pm->add(llvm::createPromoteMemoryToRegisterPass());
618
alan-baker1b13e8f2019-08-08 17:56:51 -0400619 // Try to deal with pointer bitcasts early. This can prevent problems like
620 // issue #409 where LLVM is looser about access chain addressing than SPIR-V.
621 // This needs to happen before instcombine and after replacing OpenCL
622 // builtins. This run of the pass will not handle all pointer bitcasts that
623 // could be handled. It should be run again after other optimizations (e.g
624 // InlineFuncWithPointerBitCastArgPass).
625 pm->add(clspv::createSimplifyPointerBitcastPass());
626 pm->add(clspv::createReplacePointerBitcastPass());
627 pm->add(llvm::createDeadCodeEliminationPass());
628
alan-bakerfec0a472018-11-08 18:09:40 -0500629 // Hide loads from __constant address space away from instcombine.
630 // This prevents us from generating select between pointers-to-__constant.
631 // See https://github.com/google/clspv/issues/71
632 pm->add(clspv::createHideConstantLoadsPass());
633
634 pm->add(llvm::createInstructionCombiningPass());
635
636 if (clspv::Option::InlineEntryPoints()) {
637 pm->add(clspv::createInlineEntryPointsPass());
638 } else {
639 pm->add(clspv::createInlineFuncWithPointerBitCastArgPass());
640 pm->add(clspv::createInlineFuncWithPointerToFunctionArgPass());
641 pm->add(clspv::createInlineFuncWithSingleCallSitePass());
642 }
643
Kévin Petitf0515712020-01-07 18:29:20 +0000644 if (clspv::Option::LanguageUsesGenericAddressSpace()) {
Kévin Petit38c52482019-05-07 20:28:00 +0800645 pm->add(llvm::createInferAddressSpacesPass(clspv::AddressSpace::Generic));
Kévin Petit0fc88042019-04-09 23:25:02 +0100646 }
647
alan-bakerfec0a472018-11-08 18:09:40 -0500648 if (0 == pmBuilder.OptLevel) {
649 // Mem2Reg pass should be run early because O0 level optimization leaves
650 // redundant alloca, load and store instructions from function arguments.
651 // clspv needs to remove them ahead of transformation.
652 pm->add(llvm::createPromoteMemoryToRegisterPass());
653
654 // SROA pass is run because it will fold structs/unions that are problematic
655 // on Vulkan SPIR-V away.
656 pm->add(llvm::createSROAPass());
657
658 // InstructionCombining pass folds bitcast and gep instructions which are
659 // not supported by Vulkan SPIR-V.
660 pm->add(llvm::createInstructionCombiningPass());
661 }
662
663 // Now we add any of the LLVM optimizations we wanted
664 pmBuilder.populateModulePassManager(*pm);
665
alan-bakerb5e74d62020-04-07 20:38:05 -0400666 // No point attempting to handle freeze currently so strip them from the IR.
667 pm->add(clspv::createStripFreezePass());
668
alan-bakerfec0a472018-11-08 18:09:40 -0500669 // Unhide loads from __constant address space. Undoes the action of
670 // HideConstantLoadsPass.
671 pm->add(clspv::createUnhideConstantLoadsPass());
672
alan-baker13568382020-04-02 17:29:27 -0400673 pm->add(clspv::createUndoInstCombinePass());
alan-bakerfec0a472018-11-08 18:09:40 -0500674 pm->add(clspv::createFunctionInternalizerPass());
675 pm->add(clspv::createReplaceLLVMIntrinsicsPass());
alan-bakerad1a12f2020-08-25 09:18:38 -0400676 // Replace LLVM intrinsics can leave dead code around.
677 pm->add(llvm::createDeadCodeEliminationPass());
alan-bakerfec0a472018-11-08 18:09:40 -0500678 pm->add(clspv::createUndoBoolPass());
alan-bakere711c762020-05-20 17:56:59 -0400679 pm->add(clspv::createUndoTruncateToOddIntegerPass());
alan-bakerfec0a472018-11-08 18:09:40 -0500680 pm->add(llvm::createStructurizeCFGPass(false));
alan-baker3fa76d92018-11-12 14:54:40 -0500681 // Must be run after structurize cfg.
alan-baker9580aef2020-01-07 22:31:48 -0500682 pm->add(clspv::createFixupStructuredCFGPass());
683 // Must be run after structured cfg fixup.
alan-bakerfec0a472018-11-08 18:09:40 -0500684 pm->add(clspv::createReorderBasicBlocksPass());
685 pm->add(clspv::createUndoGetElementPtrConstantExprPass());
686 pm->add(clspv::createSplatArgPass());
687 pm->add(clspv::createSimplifyPointerBitcastPass());
688 pm->add(clspv::createReplacePointerBitcastPass());
689
690 pm->add(clspv::createUndoTranslateSamplerFoldPass());
691
692 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
693 pm->add(clspv::createClusterModuleScopeConstantVars());
694 }
695
696 pm->add(clspv::createShareModuleScopeVariablesPass());
alan-bakerf67468c2019-11-25 15:51:49 -0500697 // Specialize images before assigning descriptors to disambiguate the various
698 // types.
699 pm->add(clspv::createSpecializeImageTypesPass());
alan-bakere9308012019-03-15 10:25:13 -0400700 // This should be run after LLVM and OpenCL intrinsics are replaced.
alan-bakerfec0a472018-11-08 18:09:40 -0500701 pm->add(clspv::createAllocateDescriptorsPass(*SamplerMapEntries));
702 pm->add(llvm::createVerifierPass());
703 pm->add(clspv::createDirectResourceAccessPass());
704 // Replacing pointer bitcasts can leave some trivial GEPs
705 // that are easy to remove. Also replace GEPs of GEPS
706 // left by replacing indirect buffer accesses.
707 pm->add(clspv::createSimplifyPointerBitcastPass());
alan-baker4217b322019-03-06 08:56:12 -0500708 // Run after DRA to clean up parameters and help reduce the need for variable
709 // pointers.
710 pm->add(clspv::createRemoveUnusedArgumentsPass());
alan-bakerfec0a472018-11-08 18:09:40 -0500711
712 pm->add(clspv::createSplatSelectConditionPass());
713 pm->add(clspv::createSignedCompareFixupPass());
714 // This pass generates insertions that need to be rewritten.
715 pm->add(clspv::createScalarizePass());
716 pm->add(clspv::createRewriteInsertsPass());
alan-bakera71f1932019-04-11 11:04:34 -0400717 // UBO Transformations
718 if (clspv::Option::ConstantArgsInUniformBuffer() &&
719 !clspv::Option::InlineEntryPoints()) {
720 // MultiVersionUBOFunctionsPass will examine non-kernel functions with UBO
721 // arguments and either multi-version them as necessary or inline them if
722 // multi-versioning cannot be accomplished.
723 pm->add(clspv::createMultiVersionUBOFunctionsPass());
724 // Cleanup passes.
725 // Specialization can blindly generate GEP chains that are easily cleaned up
726 // by SimplifyPointerBitcastPass.
727 pm->add(clspv::createSimplifyPointerBitcastPass());
728 // RemoveUnusedArgumentsPass removes the actual UBO arguments that were
729 // problematic to begin with now that they have no uses.
730 pm->add(clspv::createRemoveUnusedArgumentsPass());
731 // DCE cleans up callers of the specialized functions.
732 pm->add(llvm::createDeadCodeEliminationPass());
733 }
alan-bakerfec0a472018-11-08 18:09:40 -0500734 // This pass mucks with types to point where you shouldn't rely on DataLayout
735 // anymore so leave this right before SPIR-V generation.
736 pm->add(clspv::createUBOTypeTransformPass());
alan-baker86ce19c2020-08-05 13:09:19 -0400737 pm->add(clspv::createSPIRVProducerPass(*binaryStream, *SamplerMapEntries,
alan-baker00e7a582019-06-07 12:54:21 -0400738 OutputFormat == "c"));
alan-bakerf5e5f692018-11-27 08:33:24 -0500739
740 return 0;
alan-bakerfec0a472018-11-08 18:09:40 -0500741}
alan-bakerfec0a472018-11-08 18:09:40 -0500742
Kévin Petitd5db2d22019-04-04 13:55:14 +0100743int ParseOptions(const int argc, const char *const argv[]) {
alan-baker227e9782020-06-02 15:35:37 -0400744 // We need to change how some of the called passes works by spoofing
745 // ParseCommandLineOptions with the specific options.
746 bool has_pre = false;
747 bool has_load_pre = false;
748 const std::string pre = "-enable-pre";
749 const std::string load_pre = "-enable-load-pre";
750 for (int i = 1; i < argc; ++i) {
751 std::string option(argv[i]);
752 auto pre_pos = option.find(pre);
753 auto load_pos = option.find(load_pre);
754 if (pre_pos == 0 || (pre_pos == 1 && option[0] == '-')) {
755 has_pre = true;
756 } else if (load_pos == 0 || (load_pos == 1 && option[0] == '-')) {
757 has_load_pre = true;
758 }
759 }
760
761 int llvmArgc = 2;
762 const char *llvmArgv[4];
763 llvmArgv[0] = argv[0];
764 llvmArgv[1] = "-simplifycfg-sink-common=false";
765 if (!has_pre) {
766 llvmArgv[llvmArgc++] = "-enable-pre=0";
767 }
768 if (!has_load_pre) {
769 llvmArgv[llvmArgc++] = "-enable-load-pre=0";
770 }
alan-bakerfec0a472018-11-08 18:09:40 -0500771
Kévin Petitd5db2d22019-04-04 13:55:14 +0100772 llvm::cl::ResetAllOptionOccurrences();
alan-bakerfec0a472018-11-08 18:09:40 -0500773 llvm::cl::ParseCommandLineOptions(llvmArgc, llvmArgv);
alan-bakerfec0a472018-11-08 18:09:40 -0500774 llvm::cl::ParseCommandLineOptions(argc, argv);
775
Kévin Petitf0515712020-01-07 18:29:20 +0000776 if (clspv::Option::LanguageUsesGenericAddressSpace() &&
777 !clspv::Option::InlineEntryPoints()) {
778 llvm::errs() << "cannot compile languages that use the generic address "
779 "space (e.g. CLC++, CL2.0) without -inline-entry-points\n";
Kévin Petit0fc88042019-04-09 23:25:02 +0100780 return -1;
781 }
782
Kévin Petitbbbda972020-03-03 19:16:31 +0000783 if (clspv::Option::ScalarBlockLayout()) {
784 llvm::errs() << "scalar block layout support unimplemented\n";
785 return -1;
786 }
787
alan-baker9b0ec3c2020-04-06 14:45:34 -0400788 // Push constant option validation.
789 if (clspv::Option::PodArgsInPushConstants()) {
790 if (clspv::Option::PodArgsInUniformBuffer()) {
791 llvm::errs() << "POD arguments can only be in either uniform buffers or "
792 "push constants\n";
793 return -1;
794 }
795
796 if (!clspv::Option::ClusterPodKernelArgs()) {
797 llvm::errs()
798 << "POD arguments must be clustered to be passed as push constants\n";
799 return -1;
800 }
801
802 // Conservatively error if a module scope push constant could be used.
James Price708cf362020-05-06 19:33:45 -0400803 if (clspv::Option::GlobalOffsetPushConstant() ||
alan-baker9b0ec3c2020-04-06 14:45:34 -0400804 clspv::Option::Language() ==
805 clspv::Option::SourceLanguage::OpenCL_C_20 ||
806 clspv::Option::Language() ==
807 clspv::Option::SourceLanguage::OpenCL_CPP) {
808 llvm::errs() << "POD arguments as push constants are not compatible with "
809 "module scope push constants\n";
810 return -1;
811 }
812 }
813
Kévin Petitd5db2d22019-04-04 13:55:14 +0100814 return 0;
815}
Diego Novillo89500852019-04-15 08:45:10 -0400816
817int GenerateIRFile(llvm::legacy::PassManager *pm, llvm::Module &module,
818 std::string output) {
819 std::error_code ec;
820 std::unique_ptr<llvm::ToolOutputFile> out(
821 new llvm::ToolOutputFile(output, ec, llvm::sys::fs::F_None));
822 if (ec) {
823 llvm::errs() << output << ": " << ec.message() << '\n';
824 return -1;
825 }
826 pm->add(llvm::createPrintModulePass(out->os(), "", false));
827 pm->run(module);
828 out->keep();
829 return 0;
830}
831
Kévin Petitd5db2d22019-04-04 13:55:14 +0100832} // namespace
833
834namespace clspv {
835int Compile(const int argc, const char *const argv[]) {
836
837 if (auto error = ParseOptions(argc, argv))
838 return error;
839
alan-bakerfec0a472018-11-08 18:09:40 -0500840 llvm::SmallVector<std::pair<unsigned, std::string>, 8> SamplerMapEntries;
alan-bakerf5e5f692018-11-27 08:33:24 -0500841 if (auto error = ParseSamplerMap("", &SamplerMapEntries))
alan-bakerfec0a472018-11-08 18:09:40 -0500842 return error;
843
844 // if no output file was provided, use a default
845 llvm::StringRef overiddenInputFilename = InputFilename.getValue();
846
847 // If we are reading our input file from stdin.
848 if ("-" == InputFilename) {
849 // We need to overwrite the file name we use.
Kévin Petitddad8f42019-09-30 15:12:08 +0100850 switch (InputLanguage) {
851 case clang::Language::OpenCL:
852 overiddenInputFilename = "stdin.cl";
853 break;
854 case clang::Language::LLVM_IR:
855 overiddenInputFilename = "stdin.ll";
856 break;
alan-baker31298a62019-10-07 13:24:30 -0400857 default:
858 // Default to fix compiler warnings/errors. Option parsing will reject a
859 // bad enum value for the option so there is no need for a message.
860 return -1;
Kévin Petitddad8f42019-09-30 15:12:08 +0100861 }
alan-bakerfec0a472018-11-08 18:09:40 -0500862 }
863
864 clang::CompilerInstance instance;
Kévin Petitddad8f42019-09-30 15:12:08 +0100865 clang::FrontendInputFile kernelFile(overiddenInputFilename,
866 clang::InputKind(InputLanguage));
alan-bakerfec0a472018-11-08 18:09:40 -0500867 std::string log;
868 llvm::raw_string_ostream diagnosticsStream(log);
alan-bakerf5e5f692018-11-27 08:33:24 -0500869 if (auto error = SetCompilerInstanceOptions(
870 instance, overiddenInputFilename, kernelFile, "", &diagnosticsStream))
alan-bakerfec0a472018-11-08 18:09:40 -0500871 return error;
872
873 // Parse.
874 llvm::LLVMContext context;
875 clang::EmitLLVMOnlyAction action(&context);
876
877 // Prepare the action for processing kernelFile
878 const bool success = action.BeginSourceFile(instance, kernelFile);
879 if (!success) {
880 return -1;
881 }
882
alan-bakerf3bce4a2019-06-28 16:01:15 -0400883 auto result = action.Execute();
alan-bakerfec0a472018-11-08 18:09:40 -0500884 action.EndSourceFile();
885
886 clang::DiagnosticConsumer *const consumer =
887 instance.getDiagnostics().getClient();
888 consumer->finish();
889
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100890 auto num_warnings = consumer->getNumWarnings();
alan-bakerfec0a472018-11-08 18:09:40 -0500891 auto num_errors = consumer->getNumErrors();
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100892 if ((num_errors > 0) || (num_warnings > 0)) {
893 llvm::errs() << log;
894 }
alan-bakerf3bce4a2019-06-28 16:01:15 -0400895 if (result || num_errors > 0) {
alan-bakerfec0a472018-11-08 18:09:40 -0500896 return -1;
897 }
898
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100899 // Don't run the passes or produce any output in verify mode.
900 // Clang doesn't always produce a valid module.
901 if (verify) {
902 return 0;
903 }
904
alan-bakerfec0a472018-11-08 18:09:40 -0500905 llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry();
906 llvm::initializeCore(Registry);
907 llvm::initializeScalarOpts(Registry);
Diego Novillo1fcff722019-05-07 13:45:53 -0400908 llvm::initializeClspvPasses(Registry);
alan-bakerfec0a472018-11-08 18:09:40 -0500909
910 std::unique_ptr<llvm::Module> module(action.takeModule());
911
912 // Optimize.
913 // Create a memory buffer for temporarily writing the result.
914 SmallVector<char, 10000> binary;
915 llvm::raw_svector_ostream binaryStream(binary);
alan-bakerfec0a472018-11-08 18:09:40 -0500916 llvm::legacy::PassManager pm;
Diego Novillo89500852019-04-15 08:45:10 -0400917
918 // If --emit-ir was requested, emit the initial LLVM IR and stop compilation.
919 if (!IROutputFile.empty()) {
920 return GenerateIRFile(&pm, *module, IROutputFile);
921 }
922
923 // Otherwise, populate the pass manager and run the regular passes.
alan-baker86ce19c2020-08-05 13:09:19 -0400924 if (auto error = PopulatePassManager(&pm, &binaryStream, &SamplerMapEntries))
alan-bakerf5e5f692018-11-27 08:33:24 -0500925 return error;
alan-bakerfec0a472018-11-08 18:09:40 -0500926 pm.run(*module);
927
928 // Write outputs
alan-bakerfec0a472018-11-08 18:09:40 -0500929 std::error_code error;
alan-bakerfec0a472018-11-08 18:09:40 -0500930
931 // Write the resulting binary.
932 // Wait until now to try writing the file so that we only write it on
933 // successful compilation.
934 if (OutputFilename.empty()) {
Kévin Petite4786902019-04-02 21:51:47 +0100935 if (OutputFormat == "c") {
alan-bakerfec0a472018-11-08 18:09:40 -0500936 OutputFilename = "a.spvinc";
937 } else {
938 OutputFilename = "a.spv";
939 }
940 }
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400941 llvm::raw_fd_ostream outStream(OutputFilename, error,
942 llvm::sys::fs::FA_Write);
alan-bakerfec0a472018-11-08 18:09:40 -0500943
944 if (error) {
945 llvm::errs() << "Unable to open output file '" << OutputFilename
946 << "': " << error.message() << '\n';
947 return -1;
948 }
949 outStream << binaryStream.str();
950
951 return 0;
952}
alan-bakerf5e5f692018-11-27 08:33:24 -0500953
alan-baker86ce19c2020-08-05 13:09:19 -0400954int CompileFromSourceString(const std::string &program,
955 const std::string &sampler_map,
956 const std::string &options,
Kévin Petit899162d2020-09-08 19:16:08 +0100957 std::vector<uint32_t> *output_binary,
958 std::string *output_log) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500959
960 llvm::SmallVector<const char *, 20> argv;
961 llvm::BumpPtrAllocator A;
962 llvm::StringSaver Saver(A);
963 argv.push_back(Saver.save("clspv").data());
964 llvm::cl::TokenizeGNUCommandLine(options, Saver, argv);
965 int argc = static_cast<int>(argv.size());
Kévin Petitd5db2d22019-04-04 13:55:14 +0100966
967 if (auto error = ParseOptions(argc, &argv[0]))
968 return error;
alan-bakerf5e5f692018-11-27 08:33:24 -0500969
970 llvm::SmallVector<std::pair<unsigned, std::string>, 8> SamplerMapEntries;
971 if (auto error = ParseSamplerMap(sampler_map, &SamplerMapEntries))
972 return error;
973
974 InputFilename = "source.cl";
975 llvm::StringRef overiddenInputFilename = InputFilename.getValue();
976
977 clang::CompilerInstance instance;
alan-bakerd354f1a2019-08-06 15:41:55 -0400978 clang::FrontendInputFile kernelFile(
979 overiddenInputFilename, clang::InputKind(clang::Language::OpenCL));
alan-bakerf5e5f692018-11-27 08:33:24 -0500980 std::string log;
981 llvm::raw_string_ostream diagnosticsStream(log);
982 if (auto error =
983 SetCompilerInstanceOptions(instance, overiddenInputFilename,
984 kernelFile, program, &diagnosticsStream))
985 return error;
986
987 // Parse.
988 llvm::LLVMContext context;
989 clang::EmitLLVMOnlyAction action(&context);
990
991 // Prepare the action for processing kernelFile
992 const bool success = action.BeginSourceFile(instance, kernelFile);
993 if (!success) {
994 return -1;
995 }
996
alan-bakerf3bce4a2019-06-28 16:01:15 -0400997 auto result = action.Execute();
alan-bakerf5e5f692018-11-27 08:33:24 -0500998 action.EndSourceFile();
999
1000 clang::DiagnosticConsumer *const consumer =
1001 instance.getDiagnostics().getClient();
1002 consumer->finish();
1003
Kévin Petit899162d2020-09-08 19:16:08 +01001004 if (output_log != nullptr) {
1005 *output_log = log;
1006 }
1007
alan-bakerf5e5f692018-11-27 08:33:24 -05001008 auto num_errors = consumer->getNumErrors();
alan-bakerf3bce4a2019-06-28 16:01:15 -04001009 if (result || num_errors > 0) {
alan-bakerf5e5f692018-11-27 08:33:24 -05001010 return -1;
1011 }
1012
alan-bakerf5e5f692018-11-27 08:33:24 -05001013 llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry();
1014 llvm::initializeCore(Registry);
1015 llvm::initializeScalarOpts(Registry);
Diego Novillo1fcff722019-05-07 13:45:53 -04001016 llvm::initializeClspvPasses(Registry);
alan-bakerf5e5f692018-11-27 08:33:24 -05001017
1018 std::unique_ptr<llvm::Module> module(action.takeModule());
1019
1020 // Optimize.
1021 // Create a memory buffer for temporarily writing the result.
1022 SmallVector<char, 10000> binary;
1023 llvm::raw_svector_ostream binaryStream(binary);
alan-bakerf5e5f692018-11-27 08:33:24 -05001024 llvm::legacy::PassManager pm;
alan-baker86ce19c2020-08-05 13:09:19 -04001025 if (auto error = PopulatePassManager(&pm, &binaryStream, &SamplerMapEntries))
alan-bakerf5e5f692018-11-27 08:33:24 -05001026 return error;
1027 pm.run(*module);
1028
alan-bakerf5e5f692018-11-27 08:33:24 -05001029 // Write the resulting binary.
1030 // Wait until now to try writing the file so that we only write it on
1031 // successful compilation.
1032 assert(output_binary && "Valid binary container is required.");
1033 if (!OutputFilename.empty()) {
1034 llvm::outs()
1035 << "Warning: -o is ignored when binary container is provided.\n";
1036 }
1037 output_binary->resize(binary.size() / 4);
1038 memcpy(output_binary->data(), binary.data(), binary.size());
1039
1040 return 0;
1041}
alan-bakerfec0a472018-11-08 18:09:40 -05001042} // namespace clspv