alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 1 | // 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 | |
| 15 | #include "clang/Basic/TargetInfo.h" |
| 16 | #include "clang/CodeGen/CodeGenAction.h" |
| 17 | #include "clang/Frontend/CompilerInstance.h" |
| 18 | #include "clang/Frontend/FrontendPluginRegistry.h" |
| 19 | #include "clang/Frontend/TextDiagnosticPrinter.h" |
| 20 | #include "clang/Lex/PreprocessorOptions.h" |
| 21 | #include "llvm/IR/LLVMContext.h" |
| 22 | #include "llvm/IR/LegacyPassManager.h" |
| 23 | #include "llvm/IR/Module.h" |
| 24 | #include "llvm/IR/Verifier.h" |
| 25 | #include "llvm/LinkAllPasses.h" |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 26 | #include "llvm/Support/Allocator.h" |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 27 | #include "llvm/Support/CommandLine.h" |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 28 | #include "llvm/Support/ErrorOr.h" |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 29 | #include "llvm/Support/MathExtras.h" |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 30 | #include "llvm/Support/StringSaver.h" |
Diego Novillo | 8950085 | 2019-04-15 08:45:10 -0400 | [diff] [blame] | 31 | #include "llvm/Support/ToolOutputFile.h" |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 32 | #include "llvm/Support/raw_ostream.h" |
| 33 | #include "llvm/Transforms/IPO/PassManagerBuilder.h" |
| 34 | |
Kévin Petit | 38c5248 | 2019-05-07 20:28:00 +0800 | [diff] [blame] | 35 | #include "clspv/AddressSpace.h" |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 36 | #include "clspv/DescriptorMap.h" |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 37 | #include "clspv/Option.h" |
| 38 | #include "clspv/Passes.h" |
| 39 | #include "clspv/opencl_builtins_header.h" |
| 40 | |
| 41 | #include "FrontendPlugin.h" |
Diego Novillo | a4c44fa | 2019-04-11 10:56:15 -0400 | [diff] [blame] | 42 | #include "Passes.h" |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 43 | |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 44 | #include <cassert> |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 45 | #include <numeric> |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 46 | #include <sstream> |
Diego Novillo | 3cc8d7a | 2019-04-10 13:30:34 -0400 | [diff] [blame] | 47 | #include <string> |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 48 | |
| 49 | using namespace clang; |
| 50 | |
| 51 | namespace { |
| 52 | // This registration must be located in the same file as the execution of the |
| 53 | // action. |
| 54 | static FrontendPluginRegistry::Add<clspv::ExtraValidationASTAction> |
| 55 | X("extra-validation", |
| 56 | "Perform extra validation on OpenCL C when targeting Vulkan"); |
| 57 | |
| 58 | static llvm::cl::opt<bool> cl_single_precision_constants( |
| 59 | "cl-single-precision-constant", llvm::cl::init(false), |
| 60 | llvm::cl::desc("Treat double precision floating-point constant as single " |
| 61 | "precision constant.")); |
| 62 | |
| 63 | static llvm::cl::opt<bool> cl_denorms_are_zero( |
| 64 | "cl-denorms-are-zero", llvm::cl::init(false), |
| 65 | llvm::cl::desc("If specified, denormalized floating point numbers may be " |
| 66 | "flushed to zero.")); |
| 67 | |
| 68 | static llvm::cl::opt<bool> cl_fp32_correctly_rounded_divide_sqrt( |
| 69 | "cl-fp32-correctly-rounded-divide-sqrt", llvm::cl::init(false), |
| 70 | llvm::cl::desc("Single precision floating-point divide (x/y and 1/x) and " |
| 71 | "sqrt used are correctly rounded.")); |
| 72 | |
| 73 | static llvm::cl::opt<bool> |
| 74 | cl_opt_disable("cl-opt-disable", llvm::cl::init(false), |
| 75 | llvm::cl::desc("This option disables all optimizations. The " |
| 76 | "default is optimizations are enabled.")); |
| 77 | |
| 78 | static llvm::cl::opt<bool> cl_mad_enable( |
| 79 | "cl-mad-enable", llvm::cl::init(false), |
| 80 | llvm::cl::desc("Allow a * b + c to be replaced by a mad. The mad computes " |
| 81 | "a * b + c with reduced accuracy.")); |
| 82 | |
| 83 | static llvm::cl::opt<bool> cl_no_signed_zeros( |
| 84 | "cl-no-signed-zeros", llvm::cl::init(false), |
| 85 | llvm::cl::desc("Allow optimizations for floating-point arithmetic that " |
| 86 | "ignore the signedness of zero.")); |
| 87 | |
| 88 | static llvm::cl::opt<bool> cl_unsafe_math_optimizations( |
| 89 | "cl-unsafe-math-optimizations", llvm::cl::init(false), |
| 90 | llvm::cl::desc("Allow optimizations for floating-point arithmetic that (a) " |
| 91 | "assume that arguments and results are valid, (b) may " |
| 92 | "violate IEEE 754 standard and (c) may violate the OpenCL " |
| 93 | "numerical compliance requirements. This option includes " |
| 94 | "the -cl-no-signed-zeros and -cl-mad-enable options.")); |
| 95 | |
| 96 | static llvm::cl::opt<bool> cl_finite_math_only( |
| 97 | "cl-finite-math-only", llvm::cl::init(false), |
| 98 | llvm::cl::desc("Allow optimizations for floating-point arithmetic that " |
| 99 | "assume that arguments and results are not NaNs or INFs.")); |
| 100 | |
| 101 | static llvm::cl::opt<bool> cl_fast_relaxed_math( |
| 102 | "cl-fast-relaxed-math", llvm::cl::init(false), |
| 103 | llvm::cl::desc("This option causes the preprocessor macro " |
| 104 | "__FAST_RELAXED_MATH__ to be defined. Sets the optimization " |
| 105 | "options -cl-finite-math-only and " |
| 106 | "-cl-unsafe-math-optimizations.")); |
| 107 | |
| 108 | static llvm::cl::list<std::string> |
| 109 | Includes(llvm::cl::Prefix, "I", |
| 110 | llvm::cl::desc("Add a directory to the list of directories " |
| 111 | "to be searched for header files."), |
| 112 | llvm::cl::ZeroOrMore, llvm::cl::value_desc("include path")); |
| 113 | |
| 114 | static llvm::cl::list<std::string> |
| 115 | Defines(llvm::cl::Prefix, "D", |
| 116 | llvm::cl::desc("Define a #define directive."), llvm::cl::ZeroOrMore, |
| 117 | llvm::cl::value_desc("define")); |
| 118 | |
| 119 | static llvm::cl::opt<std::string> |
| 120 | InputFilename(llvm::cl::Positional, llvm::cl::desc("<input .cl file>"), |
| 121 | llvm::cl::init("-")); |
| 122 | |
Kévin Petit | ddad8f4 | 2019-09-30 15:12:08 +0100 | [diff] [blame] | 123 | static llvm::cl::opt<clang::Language> InputLanguage( |
| 124 | "x", llvm::cl::desc("Select input type"), |
| 125 | llvm::cl::init(clang::Language::OpenCL), |
| 126 | llvm::cl::values(clEnumValN(clang::Language::OpenCL, "cl", "OpenCL source"), |
| 127 | clEnumValN(clang::Language::LLVM_IR, "ir", "LLVM IR"))); |
| 128 | |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 129 | static llvm::cl::opt<std::string> |
| 130 | OutputFilename("o", llvm::cl::desc("Override output filename"), |
| 131 | llvm::cl::value_desc("filename")); |
| 132 | |
| 133 | static llvm::cl::opt<std::string> |
| 134 | DescriptorMapFilename("descriptormap", |
| 135 | llvm::cl::desc("Output file for descriptor map"), |
| 136 | llvm::cl::value_desc("filename")); |
| 137 | |
| 138 | static llvm::cl::opt<char> |
| 139 | OptimizationLevel(llvm::cl::Prefix, "O", llvm::cl::init('2'), |
| 140 | llvm::cl::desc("Optimization level to use"), |
| 141 | llvm::cl::value_desc("level")); |
| 142 | |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 143 | static llvm::cl::opt<std::string> OutputFormat( |
| 144 | "mfmt", llvm::cl::init(""), |
| 145 | llvm::cl::desc( |
| 146 | "Specify special output format. 'c' is as a C initializer list"), |
| 147 | llvm::cl::value_desc("format")); |
| 148 | |
| 149 | static llvm::cl::opt<std::string> |
| 150 | SamplerMap("samplermap", llvm::cl::desc("Literal sampler map"), |
| 151 | llvm::cl::value_desc("filename")); |
| 152 | |
| 153 | static llvm::cl::opt<bool> cluster_non_pointer_kernel_args( |
| 154 | "cluster-pod-kernel-args", llvm::cl::init(false), |
| 155 | llvm::cl::desc("Collect plain-old-data kernel arguments into a struct in " |
| 156 | "a single storage buffer, using a binding number after " |
| 157 | "other arguments. Use this to reduce storage buffer " |
| 158 | "descriptors.")); |
| 159 | |
| 160 | static llvm::cl::opt<bool> verify("verify", llvm::cl::init(false), |
| 161 | llvm::cl::desc("Verify diagnostic outputs")); |
| 162 | |
Kévin Petit | 6b07cbe | 2019-04-02 21:52:16 +0100 | [diff] [blame] | 163 | static llvm::cl::opt<bool> |
| 164 | IgnoreWarnings("w", llvm::cl::init(false), |
| 165 | llvm::cl::desc("Disable all warnings")); |
| 166 | |
| 167 | static llvm::cl::opt<bool> |
| 168 | WarningsAsErrors("Werror", llvm::cl::init(false), |
Diego Novillo | 3cc8d7a | 2019-04-10 13:30:34 -0400 | [diff] [blame] | 169 | llvm::cl::desc("Turn warnings into errors")); |
Kévin Petit | 6b07cbe | 2019-04-02 21:52:16 +0100 | [diff] [blame] | 170 | |
Diego Novillo | 8950085 | 2019-04-15 08:45:10 -0400 | [diff] [blame] | 171 | static llvm::cl::opt<std::string> IROutputFile( |
| 172 | "emit-ir", |
| 173 | llvm::cl::desc( |
| 174 | "Emit LLVM IR to the given file after parsing and stop compilation."), |
| 175 | llvm::cl::value_desc("filename")); |
| 176 | |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 177 | // Populates |SamplerMapEntries| with data from the input sampler map. Returns 0 |
| 178 | // if successful. |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 179 | int ParseSamplerMap(const std::string &sampler_map, |
| 180 | llvm::SmallVectorImpl<std::pair<unsigned, std::string>> |
| 181 | *SamplerMapEntries) { |
| 182 | std::unique_ptr<llvm::MemoryBuffer> samplerMapBuffer(nullptr); |
| 183 | if (!sampler_map.empty()) { |
| 184 | // Parse the sampler map from the provided string. |
| 185 | samplerMapBuffer = llvm::MemoryBuffer::getMemBuffer(sampler_map); |
| 186 | |
| 187 | if (!SamplerMap.empty()) { |
| 188 | llvm::outs() << "Warning: -samplermap is ignored when the sampler map is " |
| 189 | "provided through a string.\n"; |
| 190 | } |
| 191 | } else if (!SamplerMap.empty()) { |
| 192 | // Parse the sampler map from the option provided file. |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 193 | auto errorOrSamplerMapFile = |
| 194 | llvm::MemoryBuffer::getFile(SamplerMap.getValue()); |
| 195 | |
| 196 | // If there was an error in getting the sampler map file. |
| 197 | if (!errorOrSamplerMapFile) { |
| 198 | llvm::errs() << "Error: " << errorOrSamplerMapFile.getError().message() |
| 199 | << " '" << SamplerMap.getValue() << "'\n"; |
| 200 | return -1; |
| 201 | } |
| 202 | |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 203 | samplerMapBuffer = std::move(errorOrSamplerMapFile.get()); |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 204 | if (0 == samplerMapBuffer->getBufferSize()) { |
| 205 | llvm::errs() << "Error: Sampler map was an empty file!\n"; |
| 206 | return -1; |
| 207 | } |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 208 | } |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 209 | |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 210 | // No sampler map to parse. |
| 211 | if (!samplerMapBuffer || 0 == samplerMapBuffer->getBufferSize()) |
| 212 | return 0; |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 213 | |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 214 | llvm::SmallVector<llvm::StringRef, 3> samplerStrings; |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 215 | |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 216 | // We need to keep track of the beginning of the current entry. |
| 217 | const char *b = samplerMapBuffer->getBufferStart(); |
| 218 | for (const char *i = b, *e = samplerMapBuffer->getBufferEnd();; i++) { |
| 219 | // If we have a separator between declarations. |
| 220 | if ((*i == '|') || (*i == ',') || (i == e)) { |
| 221 | if (i == b) { |
| 222 | llvm::errs() << "Error: Sampler map contained an empty entry!\n"; |
| 223 | return -1; |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 224 | } |
| 225 | |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 226 | samplerStrings.push_back(llvm::StringRef(b, i - b).trim()); |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 227 | |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 228 | // And set b the next character after i. |
| 229 | b = i + 1; |
| 230 | } |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 231 | |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 232 | // If we have a separator between declarations within a single sampler. |
| 233 | if ((*i == ',') || (i == e)) { |
| 234 | enum NormalizedCoords { |
| 235 | CLK_NORMALIZED_COORDS_FALSE = 0x00, |
| 236 | CLK_NORMALIZED_COORDS_TRUE = 0x01, |
| 237 | CLK_NORMALIZED_COORDS_NOT_SET |
| 238 | } NormalizedCoord = CLK_NORMALIZED_COORDS_NOT_SET; |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 239 | |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 240 | enum AddressingModes { |
| 241 | CLK_ADDRESS_NONE = 0x00, |
| 242 | CLK_ADDRESS_CLAMP_TO_EDGE = 0x02, |
| 243 | CLK_ADDRESS_CLAMP = 0x04, |
| 244 | CLK_ADDRESS_MIRRORED_REPEAT = 0x08, |
| 245 | CLK_ADDRESS_REPEAT = 0x06, |
| 246 | CLK_ADDRESS_NOT_SET |
| 247 | } AddressingMode = CLK_ADDRESS_NOT_SET; |
| 248 | |
| 249 | enum FilterModes { |
| 250 | CLK_FILTER_NEAREST = 0x10, |
| 251 | CLK_FILTER_LINEAR = 0x20, |
| 252 | CLK_FILTER_NOT_SET |
| 253 | } FilterMode = CLK_FILTER_NOT_SET; |
| 254 | |
| 255 | for (auto str : samplerStrings) { |
| 256 | if ("CLK_NORMALIZED_COORDS_FALSE" == str) { |
| 257 | if (CLK_NORMALIZED_COORDS_NOT_SET != NormalizedCoord) { |
| 258 | llvm::errs() << "Error: Sampler map normalized coordinates was " |
| 259 | "previously set!\n"; |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 260 | return -1; |
| 261 | } |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 262 | NormalizedCoord = CLK_NORMALIZED_COORDS_FALSE; |
| 263 | } else if ("CLK_NORMALIZED_COORDS_TRUE" == str) { |
| 264 | if (CLK_NORMALIZED_COORDS_NOT_SET != NormalizedCoord) { |
| 265 | llvm::errs() << "Error: Sampler map normalized coordinates was " |
| 266 | "previously set!\n"; |
| 267 | return -1; |
| 268 | } |
| 269 | NormalizedCoord = CLK_NORMALIZED_COORDS_TRUE; |
| 270 | } else if ("CLK_ADDRESS_NONE" == str) { |
| 271 | if (CLK_ADDRESS_NOT_SET != AddressingMode) { |
| 272 | llvm::errs() |
| 273 | << "Error: Sampler map addressing mode was previously set!\n"; |
| 274 | return -1; |
| 275 | } |
| 276 | AddressingMode = CLK_ADDRESS_NONE; |
| 277 | } else if ("CLK_ADDRESS_CLAMP_TO_EDGE" == str) { |
| 278 | if (CLK_ADDRESS_NOT_SET != AddressingMode) { |
| 279 | llvm::errs() |
| 280 | << "Error: Sampler map addressing mode was previously set!\n"; |
| 281 | return -1; |
| 282 | } |
| 283 | AddressingMode = CLK_ADDRESS_CLAMP_TO_EDGE; |
| 284 | } else if ("CLK_ADDRESS_CLAMP" == str) { |
| 285 | if (CLK_ADDRESS_NOT_SET != AddressingMode) { |
| 286 | llvm::errs() |
| 287 | << "Error: Sampler map addressing mode was previously set!\n"; |
| 288 | return -1; |
| 289 | } |
| 290 | AddressingMode = CLK_ADDRESS_CLAMP; |
| 291 | } else if ("CLK_ADDRESS_MIRRORED_REPEAT" == str) { |
| 292 | if (CLK_ADDRESS_NOT_SET != AddressingMode) { |
| 293 | llvm::errs() |
| 294 | << "Error: Sampler map addressing mode was previously set!\n"; |
| 295 | return -1; |
| 296 | } |
| 297 | AddressingMode = CLK_ADDRESS_MIRRORED_REPEAT; |
| 298 | } else if ("CLK_ADDRESS_REPEAT" == str) { |
| 299 | if (CLK_ADDRESS_NOT_SET != AddressingMode) { |
| 300 | llvm::errs() |
| 301 | << "Error: Sampler map addressing mode was previously set!\n"; |
| 302 | return -1; |
| 303 | } |
| 304 | AddressingMode = CLK_ADDRESS_REPEAT; |
| 305 | } else if ("CLK_FILTER_NEAREST" == str) { |
| 306 | if (CLK_FILTER_NOT_SET != FilterMode) { |
| 307 | llvm::errs() |
| 308 | << "Error: Sampler map filtering mode was previously set!\n"; |
| 309 | return -1; |
| 310 | } |
| 311 | FilterMode = CLK_FILTER_NEAREST; |
| 312 | } else if ("CLK_FILTER_LINEAR" == str) { |
| 313 | if (CLK_FILTER_NOT_SET != FilterMode) { |
| 314 | llvm::errs() |
| 315 | << "Error: Sampler map filtering mode was previously set!\n"; |
| 316 | return -1; |
| 317 | } |
| 318 | FilterMode = CLK_FILTER_LINEAR; |
| 319 | } else { |
| 320 | llvm::errs() << "Error: Unknown sampler string '" << str |
| 321 | << "' found!\n"; |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 322 | return -1; |
| 323 | } |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 324 | } |
| 325 | |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 326 | if (CLK_NORMALIZED_COORDS_NOT_SET == NormalizedCoord) { |
| 327 | llvm::errs() << "Error: Sampler map entry did not contain normalized " |
| 328 | "coordinates entry!\n"; |
| 329 | return -1; |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 330 | } |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 331 | |
| 332 | if (CLK_ADDRESS_NOT_SET == AddressingMode) { |
| 333 | llvm::errs() << "Error: Sampler map entry did not contain addressing " |
| 334 | "mode entry!\n"; |
| 335 | return -1; |
| 336 | } |
| 337 | |
| 338 | if (CLK_FILTER_NOT_SET == FilterMode) { |
| 339 | llvm::errs() |
| 340 | << "Error: Sampler map entry did not contain filer mode entry!\n"; |
| 341 | return -1; |
| 342 | } |
| 343 | |
| 344 | // Generate an equivalent expression in string form. Sort the |
| 345 | // strings to get a canonical ordering. |
| 346 | std::sort(samplerStrings.begin(), samplerStrings.end(), |
| 347 | std::less<StringRef>()); |
| 348 | const auto samplerExpr = std::accumulate( |
| 349 | samplerStrings.begin(), samplerStrings.end(), std::string(), |
| 350 | [](std::string left, std::string right) { |
| 351 | return left + std::string(left.empty() ? "" : "|") + right; |
| 352 | }); |
| 353 | |
| 354 | // SamplerMapEntries->push_back(std::make_pair( |
| 355 | // NormalizedCoord | AddressingMode | FilterMode, samplerExpr)); |
| 356 | SamplerMapEntries->emplace_back( |
| 357 | NormalizedCoord | AddressingMode | FilterMode, samplerExpr); |
| 358 | |
| 359 | // And reset the sampler strings for the next sampler in the map. |
| 360 | samplerStrings.clear(); |
| 361 | } |
| 362 | |
| 363 | // And lastly, if we are at the end of the file |
| 364 | if (i == e) { |
| 365 | break; |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 366 | } |
| 367 | } |
| 368 | |
| 369 | return 0; |
| 370 | } |
| 371 | |
| 372 | // Sets |instance|'s options for compiling. Returns 0 if successful. |
| 373 | int SetCompilerInstanceOptions(CompilerInstance &instance, |
| 374 | const llvm::StringRef &overiddenInputFilename, |
| 375 | const clang::FrontendInputFile &kernelFile, |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 376 | const std::string &program, |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 377 | llvm::raw_string_ostream *diagnosticsStream) { |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 378 | std::unique_ptr<llvm::MemoryBuffer> memory_buffer(nullptr); |
| 379 | llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> errorOrInputFile(nullptr); |
| 380 | if (program.empty()) { |
| 381 | auto errorOrInputFile = |
| 382 | llvm::MemoryBuffer::getFileOrSTDIN(InputFilename.getValue()); |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 383 | |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 384 | // If there was an error in getting the input file. |
| 385 | if (!errorOrInputFile) { |
| 386 | llvm::errs() << "Error: " << errorOrInputFile.getError().message() << " '" |
| 387 | << InputFilename.getValue() << "'\n"; |
| 388 | return -1; |
| 389 | } |
| 390 | memory_buffer.reset(errorOrInputFile.get().release()); |
| 391 | } else { |
| 392 | memory_buffer = llvm::MemoryBuffer::getMemBuffer(program.c_str(), |
| 393 | overiddenInputFilename); |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 394 | } |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 395 | |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 396 | if (verify) { |
| 397 | instance.getDiagnosticOpts().VerifyDiagnostics = true; |
alan-baker | bccf62c | 2019-03-29 10:32:41 -0400 | [diff] [blame] | 398 | instance.getDiagnosticOpts().VerifyPrefixes.push_back("expected"); |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 399 | } |
| 400 | |
Kévin Petit | 0fc8804 | 2019-04-09 23:25:02 +0100 | [diff] [blame] | 401 | clang::LangStandard::Kind standard; |
| 402 | if (clspv::Option::CPlusPlus()) { |
| 403 | standard = clang::LangStandard::lang_openclcpp; |
| 404 | } else { |
| 405 | standard = clang::LangStandard::lang_opencl12; |
| 406 | } |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 407 | |
| 408 | // We are targeting OpenCL 1.2 only |
| 409 | instance.getLangOpts().OpenCLVersion = 120; |
| 410 | |
| 411 | instance.getLangOpts().C99 = true; |
| 412 | instance.getLangOpts().RTTI = false; |
| 413 | instance.getLangOpts().RTTIData = false; |
| 414 | instance.getLangOpts().MathErrno = false; |
| 415 | instance.getLangOpts().Optimize = false; |
| 416 | instance.getLangOpts().NoBuiltin = true; |
| 417 | instance.getLangOpts().ModulesSearchAll = false; |
| 418 | instance.getLangOpts().SinglePrecisionConstants = true; |
| 419 | instance.getCodeGenOpts().StackRealignment = true; |
| 420 | instance.getCodeGenOpts().SimplifyLibCalls = false; |
| 421 | instance.getCodeGenOpts().EmitOpenCLArgMetadata = false; |
| 422 | instance.getCodeGenOpts().DisableO0ImplyOptNone = true; |
Kévin Petit | 6b07cbe | 2019-04-02 21:52:16 +0100 | [diff] [blame] | 423 | instance.getDiagnosticOpts().IgnoreWarnings = IgnoreWarnings; |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 424 | |
| 425 | instance.getLangOpts().SinglePrecisionConstants = |
| 426 | cl_single_precision_constants; |
| 427 | // cl_denorms_are_zero ignored for now! |
| 428 | // cl_fp32_correctly_rounded_divide_sqrt ignored for now! |
| 429 | instance.getCodeGenOpts().LessPreciseFPMAD = |
| 430 | cl_mad_enable || cl_unsafe_math_optimizations; |
| 431 | // cl_no_signed_zeros ignored for now! |
| 432 | instance.getCodeGenOpts().UnsafeFPMath = |
| 433 | cl_unsafe_math_optimizations || cl_fast_relaxed_math; |
| 434 | instance.getLangOpts().FiniteMathOnly = |
| 435 | cl_finite_math_only || cl_fast_relaxed_math; |
| 436 | instance.getLangOpts().FastRelaxedMath = cl_fast_relaxed_math; |
| 437 | |
| 438 | // Preprocessor options |
Kévin Petit | a624c0c | 2019-05-07 20:27:43 +0800 | [diff] [blame] | 439 | if (!clspv::Option::ImageSupport()) { |
| 440 | instance.getPreprocessorOpts().addMacroUndef("__IMAGE_SUPPORT__"); |
| 441 | } |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 442 | if (cl_fast_relaxed_math) { |
| 443 | instance.getPreprocessorOpts().addMacroDef("__FAST_RELAXED_MATH__"); |
| 444 | } |
| 445 | |
| 446 | for (auto define : Defines) { |
| 447 | instance.getPreprocessorOpts().addMacroDef(define); |
| 448 | } |
| 449 | |
| 450 | // Header search options |
| 451 | for (auto include : Includes) { |
| 452 | instance.getHeaderSearchOpts().AddPath(include, clang::frontend::After, |
| 453 | false, false); |
| 454 | } |
| 455 | |
| 456 | // We always compile on opt 0 so we preserve as much debug information about |
| 457 | // the source as possible. We'll run optimization later, once we've had a |
| 458 | // chance to view the unoptimal code first |
| 459 | instance.getCodeGenOpts().OptimizationLevel = 0; |
| 460 | |
| 461 | // Debug information is disabled temporarily to call instruction. |
| 462 | #if 0 |
| 463 | instance.getCodeGenOpts().setDebugInfo(clang::codegenoptions::FullDebugInfo); |
| 464 | #endif |
| 465 | |
| 466 | // We use the 32-bit pointer-width SPIR triple |
| 467 | llvm::Triple triple("spir-unknown-unknown"); |
| 468 | |
| 469 | instance.getInvocation().setLangDefaults( |
alan-baker | d354f1a | 2019-08-06 15:41:55 -0400 | [diff] [blame] | 470 | instance.getLangOpts(), clang::InputKind(clang::Language::OpenCL), triple, |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 471 | instance.getPreprocessorOpts(), standard); |
| 472 | |
| 473 | // Override the C99 inline semantics to accommodate for more OpenCL C |
| 474 | // programs in the wild. |
| 475 | instance.getLangOpts().GNUInline = true; |
Kévin Petit | 6b07cbe | 2019-04-02 21:52:16 +0100 | [diff] [blame] | 476 | |
| 477 | // Set up diagnostics |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 478 | instance.createDiagnostics( |
| 479 | new clang::TextDiagnosticPrinter(*diagnosticsStream, |
| 480 | &instance.getDiagnosticOpts()), |
| 481 | true); |
Kévin Petit | 6b07cbe | 2019-04-02 21:52:16 +0100 | [diff] [blame] | 482 | instance.getDiagnostics().setWarningsAsErrors(WarningsAsErrors); |
| 483 | instance.getDiagnostics().setEnableAllWarnings(true); |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 484 | |
| 485 | instance.getTargetOpts().Triple = triple.str(); |
| 486 | |
| 487 | instance.getCodeGenOpts().MainFileName = overiddenInputFilename; |
| 488 | instance.getCodeGenOpts().PreserveVec3Type = true; |
| 489 | // Disable generation of lifetime intrinsic. |
| 490 | instance.getCodeGenOpts().DisableLifetimeMarkers = true; |
| 491 | instance.getFrontendOpts().Inputs.push_back(kernelFile); |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 492 | instance.getPreprocessorOpts().addRemappedFile(overiddenInputFilename, |
| 493 | memory_buffer.release()); |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 494 | |
| 495 | struct OpenCLBuiltinMemoryBuffer final : public llvm::MemoryBuffer { |
| 496 | OpenCLBuiltinMemoryBuffer(const void *data, uint64_t data_length) { |
| 497 | const char *dataCasted = reinterpret_cast<const char *>(data); |
| 498 | init(dataCasted, dataCasted + data_length, true); |
| 499 | } |
| 500 | |
| 501 | virtual llvm::MemoryBuffer::BufferKind getBufferKind() const override { |
| 502 | return llvm::MemoryBuffer::MemoryBuffer_Malloc; |
| 503 | } |
| 504 | |
| 505 | virtual ~OpenCLBuiltinMemoryBuffer() override {} |
| 506 | }; |
| 507 | |
| 508 | std::unique_ptr<llvm::MemoryBuffer> openCLBuiltinMemoryBuffer( |
| 509 | new OpenCLBuiltinMemoryBuffer(opencl_builtins_header_data, |
| 510 | opencl_builtins_header_size - 1)); |
| 511 | |
| 512 | instance.getPreprocessorOpts().Includes.push_back("openclc.h"); |
| 513 | |
alan-baker | f3bce4a | 2019-06-28 16:01:15 -0400 | [diff] [blame] | 514 | std::unique_ptr<llvm::MemoryBuffer> openCLBaseBuiltinMemoryBuffer( |
| 515 | new OpenCLBuiltinMemoryBuffer(opencl_base_builtins_header_data, |
| 516 | opencl_base_builtins_header_size - 1)); |
| 517 | |
| 518 | instance.getPreprocessorOpts().Includes.push_back("opencl-c-base.h"); |
| 519 | |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 520 | // Add the VULKAN macro. |
| 521 | instance.getPreprocessorOpts().addMacroDef("VULKAN=100"); |
| 522 | |
| 523 | // Add the __OPENCL_VERSION__ macro. |
| 524 | instance.getPreprocessorOpts().addMacroDef("__OPENCL_VERSION__=120"); |
| 525 | |
| 526 | instance.setTarget(clang::TargetInfo::CreateTargetInfo( |
| 527 | instance.getDiagnostics(), |
| 528 | std::make_shared<clang::TargetOptions>(instance.getTargetOpts()))); |
| 529 | |
| 530 | instance.createFileManager(); |
| 531 | instance.createSourceManager(instance.getFileManager()); |
| 532 | |
| 533 | #ifdef _MSC_VER |
| 534 | std::string includePrefix("include\\"); |
| 535 | #else |
| 536 | std::string includePrefix("include/"); |
| 537 | #endif |
| 538 | |
| 539 | auto entry = instance.getFileManager().getVirtualFile( |
| 540 | includePrefix + "openclc.h", openCLBuiltinMemoryBuffer->getBufferSize(), |
| 541 | 0); |
| 542 | |
| 543 | instance.getSourceManager().overrideFileContents( |
| 544 | entry, std::move(openCLBuiltinMemoryBuffer)); |
| 545 | |
alan-baker | f3bce4a | 2019-06-28 16:01:15 -0400 | [diff] [blame] | 546 | auto base_entry = instance.getFileManager().getVirtualFile( |
| 547 | includePrefix + "opencl-c-base.h", |
| 548 | openCLBaseBuiltinMemoryBuffer->getBufferSize(), 0); |
| 549 | |
| 550 | instance.getSourceManager().overrideFileContents( |
| 551 | base_entry, std::move(openCLBaseBuiltinMemoryBuffer)); |
| 552 | |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 553 | return 0; |
| 554 | } |
| 555 | |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 556 | // Populates |pm| with necessary passes to optimize and legalize the IR. |
| 557 | int PopulatePassManager( |
| 558 | llvm::legacy::PassManager *pm, llvm::raw_svector_ostream *binaryStream, |
| 559 | std::vector<clspv::version0::DescriptorMapEntry> *descriptor_map_entries, |
| 560 | llvm::SmallVectorImpl<std::pair<unsigned, std::string>> |
| 561 | *SamplerMapEntries) { |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 562 | llvm::PassManagerBuilder pmBuilder; |
| 563 | |
| 564 | switch (OptimizationLevel) { |
| 565 | case '0': |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 566 | case '1': |
| 567 | case '2': |
| 568 | case '3': |
| 569 | case 's': |
| 570 | case 'z': |
| 571 | break; |
| 572 | default: |
| 573 | llvm::errs() << "Unknown optimization level -O" << OptimizationLevel |
| 574 | << " specified!\n"; |
| 575 | return -1; |
| 576 | } |
| 577 | |
| 578 | switch (OptimizationLevel) { |
| 579 | case '0': |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 580 | pmBuilder.OptLevel = 0; |
| 581 | break; |
| 582 | case '1': |
| 583 | pmBuilder.OptLevel = 1; |
| 584 | break; |
| 585 | case '2': |
| 586 | pmBuilder.OptLevel = 2; |
| 587 | break; |
| 588 | case '3': |
| 589 | pmBuilder.OptLevel = 3; |
| 590 | break; |
| 591 | case 's': |
| 592 | pmBuilder.SizeLevel = 1; |
| 593 | break; |
| 594 | case 'z': |
| 595 | pmBuilder.SizeLevel = 2; |
| 596 | break; |
| 597 | default: |
| 598 | break; |
| 599 | } |
| 600 | |
| 601 | pm->add(clspv::createZeroInitializeAllocasPass()); |
| 602 | pm->add(clspv::createDefineOpenCLWorkItemBuiltinsPass()); |
| 603 | |
| 604 | if (0 < pmBuilder.OptLevel) { |
| 605 | pm->add(clspv::createOpenCLInlinerPass()); |
| 606 | } |
| 607 | |
| 608 | pm->add(clspv::createUndoByvalPass()); |
| 609 | pm->add(clspv::createUndoSRetPass()); |
| 610 | if (cluster_non_pointer_kernel_args) { |
| 611 | pm->add(clspv::createClusterPodKernelArgumentsPass()); |
| 612 | } |
| 613 | pm->add(clspv::createReplaceOpenCLBuiltinPass()); |
| 614 | |
| 615 | // We need to run mem2reg and inst combine early because our |
| 616 | // createInlineFuncWithPointerBitCastArgPass pass cannot handle the pattern |
| 617 | // %1 = alloca i32 1 |
| 618 | // store <something> %1 |
| 619 | // %2 = bitcast float* %1 |
| 620 | // %3 = load float %2 |
| 621 | pm->add(llvm::createPromoteMemoryToRegisterPass()); |
| 622 | |
alan-baker | 1b13e8f | 2019-08-08 17:56:51 -0400 | [diff] [blame] | 623 | // Try to deal with pointer bitcasts early. This can prevent problems like |
| 624 | // issue #409 where LLVM is looser about access chain addressing than SPIR-V. |
| 625 | // This needs to happen before instcombine and after replacing OpenCL |
| 626 | // builtins. This run of the pass will not handle all pointer bitcasts that |
| 627 | // could be handled. It should be run again after other optimizations (e.g |
| 628 | // InlineFuncWithPointerBitCastArgPass). |
| 629 | pm->add(clspv::createSimplifyPointerBitcastPass()); |
| 630 | pm->add(clspv::createReplacePointerBitcastPass()); |
| 631 | pm->add(llvm::createDeadCodeEliminationPass()); |
| 632 | |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 633 | // Hide loads from __constant address space away from instcombine. |
| 634 | // This prevents us from generating select between pointers-to-__constant. |
| 635 | // See https://github.com/google/clspv/issues/71 |
| 636 | pm->add(clspv::createHideConstantLoadsPass()); |
| 637 | |
| 638 | pm->add(llvm::createInstructionCombiningPass()); |
| 639 | |
| 640 | if (clspv::Option::InlineEntryPoints()) { |
| 641 | pm->add(clspv::createInlineEntryPointsPass()); |
| 642 | } else { |
| 643 | pm->add(clspv::createInlineFuncWithPointerBitCastArgPass()); |
| 644 | pm->add(clspv::createInlineFuncWithPointerToFunctionArgPass()); |
| 645 | pm->add(clspv::createInlineFuncWithSingleCallSitePass()); |
| 646 | } |
| 647 | |
Kévin Petit | 0fc8804 | 2019-04-09 23:25:02 +0100 | [diff] [blame] | 648 | if (clspv::Option::CPlusPlus()) { |
Kévin Petit | 38c5248 | 2019-05-07 20:28:00 +0800 | [diff] [blame] | 649 | pm->add(llvm::createInferAddressSpacesPass(clspv::AddressSpace::Generic)); |
Kévin Petit | 0fc8804 | 2019-04-09 23:25:02 +0100 | [diff] [blame] | 650 | } |
| 651 | |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 652 | if (0 == pmBuilder.OptLevel) { |
| 653 | // Mem2Reg pass should be run early because O0 level optimization leaves |
| 654 | // redundant alloca, load and store instructions from function arguments. |
| 655 | // clspv needs to remove them ahead of transformation. |
| 656 | pm->add(llvm::createPromoteMemoryToRegisterPass()); |
| 657 | |
| 658 | // SROA pass is run because it will fold structs/unions that are problematic |
| 659 | // on Vulkan SPIR-V away. |
| 660 | pm->add(llvm::createSROAPass()); |
| 661 | |
| 662 | // InstructionCombining pass folds bitcast and gep instructions which are |
| 663 | // not supported by Vulkan SPIR-V. |
| 664 | pm->add(llvm::createInstructionCombiningPass()); |
| 665 | } |
| 666 | |
| 667 | // Now we add any of the LLVM optimizations we wanted |
| 668 | pmBuilder.populateModulePassManager(*pm); |
| 669 | |
| 670 | // Unhide loads from __constant address space. Undoes the action of |
| 671 | // HideConstantLoadsPass. |
| 672 | pm->add(clspv::createUnhideConstantLoadsPass()); |
| 673 | |
| 674 | pm->add(clspv::createFunctionInternalizerPass()); |
| 675 | pm->add(clspv::createReplaceLLVMIntrinsicsPass()); |
| 676 | pm->add(clspv::createUndoBoolPass()); |
| 677 | pm->add(clspv::createUndoTruncatedSwitchConditionPass()); |
| 678 | pm->add(llvm::createStructurizeCFGPass(false)); |
alan-baker | 3fa76d9 | 2018-11-12 14:54:40 -0500 | [diff] [blame] | 679 | // Must be run after structurize cfg. |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 680 | pm->add(clspv::createReorderBasicBlocksPass()); |
| 681 | pm->add(clspv::createUndoGetElementPtrConstantExprPass()); |
| 682 | pm->add(clspv::createSplatArgPass()); |
| 683 | pm->add(clspv::createSimplifyPointerBitcastPass()); |
| 684 | pm->add(clspv::createReplacePointerBitcastPass()); |
| 685 | |
| 686 | pm->add(clspv::createUndoTranslateSamplerFoldPass()); |
| 687 | |
| 688 | if (clspv::Option::ModuleConstantsInStorageBuffer()) { |
| 689 | pm->add(clspv::createClusterModuleScopeConstantVars()); |
| 690 | } |
| 691 | |
| 692 | pm->add(clspv::createShareModuleScopeVariablesPass()); |
alan-baker | e930801 | 2019-03-15 10:25:13 -0400 | [diff] [blame] | 693 | // This should be run after LLVM and OpenCL intrinsics are replaced. |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 694 | pm->add(clspv::createAllocateDescriptorsPass(*SamplerMapEntries)); |
| 695 | pm->add(llvm::createVerifierPass()); |
| 696 | pm->add(clspv::createDirectResourceAccessPass()); |
| 697 | // Replacing pointer bitcasts can leave some trivial GEPs |
| 698 | // that are easy to remove. Also replace GEPs of GEPS |
| 699 | // left by replacing indirect buffer accesses. |
| 700 | pm->add(clspv::createSimplifyPointerBitcastPass()); |
alan-baker | 4217b32 | 2019-03-06 08:56:12 -0500 | [diff] [blame] | 701 | // Run after DRA to clean up parameters and help reduce the need for variable |
| 702 | // pointers. |
| 703 | pm->add(clspv::createRemoveUnusedArgumentsPass()); |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 704 | |
| 705 | pm->add(clspv::createSplatSelectConditionPass()); |
| 706 | pm->add(clspv::createSignedCompareFixupPass()); |
| 707 | // This pass generates insertions that need to be rewritten. |
| 708 | pm->add(clspv::createScalarizePass()); |
| 709 | pm->add(clspv::createRewriteInsertsPass()); |
alan-baker | a71f193 | 2019-04-11 11:04:34 -0400 | [diff] [blame] | 710 | // UBO Transformations |
| 711 | if (clspv::Option::ConstantArgsInUniformBuffer() && |
| 712 | !clspv::Option::InlineEntryPoints()) { |
| 713 | // MultiVersionUBOFunctionsPass will examine non-kernel functions with UBO |
| 714 | // arguments and either multi-version them as necessary or inline them if |
| 715 | // multi-versioning cannot be accomplished. |
| 716 | pm->add(clspv::createMultiVersionUBOFunctionsPass()); |
| 717 | // Cleanup passes. |
| 718 | // Specialization can blindly generate GEP chains that are easily cleaned up |
| 719 | // by SimplifyPointerBitcastPass. |
| 720 | pm->add(clspv::createSimplifyPointerBitcastPass()); |
| 721 | // RemoveUnusedArgumentsPass removes the actual UBO arguments that were |
| 722 | // problematic to begin with now that they have no uses. |
| 723 | pm->add(clspv::createRemoveUnusedArgumentsPass()); |
| 724 | // DCE cleans up callers of the specialized functions. |
| 725 | pm->add(llvm::createDeadCodeEliminationPass()); |
| 726 | } |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 727 | // This pass mucks with types to point where you shouldn't rely on DataLayout |
| 728 | // anymore so leave this right before SPIR-V generation. |
| 729 | pm->add(clspv::createUBOTypeTransformPass()); |
alan-baker | 00e7a58 | 2019-06-07 12:54:21 -0400 | [diff] [blame] | 730 | pm->add(clspv::createSPIRVProducerPass(*binaryStream, descriptor_map_entries, |
| 731 | *SamplerMapEntries, |
| 732 | OutputFormat == "c")); |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 733 | |
| 734 | return 0; |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 735 | } |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 736 | |
Kévin Petit | d5db2d2 | 2019-04-04 13:55:14 +0100 | [diff] [blame] | 737 | int ParseOptions(const int argc, const char *const argv[]) { |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 738 | // We need to change how one of the called passes works by spoofing |
| 739 | // ParseCommandLineOptions with the specific option. |
| 740 | const int llvmArgc = 2; |
| 741 | const char *llvmArgv[llvmArgc] = { |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 742 | argv[0], |
| 743 | "-simplifycfg-sink-common=false", |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 744 | }; |
| 745 | |
Kévin Petit | d5db2d2 | 2019-04-04 13:55:14 +0100 | [diff] [blame] | 746 | llvm::cl::ResetAllOptionOccurrences(); |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 747 | llvm::cl::ParseCommandLineOptions(llvmArgc, llvmArgv); |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 748 | llvm::cl::ParseCommandLineOptions(argc, argv); |
| 749 | |
Diego Novillo | 3cc8d7a | 2019-04-10 13:30:34 -0400 | [diff] [blame] | 750 | if (clspv::Option::CPlusPlus() && !clspv::Option::InlineEntryPoints()) { |
Kévin Petit | 0fc8804 | 2019-04-09 23:25:02 +0100 | [diff] [blame] | 751 | llvm::errs() << "cannot use -c++ without -inline-entry-points\n"; |
| 752 | return -1; |
| 753 | } |
| 754 | |
Kévin Petit | d5db2d2 | 2019-04-04 13:55:14 +0100 | [diff] [blame] | 755 | return 0; |
| 756 | } |
Diego Novillo | 8950085 | 2019-04-15 08:45:10 -0400 | [diff] [blame] | 757 | |
| 758 | int GenerateIRFile(llvm::legacy::PassManager *pm, llvm::Module &module, |
| 759 | std::string output) { |
| 760 | std::error_code ec; |
| 761 | std::unique_ptr<llvm::ToolOutputFile> out( |
| 762 | new llvm::ToolOutputFile(output, ec, llvm::sys::fs::F_None)); |
| 763 | if (ec) { |
| 764 | llvm::errs() << output << ": " << ec.message() << '\n'; |
| 765 | return -1; |
| 766 | } |
| 767 | pm->add(llvm::createPrintModulePass(out->os(), "", false)); |
| 768 | pm->run(module); |
| 769 | out->keep(); |
| 770 | return 0; |
| 771 | } |
| 772 | |
Kévin Petit | d5db2d2 | 2019-04-04 13:55:14 +0100 | [diff] [blame] | 773 | } // namespace |
| 774 | |
| 775 | namespace clspv { |
| 776 | int Compile(const int argc, const char *const argv[]) { |
| 777 | |
| 778 | if (auto error = ParseOptions(argc, argv)) |
| 779 | return error; |
| 780 | |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 781 | llvm::SmallVector<std::pair<unsigned, std::string>, 8> SamplerMapEntries; |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 782 | if (auto error = ParseSamplerMap("", &SamplerMapEntries)) |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 783 | return error; |
| 784 | |
| 785 | // if no output file was provided, use a default |
| 786 | llvm::StringRef overiddenInputFilename = InputFilename.getValue(); |
| 787 | |
| 788 | // If we are reading our input file from stdin. |
| 789 | if ("-" == InputFilename) { |
| 790 | // We need to overwrite the file name we use. |
Kévin Petit | ddad8f4 | 2019-09-30 15:12:08 +0100 | [diff] [blame] | 791 | switch (InputLanguage) { |
| 792 | case clang::Language::OpenCL: |
| 793 | overiddenInputFilename = "stdin.cl"; |
| 794 | break; |
| 795 | case clang::Language::LLVM_IR: |
| 796 | overiddenInputFilename = "stdin.ll"; |
| 797 | break; |
| 798 | } |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 799 | } |
| 800 | |
| 801 | clang::CompilerInstance instance; |
Kévin Petit | ddad8f4 | 2019-09-30 15:12:08 +0100 | [diff] [blame] | 802 | clang::FrontendInputFile kernelFile(overiddenInputFilename, |
| 803 | clang::InputKind(InputLanguage)); |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 804 | std::string log; |
| 805 | llvm::raw_string_ostream diagnosticsStream(log); |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 806 | if (auto error = SetCompilerInstanceOptions( |
| 807 | instance, overiddenInputFilename, kernelFile, "", &diagnosticsStream)) |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 808 | return error; |
| 809 | |
| 810 | // Parse. |
| 811 | llvm::LLVMContext context; |
| 812 | clang::EmitLLVMOnlyAction action(&context); |
| 813 | |
| 814 | // Prepare the action for processing kernelFile |
| 815 | const bool success = action.BeginSourceFile(instance, kernelFile); |
| 816 | if (!success) { |
| 817 | return -1; |
| 818 | } |
| 819 | |
alan-baker | f3bce4a | 2019-06-28 16:01:15 -0400 | [diff] [blame] | 820 | auto result = action.Execute(); |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 821 | action.EndSourceFile(); |
| 822 | |
| 823 | clang::DiagnosticConsumer *const consumer = |
| 824 | instance.getDiagnostics().getClient(); |
| 825 | consumer->finish(); |
| 826 | |
Kévin Petit | 6b07cbe | 2019-04-02 21:52:16 +0100 | [diff] [blame] | 827 | auto num_warnings = consumer->getNumWarnings(); |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 828 | auto num_errors = consumer->getNumErrors(); |
Kévin Petit | 6b07cbe | 2019-04-02 21:52:16 +0100 | [diff] [blame] | 829 | if ((num_errors > 0) || (num_warnings > 0)) { |
| 830 | llvm::errs() << log; |
| 831 | } |
alan-baker | f3bce4a | 2019-06-28 16:01:15 -0400 | [diff] [blame] | 832 | if (result || num_errors > 0) { |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 833 | return -1; |
| 834 | } |
| 835 | |
Kévin Petit | 6b07cbe | 2019-04-02 21:52:16 +0100 | [diff] [blame] | 836 | // Don't run the passes or produce any output in verify mode. |
| 837 | // Clang doesn't always produce a valid module. |
| 838 | if (verify) { |
| 839 | return 0; |
| 840 | } |
| 841 | |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 842 | llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry(); |
| 843 | llvm::initializeCore(Registry); |
| 844 | llvm::initializeScalarOpts(Registry); |
Diego Novillo | 1fcff72 | 2019-05-07 13:45:53 -0400 | [diff] [blame] | 845 | llvm::initializeClspvPasses(Registry); |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 846 | |
| 847 | std::unique_ptr<llvm::Module> module(action.takeModule()); |
| 848 | |
| 849 | // Optimize. |
| 850 | // Create a memory buffer for temporarily writing the result. |
| 851 | SmallVector<char, 10000> binary; |
| 852 | llvm::raw_svector_ostream binaryStream(binary); |
| 853 | std::string descriptor_map; |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 854 | llvm::legacy::PassManager pm; |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 855 | std::vector<version0::DescriptorMapEntry> descriptor_map_entries; |
Diego Novillo | 8950085 | 2019-04-15 08:45:10 -0400 | [diff] [blame] | 856 | |
| 857 | // If --emit-ir was requested, emit the initial LLVM IR and stop compilation. |
| 858 | if (!IROutputFile.empty()) { |
| 859 | return GenerateIRFile(&pm, *module, IROutputFile); |
| 860 | } |
| 861 | |
| 862 | // Otherwise, populate the pass manager and run the regular passes. |
Diego Novillo | 3cc8d7a | 2019-04-10 13:30:34 -0400 | [diff] [blame] | 863 | if (auto error = PopulatePassManager( |
| 864 | &pm, &binaryStream, &descriptor_map_entries, &SamplerMapEntries)) |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 865 | return error; |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 866 | pm.run(*module); |
| 867 | |
| 868 | // Write outputs |
| 869 | |
| 870 | // Write the descriptor map, if requested. |
| 871 | std::error_code error; |
| 872 | if (!DescriptorMapFilename.empty()) { |
Diego Novillo | 3cc8d7a | 2019-04-10 13:30:34 -0400 | [diff] [blame] | 873 | llvm::raw_fd_ostream descriptor_map_out_fd( |
| 874 | DescriptorMapFilename, error, llvm::sys::fs::CD_CreateAlways, |
| 875 | llvm::sys::fs::FA_Write, llvm::sys::fs::F_Text); |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 876 | if (error) { |
| 877 | llvm::errs() << "Unable to open descriptor map file '" |
| 878 | << DescriptorMapFilename << "': " << error.message() << '\n'; |
| 879 | return -1; |
| 880 | } |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 881 | std::string descriptor_map_string; |
| 882 | std::ostringstream str(descriptor_map_string); |
| 883 | for (const auto &entry : descriptor_map_entries) { |
| 884 | str << entry << "\n"; |
| 885 | } |
| 886 | descriptor_map_out_fd << str.str(); |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 887 | descriptor_map_out_fd.close(); |
| 888 | } |
| 889 | |
| 890 | // Write the resulting binary. |
| 891 | // Wait until now to try writing the file so that we only write it on |
| 892 | // successful compilation. |
| 893 | if (OutputFilename.empty()) { |
Kévin Petit | e478690 | 2019-04-02 21:51:47 +0100 | [diff] [blame] | 894 | if (OutputFormat == "c") { |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 895 | OutputFilename = "a.spvinc"; |
| 896 | } else { |
| 897 | OutputFilename = "a.spv"; |
| 898 | } |
| 899 | } |
Diego Novillo | 3cc8d7a | 2019-04-10 13:30:34 -0400 | [diff] [blame] | 900 | llvm::raw_fd_ostream outStream(OutputFilename, error, |
| 901 | llvm::sys::fs::FA_Write); |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 902 | |
| 903 | if (error) { |
| 904 | llvm::errs() << "Unable to open output file '" << OutputFilename |
| 905 | << "': " << error.message() << '\n'; |
| 906 | return -1; |
| 907 | } |
| 908 | outStream << binaryStream.str(); |
| 909 | |
| 910 | return 0; |
| 911 | } |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 912 | |
Diego Novillo | 3cc8d7a | 2019-04-10 13:30:34 -0400 | [diff] [blame] | 913 | int CompileFromSourceString( |
| 914 | const std::string &program, const std::string &sampler_map, |
| 915 | const std::string &options, std::vector<uint32_t> *output_binary, |
| 916 | std::vector<clspv::version0::DescriptorMapEntry> *descriptor_map_entries) { |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 917 | |
| 918 | llvm::SmallVector<const char *, 20> argv; |
| 919 | llvm::BumpPtrAllocator A; |
| 920 | llvm::StringSaver Saver(A); |
| 921 | argv.push_back(Saver.save("clspv").data()); |
| 922 | llvm::cl::TokenizeGNUCommandLine(options, Saver, argv); |
| 923 | int argc = static_cast<int>(argv.size()); |
Kévin Petit | d5db2d2 | 2019-04-04 13:55:14 +0100 | [diff] [blame] | 924 | |
| 925 | if (auto error = ParseOptions(argc, &argv[0])) |
| 926 | return error; |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 927 | |
| 928 | llvm::SmallVector<std::pair<unsigned, std::string>, 8> SamplerMapEntries; |
| 929 | if (auto error = ParseSamplerMap(sampler_map, &SamplerMapEntries)) |
| 930 | return error; |
| 931 | |
| 932 | InputFilename = "source.cl"; |
| 933 | llvm::StringRef overiddenInputFilename = InputFilename.getValue(); |
| 934 | |
| 935 | clang::CompilerInstance instance; |
alan-baker | d354f1a | 2019-08-06 15:41:55 -0400 | [diff] [blame] | 936 | clang::FrontendInputFile kernelFile( |
| 937 | overiddenInputFilename, clang::InputKind(clang::Language::OpenCL)); |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 938 | std::string log; |
| 939 | llvm::raw_string_ostream diagnosticsStream(log); |
| 940 | if (auto error = |
| 941 | SetCompilerInstanceOptions(instance, overiddenInputFilename, |
| 942 | kernelFile, program, &diagnosticsStream)) |
| 943 | return error; |
| 944 | |
| 945 | // Parse. |
| 946 | llvm::LLVMContext context; |
| 947 | clang::EmitLLVMOnlyAction action(&context); |
| 948 | |
| 949 | // Prepare the action for processing kernelFile |
| 950 | const bool success = action.BeginSourceFile(instance, kernelFile); |
| 951 | if (!success) { |
| 952 | return -1; |
| 953 | } |
| 954 | |
alan-baker | f3bce4a | 2019-06-28 16:01:15 -0400 | [diff] [blame] | 955 | auto result = action.Execute(); |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 956 | action.EndSourceFile(); |
| 957 | |
| 958 | clang::DiagnosticConsumer *const consumer = |
| 959 | instance.getDiagnostics().getClient(); |
| 960 | consumer->finish(); |
| 961 | |
| 962 | auto num_errors = consumer->getNumErrors(); |
alan-baker | f3bce4a | 2019-06-28 16:01:15 -0400 | [diff] [blame] | 963 | if (result || num_errors > 0) { |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 964 | llvm::errs() << log << "\n"; |
| 965 | return -1; |
| 966 | } |
| 967 | |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 968 | llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry(); |
| 969 | llvm::initializeCore(Registry); |
| 970 | llvm::initializeScalarOpts(Registry); |
Diego Novillo | 1fcff72 | 2019-05-07 13:45:53 -0400 | [diff] [blame] | 971 | llvm::initializeClspvPasses(Registry); |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 972 | |
| 973 | std::unique_ptr<llvm::Module> module(action.takeModule()); |
| 974 | |
| 975 | // Optimize. |
| 976 | // Create a memory buffer for temporarily writing the result. |
| 977 | SmallVector<char, 10000> binary; |
| 978 | llvm::raw_svector_ostream binaryStream(binary); |
| 979 | std::string descriptor_map; |
| 980 | llvm::legacy::PassManager pm; |
Diego Novillo | 3cc8d7a | 2019-04-10 13:30:34 -0400 | [diff] [blame] | 981 | if (auto error = PopulatePassManager( |
| 982 | &pm, &binaryStream, descriptor_map_entries, &SamplerMapEntries)) |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 983 | return error; |
| 984 | pm.run(*module); |
| 985 | |
| 986 | // Write outputs |
| 987 | |
| 988 | // Write the descriptor map. This is required. |
Diego Novillo | 3cc8d7a | 2019-04-10 13:30:34 -0400 | [diff] [blame] | 989 | assert(descriptor_map_entries && |
| 990 | "Valid descriptor map container is required."); |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 991 | if (!DescriptorMapFilename.empty()) { |
Diego Novillo | 3cc8d7a | 2019-04-10 13:30:34 -0400 | [diff] [blame] | 992 | llvm::errs() << "Warning: -descriptormap is ignored descriptor map " |
| 993 | "container is provided.\n"; |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 994 | } |
| 995 | |
| 996 | // Write the resulting binary. |
| 997 | // Wait until now to try writing the file so that we only write it on |
| 998 | // successful compilation. |
| 999 | assert(output_binary && "Valid binary container is required."); |
| 1000 | if (!OutputFilename.empty()) { |
| 1001 | llvm::outs() |
| 1002 | << "Warning: -o is ignored when binary container is provided.\n"; |
| 1003 | } |
| 1004 | output_binary->resize(binary.size() / 4); |
| 1005 | memcpy(output_binary->data(), binary.data(), binary.size()); |
| 1006 | |
| 1007 | return 0; |
| 1008 | } |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 1009 | } // namespace clspv |