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