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"
48#if MLIR_XEVM_OCLOC_LIB_AVAILABLE
58enum OclocErrorCode :
int { OCLOC_SUCCESS = 0 };
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);
132int oclocFreeOutput(
unsigned *numOutputs, uint8_t ***dataOutputs,
133 uint64_t **lenOutputs,
char ***nameOutputs);
140class XeVMTargetAttrImpl
141 :
public gpu::TargetAttrInterface::FallbackModel<XeVMTargetAttrImpl> {
143 std::optional<mlir::gpu::SerializedObject>
144 serializeToObject(Attribute attribute, Operation *module,
145 const gpu::TargetOptions &
options)
const;
147 Attribute createObject(Attribute attribute, Operation *module,
148 const mlir::gpu::SerializedObject &
object,
149 const gpu::TargetOptions &
options)
const;
156 XeVMTargetAttr::attachInterface<XeVMTargetAttrImpl>(*ctx);
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());
181std::optional<SmallVector<std::unique_ptr<llvm::Module>>>
189 return std::move(bcFiles);
200#if MLIR_XEVM_OCLOC_LIB_AVAILABLE
201FailureOr<SmallVector<char, 0>>
203 StringRef inputFormat) {
205 std::string asmFname = llvm::formatv(
206 "mlir-{0}-{1}-{2}.asm",
getGPUModuleOp().getNameAttr().getValue(),
210 std::pair<llvm::BumpPtrAllocator, SmallVector<const char *>> cmdOpts =
213 const std::string cmdOptsStr =
"\"" + llvm::join(cmdOpts.second,
" ") +
"\"";
214 std::vector<std::string> oclocArgs = {
"ocloc",
225#define DEBUG_TYPE "serialize-to-binary"
227 llvm::dbgs() <<
"libocloc invocation for module: "
229 llvm::interleave(oclocArgs, llvm::dbgs(),
" ");
230 llvm::dbgs() <<
"\n";
235 std::vector<const char *> argv;
236 for (
const auto &str : oclocArgs)
237 argv.push_back(str.c_str());
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()};
245 uint32_t outputsNum = 0;
246 uint8_t **outputs =
nullptr;
247 uint64_t *outputLengths =
nullptr;
248 char **outputNames =
nullptr;
250 auto freeOutputs = llvm::scope_exit([&]() {
251 oclocFreeOutput(&outputsNum, &outputs, &outputLengths, &outputNames);
254 int err = oclocInvoke(
static_cast<uint32_t
>(argv.size()), argv.data(),
255 1, dataSources, lenSources, nameSources,
256 0,
nullptr,
nullptr,
nullptr,
257 &outputsNum, &outputs, &outputLengths, &outputNames);
259 if (err != OCLOC_SUCCESS) {
260 emitError(loc) <<
"libocloc: `oclocInvoke` failed, error code: " << err;
262 for (uint32_t i = 0; i < outputsNum; ++i) {
263 if (llvm::StringRef(outputNames[i]).ends_with(
".log"))
265 << llvm::StringRef(
reinterpret_cast<char *
>(outputs[i]),
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]);
278 return emitError(loc) <<
"`oclocInvoke` did not produce `.bin` output";
287FailureOr<SmallVector<char, 0>>
289 StringRef inputFormat) {
290 using TmpFile = std::pair<llvm::SmallString<128>, llvm::FileRemover>;
293 std::optional<std::string> oclocPath =
findTool(
"ocloc");
300 std::string basename = llvm::formatv(
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();
313 return TmpFile(path, llvm::FileRemover(path.c_str()));
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)
325 llvm::raw_fd_ostream asmStream(asmFile->first, ec);
327 emitError(loc) <<
"Couldn't open `" << asmFile->first
328 <<
"`: " << ec.message();
332 if (asmStream.has_error()) {
333 emitError(loc) <<
"Error writing assembly to `" << asmFile->first <<
"`";
340 std::pair<llvm::BumpPtrAllocator, SmallVector<const char *>> cmdOpts =
342 const std::string cmdOptsStr =
"\"" + llvm::join(cmdOpts.second,
" ") +
"\"";
345 {
"ocloc",
"compile",
"-file", asmFile->first, inputFormat,
"-device",
346 getTarget().getChip(),
"-output", binFile->first,
"-output_no_suffix",
347 "-options", cmdOptsStr});
350#define DEBUG_TYPE "serialize-to-binary"
352 llvm::dbgs() <<
"Tool invocation for module: "
354 llvm::interleave(oclocArgs, llvm::dbgs(),
" ");
355 llvm::dbgs() <<
"\n";
360 std::optional<StringRef> redirects[] = {std::nullopt, logFile->first,
363 std::string errorMsg;
364 if (llvm::sys::ExecuteAndWait(*oclocPath, oclocArgs, std::nullopt, redirects,
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();
373 emitError(loc) <<
"`ocloc` invocation failed (no log available)";
379 binFile->first.append(
".bin");
380 auto binaryBuffer = llvm::MemoryBuffer::getFile(binFile->first);
382 emitError(loc) <<
"Couldn't open binary output `" << binFile->first
383 <<
"`: " << binaryBuffer.getError().message();
386 StringRef bin = (*binaryBuffer)->getBuffer();
394FailureOr<SmallVector<char, 0>>
396 StringRef inputFormat) {
397#if MLIR_XEVM_OCLOC_LIB_AVAILABLE
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);
416 if (oclocInvoke(std::size(argv), argv, 0,
nullptr,
nullptr,
417 nullptr, 0,
nullptr,
nullptr,
nullptr,
418 &outputsNum, &outputs, &outputLengths,
419 &outputNames) != OCLOC_SUCCESS)
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]),
434 if (!oclocPath || llvm::sys::fs::createTemporaryFile(
"ocloc",
"query", out))
436 llvm::FileRemover outRemover(out);
438 static std::mutex queryMutex;
439 std::lock_guard<std::mutex> lock(queryMutex);
442 llvm::FileRemover queryRemover(
query,
443 !llvm::sys::fs::exists(
query));
444 std::optional<StringRef> redirects[] = {std::nullopt, out.str(),
446 if (llvm::sys::ExecuteAndWait(*oclocPath, {
"ocloc",
"query",
query},
447 std::nullopt, redirects))
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())
460std::optional<std::string>
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();
473 if (llvm::ErrorOr<std::string> toolPath = llvm::sys::findProgramByName(tool))
482 <<
"Couldn't find the `" << tool
483 <<
"` binary. Please specify the toolkit "
484 "path via GpuModuleToBinaryPass or add the compiler to $PATH`.";
490 SPIRVSerializer(
Operation &module, XeVMTargetAttr xeTarget,
498 FailureOr<SmallVector<char, 0>>
499 moduleToObject(llvm::Module &llvmModule)
override;
502 std::optional<SmallVector<char, 0>> run()
override;
507 std::optional<std::string>
508 translateToSPIRVBinary(llvm::Module &llvmModule,
509 llvm::TargetMachine &targetMachine);
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();
525#if LLVM_HAS_SPIRV_TARGET
531static const std::vector<std::string> getDefaultSPIRVExtensions() {
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",
546SPIRVTranslateModule(Module *M, std::string &SpirvObj, std::string &ErrMsg,
547 const std::vector<std::string> &AllowExtNames,
548 const std::vector<std::string> &Opts);
556FailureOr<SmallVector<char, 0>>
557SPIRVSerializer::moduleToObject(llvm::Module &llvmModule) {
558#define DEBUG_TYPE "serialize-to-llvm"
560 llvm::dbgs() <<
"LLVM IR for module: " << getGPUModuleOp().getNameAttr()
562 llvm::dbgs() << llvmModule <<
"\n";
563 llvm::dbgs().flush();
568 if (targetOptions.getCompilationTarget() == gpu::CompilationTarget::Offload)
571#if !LLVM_HAS_SPIRV_TARGET
572 return getGPUModuleOp()->emitError(
573 "The `SPIRV` target was not built. Please enable "
574 "it when building LLVM.");
576 std::string serializedSPIRVBinary;
578 std::vector<std::string> Opts;
579 Opts.push_back(triple.str());
580 Opts.push_back(std::to_string(optLevel));
584 SPIRVTranslateModule(&llvmModule, serializedSPIRVBinary, ErrMsg,
585 getDefaultSPIRVExtensions(), Opts);
588 return getGPUModuleOp().emitError()
589 <<
"Failed translating the module to Binary."
590 <<
"Error message: " << ErrMsg;
592 if (serializedSPIRVBinary.size() % 4)
593 return getGPUModuleOp().emitError()
594 <<
"SPIRV code size must be a multiple of 4.";
596 StringRef spirvBin(serializedSPIRVBinary.c_str(),
597 serializedSPIRVBinary.size());
603 if (targetOptions.getCompilationTarget() ==
604 gpu::CompilationTarget::Assembly) {
605#define DEBUG_TYPE "serialize-to-isa"
607 llvm::dbgs() <<
"SPIR-V for module: " << getGPUModuleOp().getNameAttr()
609 llvm::dbgs() << serializedSPIRVBinary <<
"\n";
610 llvm::dbgs().flush();
613 return SmallVector<char, 0>(spirvBin.begin(), spirvBin.end());
619 return compileToBinary(spirvBin,
"-spirv_input");
623std::optional<SmallVector<char, 0>> SPIRVSerializer::run() {
625 llvm::LLVMContext llvmContext;
626 std::unique_ptr<llvm::Module> llvmModule = translateToLLVMIR(llvmContext);
628 getOperation().emitError() <<
"Failed creating the llvm::Module.";
631 setDataLayoutAndTriple(*llvmModule);
633 if (initialLlvmIRCallback)
634 initialLlvmIRCallback(*llvmModule);
637 handleModulePreLink(*llvmModule);
639 auto libs = loadBitcodeFiles(*llvmModule);
643 if (
failed(linkFiles(*llvmModule, std::move(*libs))))
645 handleModulePostLink(*llvmModule);
648 if (linkedLlvmIRCallback)
649 linkedLlvmIRCallback(*llvmModule);
652 return moduleToObject(*llvmModule);
655std::optional<std::string>
656SPIRVSerializer::translateToSPIRVBinary(llvm::Module &llvmModule,
657 llvm::TargetMachine &targetMachine) {
658 std::string targetISA;
659 llvm::raw_string_ostream stream(targetISA);
662 llvm::buffer_ostream pstream(stream);
663 llvm::legacy::PassManager codegenPasses;
664 if (targetMachine.addPassesToEmitFile(codegenPasses, pstream,
nullptr,
665 llvm::CodeGenFileType::ObjectFile))
668 codegenPasses.run(llvmModule);
673std::optional<mlir::gpu::SerializedObject>
674XeVMTargetAttrImpl::serializeToObject(Attribute attribute, Operation *module,
675 const gpu::TargetOptions &
options)
const {
678 auto gpuMod = dyn_cast<gpu::GPUModuleOp>(module);
680 module->emitError("expected to be a gpu.module op");
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);
690 SPIRVSerializer serializer(*module, cast<XeVMTargetAttr>(attribute),
694#if !LLVM_HAS_SPIRV_TARGET
695 module->emitError("Cannot run `TargetRegistry::lookupTarget()` for SPIRV "
696 "without having the target built.");
699 std::optional<SmallVector<char, 0>> binary = serializer.run();
702 return gpu::SerializedObject{std::move(*binary)};
704 module->emitError("Unsupported XeVM target triple: ") << xeTarget.getTriple();
709XeVMTargetAttrImpl::createObject(Attribute attribute, Operation *module,
710 const mlir::gpu::SerializedObject &
object,
711 const gpu::TargetOptions &
options)
const {
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())));
720 DictionaryAttr objectProps;
721 if (!properties.empty())
722 objectProps = builder.getDictionaryAttr(properties);
724 return builder.getAttr<gpu::ObjectAttr>(
726 builder.getStringAttr(
727 StringRef(
object.getObject().data(),
object.getObject().size())),
728 objectProps,
nullptr);
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...
MLIRContext is the top-level object for a collection of MLIR operations.
void appendDialectRegistry(const DialectRegistry ®istry)
Append the contents of the given dialect registry to the registry associated with this context.
Operation is the basic unit of execution within MLIR.
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.
Base class for all XeVM serializations from GPU modules into binary strings.
gpu::TargetOptions targetOptions
GPU compilation target options.
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.
FailureOr< SmallVector< char, 0 > > compileToBinary(StringRef asmStr, StringRef inputFormat)
Compiles to native code using ocloc (API or tool).
FailureOr< SmallVector< char, 0 > > compileToBinaryViaOclocTool(StringRef asmStr, StringRef inputFormat)
Compiles to native code using the ocloc command-line tool, communicating through temporary files.
std::optional< SmallVector< std::unique_ptr< llvm::Module > > > loadBitcodeFiles(llvm::Module &module) override
Loads the bitcode files in librariesToLink.
SmallVector< Attribute > librariesToLink
List of LLVM bitcode to link into after translation to LLVM IR.
SerializeGPUModuleBase(Operation &module, XeVMTargetAttr target, const gpu::TargetOptions &targetOptions={})
XeVMTargetAttr xeTarget
XeVM Target attribute.
std::optional< std::string > findTool(StringRef tool)
Returns the path to the tool used for serialization.
gpu::GPUModuleOp getGPUModuleOp()
Returns the gpu module being serialized.
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.
void registerXeVMTargetInterfaceExternalModels(mlir::DialectRegistry ®istry)
Registers the TargetAttrInterface for the #xevm.target attribute in the given registry.
Include the generated interface declarations.
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.