LLVM 24.0.0git
SPIRVAPI.cpp
Go to the documentation of this file.
1//===-- SPIRVAPI.cpp - SPIR-V Backend API ---------------------*- 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#include "SPIRVCommandLine.h"
10#include "SPIRVSubtarget.h"
11#include "SPIRVTargetMachine.h"
16#include "llvm/IR/DataLayout.h"
17#include "llvm/IR/LLVMContext.h"
19#include "llvm/IR/Module.h"
20#include "llvm/IR/Verifier.h"
22#include "llvm/Pass.h"
27#include <optional>
28#include <string>
29#include <vector>
30
31using namespace llvm;
32
33namespace {
34
35std::once_flag InitOnceFlag;
36void InitializeSPIRVTarget() {
37 std::call_once(InitOnceFlag, []() {
41 LLVMInitializeSPIRVAsmPrinter();
42 });
43}
44} // namespace
45
46namespace llvm {
47
48// The goal of this function is to facilitate integration of SPIRV Backend into
49// tools and libraries by means of exposing an API call that translate LLVM
50// module to SPIR-V and write results into a string as binary SPIR-V output,
51// providing diagnostics on fail and means of configuring translation.
52extern "C" LLVM_EXTERNAL_VISIBILITY bool
53SPIRVTranslate(Module *M, std::string &SpirvObj, std::string &ErrMsg,
54 const std::vector<std::string> &AllowExtNames,
55 llvm::CodeGenOptLevel OLevel, Triple TargetTriple) {
56 // Fallbacks for option values.
57 static const std::string DefaultTriple = "spirv64-unknown-unknown";
58 static const std::string DefaultMArch = "";
59
60 ExtensionSet AllowedExtIds;
61 StringRef UnknownExt =
62 SPIRVExtensionsParser::checkExtensions(AllowExtNames, AllowedExtIds);
63 if (!UnknownExt.empty()) {
64 ErrMsg = "Unknown SPIR-V extension: " + UnknownExt.str();
65 return false;
66 }
67
68 // SPIR-V-specific target initialization.
69 InitializeSPIRVTarget();
70
71 if (TargetTriple.getTriple().empty()) {
72 TargetTriple.setTriple(DefaultTriple);
73 M->setTargetTriple(TargetTriple);
74 }
75 const Target *TheTarget =
76 TargetRegistry::lookupTarget(DefaultMArch, TargetTriple, ErrMsg);
77 if (!TheTarget)
78 return false;
79
80 // A call to codegen::InitTargetOptionsFromCodeGenFlags(TargetTriple) hits an
81 // assertion in one of the codegen flag getters in
82 // llvm/lib/CodeGen/CommandFlags.cpp:
83 // `...View && "RegisterCodeGenFlags not created."' failed.
85 std::optional<Reloc::Model> RM;
86 std::optional<CodeModel::Model> CM;
87 std::unique_ptr<TargetMachine> Target(TheTarget->createTargetMachine(
88 TargetTriple, "", "", Options, RM, CM, OLevel));
89 if (!Target) {
90 ErrMsg = "Could not allocate target machine!";
91 return false;
92 }
93
94 // Set available extensions.
95 SPIRVTargetMachine *STM = static_cast<SPIRVTargetMachine *>(Target.get());
96 const_cast<SPIRVSubtarget *>(STM->getSubtargetImpl())
97 ->initAvailableExtensions(AllowedExtIds);
98
99 if (M->getCodeModel())
100 Target->setCodeModel(*M->getCodeModel());
101
102 std::string DLStr = M->getDataLayoutStr();
104 DLStr.empty() ? TargetTriple.computeDataLayout() : DLStr);
105 if (!MaybeDL) {
106 ErrMsg = toString(MaybeDL.takeError());
107 return false;
108 }
109 M->setDataLayout(MaybeDL.get());
110
111 TargetLibraryInfoImpl TLII(M->getTargetTriple());
113 PM.add(new TargetLibraryInfoWrapperPass(TLII));
114
115 SmallString<4096> OutBuffer;
116 raw_svector_ostream OutStream(OutBuffer);
117 if (Target->addPassesToEmitFile(PM, OutStream, nullptr,
119 ErrMsg = "Target machine cannot emit a file of this type";
120 return false;
121 }
122
123 PM.run(*M);
124 SpirvObj = OutBuffer.str();
125
126 return true;
127}
128
129// TODO: Remove this wrapper after existing clients switch into a newer
130// implementation of SPIRVTranslate().
131extern "C" LLVM_EXTERNAL_VISIBILITY bool
132SPIRVTranslateModule(Module *M, std::string &SpirvObj, std::string &ErrMsg,
133 const std::vector<std::string> &AllowExtNames,
134 const std::vector<std::string> &Opts) {
135 // optional: Opts[0] is a string representation of Triple,
136 // take Module triple otherwise
137 Triple TargetTriple = Opts.empty() || Opts[0].empty()
138 ? M->getTargetTriple()
139 : Triple(Triple::normalize(Opts[0]));
140 // optional: Opts[1] is a string representation of CodeGenOptLevel,
141 // no optimization otherwise
143 if (Opts.size() > 1 && !Opts[1].empty()) {
144 if (auto Level = CodeGenOpt::parseLevel(Opts[1][0])) {
145 OLevel = *Level;
146 } else {
147 ErrMsg = "Invalid optimization level!";
148 return false;
149 }
150 }
151 return SPIRVTranslate(M, SpirvObj, ErrMsg, AllowExtNames, OLevel,
152 std::move(TargetTriple));
153}
154
155} // namespace llvm
#define LLVM_EXTERNAL_VISIBILITY
Definition Compiler.h:132
Module.h This file contains the declarations for the Module class.
static LVOptions Options
Definition LVOptions.cpp:25
LLVM_ABI LLVM_EXTERNAL_VISIBILITY void LLVMInitializeSPIRVTargetMC()
LLVM_ABI LLVM_EXTERNAL_VISIBILITY void LLVMInitializeSPIRVTargetInfo()
LLVM_ABI LLVM_EXTERNAL_VISIBILITY void LLVMInitializeSPIRVTarget()
Target-Independent Code Generator Pass Configuration Options pass.
static LLVM_ABI Expected< DataLayout > parse(StringRef LayoutString)
Parse a data layout string and return the layout.
Tagged union holding either a T or a Error.
Definition Error.h:485
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
reference get()
Returns a reference to the stored T value.
Definition Error.h:582
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
void initAvailableExtensions(const ExtensionSet &AllowedExtIds)
const SPIRVSubtarget * getSubtargetImpl() const
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
StringRef str() const
Explicit conversion to StringRef.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::string str() const
Get the contents as an std::string.
Definition StringRef.h:222
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
Implementation of the target library information.
Target - Wrapper for Target specific information.
TargetMachine * createTargetMachine(const Triple &TT, StringRef CPU, StringRef Features, const TargetOptions &Options, std::optional< Reloc::Model > RM, std::optional< CodeModel::Model > CM=std::nullopt, CodeGenOptLevel OL=CodeGenOptLevel::Default, bool JIT=false) const
createTargetMachine - Create a target specific machine implementation for the specified Triple.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
LLVM_ABI std::string computeDataLayout(StringRef ABIName="") const
Compute the LLVM IR data layout string based on the triple.
LLVM_ABI void setTriple(const Twine &Str)
Set all components to the new triple Str.
Definition Triple.cpp:1680
static LLVM_ABI std::string normalize(StringRef Str, CanonicalForm Form=CanonicalForm::ANY)
Turn an arbitrary machine specification into the canonical triple form (or something sensible that th...
Definition Triple.cpp:1192
const std::string & getTriple() const
Definition Triple.h:582
PassManager manages ModulePassManagers.
void add(Pass *P) override
Add a pass to the queue of passes to run.
bool run(Module &M)
run - Execute all of the passes scheduled for execution.
A raw_ostream that writes to an SmallVector or SmallString.
std::optional< CodeGenOptLevel > parseLevel(char C)
Parse C as a single digit integer and get matching CodeGenLevel.
Definition CodeGen.h:246
This is an optimization pass for GlobalISel generic memory operations.
DenseSet< SPIRV::Extension::Extension > ExtensionSet
LLVM_EXTERNAL_VISIBILITY bool SPIRVTranslate(Module *M, std::string &SpirvObj, std::string &ErrMsg, const std::vector< std::string > &AllowExtNames, llvm::CodeGenOptLevel OLevel, Triple TargetTriple)
Definition SPIRVAPI.cpp:53
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:227
LLVM_EXTERNAL_VISIBILITY bool SPIRVTranslateModule(Module *M, std::string &SpirvObj, std::string &ErrMsg, const std::vector< std::string > &AllowExtNames, const std::vector< std::string > &Opts)
Definition SPIRVAPI.cpp:132
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
static StringRef checkExtensions(ArrayRef< std::string > ExtNames, ExtensionSet &AllowedExtensions)
Validates and converts extension names into internal enum values.
static LLVM_ABI const Target * lookupTarget(const Triple &TheTriple, std::string &Error)
lookupTarget - Lookup a target based on a target triple.