MLIR 24.0.0git
Target.cpp
Go to the documentation of this file.
1//===- Target.cpp - MLIR LLVM XeVM target compilation -----------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This files defines XeVM target related functions including registration
10// calls for the `#xevm.target` compilation attribute.
11//
12//===----------------------------------------------------------------------===//
13
27#include "llvm/ADT/ScopeExit.h"
28#include "llvm/Bitcode/BitcodeWriter.h"
29#include "llvm/Config/Targets.h"
30#include "llvm/IR/LegacyPassManager.h"
31#include "llvm/Support/FileSystem.h"
32#include "llvm/Support/FileUtilities.h"
33#include "llvm/Support/FormatVariadic.h"
34#include "llvm/Support/MemoryBuffer.h"
35#include "llvm/Support/Path.h"
36#include "llvm/Support/Program.h"
37#include "llvm/Support/TargetSelect.h"
38#include "llvm/Support/raw_ostream.h"
39#include "llvm/Target/TargetMachine.h"
40
41#include <cstdint>
42#include <cstdlib>
43#include <mutex>
44
45using namespace mlir;
46using namespace mlir::xevm;
47
48#if MLIR_XEVM_OCLOC_LIB_AVAILABLE
49// Intel compute runtime includes libocloc in the distribution, but
50// <ocloc_api.h> isn't included. Hence forward declarations for the libocloc
51// shared-library APIs is needed. These replace the inclusion of <ocloc_api.h>
52// so that the header is not a build-time requirement; the symbols are resolved
53// at link/load time via the ocloc shared library.
54extern "C" {
55
56// Return code indicating successful ocloc compilation.
57// Matches the OCLOC_SUCCESS enumerator in the real header (value 0).
58enum OclocErrorCode : int { OCLOC_SUCCESS = 0 };
59
60// Drives an in-process ocloc compilation.
61/// Invokes ocloc API using C interface. Supported commands match
62/// the functionality of ocloc executable (check ocloc's "help"
63/// for reference : shared/offline_compiler/source/ocloc_api.cpp).
64///
65/// numArgs and argv params represent the command line.
66/// Remaining params represent I/O.
67/// Output params should be freed using oclocFreeOutput when
68/// no longer needed.
69/// List and names of outputs match outputs of ocloc executable.
70///
71/// \param numArgs is the number of arguments to pass to ocloc
72///
73/// \param argv is an array of arguments to be passed to ocloc
74///
75/// \param numSources is the number of in-memory representations
76/// of source files to be passed to ocloc
77///
78/// \param dataSources is an array of in-memory representations
79/// of source files to be passed to ocloc
80///
81/// \param lenSources is an array of sizes of in-memory representations
82/// of source files passed to ocloc as dataSources
83///
84/// \param nameSources is an array of names of in-memory representations
85/// of source files passed to ocloc as dataSources
86///
87/// \param numInputHeaders is the number of in-memory representations
88/// of header files to be passed to ocloc
89///
90/// \param dataInputHeaders is an array of in-memory representations
91/// of header files to be passed to ocloc
92///
93/// \param lenInputHeaders is an array of sizes of in-memory representations
94/// of header files passed to ocloc as dataInputHeaders
95///
96/// \param nameInputHeaders is an array of names of in-memory representations
97/// of header files passed to ocloc as dataInputHeaders
98///
99/// \param numOutputs returns the number of outputs
100///
101/// \param dataOutputs returns an array of in-memory representations
102/// of output files
103///
104/// \param lenOutputs returns an array of sizes of in-memory representations
105/// of output files
106///
107/// \param nameOutputs returns an array of names of in-memory representations
108/// of output files. Special name stdout.log describes output that contains
109/// messages generated by ocloc (e.g. compiler errors/warnings)
110///
111/// \returns 0 on success. Returns non-0 in case of failure.
112
113int oclocInvoke(unsigned numArgs, const char **argv, unsigned numSources,
114 const uint8_t **dataSources, const uint64_t *lenSources,
115 const char **nameSources, unsigned numHeaders,
116 const uint8_t **dataHeaders, const uint64_t *lenHeaders,
117 const char **nameHeaders, unsigned *numOutputs,
118 uint8_t ***dataOutputs, uint64_t **lenOutputs,
119 char ***nameOutputs);
120
121/// Frees results of oclocInvoke
122///
123/// \param numOutputs is number of outputs as returned by oclocInvoke
124///
125/// \param dataOutputs is array of outputs as returned by oclocInvoke
126///
127/// \param lenOutputs is array of sizes of outputs as returned by oclocInvoke
128///
129/// \param nameOutputs is array of names of outputs as returned by oclocInvoke
130///
131/// \returns 0 on success. Returns non-0 in case of failure.
132int oclocFreeOutput(unsigned *numOutputs, uint8_t ***dataOutputs,
133 uint64_t **lenOutputs, char ***nameOutputs);
134
135} // extern "C"
136#endif // MLIR_XEVM_OCLOC_LIB_AVAILABLE
137
138namespace {
139// XeVM implementation of the gpu:TargetAttrInterface.
140class XeVMTargetAttrImpl
141 : public gpu::TargetAttrInterface::FallbackModel<XeVMTargetAttrImpl> {
142public:
143 std::optional<mlir::gpu::SerializedObject>
144 serializeToObject(Attribute attribute, Operation *module,
145 const gpu::TargetOptions &options) const;
146
147 Attribute createObject(Attribute attribute, Operation *module,
148 const mlir::gpu::SerializedObject &object,
149 const gpu::TargetOptions &options) const;
150};
151} // namespace
152
154 DialectRegistry &registry) {
155 registry.addExtension(+[](MLIRContext *ctx, XeVMDialect *dialect) {
156 XeVMTargetAttr::attachInterface<XeVMTargetAttrImpl>(*ctx);
157 });
158}
159
166
168 Operation &module, XeVMTargetAttr xeTarget,
170 : ModuleToObject(module, xeTarget.getTriple(), "", {}, xeTarget.getO(), {},
171 {}, {}, {}, targetOptions.getLibraryOptions()),
172 xeTarget(xeTarget), librariesToLink(targetOptions.getLibrariesToLink()),
173 targetOptions(targetOptions) {
174 if (xeTarget.getLinkFiles())
175 librariesToLink.append(xeTarget.getLinkFiles().begin(),
176 xeTarget.getLinkFiles().end());
177}
178
179XeVMTargetAttr SerializeGPUModuleBase::getTarget() const { return xeTarget; }
180
181std::optional<SmallVector<std::unique_ptr<llvm::Module>>>
183 if (librariesToLink.empty())
186 if (failed(loadBitcodeFilesFromList(module.getContext(), librariesToLink,
187 bcFiles)))
188 return std::nullopt;
189 return std::move(bcFiles);
190}
191
193 return dyn_cast<gpu::GPUModuleOp>(&SerializeGPUModuleBase::getOperation());
194}
195
196// ----------------------------------------------------------------------------
197// compile via the ocloc shared-library API (in-process, no temp files). Only
198// compiled when the library is available at build time.
199// ----------------------------------------------------------------------------
200#if MLIR_XEVM_OCLOC_LIB_AVAILABLE
201FailureOr<SmallVector<char, 0>>
203 StringRef inputFormat) {
204 Location loc = getGPUModuleOp().getLoc();
205 std::string asmFname = llvm::formatv(
206 "mlir-{0}-{1}-{2}.asm", getGPUModuleOp().getNameAttr().getValue(),
207 getTarget().getTriple(), getTarget().getChip());
208
209 // Build command-line options.
210 std::pair<llvm::BumpPtrAllocator, SmallVector<const char *>> cmdOpts =
212 // Example: --gpu-module-to-binary="opts='opt1 opt2'"
213 const std::string cmdOptsStr = "\"" + llvm::join(cmdOpts.second, " ") + "\"";
214 std::vector<std::string> oclocArgs = {"ocloc",
215 "compile",
216 "-file",
217 asmFname,
218 inputFormat.str(),
219 "-device",
220 getTarget().getChip().str(),
221 "-options",
222 cmdOptsStr};
223
224// Dump tool invocation commands.
225#define DEBUG_TYPE "serialize-to-binary"
226 LLVM_DEBUG({
227 llvm::dbgs() << "libocloc invocation for module: "
228 << getGPUModuleOp().getNameAttr() << "\n";
229 llvm::interleave(oclocArgs, llvm::dbgs(), " ");
230 llvm::dbgs() << "\n";
231 });
232#undef DEBUG_TYPE
233
234 // Build a plain argv array expected by oclocInvoke.
235 std::vector<const char *> argv;
236 for (const auto &str : oclocArgs)
237 argv.push_back(str.c_str());
238
239 // Wire up in-memory source file.
240 const uint8_t *dataSources[1] = {
241 reinterpret_cast<const uint8_t *>(asmStr.data())};
242 const uint64_t lenSources[1] = {asmStr.size()};
243 const char *nameSources[1] = {asmFname.c_str()};
244
245 uint32_t outputsNum = 0;
246 uint8_t **outputs = nullptr;
247 uint64_t *outputLengths = nullptr;
248 char **outputNames = nullptr;
249 // Ensure ocloc output buffers are always freed on exit.
250 auto freeOutputs = llvm::scope_exit([&]() {
251 oclocFreeOutput(&outputsNum, &outputs, &outputLengths, &outputNames);
252 });
253
254 int err = oclocInvoke(static_cast<uint32_t>(argv.size()), argv.data(),
255 /*numSources=*/1, dataSources, lenSources, nameSources,
256 /*numHeaders=*/0, nullptr, nullptr, nullptr,
257 &outputsNum, &outputs, &outputLengths, &outputNames);
258
259 if (err != OCLOC_SUCCESS) {
260 emitError(loc) << "libocloc: `oclocInvoke` failed, error code: " << err;
261 // Emit any compiler log that ocloc produced.
262 for (uint32_t i = 0; i < outputsNum; ++i) {
263 if (llvm::StringRef(outputNames[i]).ends_with(".log"))
264 emitError(loc) << "Compiler log:\n"
265 << llvm::StringRef(reinterpret_cast<char *>(outputs[i]),
266 outputLengths[i]);
267 }
268 return failure();
269 }
270
271 // Find and return the .bin output.
272 for (uint32_t i = 0; i < outputsNum; ++i) {
273 if (llvm::StringRef(outputNames[i]).ends_with(".bin")) {
274 char *begin = reinterpret_cast<char *>(outputs[i]);
275 return SmallVector<char, 0>(begin, begin + outputLengths[i]);
276 }
277 }
278 return emitError(loc) << "`oclocInvoke` did not produce `.bin` output";
279}
280#endif // MLIR_XEVM_OCLOC_LIB_AVAILABLE
281
282// ----------------------------------------------------------------------------
283// Compile by spawning the `ocloc` command-line tool as a process,
284// communicating through temporary files. Acts as a fallback when the shared
285// library is not available.
286// ----------------------------------------------------------------------------
287FailureOr<SmallVector<char, 0>>
289 StringRef inputFormat) {
290 using TmpFile = std::pair<llvm::SmallString<128>, llvm::FileRemover>;
291
292 // Locate the `ocloc` executable on PATH.
293 std::optional<std::string> oclocPath = findTool("ocloc");
294 if (!oclocPath) {
295 emitError(getGPUModuleOp().getLoc()) << "Could not find `ocloc` on PATH";
296 return failure();
297 }
298
299 Location loc = getGPUModuleOp().getLoc();
300 std::string basename = llvm::formatv(
301 "mlir-{0}-{1}-{2}", getGPUModuleOp().getNameAttr().getValue(),
302 getTarget().getTriple(), getTarget().getChip());
303
304 // Helper: create a named temporary file, returning path + auto-remover.
305 auto createTemp = [&](StringRef name,
306 StringRef suffix) -> std::optional<TmpFile> {
308 if (auto ec = llvm::sys::fs::createTemporaryFile(name, suffix, path)) {
309 emitError(loc) << "Couldn't create temp file `" << path
310 << "`: " << ec.message();
311 return std::nullopt;
312 }
313 return TmpFile(path, llvm::FileRemover(path.c_str()));
314 };
315
316 std::optional<TmpFile> asmFile = createTemp(basename, "asm");
317 std::optional<TmpFile> binFile = createTemp(basename, "");
318 std::optional<TmpFile> logFile = createTemp(basename, "log");
319 if (!asmFile || !binFile || !logFile)
320 return failure();
321
322 // Write the assembly source to a temp file.
323 {
324 std::error_code ec;
325 llvm::raw_fd_ostream asmStream(asmFile->first, ec);
326 if (ec) {
327 emitError(loc) << "Couldn't open `" << asmFile->first
328 << "`: " << ec.message();
329 return failure();
330 }
331 asmStream << asmStr;
332 if (asmStream.has_error()) {
333 emitError(loc) << "Error writing assembly to `" << asmFile->first << "`";
334 return failure();
335 }
336 asmStream.flush();
337 }
338
339 // Build command-line options.
340 std::pair<llvm::BumpPtrAllocator, SmallVector<const char *>> cmdOpts =
341 targetOptions.tokenizeCmdOptions();
342 const std::string cmdOptsStr = "\"" + llvm::join(cmdOpts.second, " ") + "\"";
343
345 {"ocloc", "compile", "-file", asmFile->first, inputFormat, "-device",
346 getTarget().getChip(), "-output", binFile->first, "-output_no_suffix",
347 "-options", cmdOptsStr});
348
349 // Dump tool invocation commands.
350#define DEBUG_TYPE "serialize-to-binary"
351 LLVM_DEBUG({
352 llvm::dbgs() << "Tool invocation for module: "
353 << getGPUModuleOp().getNameAttr() << "\n";
354 llvm::interleave(oclocArgs, llvm::dbgs(), " ");
355 llvm::dbgs() << "\n";
356 });
357#undef DEBUG_TYPE
358
359 // Redirect stdout/stderr to the log temp file.
360 std::optional<StringRef> redirects[] = {std::nullopt, logFile->first,
361 logFile->first};
362
363 std::string errorMsg;
364 if (llvm::sys::ExecuteAndWait(*oclocPath, oclocArgs, std::nullopt, redirects,
365 0, 0, &errorMsg)) {
366 // Prefer a structured error message; otherwise dump the log file.
367 if (!errorMsg.empty()) {
368 emitError(loc) << "`ocloc` invocation failed: " << errorMsg;
369 } else if (auto log = llvm::MemoryBuffer::getFile(logFile->first)) {
370 emitError(loc) << "`ocloc` invocation failed. Log:\n"
371 << (*log)->getBuffer();
372 } else {
373 emitError(loc) << "`ocloc` invocation failed (no log available)";
374 }
375 return failure();
376 }
377
378 // Read back the binary output (ocloc appends ".bin" to the base name).
379 binFile->first.append(".bin");
380 auto binaryBuffer = llvm::MemoryBuffer::getFile(binFile->first);
381 if (!binaryBuffer) {
382 emitError(loc) << "Couldn't open binary output `" << binFile->first
383 << "`: " << binaryBuffer.getError().message();
384 return failure();
385 }
386 StringRef bin = (*binaryBuffer)->getBuffer();
387 return SmallVector<char, 0>(bin.begin(), bin.end());
388}
389
390// ----------------------------------------------------------------------------
391// Public entry-point: prefer the in-process library path; fall back to the
392// external tool when the library is not available.
393// ----------------------------------------------------------------------------
394FailureOr<SmallVector<char, 0>>
396 StringRef inputFormat) {
397#if MLIR_XEVM_OCLOC_LIB_AVAILABLE
398 return compileToBinaryViaLibocloc(asmStr, inputFormat);
399#else
400 return compileToBinaryViaOclocTool(asmStr, inputFormat);
401#endif
402}
403
405 [[maybe_unused]] const gpu::TargetOptions &targetOptions) {
406 static constexpr const char *query = "OCL_DRIVER_VERSION";
407#if MLIR_XEVM_OCLOC_LIB_AVAILABLE
408 const char *argv[] = {"ocloc", "query", query};
409 uint32_t outputsNum = 0;
410 uint8_t **outputs = nullptr;
411 uint64_t *outputLengths = nullptr;
412 char **outputNames = nullptr;
413 auto freeOutputs = llvm::scope_exit([&]() {
414 oclocFreeOutput(&outputsNum, &outputs, &outputLengths, &outputNames);
415 });
416 if (oclocInvoke(std::size(argv), argv, /*numSources=*/0, nullptr, nullptr,
417 nullptr, /*numHeaders=*/0, nullptr, nullptr, nullptr,
418 &outputsNum, &outputs, &outputLengths,
419 &outputNames) != OCLOC_SUCCESS)
420 return {};
421 for (uint32_t i = 0; i < outputsNum; ++i)
422 if (outputNames && outputNames[i] && StringRef(outputNames[i]) == query)
423 return outputs && outputs[i] && outputLengths
424 ? StringRef(reinterpret_cast<char *>(outputs[i]),
425 outputLengths[i])
426 .rtrim('\0')
427 .trim()
428 .str()
429 : std::string();
430 return {};
431#else
432 std::optional<std::string> oclocPath = findTool("ocloc", targetOptions);
434 if (!oclocPath || llvm::sys::fs::createTemporaryFile("ocloc", "query", out))
435 return {};
436 llvm::FileRemover outRemover(out);
437 // ocloc writes the result to a file in the CWD, serialize the queries.
438 static std::mutex queryMutex;
439 std::lock_guard<std::mutex> lock(queryMutex);
440 // Remove the file created by ocloc unless it already existed. ocloc
441 // overwrites an existing file, so only the file is kept, not its content.
442 llvm::FileRemover queryRemover(query,
443 /*deleteIt=*/!llvm::sys::fs::exists(query));
444 std::optional<StringRef> redirects[] = {std::nullopt, out.str(),
445 StringRef("")};
446 if (llvm::sys::ExecuteAndWait(*oclocPath, {"ocloc", "query", query},
447 std::nullopt, redirects))
448 return {};
449 // Newer versions also print the result to stdout, older ones write only the
450 // file in the CWD.
451 for (StringRef file : {out.str(), StringRef(query)})
452 if (llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> buf =
453 llvm::MemoryBuffer::getFile(file))
454 if (StringRef ver = (*buf)->getBuffer().rtrim('\0').trim(); !ver.empty())
455 return ver.str();
456 return {};
457#endif
458}
459
460std::optional<std::string>
463 // 1. Check the toolkit path given in the command line.
464 StringRef pathRef = targetOptions.getToolkitPath();
466 if (!pathRef.empty()) {
467 path.insert(path.begin(), pathRef.begin(), pathRef.end());
468 llvm::sys::path::append(path, "bin", tool);
469 if (llvm::sys::fs::can_execute(path))
470 return StringRef(path.data(), path.size()).str();
471 }
472 // 2. Check PATH.
473 if (llvm::ErrorOr<std::string> toolPath = llvm::sys::findProgramByName(tool))
474 return *toolPath;
475 return std::nullopt;
476}
477
478std::optional<std::string> SerializeGPUModuleBase::findTool(StringRef tool) {
479 if (std::optional<std::string> path = findTool(tool, targetOptions))
480 return path;
481 getGPUModuleOp().emitError()
482 << "Couldn't find the `" << tool
483 << "` binary. Please specify the toolkit "
484 "path via GpuModuleToBinaryPass or add the compiler to $PATH`.";
485 return std::nullopt;
486}
487namespace {
488class SPIRVSerializer : public SerializeGPUModuleBase {
489public:
490 SPIRVSerializer(Operation &module, XeVMTargetAttr xeTarget,
491 const gpu::TargetOptions &targetOptions)
492 : SerializeGPUModuleBase(module, xeTarget, targetOptions) {}
493
494 static void init();
495
496 /// Serializes the LLVM module to an object format, depending on the
497 /// compilation target selected in target options.
498 FailureOr<SmallVector<char, 0>>
499 moduleToObject(llvm::Module &llvmModule) override;
500
501 /// Runs the serialization pipeline, returning `std::nullopt` on error.
502 std::optional<SmallVector<char, 0>> run() override;
503
504private:
505 /// Translates the LLVM module to SPIR-V binary using LLVM's
506 /// SPIR-V target.
507 std::optional<std::string>
508 translateToSPIRVBinary(llvm::Module &llvmModule,
509 llvm::TargetMachine &targetMachine);
510};
511} // namespace
512
513void SPIRVSerializer::init() {
514 static llvm::once_flag initializeBackendOnce;
515 llvm::call_once(initializeBackendOnce, []() {
516#if LLVM_HAS_SPIRV_TARGET
517 LLVMInitializeSPIRVTarget();
518 LLVMInitializeSPIRVTargetInfo();
519 LLVMInitializeSPIRVTargetMC();
520 LLVMInitializeSPIRVAsmPrinter();
521#endif
522 });
523}
524
525#if LLVM_HAS_SPIRV_TARGET
526// Enable default set of SPIR-V extensions.
527// Supported extensions vary based on chip. See,
528// https://github.com/intel/intel-graphics-compiler/blob/master/
529// documentation/igc/supported-spirv-extensions.md
530// for details.
531static const std::vector<std::string> getDefaultSPIRVExtensions() {
532 return {
533 "SPV_KHR_bfloat16",
534 "SPV_EXT_relaxed_printf_string_address_space",
535 "SPV_INTEL_cache_controls",
536 "SPV_INTEL_variable_length_array",
537 "SPV_EXT_bfloat16_arithmetic",
538 "SPV_INTEL_subgroups",
539 };
540}
541
542namespace llvm {
543class Module;
544
545extern "C" bool
546SPIRVTranslateModule(Module *M, std::string &SpirvObj, std::string &ErrMsg,
547 const std::vector<std::string> &AllowExtNames,
548 const std::vector<std::string> &Opts);
549} // namespace llvm
550#endif
551
552// There is 1 way to finalize IL to native code: IGC
553// There are 2 ways to access IGC: AOT (ocloc) and JIT (L0 runtime).
554// - L0 runtime consumes IL and is external to MLIR codebase (rt wrappers).
555// - `ocloc` tool can be "queried" from within MLIR.
556FailureOr<SmallVector<char, 0>>
557SPIRVSerializer::moduleToObject(llvm::Module &llvmModule) {
558#define DEBUG_TYPE "serialize-to-llvm"
559 LLVM_DEBUG({
560 llvm::dbgs() << "LLVM IR for module: " << getGPUModuleOp().getNameAttr()
561 << "\n";
562 llvm::dbgs() << llvmModule << "\n";
563 llvm::dbgs().flush();
564 });
565#undef DEBUG_TYPE
566
567 // Return LLVM IR if the compilation target is `offload`.
568 if (targetOptions.getCompilationTarget() == gpu::CompilationTarget::Offload)
570
571#if !LLVM_HAS_SPIRV_TARGET
572 return getGPUModuleOp()->emitError(
573 "The `SPIRV` target was not built. Please enable "
574 "it when building LLVM.");
575#else
576 std::string serializedSPIRVBinary;
577 std::string ErrMsg;
578 std::vector<std::string> Opts;
579 Opts.push_back(triple.str());
580 Opts.push_back(std::to_string(optLevel));
581
582 // Translate the LLVM module to SPIR-V binary using LLVM's SPIR-V Backend API.
583 bool success =
584 SPIRVTranslateModule(&llvmModule, serializedSPIRVBinary, ErrMsg,
585 getDefaultSPIRVExtensions(), Opts);
586
587 if (!success)
588 return getGPUModuleOp().emitError()
589 << "Failed translating the module to Binary."
590 << "Error message: " << ErrMsg;
591
592 if (serializedSPIRVBinary.size() % 4)
593 return getGPUModuleOp().emitError()
594 << "SPIRV code size must be a multiple of 4.";
595
596 StringRef spirvBin(serializedSPIRVBinary.c_str(),
597 serializedSPIRVBinary.size());
598
599 // Return SPIRV binary if the compilation target is `assembly`. Optimization
600 // and SPIR-V extensions are enabled for SPIR-V binary output in both paths
601 // (assembly and binary) as of now. SPIR-V binary
602 // is generated directly using the SPIR-V backends `SPIRVTranslateModule` API.
603 if (targetOptions.getCompilationTarget() ==
604 gpu::CompilationTarget::Assembly) {
605#define DEBUG_TYPE "serialize-to-isa"
606 LLVM_DEBUG({
607 llvm::dbgs() << "SPIR-V for module: " << getGPUModuleOp().getNameAttr()
608 << "\n";
609 llvm::dbgs() << serializedSPIRVBinary << "\n";
610 llvm::dbgs().flush();
611 });
612#undef DEBUG_TYPE
613 return SmallVector<char, 0>(spirvBin.begin(), spirvBin.end());
614 }
615
616 // Return native binary. Compile the SPIR-V binary to native binary for Intel
617 // GPUs using `ocloc` compiler (Intel's OpenCL Offline Compiler).
618
619 return compileToBinary(spirvBin, "-spirv_input");
620#endif // LLVM_HAS_SPIRV_TARGET
621}
622
623std::optional<SmallVector<char, 0>> SPIRVSerializer::run() {
624 // Translate the module to LLVM IR.
625 llvm::LLVMContext llvmContext;
626 std::unique_ptr<llvm::Module> llvmModule = translateToLLVMIR(llvmContext);
627 if (!llvmModule) {
628 getOperation().emitError() << "Failed creating the llvm::Module.";
629 return std::nullopt;
630 }
631 setDataLayoutAndTriple(*llvmModule);
632
633 if (initialLlvmIRCallback)
634 initialLlvmIRCallback(*llvmModule);
635
636 // Link bitcode files.
637 handleModulePreLink(*llvmModule);
638 {
639 auto libs = loadBitcodeFiles(*llvmModule);
640 if (!libs)
641 return std::nullopt;
642 if (!libs->empty())
643 if (failed(linkFiles(*llvmModule, std::move(*libs))))
644 return std::nullopt;
645 handleModulePostLink(*llvmModule);
646 }
647
648 if (linkedLlvmIRCallback)
649 linkedLlvmIRCallback(*llvmModule);
650
651 // Return the serialized object.
652 return moduleToObject(*llvmModule);
653}
654
655std::optional<std::string>
656SPIRVSerializer::translateToSPIRVBinary(llvm::Module &llvmModule,
657 llvm::TargetMachine &targetMachine) {
658 std::string targetISA;
659 llvm::raw_string_ostream stream(targetISA);
660
661 { // Drop pstream after this to prevent the ISA from being stuck buffering
662 llvm::buffer_ostream pstream(stream);
663 llvm::legacy::PassManager codegenPasses;
664 if (targetMachine.addPassesToEmitFile(codegenPasses, pstream, nullptr,
665 llvm::CodeGenFileType::ObjectFile))
666 return std::nullopt;
667
668 codegenPasses.run(llvmModule);
669 }
670 return targetISA;
671}
672
673std::optional<mlir::gpu::SerializedObject>
674XeVMTargetAttrImpl::serializeToObject(Attribute attribute, Operation *module,
675 const gpu::TargetOptions &options) const {
676 if (!module)
677 return std::nullopt;
678 auto gpuMod = dyn_cast<gpu::GPUModuleOp>(module);
679 if (!gpuMod) {
680 module->emitError("expected to be a gpu.module op");
681 return std::nullopt;
682 }
683 auto xeTarget = cast<XeVMTargetAttr>(attribute);
684 if (xeTarget.getTriple().starts_with("spirv")) {
685 gpuMod.walk([&](LLVM::LLVMFuncOp funcOp) {
686 if (funcOp->hasDiscardableAttr(gpu::GPUDialect::getKernelFuncAttrName()))
687 funcOp.setIntelReqdSubGroupSize(16);
688 });
689
690 SPIRVSerializer serializer(*module, cast<XeVMTargetAttr>(attribute),
691 options);
692 serializer.init();
693
694#if !LLVM_HAS_SPIRV_TARGET
695 module->emitError("Cannot run `TargetRegistry::lookupTarget()` for SPIRV "
696 "without having the target built.");
697#endif
698
699 std::optional<SmallVector<char, 0>> binary = serializer.run();
700 if (!binary)
701 return std::nullopt;
702 return gpu::SerializedObject{std::move(*binary)};
703 }
704 module->emitError("Unsupported XeVM target triple: ") << xeTarget.getTriple();
705 return std::nullopt;
706}
707
708Attribute
709XeVMTargetAttrImpl::createObject(Attribute attribute, Operation *module,
710 const mlir::gpu::SerializedObject &object,
711 const gpu::TargetOptions &options) const {
712 Builder builder(attribute.getContext());
713 gpu::CompilationTarget format = options.getCompilationTarget();
714 auto xeTarget = cast<XeVMTargetAttr>(attribute);
715 SmallVector<NamedAttribute, 2> properties;
716 if (format == gpu::CompilationTarget::Assembly)
717 properties.push_back(
718 builder.getNamedAttr("O", builder.getI32IntegerAttr(xeTarget.getO())));
719
720 DictionaryAttr objectProps;
721 if (!properties.empty())
722 objectProps = builder.getDictionaryAttr(properties);
723
724 return builder.getAttr<gpu::ObjectAttr>(
725 attribute, format,
726 builder.getStringAttr(
727 StringRef(object.getObject().data(), object.getObject().size())),
728 objectProps, /*kernels=*/nullptr);
729}
return success()
static llvm::ManagedStatic< PassManagerOptions > options
MLIRContext * getContext() const
Return the context this attribute belongs to.
The DialectRegistry maps a dialect namespace to a constructor for the matching dialect.
bool addExtension(TypeID extensionID, std::unique_ptr< DialectExtensionBase > extension)
Add the given extension to the registry.
LogicalResult loadBitcodeFilesFromList(llvm::LLVMContext &context, ArrayRef< Attribute > librariesToLink, SmallVector< std::unique_ptr< llvm::Module > > &llvmModules, bool failureOnError=true)
Loads multiple bitcode files.
virtual FailureOr< SmallVector< char, 0 > > moduleToObject(llvm::Module &llvmModule)
Serializes the LLVM IR bitcode to an object file, by default it serializes to LLVM bitcode.
Operation & getOperation()
Returns the operation being serialized.
ModuleToObject(Operation &module, StringRef triple, StringRef chip, StringRef features={}, int optLevel=3, function_ref< void(llvm::Module &)> initialLlvmIRCallback={}, function_ref< void(llvm::Module &)> linkedLlvmIRCallback={}, function_ref< void(llvm::Module &)> optimizedLlvmIRCallback={}, function_ref< void(StringRef)> isaCallback={}, const llvm::cl::LibraryOptionsContext *libraryOptions=nullptr)
Operation & module
Module to transform to a binary object.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
void appendDialectRegistry(const DialectRegistry &registry)
Append the contents of the given dialect registry to the registry associated with this context.
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
This class serves as an opaque interface for passing options to the TargetAttrInterface methods.
std::pair< llvm::BumpPtrAllocator, SmallVector< const char * > > tokenizeCmdOptions() const
Returns a tokenization of the command line options.
Definition GPUBase.cpp:474
Base class for all XeVM serializations from GPU modules into binary strings.
Definition Utils.h:27
gpu::TargetOptions targetOptions
GPU compilation target options.
Definition Utils.h:75
FailureOr< SmallVector< char, 0 > > compileToBinaryViaLibocloc(StringRef asmStr, StringRef inputFormat)
Compiles to native code using the ocloc shared library API, in-process, without temporary files.
XeVMTargetAttr getTarget() const
Returns the target attribute.
Definition Target.cpp:179
FailureOr< SmallVector< char, 0 > > compileToBinary(StringRef asmStr, StringRef inputFormat)
Compiles to native code using ocloc (API or tool).
Definition Target.cpp:395
FailureOr< SmallVector< char, 0 > > compileToBinaryViaOclocTool(StringRef asmStr, StringRef inputFormat)
Compiles to native code using the ocloc command-line tool, communicating through temporary files.
Definition Target.cpp:288
std::optional< SmallVector< std::unique_ptr< llvm::Module > > > loadBitcodeFiles(llvm::Module &module) override
Loads the bitcode files in librariesToLink.
Definition Target.cpp:182
SmallVector< Attribute > librariesToLink
List of LLVM bitcode to link into after translation to LLVM IR.
Definition Utils.h:57
SerializeGPUModuleBase(Operation &module, XeVMTargetAttr target, const gpu::TargetOptions &targetOptions={})
Definition Target.cpp:167
XeVMTargetAttr xeTarget
XeVM Target attribute.
Definition Utils.h:53
std::optional< std::string > findTool(StringRef tool)
Returns the path to the tool used for serialization.
Definition Target.cpp:478
gpu::GPUModuleOp getGPUModuleOp()
Returns the gpu module being serialized.
Definition Target.cpp:192
static std::string getCompilerInfo(const gpu::TargetOptions &targetOptions={})
Returns the GPU compiler version info, or an empty string if the version can't be determined.
Definition Target.cpp:404
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
void registerXeVMTargetInterfaceExternalModels(mlir::DialectRegistry &registry)
Registers the TargetAttrInterface for the #xevm.target attribute in the given registry.
Definition Target.cpp:153
Include the generated interface declarations.
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.