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"
12#include "llvm/CodeGen/CommandFlags.h"
13#include "llvm/CodeGen/TargetPassConfig.h"
14#include "llvm/CodeGen/TargetSubtargetInfo.h"
15#include "llvm/IR/DataLayout.h"
16#include "llvm/IR/LLVMContext.h"
17#include "llvm/IR/Module.h"
18#include "llvm/IR/Verifier.h"
19#include "llvm/MC/TargetRegistry.h"
20#include "llvm/Passes/RunCodeGen.h"
21#include "llvm/Support/TargetSelect.h"
22#include "llvm/Target/TargetMachine.h"
23#include "llvm/TargetParser/SubtargetFeature.h"
24#include "llvm/TargetParser/Triple.h"
25#include <optional>
26#include <string>
27#include <vector>
28
29using namespace llvm;
30
31namespace {
32
33std::once_flag InitOnceFlag;
34void InitializeSPIRVTarget() {
35 std::call_once(once&: InitOnceFlag, f: []() {
36 LLVMInitializeSPIRVTargetInfo();
37 LLVMInitializeSPIRVTarget();
38 LLVMInitializeSPIRVTargetMC();
39 LLVMInitializeSPIRVAsmPrinter();
40 });
41}
42} // namespace
43
44namespace llvm {
45
46// The goal of this function is to facilitate integration of SPIRV Backend into
47// tools and libraries by means of exposing an API call that translate LLVM
48// module to SPIR-V and write results into a string as binary SPIR-V output,
49// providing diagnostics on fail and means of configuring translation.
50extern "C" LLVM_EXTERNAL_VISIBILITY bool
51SPIRVTranslate(Module *M, std::string &SpirvObj, std::string &ErrMsg,
52 const std::vector<std::string> &AllowExtNames,
53 llvm::CodeGenOptLevel OLevel, Triple TargetTriple) {
54 // Fallbacks for option values.
55 static const std::string DefaultTriple = "spirv64-unknown-unknown";
56 static const std::string DefaultMArch = "";
57
58 ExtensionSet AllowedExtIds;
59 StringRef UnknownExt =
60 SPIRVExtensionsParser::checkExtensions(ExtNames: AllowExtNames, AllowedExtensions&: AllowedExtIds);
61 if (!UnknownExt.empty()) {
62 ErrMsg = "Unknown SPIR-V extension: " + UnknownExt.str();
63 return false;
64 }
65
66 // SPIR-V-specific target initialization.
67 InitializeSPIRVTarget();
68
69 if (TargetTriple.getTriple().empty()) {
70 TargetTriple.setTriple(DefaultTriple);
71 M->setTargetTriple(TargetTriple);
72 }
73 const Target *TheTarget =
74 TargetRegistry::lookupTarget(ArchName: DefaultMArch, TheTriple&: TargetTriple, Error&: ErrMsg);
75 if (!TheTarget)
76 return false;
77
78 // A call to codegen::getTargetOptions(TargetTriple) hits an
79 // assertion in one of the codegen flag getters in
80 // llvm/lib/CodeGen/CommandFlags.cpp:
81 // `...View && "RegisterCodeGenFlags not created."' failed.
82 TargetOptions Options;
83 std::optional<Reloc::Model> RM;
84 std::optional<CodeModel::Model> CM;
85 std::unique_ptr<TargetMachine> Target(TheTarget->createTargetMachine(
86 TT: TargetTriple, CPU: "", Features: "", Options, RM, CM, OL: OLevel));
87 if (!Target) {
88 ErrMsg = "Could not allocate target machine!";
89 return false;
90 }
91
92 // Set available extensions.
93 SPIRVTargetMachine *STM = static_cast<SPIRVTargetMachine *>(Target.get());
94 const_cast<SPIRVSubtarget *>(STM->getSubtargetImpl())
95 ->initAvailableExtensions(AllowedExtIds);
96
97 if (M->getCodeModel())
98 Target->setCodeModel(*M->getCodeModel());
99
100 std::string DLStr = M->getDataLayoutStr();
101 Expected<DataLayout> MaybeDL = DataLayout::parse(
102 LayoutString: DLStr.empty() ? TargetTriple.computeDataLayout() : DLStr);
103 if (!MaybeDL) {
104 ErrMsg = toString(E: MaybeDL.takeError());
105 return false;
106 }
107 M->setDataLayout(MaybeDL.get());
108
109 SmallString<4096> OutBuffer;
110 raw_svector_ostream OutStream(OutBuffer);
111 if (Error Err = runCodeGenPipeline(TM&: *Target, M&: *M, OS&: OutStream, DwoOS: nullptr,
112 CGFT: CodeGenFileType::ObjectFile)) {
113 ErrMsg = toString(E: std::move(Err));
114 return false;
115 }
116 SpirvObj = OutBuffer.str();
117
118 return true;
119}
120
121// TODO: Remove this wrapper after existing clients switch into a newer
122// implementation of SPIRVTranslate().
123extern "C" LLVM_EXTERNAL_VISIBILITY bool
124SPIRVTranslateModule(Module *M, std::string &SpirvObj, std::string &ErrMsg,
125 const std::vector<std::string> &AllowExtNames,
126 const std::vector<std::string> &Opts) {
127 // optional: Opts[0] is a string representation of Triple,
128 // take Module triple otherwise
129 Triple TargetTriple = Opts.empty() || Opts[0].empty()
130 ? M->getTargetTriple()
131 : Triple(Triple::normalize(Str: Opts[0]));
132 // optional: Opts[1] is a string representation of CodeGenOptLevel,
133 // no optimization otherwise
134 llvm::CodeGenOptLevel OLevel = CodeGenOptLevel::None;
135 if (Opts.size() > 1 && !Opts[1].empty()) {
136 if (auto Level = CodeGenOpt::parseLevel(C: Opts[1][0])) {
137 OLevel = *Level;
138 } else {
139 ErrMsg = "Invalid optimization level!";
140 return false;
141 }
142 }
143 return SPIRVTranslate(M, SpirvObj, ErrMsg, AllowExtNames, OLevel,
144 TargetTriple: std::move(TargetTriple));
145}
146
147} // namespace llvm
148