blob: c7356161e3b9c22e19ee03ef75f82563a9fda25a [file] [log] [blame]
David Neto22f144c2017-06-12 14:26:21 -04001// Copyright 2017 The Clspv Authors. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#ifdef _MSC_VER
16#pragma warning(push, 0)
17#endif
18
David Neto156783e2017-07-05 15:39:41 -040019#include <cassert>
David Neto257c3892018-04-11 13:19:45 -040020#include <cstring>
David Neto118188e2018-08-24 11:27:54 -040021#include <iomanip>
22#include <list>
David Neto862b7d82018-06-14 18:48:37 -040023#include <memory>
David Neto118188e2018-08-24 11:27:54 -040024#include <set>
25#include <sstream>
26#include <string>
27#include <tuple>
28#include <unordered_set>
29#include <utility>
David Neto862b7d82018-06-14 18:48:37 -040030
David Neto118188e2018-08-24 11:27:54 -040031#include "llvm/ADT/StringSwitch.h"
32#include "llvm/ADT/UniqueVector.h"
33#include "llvm/Analysis/LoopInfo.h"
34#include "llvm/IR/Constants.h"
35#include "llvm/IR/Dominators.h"
36#include "llvm/IR/Instructions.h"
alan-baker5f2e88e2020-12-07 15:24:04 -050037#include "llvm/IR/Intrinsics.h"
David Neto118188e2018-08-24 11:27:54 -040038#include "llvm/IR/Metadata.h"
39#include "llvm/IR/Module.h"
alan-bakerf67468c2019-11-25 15:51:49 -050040#include "llvm/IR/ValueSymbolTable.h"
David Neto118188e2018-08-24 11:27:54 -040041#include "llvm/Pass.h"
42#include "llvm/Support/CommandLine.h"
alan-baker3f772c02021-06-15 22:18:11 -040043#include "llvm/Support/FileSystem.h"
Kévin Petitbbbda972020-03-03 19:16:31 +000044#include "llvm/Support/MathExtras.h"
David Neto118188e2018-08-24 11:27:54 -040045#include "llvm/Support/raw_ostream.h"
46#include "llvm/Transforms/Utils/Cloning.h"
David Neto22f144c2017-06-12 14:26:21 -040047
SJWf93f5f32020-05-05 07:27:56 -050048// enable spv::HasResultAndType
49#define SPV_ENABLE_UTILITY_CODE
alan-bakere0902602020-03-23 08:43:40 -040050#include "spirv/unified1/spirv.hpp"
David Neto118188e2018-08-24 11:27:54 -040051
David Neto85082642018-03-24 06:55:20 -070052#include "clspv/AddressSpace.h"
David Neto118188e2018-08-24 11:27:54 -040053#include "clspv/Option.h"
alan-baker86ce19c2020-08-05 13:09:19 -040054#include "clspv/PushConstant.h"
55#include "clspv/SpecConstant.h"
David Neto85082642018-03-24 06:55:20 -070056#include "clspv/spirv_c_strings.hpp"
57#include "clspv/spirv_glsl.hpp"
alan-baker86ce19c2020-08-05 13:09:19 -040058#include "clspv/spirv_reflection.hpp"
David Neto22f144c2017-06-12 14:26:21 -040059
David Neto4feb7a42017-10-06 17:29:42 -040060#include "ArgKind.h"
alan-bakerf67468c2019-11-25 15:51:49 -050061#include "Builtins.h"
alan-baker06cad652019-12-03 17:56:47 -050062#include "ComputeStructuredOrder.h"
David Neto85082642018-03-24 06:55:20 -070063#include "ConstantEmitter.h"
Alan Baker202c8c72018-08-13 13:47:44 -040064#include "Constants.h"
David Neto78383442018-06-15 20:31:56 -040065#include "DescriptorCounter.h"
alan-bakerc4579bb2020-04-29 14:15:50 -040066#include "Layout.h"
alan-baker56f7aff2019-05-22 08:06:42 -040067#include "NormalizeGlobalVariable.h"
Diego Novilloa4c44fa2019-04-11 10:56:15 -040068#include "Passes.h"
alan-bakera1be3322020-04-20 12:48:18 -040069#include "SpecConstant.h"
alan-bakerce179f12019-12-06 19:02:22 -050070#include "Types.h"
David Neto48f56a42017-10-06 16:44:25 -040071
David Neto22f144c2017-06-12 14:26:21 -040072#if defined(_MSC_VER)
73#pragma warning(pop)
74#endif
75
76using namespace llvm;
77using namespace clspv;
SJW173c7e92020-03-16 08:44:47 -050078using namespace clspv::Builtins;
SJW806a5d82020-07-15 12:51:38 -050079using namespace clspv::Option;
David Neto156783e2017-07-05 15:39:41 -040080using namespace mdconst;
David Neto22f144c2017-06-12 14:26:21 -040081
82namespace {
David Netocd8ca5f2017-10-02 23:34:11 -040083
alan-baker3f772c02021-06-15 22:18:11 -040084cl::opt<std::string> TestOutFile("producer-out-file", cl::init("test.spv"),
85 cl::ReallyHidden,
86 cl::desc("SPIRVProducer testing output file"));
87
David Neto862b7d82018-06-14 18:48:37 -040088cl::opt<bool> ShowResourceVars("show-rv", cl::init(false), cl::Hidden,
89 cl::desc("Show resource variable creation"));
90
alan-baker5ed87542020-03-23 11:05:22 -040091cl::opt<bool>
92 ShowProducerIR("show-producer-ir", cl::init(false), cl::ReallyHidden,
93 cl::desc("Dump the IR at the start of SPIRVProducer"));
94
David Neto862b7d82018-06-14 18:48:37 -040095// These hacks exist to help transition code generation algorithms
96// without making huge noise in detailed test output.
97const bool Hack_generate_runtime_array_stride_early = true;
98
David Neto3fbb4072017-10-16 11:28:14 -040099// The value of 1/pi. This value is from MSDN
100// https://msdn.microsoft.com/en-us/library/4hwaceh6.aspx
101const double kOneOverPi = 0.318309886183790671538;
102const glsl::ExtInst kGlslExtInstBad = static_cast<glsl::ExtInst>(0);
103
alan-baker86ce19c2020-08-05 13:09:19 -0400104// SPIRV Module Sections (per 2.4 of the SPIR-V spec)
SJW69939d52020-04-16 07:29:07 -0500105// These are used to collect SPIRVInstructions by type on-the-fly.
106enum SPIRVSection {
107 kCapabilities,
108 kExtensions,
109 kImports,
110 kMemoryModel,
111 kEntryPoints,
112 kExecutionModes,
113
114 kDebug,
115 kAnnotations,
116
117 kTypes,
118 kConstants = kTypes,
119 kGlobalVariables,
120
121 kFunctions,
122
alan-baker86ce19c2020-08-05 13:09:19 -0400123 // This is not a section of the SPIR-V spec and should always immediately
124 // precede kSectionCount. It is a convenient place for the embedded
125 // reflection data.
126 kReflection,
SJW69939d52020-04-16 07:29:07 -0500127 kSectionCount
128};
129
SJW01901d92020-05-21 08:58:31 -0500130class SPIRVID {
131 uint32_t id;
132
133public:
134 SPIRVID(uint32_t _id = 0) : id(_id) {}
135 uint32_t get() const { return id; }
136 bool isValid() const { return id != 0; }
137 bool operator==(const SPIRVID &that) const { return id == that.id; }
SJW806a5d82020-07-15 12:51:38 -0500138 bool operator<(const SPIRVID &that) const { return id < that.id; }
SJW01901d92020-05-21 08:58:31 -0500139};
SJWf93f5f32020-05-05 07:27:56 -0500140
SJW88ed5fe2020-05-11 12:40:57 -0500141enum SPIRVOperandType { NUMBERID, LITERAL_WORD, LITERAL_DWORD, LITERAL_STRING };
David Neto22f144c2017-06-12 14:26:21 -0400142
143struct SPIRVOperand {
alan-baker3f772c02021-06-15 22:18:11 -0400144 SPIRVOperand(SPIRVOperandType Ty, uint32_t Num) : Type(Ty) {
SJW88ed5fe2020-05-11 12:40:57 -0500145 LiteralNum[0] = Num;
146 }
alan-baker3f772c02021-06-15 22:18:11 -0400147 SPIRVOperand(SPIRVOperandType Ty, const char *Str)
David Neto22f144c2017-06-12 14:26:21 -0400148 : Type(Ty), LiteralStr(Str) {}
alan-baker3f772c02021-06-15 22:18:11 -0400149 SPIRVOperand(SPIRVOperandType Ty, StringRef Str)
David Neto22f144c2017-06-12 14:26:21 -0400150 : Type(Ty), LiteralStr(Str) {}
SJW88ed5fe2020-05-11 12:40:57 -0500151 explicit SPIRVOperand(ArrayRef<uint32_t> NumVec) {
152 auto sz = NumVec.size();
153 assert(sz >= 1 && sz <= 2);
154 Type = sz == 1 ? LITERAL_WORD : LITERAL_DWORD;
155 LiteralNum[0] = NumVec[0];
156 if (sz == 2) {
157 LiteralNum[1] = NumVec[1];
158 }
159 }
David Neto22f144c2017-06-12 14:26:21 -0400160
alan-baker7506abb2020-09-10 15:02:55 -0400161 SPIRVOperandType getType() const { return Type; }
162 uint32_t getNumID() const { return LiteralNum[0]; }
163 std::string getLiteralStr() const { return LiteralStr; }
164 const uint32_t *getLiteralNum() const { return LiteralNum; }
David Neto22f144c2017-06-12 14:26:21 -0400165
David Neto87846742018-04-11 17:36:22 -0400166 uint32_t GetNumWords() const {
167 switch (Type) {
168 case NUMBERID:
SJW88ed5fe2020-05-11 12:40:57 -0500169 case LITERAL_WORD:
David Neto87846742018-04-11 17:36:22 -0400170 return 1;
SJW88ed5fe2020-05-11 12:40:57 -0500171 case LITERAL_DWORD:
172 return 2;
David Neto87846742018-04-11 17:36:22 -0400173 case LITERAL_STRING:
174 // Account for the terminating null character.
David Netoee2660d2018-06-28 16:31:29 -0400175 return uint32_t((LiteralStr.size() + 4) / 4);
David Neto87846742018-04-11 17:36:22 -0400176 }
177 llvm_unreachable("Unhandled case in SPIRVOperand::GetNumWords()");
178 }
179
David Neto22f144c2017-06-12 14:26:21 -0400180private:
181 SPIRVOperandType Type;
182 std::string LiteralStr;
SJW88ed5fe2020-05-11 12:40:57 -0500183 uint32_t LiteralNum[2];
David Neto22f144c2017-06-12 14:26:21 -0400184};
185
SJW88ed5fe2020-05-11 12:40:57 -0500186typedef SmallVector<SPIRVOperand, 4> SPIRVOperandVec;
David Netoc6f3ab22018-04-06 18:02:31 -0400187
David Neto22f144c2017-06-12 14:26:21 -0400188struct SPIRVInstruction {
SJWf93f5f32020-05-05 07:27:56 -0500189 // Primary constructor must have Opcode, initializes WordCount based on ResID.
190 SPIRVInstruction(spv::Op Opc, SPIRVID ResID = 0)
191 : Opcode(static_cast<uint16_t>(Opc)) {
192 setResult(ResID);
David Neto87846742018-04-11 17:36:22 -0400193 }
David Neto22f144c2017-06-12 14:26:21 -0400194
SJWf93f5f32020-05-05 07:27:56 -0500195 // Creates an instruction with an opcode and no result ID, and with the given
196 // operands. This calls primary constructor to initialize Opcode, WordCount.
197 // Takes ownership of the operands and clears |Ops|.
198 SPIRVInstruction(spv::Op Opc, SPIRVOperandVec &Ops) : SPIRVInstruction(Opc) {
199 setOperands(Ops);
David Netoef5ba2b2019-12-20 08:35:54 -0500200 }
SJWf93f5f32020-05-05 07:27:56 -0500201 // Creates an instruction with an opcode and no result ID, and with the given
202 // operands. This calls primary constructor to initialize Opcode, WordCount.
203 // Takes ownership of the operands and clears |Ops|.
204 SPIRVInstruction(spv::Op Opc, SPIRVID ResID, SPIRVOperandVec &Ops)
205 : SPIRVInstruction(Opc, ResID) {
206 setOperands(Ops);
David Netoef5ba2b2019-12-20 08:35:54 -0500207 }
David Netoef5ba2b2019-12-20 08:35:54 -0500208
David Netoee2660d2018-06-28 16:31:29 -0400209 uint32_t getWordCount() const { return WordCount; }
David Neto22f144c2017-06-12 14:26:21 -0400210 uint16_t getOpcode() const { return Opcode; }
SJW88ed5fe2020-05-11 12:40:57 -0500211 SPIRVID getResultID() const { return ResultID; }
212 const SPIRVOperandVec &getOperands() const { return Operands; }
David Neto22f144c2017-06-12 14:26:21 -0400213
214private:
SJW01901d92020-05-21 08:58:31 -0500215 void setResult(SPIRVID ResID = 0) {
216 WordCount = 1 + (ResID.isValid() ? 1 : 0);
SJWf93f5f32020-05-05 07:27:56 -0500217 ResultID = ResID;
218 }
219
220 void setOperands(SPIRVOperandVec &Ops) {
221 assert(Operands.empty());
222 Operands = std::move(Ops);
223 for (auto &opd : Operands) {
SJW88ed5fe2020-05-11 12:40:57 -0500224 WordCount += uint16_t(opd.GetNumWords());
SJWf93f5f32020-05-05 07:27:56 -0500225 }
226 }
227
228private:
David Netoee2660d2018-06-28 16:31:29 -0400229 uint32_t WordCount; // Check the 16-bit bound at code generation time.
David Neto22f144c2017-06-12 14:26:21 -0400230 uint16_t Opcode;
SJW88ed5fe2020-05-11 12:40:57 -0500231 SPIRVID ResultID;
SJWf93f5f32020-05-05 07:27:56 -0500232 SPIRVOperandVec Operands;
David Neto22f144c2017-06-12 14:26:21 -0400233};
234
235struct SPIRVProducerPass final : public ModulePass {
alan-baker3f772c02021-06-15 22:18:11 -0400236 static char ID;
237
SJW01901d92020-05-21 08:58:31 -0500238 typedef DenseMap<Type *, SPIRVID> TypeMapType;
alan-baker3f772c02021-06-15 22:18:11 -0400239 typedef DenseMap<Type *, SmallVector<SPIRVID, 2>> LayoutTypeMapType;
David Neto22f144c2017-06-12 14:26:21 -0400240 typedef UniqueVector<Type *> TypeList;
SJW88ed5fe2020-05-11 12:40:57 -0500241 typedef DenseMap<Value *, SPIRVID> ValueMapType;
SJW806a5d82020-07-15 12:51:38 -0500242 typedef std::list<SPIRVID> SPIRVIDListType;
SJW01901d92020-05-21 08:58:31 -0500243 typedef std::vector<std::pair<Value *, SPIRVID>> EntryPointVecType;
244 typedef std::set<uint32_t> CapabilitySetType;
SJW88ed5fe2020-05-11 12:40:57 -0500245 typedef std::list<SPIRVInstruction> SPIRVInstructionList;
SJW806a5d82020-07-15 12:51:38 -0500246 typedef std::map<spv::BuiltIn, SPIRVID> BuiltinConstantMapType;
SJW88ed5fe2020-05-11 12:40:57 -0500247 // A vector of pairs, each of which is:
David Neto87846742018-04-11 17:36:22 -0400248 // - the LLVM instruction that we will later generate SPIR-V code for
SJW88ed5fe2020-05-11 12:40:57 -0500249 // - the SPIR-V instruction placeholder that will be replaced
250 typedef std::vector<std::pair<Value *, SPIRVInstruction *>>
David Neto22f144c2017-06-12 14:26:21 -0400251 DeferredInstVecType;
252 typedef DenseMap<FunctionType *, std::pair<FunctionType *, uint32_t>>
253 GlobalConstFuncMapType;
254
alan-baker3f772c02021-06-15 22:18:11 -0400255 SPIRVProducerPass(
256 raw_pwrite_stream *out,
257 SmallVectorImpl<std::pair<unsigned, std::string>> *samplerMap,
David Neto44795152017-07-13 15:45:28 -0400258 bool outputCInitList)
SJW01901d92020-05-21 08:58:31 -0500259 : ModulePass(ID), module(nullptr), samplerMap(samplerMap), out(out),
alan-baker3f772c02021-06-15 22:18:11 -0400260 binaryTempOut(binaryTempUnderlyingVector), binaryOut(out),
David Neto0676e6f2017-07-11 18:47:44 -0400261 outputCInitList(outputCInitList), patchBoundOffset(0), nextID(1),
alan-baker5b86ed72019-02-15 08:26:50 -0500262 OpExtInstImportID(0), HasVariablePointersStorageBuffer(false),
263 HasVariablePointers(false), SamplerTy(nullptr), WorkgroupSizeValueID(0),
alan-baker3f772c02021-06-15 22:18:11 -0400264 WorkgroupSizeVarID(0), TestOutput(false) {
265 addCapability(spv::CapabilityShader);
266 Ptr = this;
267 }
268
269 SPIRVProducerPass()
270 : ModulePass(ID), module(nullptr), samplerMap(nullptr), out(nullptr),
271 binaryTempOut(binaryTempUnderlyingVector), binaryOut(nullptr),
272 outputCInitList(false), patchBoundOffset(0), nextID(1),
273 OpExtInstImportID(0), HasVariablePointersStorageBuffer(false),
274 HasVariablePointers(false), SamplerTy(nullptr), WorkgroupSizeValueID(0),
275 WorkgroupSizeVarID(0), TestOutput(true) {
SJW01901d92020-05-21 08:58:31 -0500276 addCapability(spv::CapabilityShader);
277 Ptr = this;
278 }
David Neto22f144c2017-06-12 14:26:21 -0400279
James Price11010dc2019-12-19 13:53:09 -0500280 virtual ~SPIRVProducerPass() {
James Price11010dc2019-12-19 13:53:09 -0500281 }
282
David Neto22f144c2017-06-12 14:26:21 -0400283 void getAnalysisUsage(AnalysisUsage &AU) const override {
284 AU.addRequired<DominatorTreeWrapperPass>();
285 AU.addRequired<LoopInfoWrapperPass>();
286 }
287
288 virtual bool runOnModule(Module &module) override;
289
290 // output the SPIR-V header block
291 void outputHeader();
292
293 // patch the SPIR-V header block
294 void patchHeader();
295
SJW01901d92020-05-21 08:58:31 -0500296 CapabilitySetType &getCapabilitySet() { return CapabilitySet; }
David Neto22f144c2017-06-12 14:26:21 -0400297 TypeMapType &getImageTypeMap() { return ImageTypeMap; }
David Neto22f144c2017-06-12 14:26:21 -0400298 ValueMapType &getValueMap() { return ValueMap; }
SJW69939d52020-04-16 07:29:07 -0500299 SPIRVInstructionList &getSPIRVInstList(SPIRVSection Section) {
300 return SPIRVSections[Section];
301 };
alan-baker7506abb2020-09-10 15:02:55 -0400302 EntryPointVecType &getEntryPointVec() { return EntryPointVec; }
303 DeferredInstVecType &getDeferredInstVec() { return DeferredInstVec; }
SJW806a5d82020-07-15 12:51:38 -0500304 SPIRVIDListType &getEntryPointInterfacesList() {
305 return EntryPointInterfacesList;
alan-baker7506abb2020-09-10 15:02:55 -0400306 }
SJW01901d92020-05-21 08:58:31 -0500307 SPIRVID getOpExtInstImportID();
alan-baker7506abb2020-09-10 15:02:55 -0400308 std::vector<SPIRVID> &getBuiltinDimVec() { return BuiltinDimensionVec; }
SJW2c317da2020-03-23 07:39:13 -0500309
alan-baker5b86ed72019-02-15 08:26:50 -0500310 bool hasVariablePointersStorageBuffer() {
311 return HasVariablePointersStorageBuffer;
312 }
SJW01901d92020-05-21 08:58:31 -0500313 void setVariablePointersStorageBuffer() {
314 if (!HasVariablePointersStorageBuffer) {
315 addCapability(spv::CapabilityVariablePointersStorageBuffer);
316 HasVariablePointersStorageBuffer = true;
317 }
alan-baker5b86ed72019-02-15 08:26:50 -0500318 }
alan-baker7506abb2020-09-10 15:02:55 -0400319 bool hasVariablePointers() { return HasVariablePointers; }
SJW01901d92020-05-21 08:58:31 -0500320 void setVariablePointers() {
321 if (!HasVariablePointers) {
322 addCapability(spv::CapabilityVariablePointers);
323 HasVariablePointers = true;
324 }
alan-baker7506abb2020-09-10 15:02:55 -0400325 }
alan-baker3f772c02021-06-15 22:18:11 -0400326 SmallVectorImpl<std::pair<unsigned, std::string>> *getSamplerMap() {
alan-bakerb6b09dc2018-11-08 16:59:28 -0500327 return samplerMap;
328 }
David Neto22f144c2017-06-12 14:26:21 -0400329 GlobalConstFuncMapType &getGlobalConstFuncTypeMap() {
330 return GlobalConstFuncTypeMap;
331 }
332 SmallPtrSet<Value *, 16> &getGlobalConstArgSet() {
333 return GlobalConstArgumentSet;
334 }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500335 TypeList &getTypesNeedingArrayStride() { return TypesNeedingArrayStride; }
David Neto22f144c2017-06-12 14:26:21 -0400336
SJW77b87ad2020-04-21 14:37:52 -0500337 void GenerateLLVMIRInfo();
alan-bakerb6b09dc2018-11-08 16:59:28 -0500338 // Populate GlobalConstFuncTypeMap. Also, if module-scope __constant will
339 // *not* be converted to a storage buffer, replace each such global variable
340 // with one in the storage class expecgted by SPIR-V.
SJW77b87ad2020-04-21 14:37:52 -0500341 void FindGlobalConstVars();
David Neto862b7d82018-06-14 18:48:37 -0400342 // Populate ResourceVarInfoList, FunctionToResourceVarsMap, and
343 // ModuleOrderedResourceVars.
SJW77b87ad2020-04-21 14:37:52 -0500344 void FindResourceVars();
SJW77b87ad2020-04-21 14:37:52 -0500345 void FindTypesForSamplerMap();
346 void FindTypesForResourceVars();
SJWf93f5f32020-05-05 07:27:56 -0500347
alan-bakerc3fd07f2020-10-22 09:48:49 -0400348 // Returns the canonical type of |type|.
349 //
350 // By default, clspv maps both __constant and __global address space pointers
351 // to StorageBuffer storage class. In order to prevent duplicate types from
352 // being generated, clspv uses the canonical type as a representative.
353 Type *CanonicalType(Type *type);
354
SJWf93f5f32020-05-05 07:27:56 -0500355 // Lookup or create Types, Constants.
356 // Returns SPIRVID once it has been created.
alan-baker3f772c02021-06-15 22:18:11 -0400357 SPIRVID getSPIRVType(Type *Ty, bool needs_layout);
SJWf93f5f32020-05-05 07:27:56 -0500358 SPIRVID getSPIRVType(Type *Ty);
359 SPIRVID getSPIRVConstant(Constant *Cst);
SJW806a5d82020-07-15 12:51:38 -0500360 SPIRVID getSPIRVInt32Constant(uint32_t CstVal);
SJWf93f5f32020-05-05 07:27:56 -0500361 // Lookup SPIRVID of llvm::Value, may create Constant.
362 SPIRVID getSPIRVValue(Value *V);
363
alan-baker3f772c02021-06-15 22:18:11 -0400364 bool PointerRequiresLayout(unsigned aspace);
365
SJW806a5d82020-07-15 12:51:38 -0500366 SPIRVID getSPIRVBuiltin(spv::BuiltIn BID, spv::Capability Cap);
367
SJW77b87ad2020-04-21 14:37:52 -0500368 void GenerateModuleInfo();
David Neto22f144c2017-06-12 14:26:21 -0400369 void GenerateGlobalVar(GlobalVariable &GV);
SJW77b87ad2020-04-21 14:37:52 -0500370 void GenerateWorkgroupVars();
alan-baker86ce19c2020-08-05 13:09:19 -0400371 // Generate reflection instructions for resource variables associated with
David Neto862b7d82018-06-14 18:48:37 -0400372 // arguments to F.
SJW77b87ad2020-04-21 14:37:52 -0500373 void GenerateSamplers();
David Neto862b7d82018-06-14 18:48:37 -0400374 // Generate OpVariables for %clspv.resource.var.* calls.
SJW77b87ad2020-04-21 14:37:52 -0500375 void GenerateResourceVars();
David Neto22f144c2017-06-12 14:26:21 -0400376 void GenerateFuncPrologue(Function &F);
377 void GenerateFuncBody(Function &F);
David Netob6e2e062018-04-25 10:32:06 -0400378 void GenerateEntryPointInitialStores();
David Neto22f144c2017-06-12 14:26:21 -0400379 spv::Op GetSPIRVCmpOpcode(CmpInst *CmpI);
380 spv::Op GetSPIRVCastOpcode(Instruction &I);
381 spv::Op GetSPIRVBinaryOpcode(Instruction &I);
SJW806a5d82020-07-15 12:51:38 -0500382 SPIRVID GenerateClspvInstruction(CallInst *Call,
383 const FunctionInfo &FuncInfo);
384 SPIRVID GenerateImageInstruction(CallInst *Call,
385 const FunctionInfo &FuncInfo);
386 SPIRVID GenerateSubgroupInstruction(CallInst *Call,
387 const FunctionInfo &FuncInfo);
388 SPIRVID GenerateInstructionFromCall(CallInst *Call);
David Neto22f144c2017-06-12 14:26:21 -0400389 void GenerateInstruction(Instruction &I);
390 void GenerateFuncEpilogue();
391 void HandleDeferredInstruction();
SJW77b87ad2020-04-21 14:37:52 -0500392 void HandleDeferredDecorations();
David Neto22f144c2017-06-12 14:26:21 -0400393 bool is4xi8vec(Type *Ty) const;
394 spv::StorageClass GetStorageClass(unsigned AddrSpace) const;
David Neto862b7d82018-06-14 18:48:37 -0400395 spv::StorageClass GetStorageClassForArgKind(clspv::ArgKind arg_kind) const;
David Neto22f144c2017-06-12 14:26:21 -0400396 spv::BuiltIn GetBuiltin(StringRef globalVarName) const;
David Neto3fbb4072017-10-16 11:28:14 -0400397 // Returns the GLSL extended instruction enum that the given function
398 // call maps to. If none, then returns the 0 value, i.e. GLSLstd4580Bad.
SJW61531372020-06-09 07:31:08 -0500399 glsl::ExtInst getExtInstEnum(const Builtins::FunctionInfo &func_info);
David Neto3fbb4072017-10-16 11:28:14 -0400400 // Returns the GLSL extended instruction enum indirectly used by the given
401 // function. That is, to implement the given function, we use an extended
402 // instruction plus one more instruction. If none, then returns the 0 value,
403 // i.e. GLSLstd4580Bad.
SJW61531372020-06-09 07:31:08 -0500404 glsl::ExtInst getIndirectExtInstEnum(const Builtins::FunctionInfo &func_info);
David Neto3fbb4072017-10-16 11:28:14 -0400405 // Returns the single GLSL extended instruction used directly or
406 // indirectly by the given function call.
SJW61531372020-06-09 07:31:08 -0500407 glsl::ExtInst
408 getDirectOrIndirectExtInstEnum(const Builtins::FunctionInfo &func_info);
David Neto22f144c2017-06-12 14:26:21 -0400409 void WriteOneWord(uint32_t Word);
SJW88ed5fe2020-05-11 12:40:57 -0500410 void WriteResultID(const SPIRVInstruction &Inst);
411 void WriteWordCountAndOpcode(const SPIRVInstruction &Inst);
412 void WriteOperand(const SPIRVOperand &Op);
David Neto22f144c2017-06-12 14:26:21 -0400413 void WriteSPIRVBinary();
SJW69939d52020-04-16 07:29:07 -0500414 void WriteSPIRVBinary(SPIRVInstructionList &SPIRVInstList);
David Neto22f144c2017-06-12 14:26:21 -0400415
Alan Baker9bf93fb2018-08-28 16:59:26 -0400416 // Returns true if |type| is compatible with OpConstantNull.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500417 bool IsTypeNullable(const Type *type) const;
Alan Baker9bf93fb2018-08-28 16:59:26 -0400418
Alan Bakerfcda9482018-10-02 17:09:59 -0400419 // Populate UBO remapped type maps.
SJW77b87ad2020-04-21 14:37:52 -0500420 void PopulateUBOTypeMaps();
Alan Bakerfcda9482018-10-02 17:09:59 -0400421
alan-baker06cad652019-12-03 17:56:47 -0500422 // Populate the merge and continue block maps.
SJW77b87ad2020-04-21 14:37:52 -0500423 void PopulateStructuredCFGMaps();
alan-baker06cad652019-12-03 17:56:47 -0500424
Alan Bakerfcda9482018-10-02 17:09:59 -0400425 // Wrapped methods of DataLayout accessors. If |type| was remapped for UBOs,
426 // uses the internal map, otherwise it falls back on the data layout.
427 uint64_t GetTypeSizeInBits(Type *type, const DataLayout &DL);
Alan Bakerfcda9482018-10-02 17:09:59 -0400428 uint64_t GetTypeAllocSize(Type *type, const DataLayout &DL);
Kévin Petitbbbda972020-03-03 19:16:31 +0000429 uint32_t GetExplicitLayoutStructMemberOffset(StructType *type,
430 unsigned member,
431 const DataLayout &DL);
Alan Bakerfcda9482018-10-02 17:09:59 -0400432
alan-baker5b86ed72019-02-15 08:26:50 -0500433 // Returns the base pointer of |v|.
434 Value *GetBasePointer(Value *v);
435
SJW01901d92020-05-21 08:58:31 -0500436 // Add Capability if not already (e.g. CapabilityGroupNonUniformBroadcast)
437 void addCapability(uint32_t c) { CapabilitySet.emplace(c); }
438
alan-baker5b86ed72019-02-15 08:26:50 -0500439 // Sets |HasVariablePointersStorageBuffer| or |HasVariablePointers| base on
440 // |address_space|.
441 void setVariablePointersCapabilities(unsigned address_space);
442
443 // Returns true if |lhs| and |rhs| represent the same resource or workgroup
444 // variable.
445 bool sameResource(Value *lhs, Value *rhs) const;
446
447 // Returns true if |inst| is phi or select that selects from the same
448 // structure (or null).
449 bool selectFromSameObject(Instruction *inst);
450
alan-bakere9308012019-03-15 10:25:13 -0400451 // Returns true if |Arg| is called with a coherent resource.
452 bool CalledWithCoherentResource(Argument &Arg);
453
SJWf93f5f32020-05-05 07:27:56 -0500454 //
455 // Primary interface for adding SPIRVInstructions to a SPIRVSection.
456 template <enum SPIRVSection TSection = kFunctions>
457 SPIRVID addSPIRVInst(spv::Op Opcode, SPIRVOperandVec &Operands) {
458 bool has_result, has_result_type;
459 spv::HasResultAndType(Opcode, &has_result, &has_result_type);
460 SPIRVID RID = has_result ? incrNextID() : 0;
SJW88ed5fe2020-05-11 12:40:57 -0500461 SPIRVSections[TSection].emplace_back(Opcode, RID, Operands);
SJWf93f5f32020-05-05 07:27:56 -0500462 return RID;
463 }
464 template <enum SPIRVSection TSection = kFunctions>
465 SPIRVID addSPIRVInst(spv::Op Op) {
466 SPIRVOperandVec Ops;
467 return addSPIRVInst<TSection>(Op, Ops);
468 }
469 template <enum SPIRVSection TSection = kFunctions>
470 SPIRVID addSPIRVInst(spv::Op Op, uint32_t V) {
471 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -0500472 Ops.emplace_back(LITERAL_WORD, V);
SJWf93f5f32020-05-05 07:27:56 -0500473 return addSPIRVInst<TSection>(Op, Ops);
474 }
475 template <enum SPIRVSection TSection = kFunctions>
476 SPIRVID addSPIRVInst(spv::Op Op, const char *V) {
477 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -0500478 Ops.emplace_back(LITERAL_STRING, V);
SJWf93f5f32020-05-05 07:27:56 -0500479 return addSPIRVInst<TSection>(Op, Ops);
480 }
481
SJW88ed5fe2020-05-11 12:40:57 -0500482 //
483 // Add placeholder for llvm::Value that references future values.
484 // Must have result ID just in case final SPIRVInstruction requires.
485 SPIRVID addSPIRVPlaceholder(Value *I) {
486 SPIRVID RID = incrNextID();
487 SPIRVOperandVec Ops;
488 SPIRVSections[kFunctions].emplace_back(spv::OpExtInst, RID, Ops);
489 DeferredInstVec.push_back({I, &SPIRVSections[kFunctions].back()});
490 return RID;
491 }
492 // Replace placeholder with actual SPIRVInstruction on the final pass
493 // (HandleDeferredInstruction).
494 SPIRVID replaceSPIRVInst(SPIRVInstruction *I, spv::Op Opcode,
495 SPIRVOperandVec &Operands) {
496 bool has_result, has_result_type;
497 spv::HasResultAndType(Opcode, &has_result, &has_result_type);
498 SPIRVID RID = has_result ? I->getResultID() : 0;
499 *I = SPIRVInstruction(Opcode, RID, Operands);
500 return RID;
501 }
502
SJW806a5d82020-07-15 12:51:38 -0500503 //
504 // Add global variable and capture entry point interface
505 SPIRVID addSPIRVGlobalVariable(const SPIRVID &TypeID, spv::StorageClass SC,
alan-baker3f772c02021-06-15 22:18:11 -0400506 const SPIRVID &InitID = SPIRVID(),
507 bool add_interface = false);
SJW806a5d82020-07-15 12:51:38 -0500508
alan-baker86ce19c2020-08-05 13:09:19 -0400509 SPIRVID getReflectionImport();
510 void GenerateReflection();
511 void GenerateKernelReflection();
512 void GeneratePushConstantReflection();
513 void GenerateSpecConstantReflection();
514 void AddArgumentReflection(SPIRVID kernel_decl, const std::string &name,
515 clspv::ArgKind arg_kind, uint32_t ordinal,
516 uint32_t descriptor_set, uint32_t binding,
517 uint32_t offset, uint32_t size, uint32_t spec_id,
518 uint32_t elem_size);
519
David Neto22f144c2017-06-12 14:26:21 -0400520private:
SJW77b87ad2020-04-21 14:37:52 -0500521
522 Module *module;
523
SJW01901d92020-05-21 08:58:31 -0500524 // Set of Capabilities required
525 CapabilitySetType CapabilitySet;
526
SJW806a5d82020-07-15 12:51:38 -0500527 // Map from clspv::BuiltinType to SPIRV Global Variable
528 BuiltinConstantMapType BuiltinConstantMap;
529
alan-baker3f772c02021-06-15 22:18:11 -0400530 SmallVectorImpl<std::pair<unsigned, std::string>> *samplerMap;
531 raw_pwrite_stream *out;
David Neto0676e6f2017-07-11 18:47:44 -0400532
533 // TODO(dneto): Wouldn't it be better to always just emit a binary, and then
534 // convert to other formats on demand?
535
536 // When emitting a C initialization list, the WriteSPIRVBinary method
537 // will actually write its words to this vector via binaryTempOut.
538 SmallVector<char, 100> binaryTempUnderlyingVector;
539 raw_svector_ostream binaryTempOut;
540
541 // Binary output writes to this stream, which might be |out| or
542 // |binaryTempOut|. It's the latter when we really want to write a C
543 // initializer list.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400544 raw_pwrite_stream *binaryOut;
David Neto0676e6f2017-07-11 18:47:44 -0400545 const bool outputCInitList; // If true, output look like {0x7023, ... , 5}
David Neto22f144c2017-06-12 14:26:21 -0400546 uint64_t patchBoundOffset;
547 uint32_t nextID;
548
SJWf93f5f32020-05-05 07:27:56 -0500549 SPIRVID incrNextID() { return nextID++; }
550
alan-bakerf67468c2019-11-25 15:51:49 -0500551 // ID for OpTypeInt 32 1.
SJW01901d92020-05-21 08:58:31 -0500552 SPIRVID int32ID;
alan-bakerf67468c2019-11-25 15:51:49 -0500553 // ID for OpTypeVector %int 4.
SJW01901d92020-05-21 08:58:31 -0500554 SPIRVID v4int32ID;
alan-bakerf67468c2019-11-25 15:51:49 -0500555
David Neto19a1bad2017-08-25 15:01:41 -0400556 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
alan-baker3f772c02021-06-15 22:18:11 -0400557 LayoutTypeMapType TypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400558 // Maps an LLVM image type to its SPIR-V ID.
David Neto22f144c2017-06-12 14:26:21 -0400559 TypeMapType ImageTypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400560 // A unique-vector of LLVM types that map to a SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400561 TypeList Types;
David Neto19a1bad2017-08-25 15:01:41 -0400562 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400563 ValueMapType ValueMap;
SJW69939d52020-04-16 07:29:07 -0500564 SPIRVInstructionList SPIRVSections[kSectionCount];
David Neto862b7d82018-06-14 18:48:37 -0400565
David Neto22f144c2017-06-12 14:26:21 -0400566 EntryPointVecType EntryPointVec;
567 DeferredInstVecType DeferredInstVec;
SJW806a5d82020-07-15 12:51:38 -0500568 SPIRVIDListType EntryPointInterfacesList;
SJW01901d92020-05-21 08:58:31 -0500569 SPIRVID OpExtInstImportID;
570 std::vector<SPIRVID> BuiltinDimensionVec;
alan-baker5b86ed72019-02-15 08:26:50 -0500571 bool HasVariablePointersStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -0400572 bool HasVariablePointers;
573 Type *SamplerTy;
SJW01901d92020-05-21 08:58:31 -0500574 DenseMap<unsigned, SPIRVID> SamplerLiteralToIDMap;
David Netoc77d9e22018-03-24 06:30:28 -0700575
576 // If a function F has a pointer-to-__constant parameter, then this variable
David Neto9ed8e2f2018-03-24 06:47:24 -0700577 // will map F's type to (G, index of the parameter), where in a first phase
Marco Antognini7e338402021-03-15 12:48:37 +0000578 // G is F's type.
David Netoc77d9e22018-03-24 06:30:28 -0700579 // TODO(dneto): This doesn't seem general enough? A function might have
580 // more than one such parameter.
David Neto22f144c2017-06-12 14:26:21 -0400581 GlobalConstFuncMapType GlobalConstFuncTypeMap;
582 SmallPtrSet<Value *, 16> GlobalConstArgumentSet;
David Neto1a1a0582017-07-07 12:01:44 -0400583 // An ordered set of pointer types of Base arguments to OpPtrAccessChain,
David Neto85082642018-03-24 06:55:20 -0700584 // or array types, and which point into transparent memory (StorageBuffer
585 // storage class). These will require an ArrayStride decoration.
David Neto1a1a0582017-07-07 12:01:44 -0400586 // See SPV_KHR_variable_pointers rev 13.
David Neto85082642018-03-24 06:55:20 -0700587 TypeList TypesNeedingArrayStride;
David Netoa60b00b2017-09-15 16:34:09 -0400588
589 // This is truly ugly, but works around what look like driver bugs.
590 // For get_local_size, an earlier part of the flow has created a module-scope
591 // variable in Private address space to hold the value for the workgroup
592 // size. Its intializer is a uint3 value marked as builtin WorkgroupSize.
593 // When this is present, save the IDs of the initializer value and variable
594 // in these two variables. We only ever do a vector load from it, and
595 // when we see one of those, substitute just the value of the intializer.
596 // This mimics what Glslang does, and that's what drivers are used to.
David Neto66cfe642018-03-24 06:13:56 -0700597 // TODO(dneto): Remove this once drivers are fixed.
SJW01901d92020-05-21 08:58:31 -0500598 SPIRVID WorkgroupSizeValueID;
599 SPIRVID WorkgroupSizeVarID;
David Neto26aaf622017-10-23 18:11:53 -0400600
alan-baker3f772c02021-06-15 22:18:11 -0400601 bool TestOutput;
602
David Neto862b7d82018-06-14 18:48:37 -0400603 // Bookkeeping for mapping kernel arguments to resource variables.
604 struct ResourceVarInfo {
605 ResourceVarInfo(int index_arg, unsigned set_arg, unsigned binding_arg,
alan-bakere9308012019-03-15 10:25:13 -0400606 Function *fn, clspv::ArgKind arg_kind_arg, int coherent_arg)
David Neto862b7d82018-06-14 18:48:37 -0400607 : index(index_arg), descriptor_set(set_arg), binding(binding_arg),
alan-bakere9308012019-03-15 10:25:13 -0400608 var_fn(fn), arg_kind(arg_kind_arg), coherent(coherent_arg),
David Neto862b7d82018-06-14 18:48:37 -0400609 addr_space(fn->getReturnType()->getPointerAddressSpace()) {}
610 const int index; // Index into ResourceVarInfoList
611 const unsigned descriptor_set;
612 const unsigned binding;
613 Function *const var_fn; // The @clspv.resource.var.* function.
614 const clspv::ArgKind arg_kind;
alan-bakere9308012019-03-15 10:25:13 -0400615 const int coherent;
David Neto862b7d82018-06-14 18:48:37 -0400616 const unsigned addr_space; // The LLVM address space
617 // The SPIR-V ID of the OpVariable. Not populated at construction time.
SJW01901d92020-05-21 08:58:31 -0500618 SPIRVID var_id;
David Neto862b7d82018-06-14 18:48:37 -0400619 };
620 // A list of resource var info. Each one correponds to a module-scope
621 // resource variable we will have to create. Resource var indices are
622 // indices into this vector.
623 SmallVector<std::unique_ptr<ResourceVarInfo>, 8> ResourceVarInfoList;
624 // This is a vector of pointers of all the resource vars, but ordered by
625 // kernel function, and then by argument.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500626 UniqueVector<ResourceVarInfo *> ModuleOrderedResourceVars;
David Neto862b7d82018-06-14 18:48:37 -0400627 // Map a function to the ordered list of resource variables it uses, one for
628 // each argument. If an argument does not use a resource variable, it
629 // will have a null pointer entry.
630 using FunctionToResourceVarsMapType =
631 DenseMap<Function *, SmallVector<ResourceVarInfo *, 8>>;
632 FunctionToResourceVarsMapType FunctionToResourceVarsMap;
633
634 // What LLVM types map to SPIR-V types needing layout? These are the
635 // arrays and structures supporting storage buffers and uniform buffers.
636 TypeList TypesNeedingLayout;
637 // What LLVM struct types map to a SPIR-V struct type with Block decoration?
638 UniqueVector<StructType *> StructTypesNeedingBlock;
639 // For a call that represents a load from an opaque type (samplers, images),
640 // map it to the variable id it should load from.
SJW01901d92020-05-21 08:58:31 -0500641 DenseMap<CallInst *, SPIRVID> ResourceVarDeferredLoadCalls;
David Neto85082642018-03-24 06:55:20 -0700642
David Netoc6f3ab22018-04-06 18:02:31 -0400643 // An ordered list of the kernel arguments of type pointer-to-local.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500644 using LocalArgList = SmallVector<Argument *, 8>;
David Netoc6f3ab22018-04-06 18:02:31 -0400645 LocalArgList LocalArgs;
646 // Information about a pointer-to-local argument.
647 struct LocalArgInfo {
648 // The SPIR-V ID of the array variable.
SJW01901d92020-05-21 08:58:31 -0500649 SPIRVID variable_id;
David Netoc6f3ab22018-04-06 18:02:31 -0400650 // The element type of the
alan-bakerb6b09dc2018-11-08 16:59:28 -0500651 Type *elem_type;
David Netoc6f3ab22018-04-06 18:02:31 -0400652 // The ID of the array type.
SJW01901d92020-05-21 08:58:31 -0500653 SPIRVID array_size_id;
David Netoc6f3ab22018-04-06 18:02:31 -0400654 // The ID of the array type.
SJW01901d92020-05-21 08:58:31 -0500655 SPIRVID array_type_id;
David Netoc6f3ab22018-04-06 18:02:31 -0400656 // The ID of the pointer to the array type.
SJW01901d92020-05-21 08:58:31 -0500657 SPIRVID ptr_array_type_id;
David Netoc6f3ab22018-04-06 18:02:31 -0400658 // The specialization constant ID of the array size.
659 int spec_id;
660 };
Alan Baker202c8c72018-08-13 13:47:44 -0400661 // A mapping from Argument to its assigned SpecId.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500662 DenseMap<const Argument *, int> LocalArgSpecIds;
Alan Baker202c8c72018-08-13 13:47:44 -0400663 // A mapping from SpecId to its LocalArgInfo.
664 DenseMap<int, LocalArgInfo> LocalSpecIdInfoMap;
Alan Bakerfcda9482018-10-02 17:09:59 -0400665 // A mapping from a remapped type to its real offsets.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500666 DenseMap<Type *, std::vector<uint32_t>> RemappedUBOTypeOffsets;
Alan Bakerfcda9482018-10-02 17:09:59 -0400667 // A mapping from a remapped type to its real sizes.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500668 DenseMap<Type *, std::tuple<uint64_t, uint64_t, uint64_t>>
669 RemappedUBOTypeSizes;
alan-baker06cad652019-12-03 17:56:47 -0500670
671 // Maps basic block to its merge block.
672 DenseMap<BasicBlock *, BasicBlock *> MergeBlocks;
673 // Maps basic block to its continue block.
674 DenseMap<BasicBlock *, BasicBlock *> ContinueBlocks;
SJW01901d92020-05-21 08:58:31 -0500675
alan-baker86ce19c2020-08-05 13:09:19 -0400676 SPIRVID ReflectionID;
677 DenseMap<Function *, SPIRVID> KernelDeclarations;
678
SJW01901d92020-05-21 08:58:31 -0500679public:
680 static SPIRVProducerPass *Ptr;
David Neto22f144c2017-06-12 14:26:21 -0400681};
682
alan-bakerb6b09dc2018-11-08 16:59:28 -0500683} // namespace
David Neto22f144c2017-06-12 14:26:21 -0400684
alan-baker3f772c02021-06-15 22:18:11 -0400685char SPIRVProducerPass::ID = 0;
686SPIRVProducerPass *SPIRVProducerPass::Ptr = nullptr;
687INITIALIZE_PASS(SPIRVProducerPass, "SPIRVProducerPass", "SPIR-V output pass",
688 false, false)
689
David Neto22f144c2017-06-12 14:26:21 -0400690namespace clspv {
alan-baker3f772c02021-06-15 22:18:11 -0400691ModulePass *createSPIRVProducerPass(
692 raw_pwrite_stream *out,
693 SmallVectorImpl<std::pair<unsigned, std::string>> *samplerMap,
694 bool outputCInitList) {
alan-baker86ce19c2020-08-05 13:09:19 -0400695 return new SPIRVProducerPass(out, samplerMap, outputCInitList);
David Neto22f144c2017-06-12 14:26:21 -0400696}
alan-baker3f772c02021-06-15 22:18:11 -0400697
698ModulePass *createSPIRVProducerPass() { return new SPIRVProducerPass(); }
David Netoc2c368d2017-06-30 16:50:17 -0400699} // namespace clspv
David Neto22f144c2017-06-12 14:26:21 -0400700
SJW01901d92020-05-21 08:58:31 -0500701namespace {
702SPIRVOperandVec &operator<<(SPIRVOperandVec &list, uint32_t num) {
703 list.emplace_back(LITERAL_WORD, num);
704 return list;
705}
706
707SPIRVOperandVec &operator<<(SPIRVOperandVec &list, int32_t num) {
708 list.emplace_back(LITERAL_WORD, static_cast<uint32_t>(num));
709 return list;
710}
711
712SPIRVOperandVec &operator<<(SPIRVOperandVec &list, ArrayRef<uint32_t> num_vec) {
713 list.emplace_back(num_vec);
714 return list;
715}
716
717SPIRVOperandVec &operator<<(SPIRVOperandVec &list, StringRef str) {
718 list.emplace_back(LITERAL_STRING, str);
719 return list;
720}
721
722SPIRVOperandVec &operator<<(SPIRVOperandVec &list, Type *t) {
723 list.emplace_back(NUMBERID, SPIRVProducerPass::Ptr->getSPIRVType(t).get());
724 return list;
725}
726
727SPIRVOperandVec &operator<<(SPIRVOperandVec &list, Value *v) {
728 list.emplace_back(NUMBERID, SPIRVProducerPass::Ptr->getSPIRVValue(v).get());
729 return list;
730}
731
SJW806a5d82020-07-15 12:51:38 -0500732SPIRVOperandVec &operator<<(SPIRVOperandVec &list, const SPIRVID &v) {
SJW01901d92020-05-21 08:58:31 -0500733 list.emplace_back(NUMBERID, v.get());
734 return list;
735}
736} // namespace
737
SJW77b87ad2020-04-21 14:37:52 -0500738bool SPIRVProducerPass::runOnModule(Module &M) {
SJW01901d92020-05-21 08:58:31 -0500739 // TODO(sjw): Need to reset all data members for each Module, or better
740 // yet create a new SPIRVProducer for every module.. For now only
741 // allow 1 call.
742 assert(module == nullptr);
SJW77b87ad2020-04-21 14:37:52 -0500743 module = &M;
alan-baker5ed87542020-03-23 11:05:22 -0400744 if (ShowProducerIR) {
SJW77b87ad2020-04-21 14:37:52 -0500745 llvm::outs() << *module << "\n";
alan-baker5ed87542020-03-23 11:05:22 -0400746 }
alan-baker3f772c02021-06-15 22:18:11 -0400747
748 SmallVector<char, 10000> *binary = nullptr;
749 if (TestOutput) {
750 binary = new SmallVector<char, 10000>();
751 out = new raw_svector_ostream(*binary);
752 }
753
754 binaryOut = outputCInitList ? &binaryTempOut : out;
David Neto0676e6f2017-07-11 18:47:44 -0400755
SJW77b87ad2020-04-21 14:37:52 -0500756 PopulateUBOTypeMaps();
757 PopulateStructuredCFGMaps();
Alan Bakerfcda9482018-10-02 17:09:59 -0400758
David Neto22f144c2017-06-12 14:26:21 -0400759 // SPIR-V always begins with its header information
760 outputHeader();
761
762 // Gather information from the LLVM IR that we require.
SJW77b87ad2020-04-21 14:37:52 -0500763 GenerateLLVMIRInfo();
David Neto22f144c2017-06-12 14:26:21 -0400764
David Neto22f144c2017-06-12 14:26:21 -0400765 // Collect information on global variables too.
SJW77b87ad2020-04-21 14:37:52 -0500766 for (GlobalVariable &GV : module->globals()) {
David Neto22f144c2017-06-12 14:26:21 -0400767 // If the GV is one of our special __spirv_* variables, remove the
768 // initializer as it was only placed there to force LLVM to not throw the
769 // value away.
Kévin Petitbbbda972020-03-03 19:16:31 +0000770 if (GV.getName().startswith("__spirv_") ||
771 GV.getAddressSpace() == clspv::AddressSpace::PushConstant) {
David Neto22f144c2017-06-12 14:26:21 -0400772 GV.setInitializer(nullptr);
773 }
David Neto22f144c2017-06-12 14:26:21 -0400774 }
775
alan-baker09cb9802019-12-10 13:16:27 -0500776 // Generate literal samplers if necessary.
SJW77b87ad2020-04-21 14:37:52 -0500777 GenerateSamplers();
David Neto22f144c2017-06-12 14:26:21 -0400778
779 // Generate SPIRV variables.
SJW77b87ad2020-04-21 14:37:52 -0500780 for (GlobalVariable &GV : module->globals()) {
David Neto22f144c2017-06-12 14:26:21 -0400781 GenerateGlobalVar(GV);
782 }
SJW77b87ad2020-04-21 14:37:52 -0500783 GenerateResourceVars();
784 GenerateWorkgroupVars();
David Neto22f144c2017-06-12 14:26:21 -0400785
786 // Generate SPIRV instructions for each function.
SJW77b87ad2020-04-21 14:37:52 -0500787 for (Function &F : *module) {
David Neto22f144c2017-06-12 14:26:21 -0400788 if (F.isDeclaration()) {
789 continue;
790 }
791
792 // Generate Function Prologue.
793 GenerateFuncPrologue(F);
794
795 // Generate SPIRV instructions for function body.
796 GenerateFuncBody(F);
797
798 // Generate Function Epilogue.
799 GenerateFuncEpilogue();
800 }
801
802 HandleDeferredInstruction();
SJW77b87ad2020-04-21 14:37:52 -0500803 HandleDeferredDecorations();
alan-bakera1be3322020-04-20 12:48:18 -0400804
David Neto22f144c2017-06-12 14:26:21 -0400805 // Generate SPIRV module information.
SJW77b87ad2020-04-21 14:37:52 -0500806 GenerateModuleInfo();
David Neto22f144c2017-06-12 14:26:21 -0400807
alan-baker86ce19c2020-08-05 13:09:19 -0400808 // Generate embedded reflection information.
809 GenerateReflection();
810
alan-baker00e7a582019-06-07 12:54:21 -0400811 WriteSPIRVBinary();
David Neto22f144c2017-06-12 14:26:21 -0400812
813 // We need to patch the SPIR-V header to set bound correctly.
814 patchHeader();
David Neto0676e6f2017-07-11 18:47:44 -0400815
816 if (outputCInitList) {
817 bool first = true;
David Neto0676e6f2017-07-11 18:47:44 -0400818 std::ostringstream os;
819
David Neto57fb0b92017-08-04 15:35:09 -0400820 auto emit_word = [&os, &first](uint32_t word) {
David Neto0676e6f2017-07-11 18:47:44 -0400821 if (!first)
David Neto57fb0b92017-08-04 15:35:09 -0400822 os << ",\n";
823 os << word;
David Neto0676e6f2017-07-11 18:47:44 -0400824 first = false;
825 };
826
827 os << "{";
David Neto57fb0b92017-08-04 15:35:09 -0400828 const std::string str(binaryTempOut.str());
829 for (unsigned i = 0; i < str.size(); i += 4) {
830 const uint32_t a = static_cast<unsigned char>(str[i]);
831 const uint32_t b = static_cast<unsigned char>(str[i + 1]);
832 const uint32_t c = static_cast<unsigned char>(str[i + 2]);
833 const uint32_t d = static_cast<unsigned char>(str[i + 3]);
834 emit_word(a | (b << 8) | (c << 16) | (d << 24));
David Neto0676e6f2017-07-11 18:47:44 -0400835 }
836 os << "}\n";
alan-baker3f772c02021-06-15 22:18:11 -0400837 *out << os.str();
838 }
839
840 if (TestOutput) {
841 std::error_code error;
842 raw_fd_ostream test_output(TestOutFile, error, llvm::sys::fs::FA_Write);
843 test_output << static_cast<raw_svector_ostream *>(out)->str();
844 delete out;
845 delete binary;
David Neto0676e6f2017-07-11 18:47:44 -0400846 }
847
David Neto22f144c2017-06-12 14:26:21 -0400848 return false;
849}
850
851void SPIRVProducerPass::outputHeader() {
alan-baker00e7a582019-06-07 12:54:21 -0400852 binaryOut->write(reinterpret_cast<const char *>(&spv::MagicNumber),
853 sizeof(spv::MagicNumber));
SJW806a5d82020-07-15 12:51:38 -0500854 uint32_t minor = 0;
alan-baker3f772c02021-06-15 22:18:11 -0400855 switch (SpvVersion()) {
856 case SPIRVVersion::SPIRV_1_0:
857 minor = 0;
858 break;
859 case SPIRVVersion::SPIRV_1_3:
SJW806a5d82020-07-15 12:51:38 -0500860 minor = 3;
alan-baker3f772c02021-06-15 22:18:11 -0400861 break;
862 case SPIRVVersion::SPIRV_1_4:
863 minor = 4;
864 break;
865 case SPIRVVersion::SPIRV_1_5:
866 minor = 5;
867 break;
868 default:
869 llvm_unreachable("unhandled spir-v version");
870 break;
SJW806a5d82020-07-15 12:51:38 -0500871 }
872 uint32_t version = (1 << 16) | (minor << 8);
873 binaryOut->write(reinterpret_cast<const char *>(&version), sizeof(version));
David Neto22f144c2017-06-12 14:26:21 -0400874
alan-baker0c18ab02019-06-12 10:23:21 -0400875 // use Google's vendor ID
876 const uint32_t vendor = 21 << 16;
alan-baker00e7a582019-06-07 12:54:21 -0400877 binaryOut->write(reinterpret_cast<const char *>(&vendor), sizeof(vendor));
David Neto22f144c2017-06-12 14:26:21 -0400878
alan-baker00e7a582019-06-07 12:54:21 -0400879 // we record where we need to come back to and patch in the bound value
880 patchBoundOffset = binaryOut->tell();
David Neto22f144c2017-06-12 14:26:21 -0400881
alan-baker00e7a582019-06-07 12:54:21 -0400882 // output a bad bound for now
883 binaryOut->write(reinterpret_cast<const char *>(&nextID), sizeof(nextID));
David Neto22f144c2017-06-12 14:26:21 -0400884
alan-baker00e7a582019-06-07 12:54:21 -0400885 // output the schema (reserved for use and must be 0)
886 const uint32_t schema = 0;
887 binaryOut->write(reinterpret_cast<const char *>(&schema), sizeof(schema));
David Neto22f144c2017-06-12 14:26:21 -0400888}
889
890void SPIRVProducerPass::patchHeader() {
alan-baker00e7a582019-06-07 12:54:21 -0400891 // for a binary we just write the value of nextID over bound
892 binaryOut->pwrite(reinterpret_cast<char *>(&nextID), sizeof(nextID),
893 patchBoundOffset);
David Neto22f144c2017-06-12 14:26:21 -0400894}
895
SJW77b87ad2020-04-21 14:37:52 -0500896void SPIRVProducerPass::GenerateLLVMIRInfo() {
David Neto22f144c2017-06-12 14:26:21 -0400897 // This function generates LLVM IR for function such as global variable for
898 // argument, constant and pointer type for argument access. These information
899 // is artificial one because we need Vulkan SPIR-V output. This function is
900 // executed ahead of FindType and FindConstant.
David Neto22f144c2017-06-12 14:26:21 -0400901
SJW77b87ad2020-04-21 14:37:52 -0500902 FindGlobalConstVars();
David Neto5c22a252018-03-15 16:07:41 -0400903
SJW77b87ad2020-04-21 14:37:52 -0500904 FindResourceVars();
David Neto22f144c2017-06-12 14:26:21 -0400905
SJW77b87ad2020-04-21 14:37:52 -0500906 FindTypesForSamplerMap();
907 FindTypesForResourceVars();
David Neto22f144c2017-06-12 14:26:21 -0400908}
909
SJW77b87ad2020-04-21 14:37:52 -0500910void SPIRVProducerPass::FindGlobalConstVars() {
911 clspv::NormalizeGlobalVariables(*module);
912 const DataLayout &DL = module->getDataLayout();
alan-baker56f7aff2019-05-22 08:06:42 -0400913
David Neto862b7d82018-06-14 18:48:37 -0400914 SmallVector<GlobalVariable *, 8> GVList;
915 SmallVector<GlobalVariable *, 8> DeadGVList;
SJW77b87ad2020-04-21 14:37:52 -0500916 for (GlobalVariable &GV : module->globals()) {
David Neto862b7d82018-06-14 18:48:37 -0400917 if (GV.getType()->getAddressSpace() == AddressSpace::Constant) {
918 if (GV.use_empty()) {
919 DeadGVList.push_back(&GV);
920 } else {
921 GVList.push_back(&GV);
922 }
923 }
924 }
925
926 // Remove dead global __constant variables.
927 for (auto GV : DeadGVList) {
928 GV->eraseFromParent();
929 }
930 DeadGVList.clear();
931
932 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
933 // For now, we only support a single storage buffer.
alan-baker7506abb2020-09-10 15:02:55 -0400934 if (!GVList.empty()) {
David Neto862b7d82018-06-14 18:48:37 -0400935 assert(GVList.size() == 1);
936 const auto *GV = GVList[0];
937 const auto constants_byte_size =
Alan Bakerfcda9482018-10-02 17:09:59 -0400938 (GetTypeSizeInBits(GV->getInitializer()->getType(), DL)) / 8;
David Neto862b7d82018-06-14 18:48:37 -0400939 const size_t kConstantMaxSize = 65536;
940 if (constants_byte_size > kConstantMaxSize) {
941 outs() << "Max __constant capacity of " << kConstantMaxSize
942 << " bytes exceeded: " << constants_byte_size << " bytes used\n";
943 llvm_unreachable("Max __constant capacity exceeded");
944 }
945 }
946 } else {
947 // Change global constant variable's address space to ModuleScopePrivate.
948 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
949 for (auto GV : GVList) {
950 // Create new gv with ModuleScopePrivate address space.
951 Type *NewGVTy = GV->getType()->getPointerElementType();
952 GlobalVariable *NewGV = new GlobalVariable(
SJW77b87ad2020-04-21 14:37:52 -0500953 *module, NewGVTy, false, GV->getLinkage(), GV->getInitializer(), "",
David Neto862b7d82018-06-14 18:48:37 -0400954 nullptr, GV->getThreadLocalMode(), AddressSpace::ModuleScopePrivate);
955 NewGV->takeName(GV);
956
957 const SmallVector<User *, 8> GVUsers(GV->user_begin(), GV->user_end());
958 SmallVector<User *, 8> CandidateUsers;
959
960 auto record_called_function_type_as_user =
961 [&GlobalConstFuncTyMap](Value *gv, CallInst *call) {
962 // Find argument index.
963 unsigned index = 0;
964 for (unsigned i = 0; i < call->getNumArgOperands(); i++) {
965 if (gv == call->getOperand(i)) {
966 // TODO(dneto): Should we break here?
967 index = i;
968 }
969 }
970
971 // Record function type with global constant.
972 GlobalConstFuncTyMap[call->getFunctionType()] =
973 std::make_pair(call->getFunctionType(), index);
974 };
975
976 for (User *GVU : GVUsers) {
977 if (CallInst *Call = dyn_cast<CallInst>(GVU)) {
978 record_called_function_type_as_user(GV, Call);
979 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(GVU)) {
980 // Check GEP users.
981 for (User *GEPU : GEP->users()) {
982 if (CallInst *GEPCall = dyn_cast<CallInst>(GEPU)) {
983 record_called_function_type_as_user(GEP, GEPCall);
984 }
985 }
986 }
987
988 CandidateUsers.push_back(GVU);
989 }
990
991 for (User *U : CandidateUsers) {
992 // Update users of gv with new gv.
alan-bakered80f572019-02-11 17:28:26 -0500993 if (!isa<Constant>(U)) {
994 // #254: Can't change operands of a constant, but this shouldn't be
995 // something that sticks around in the module.
996 U->replaceUsesOfWith(GV, NewGV);
997 }
David Neto862b7d82018-06-14 18:48:37 -0400998 }
999
1000 // Delete original gv.
1001 GV->eraseFromParent();
1002 }
1003 }
1004}
1005
SJW77b87ad2020-04-21 14:37:52 -05001006void SPIRVProducerPass::FindResourceVars() {
David Neto862b7d82018-06-14 18:48:37 -04001007 ResourceVarInfoList.clear();
1008 FunctionToResourceVarsMap.clear();
1009 ModuleOrderedResourceVars.reset();
1010 // Normally, there is one resource variable per clspv.resource.var.*
1011 // function, since that is unique'd by arg type and index. By design,
1012 // we can share these resource variables across kernels because all
1013 // kernels use the same descriptor set.
1014 //
1015 // But if the user requested distinct descriptor sets per kernel, then
1016 // the descriptor allocator has made different (set,binding) pairs for
1017 // the same (type,arg_index) pair. Since we can decorate a resource
1018 // variable with only exactly one DescriptorSet and Binding, we are
1019 // forced in this case to make distinct resource variables whenever
Kévin Petitbbbda972020-03-03 19:16:31 +00001020 // the same clspv.resource.var.X function is seen with disintct
David Neto862b7d82018-06-14 18:48:37 -04001021 // (set,binding) values.
1022 const bool always_distinct_sets =
1023 clspv::Option::DistinctKernelDescriptorSets();
SJW77b87ad2020-04-21 14:37:52 -05001024 for (Function &F : *module) {
David Neto862b7d82018-06-14 18:48:37 -04001025 // Rely on the fact the resource var functions have a stable ordering
1026 // in the module.
SJW61531372020-06-09 07:31:08 -05001027 if (Builtins::Lookup(&F) == Builtins::kClspvResource) {
David Neto862b7d82018-06-14 18:48:37 -04001028 // Find all calls to this function with distinct set and binding pairs.
1029 // Save them in ResourceVarInfoList.
1030
1031 // Determine uniqueness of the (set,binding) pairs only withing this
1032 // one resource-var builtin function.
1033 using SetAndBinding = std::pair<unsigned, unsigned>;
1034 // Maps set and binding to the resource var info.
1035 DenseMap<SetAndBinding, ResourceVarInfo *> set_and_binding_map;
1036 bool first_use = true;
1037 for (auto &U : F.uses()) {
1038 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
1039 const auto set = unsigned(
1040 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
1041 const auto binding = unsigned(
1042 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
1043 const auto arg_kind = clspv::ArgKind(
1044 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
1045 const auto arg_index = unsigned(
1046 dyn_cast<ConstantInt>(call->getArgOperand(3))->getZExtValue());
alan-bakere9308012019-03-15 10:25:13 -04001047 const auto coherent = unsigned(
1048 dyn_cast<ConstantInt>(call->getArgOperand(5))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04001049
1050 // Find or make the resource var info for this combination.
1051 ResourceVarInfo *rv = nullptr;
1052 if (always_distinct_sets) {
1053 // Make a new resource var any time we see a different
1054 // (set,binding) pair.
1055 SetAndBinding key{set, binding};
1056 auto where = set_and_binding_map.find(key);
1057 if (where == set_and_binding_map.end()) {
alan-baker7506abb2020-09-10 15:02:55 -04001058 rv = new ResourceVarInfo(
1059 static_cast<int>(ResourceVarInfoList.size()), set, binding,
1060 &F, arg_kind, coherent);
David Neto862b7d82018-06-14 18:48:37 -04001061 ResourceVarInfoList.emplace_back(rv);
1062 set_and_binding_map[key] = rv;
1063 } else {
1064 rv = where->second;
1065 }
1066 } else {
1067 // The default is to make exactly one resource for each
1068 // clspv.resource.var.* function.
1069 if (first_use) {
1070 first_use = false;
alan-baker7506abb2020-09-10 15:02:55 -04001071 rv = new ResourceVarInfo(
1072 static_cast<int>(ResourceVarInfoList.size()), set, binding,
1073 &F, arg_kind, coherent);
David Neto862b7d82018-06-14 18:48:37 -04001074 ResourceVarInfoList.emplace_back(rv);
1075 } else {
1076 rv = ResourceVarInfoList.back().get();
1077 }
1078 }
1079
1080 // Now populate FunctionToResourceVarsMap.
1081 auto &mapping =
1082 FunctionToResourceVarsMap[call->getParent()->getParent()];
1083 while (mapping.size() <= arg_index) {
1084 mapping.push_back(nullptr);
1085 }
1086 mapping[arg_index] = rv;
1087 }
1088 }
1089 }
1090 }
1091
1092 // Populate ModuleOrderedResourceVars.
SJW77b87ad2020-04-21 14:37:52 -05001093 for (Function &F : *module) {
David Neto862b7d82018-06-14 18:48:37 -04001094 auto where = FunctionToResourceVarsMap.find(&F);
1095 if (where != FunctionToResourceVarsMap.end()) {
1096 for (auto &rv : where->second) {
1097 if (rv != nullptr) {
1098 ModuleOrderedResourceVars.insert(rv);
1099 }
1100 }
1101 }
1102 }
1103 if (ShowResourceVars) {
1104 for (auto *info : ModuleOrderedResourceVars) {
1105 outs() << "MORV index " << info->index << " (" << info->descriptor_set
1106 << "," << info->binding << ") " << *(info->var_fn->getReturnType())
1107 << "\n";
1108 }
1109 }
1110}
1111
SJW77b87ad2020-04-21 14:37:52 -05001112void SPIRVProducerPass::FindTypesForSamplerMap() {
David Neto862b7d82018-06-14 18:48:37 -04001113 // If we are using a sampler map, find the type of the sampler.
SJW77b87ad2020-04-21 14:37:52 -05001114 if (module->getFunction(clspv::LiteralSamplerFunction()) ||
alan-baker3f772c02021-06-15 22:18:11 -04001115 (getSamplerMap() && !getSamplerMap()->empty())) {
James Pricecbe834f2020-12-01 13:42:25 -05001116 auto SamplerStructTy =
1117 StructType::getTypeByName(module->getContext(), "opencl.sampler_t");
David Neto862b7d82018-06-14 18:48:37 -04001118 if (!SamplerStructTy) {
SJW77b87ad2020-04-21 14:37:52 -05001119 SamplerStructTy =
1120 StructType::create(module->getContext(), "opencl.sampler_t");
David Neto862b7d82018-06-14 18:48:37 -04001121 }
David Neto862b7d82018-06-14 18:48:37 -04001122 SamplerTy = SamplerStructTy->getPointerTo(AddressSpace::UniformConstant);
David Neto862b7d82018-06-14 18:48:37 -04001123 }
1124}
1125
SJW77b87ad2020-04-21 14:37:52 -05001126void SPIRVProducerPass::FindTypesForResourceVars() {
David Neto862b7d82018-06-14 18:48:37 -04001127 // Record types so they are generated.
1128 TypesNeedingLayout.reset();
1129 StructTypesNeedingBlock.reset();
1130
David Neto862b7d82018-06-14 18:48:37 -04001131 for (const auto *info : ModuleOrderedResourceVars) {
1132 Type *type = info->var_fn->getReturnType();
1133
1134 switch (info->arg_kind) {
1135 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04001136 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04001137 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1138 StructTypesNeedingBlock.insert(sty);
1139 } else {
1140 errs() << *type << "\n";
1141 llvm_unreachable("Buffer arguments must map to structures!");
1142 }
1143 break;
1144 case clspv::ArgKind::Pod:
alan-baker9b0ec3c2020-04-06 14:45:34 -04001145 case clspv::ArgKind::PodUBO:
1146 case clspv::ArgKind::PodPushConstant:
David Neto862b7d82018-06-14 18:48:37 -04001147 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1148 StructTypesNeedingBlock.insert(sty);
1149 } else {
1150 errs() << *type << "\n";
1151 llvm_unreachable("POD arguments must map to structures!");
1152 }
1153 break;
alan-bakerf6bc8252020-09-23 14:58:55 -04001154 case clspv::ArgKind::SampledImage:
1155 case clspv::ArgKind::StorageImage:
David Neto862b7d82018-06-14 18:48:37 -04001156 case clspv::ArgKind::Sampler:
1157 // Sampler and image types map to the pointee type but
1158 // in the uniform constant address space.
1159 type = PointerType::get(type->getPointerElementType(),
1160 clspv::AddressSpace::UniformConstant);
1161 break;
1162 default:
1163 break;
1164 }
David Neto862b7d82018-06-14 18:48:37 -04001165 }
1166
alan-bakerdcd97412019-09-16 15:32:30 -04001167 // If module constants are clustered in a storage buffer then that struct
1168 // needs layout decorations.
1169 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
SJW77b87ad2020-04-21 14:37:52 -05001170 for (GlobalVariable &GV : module->globals()) {
alan-bakerdcd97412019-09-16 15:32:30 -04001171 PointerType *PTy = cast<PointerType>(GV.getType());
1172 const auto AS = PTy->getAddressSpace();
1173 const bool module_scope_constant_external_init =
1174 (AS == AddressSpace::Constant) && GV.hasInitializer();
1175 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
1176 if (module_scope_constant_external_init &&
1177 spv::BuiltInMax == BuiltinType) {
1178 StructTypesNeedingBlock.insert(
1179 cast<StructType>(PTy->getPointerElementType()));
1180 }
1181 }
1182 }
1183
SJW77b87ad2020-04-21 14:37:52 -05001184 for (const GlobalVariable &GV : module->globals()) {
Kévin Petitbbbda972020-03-03 19:16:31 +00001185 if (GV.getAddressSpace() == clspv::AddressSpace::PushConstant) {
1186 auto Ty = cast<PointerType>(GV.getType())->getPointerElementType();
1187 assert(Ty->isStructTy() && "Push constants have to be structures.");
1188 auto STy = cast<StructType>(Ty);
1189 StructTypesNeedingBlock.insert(STy);
1190 }
1191 }
1192
David Neto862b7d82018-06-14 18:48:37 -04001193 // Traverse the arrays and structures underneath each Block, and
1194 // mark them as needing layout.
1195 std::vector<Type *> work_list(StructTypesNeedingBlock.begin(),
1196 StructTypesNeedingBlock.end());
1197 while (!work_list.empty()) {
1198 Type *type = work_list.back();
1199 work_list.pop_back();
1200 TypesNeedingLayout.insert(type);
1201 switch (type->getTypeID()) {
1202 case Type::ArrayTyID:
1203 work_list.push_back(type->getArrayElementType());
1204 if (!Hack_generate_runtime_array_stride_early) {
1205 // Remember this array type for deferred decoration.
1206 TypesNeedingArrayStride.insert(type);
1207 }
1208 break;
1209 case Type::StructTyID:
1210 for (auto *elem_ty : cast<StructType>(type)->elements()) {
1211 work_list.push_back(elem_ty);
1212 }
1213 default:
1214 // This type and its contained types don't get layout.
1215 break;
1216 }
1217 }
1218}
1219
SJWf93f5f32020-05-05 07:27:56 -05001220void SPIRVProducerPass::GenerateWorkgroupVars() {
Alan Baker202c8c72018-08-13 13:47:44 -04001221 // The SpecId assignment for pointer-to-local arguments is recorded in
1222 // module-level metadata. Translate that information into local argument
1223 // information.
SJWf93f5f32020-05-05 07:27:56 -05001224 LLVMContext &Context = module->getContext();
SJW77b87ad2020-04-21 14:37:52 -05001225 NamedMDNode *nmd = module->getNamedMetadata(clspv::LocalSpecIdMetadataName());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001226 if (!nmd)
1227 return;
Alan Baker202c8c72018-08-13 13:47:44 -04001228 for (auto operand : nmd->operands()) {
1229 MDTuple *tuple = cast<MDTuple>(operand);
1230 ValueAsMetadata *fn_md = cast<ValueAsMetadata>(tuple->getOperand(0));
1231 Function *func = cast<Function>(fn_md->getValue());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001232 ConstantAsMetadata *arg_index_md =
1233 cast<ConstantAsMetadata>(tuple->getOperand(1));
1234 int arg_index = static_cast<int>(
1235 cast<ConstantInt>(arg_index_md->getValue())->getSExtValue());
1236 Argument *arg = &*(func->arg_begin() + arg_index);
Alan Baker202c8c72018-08-13 13:47:44 -04001237
1238 ConstantAsMetadata *spec_id_md =
1239 cast<ConstantAsMetadata>(tuple->getOperand(2));
alan-bakerb6b09dc2018-11-08 16:59:28 -05001240 int spec_id = static_cast<int>(
1241 cast<ConstantInt>(spec_id_md->getValue())->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04001242
Alan Baker202c8c72018-08-13 13:47:44 -04001243 LocalArgSpecIds[arg] = spec_id;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001244 if (LocalSpecIdInfoMap.count(spec_id))
1245 continue;
Alan Baker202c8c72018-08-13 13:47:44 -04001246
SJWf93f5f32020-05-05 07:27:56 -05001247 // Generate the spec constant.
1248 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05001249 Ops << Type::getInt32Ty(Context) << 1;
SJWf93f5f32020-05-05 07:27:56 -05001250 SPIRVID ArraySizeID = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
Alan Baker202c8c72018-08-13 13:47:44 -04001251
SJWf93f5f32020-05-05 07:27:56 -05001252 // Generate the array type.
1253 Type *ElemTy = arg->getType()->getPointerElementType();
1254 Ops.clear();
1255 // The element type must have been created.
SJW01901d92020-05-21 08:58:31 -05001256 Ops << ElemTy << ArraySizeID;
SJWf93f5f32020-05-05 07:27:56 -05001257
1258 SPIRVID ArrayTypeID = addSPIRVInst<kTypes>(spv::OpTypeArray, Ops);
1259
1260 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05001261 Ops << spv::StorageClassWorkgroup << ArrayTypeID;
SJWf93f5f32020-05-05 07:27:56 -05001262 SPIRVID PtrArrayTypeID = addSPIRVInst<kTypes>(spv::OpTypePointer, Ops);
1263
1264 // Generate OpVariable.
1265 //
1266 // Ops[0] : Result Type ID
1267 // Ops[1] : Storage Class
SJW806a5d82020-07-15 12:51:38 -05001268 SPIRVID VariableID =
1269 addSPIRVGlobalVariable(PtrArrayTypeID, spv::StorageClassWorkgroup);
SJWf93f5f32020-05-05 07:27:56 -05001270
1271 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05001272 Ops << ArraySizeID << spv::DecorationSpecId << spec_id;
SJWf93f5f32020-05-05 07:27:56 -05001273 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
1274
1275 LocalArgInfo info{VariableID, ElemTy, ArraySizeID,
1276 ArrayTypeID, PtrArrayTypeID, spec_id};
1277 LocalSpecIdInfoMap[spec_id] = info;
Alan Baker202c8c72018-08-13 13:47:44 -04001278 }
1279}
1280
David Neto22f144c2017-06-12 14:26:21 -04001281spv::StorageClass SPIRVProducerPass::GetStorageClass(unsigned AddrSpace) const {
1282 switch (AddrSpace) {
1283 default:
1284 llvm_unreachable("Unsupported OpenCL address space");
1285 case AddressSpace::Private:
1286 return spv::StorageClassFunction;
1287 case AddressSpace::Global:
David Neto22f144c2017-06-12 14:26:21 -04001288 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001289 case AddressSpace::Constant:
1290 return clspv::Option::ConstantArgsInUniformBuffer()
1291 ? spv::StorageClassUniform
1292 : spv::StorageClassStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -04001293 case AddressSpace::Input:
1294 return spv::StorageClassInput;
1295 case AddressSpace::Local:
1296 return spv::StorageClassWorkgroup;
1297 case AddressSpace::UniformConstant:
1298 return spv::StorageClassUniformConstant;
David Neto9ed8e2f2018-03-24 06:47:24 -07001299 case AddressSpace::Uniform:
David Netoe439d702018-03-23 13:14:08 -07001300 return spv::StorageClassUniform;
David Neto22f144c2017-06-12 14:26:21 -04001301 case AddressSpace::ModuleScopePrivate:
1302 return spv::StorageClassPrivate;
Kévin Petitbbbda972020-03-03 19:16:31 +00001303 case AddressSpace::PushConstant:
1304 return spv::StorageClassPushConstant;
David Neto22f144c2017-06-12 14:26:21 -04001305 }
1306}
1307
David Neto862b7d82018-06-14 18:48:37 -04001308spv::StorageClass
1309SPIRVProducerPass::GetStorageClassForArgKind(clspv::ArgKind arg_kind) const {
1310 switch (arg_kind) {
1311 case clspv::ArgKind::Buffer:
1312 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001313 case clspv::ArgKind::BufferUBO:
1314 return spv::StorageClassUniform;
David Neto862b7d82018-06-14 18:48:37 -04001315 case clspv::ArgKind::Pod:
alan-baker9b0ec3c2020-04-06 14:45:34 -04001316 return spv::StorageClassStorageBuffer;
1317 case clspv::ArgKind::PodUBO:
1318 return spv::StorageClassUniform;
1319 case clspv::ArgKind::PodPushConstant:
1320 return spv::StorageClassPushConstant;
David Neto862b7d82018-06-14 18:48:37 -04001321 case clspv::ArgKind::Local:
1322 return spv::StorageClassWorkgroup;
alan-bakerf6bc8252020-09-23 14:58:55 -04001323 case clspv::ArgKind::SampledImage:
1324 case clspv::ArgKind::StorageImage:
David Neto862b7d82018-06-14 18:48:37 -04001325 case clspv::ArgKind::Sampler:
1326 return spv::StorageClassUniformConstant;
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001327 default:
1328 llvm_unreachable("Unsupported storage class for argument kind");
David Neto862b7d82018-06-14 18:48:37 -04001329 }
1330}
1331
David Neto22f144c2017-06-12 14:26:21 -04001332spv::BuiltIn SPIRVProducerPass::GetBuiltin(StringRef Name) const {
1333 return StringSwitch<spv::BuiltIn>(Name)
1334 .Case("__spirv_GlobalInvocationId", spv::BuiltInGlobalInvocationId)
1335 .Case("__spirv_LocalInvocationId", spv::BuiltInLocalInvocationId)
1336 .Case("__spirv_WorkgroupSize", spv::BuiltInWorkgroupSize)
1337 .Case("__spirv_NumWorkgroups", spv::BuiltInNumWorkgroups)
1338 .Case("__spirv_WorkgroupId", spv::BuiltInWorkgroupId)
alan-bakerbed3a882020-04-21 14:42:41 -04001339 .Case("__spirv_WorkDim", spv::BuiltInWorkDim)
alan-bakere1996972020-05-04 08:38:12 -04001340 .Case("__spirv_GlobalOffset", spv::BuiltInGlobalOffset)
David Neto22f144c2017-06-12 14:26:21 -04001341 .Default(spv::BuiltInMax);
1342}
1343
SJW01901d92020-05-21 08:58:31 -05001344SPIRVID SPIRVProducerPass::getOpExtInstImportID() {
1345 if (OpExtInstImportID == 0) {
1346 //
1347 // Generate OpExtInstImport.
1348 //
1349 // Ops[0] ... Ops[n] = Name (Literal String)
David Neto22f144c2017-06-12 14:26:21 -04001350
SJW01901d92020-05-21 08:58:31 -05001351 OpExtInstImportID =
1352 addSPIRVInst<kImports>(spv::OpExtInstImport, "GLSL.std.450");
1353 }
1354 return OpExtInstImportID;
SJWf93f5f32020-05-05 07:27:56 -05001355}
1356
SJW806a5d82020-07-15 12:51:38 -05001357SPIRVID SPIRVProducerPass::addSPIRVGlobalVariable(const SPIRVID &TypeID,
1358 spv::StorageClass SC,
alan-baker3f772c02021-06-15 22:18:11 -04001359 const SPIRVID &InitID,
1360 bool add_interface) {
SJW806a5d82020-07-15 12:51:38 -05001361 // Generate OpVariable.
1362 //
1363 // Ops[0] : Result Type ID
1364 // Ops[1] : Storage Class
1365 // Ops[2] : Initialization Value ID (optional)
1366
1367 SPIRVOperandVec Ops;
1368 Ops << TypeID << SC;
1369 if (InitID.isValid()) {
1370 Ops << InitID;
1371 }
1372
1373 SPIRVID VID = addSPIRVInst<kGlobalVariables>(spv::OpVariable, Ops);
1374
alan-baker3f772c02021-06-15 22:18:11 -04001375 if (SC == spv::StorageClassInput ||
1376 (add_interface && SpvVersion() >= SPIRVVersion::SPIRV_1_4)) {
SJW806a5d82020-07-15 12:51:38 -05001377 getEntryPointInterfacesList().push_back(VID);
1378 }
1379
1380 return VID;
1381}
1382
alan-bakerc3fd07f2020-10-22 09:48:49 -04001383Type *SPIRVProducerPass::CanonicalType(Type *type) {
1384 if (type->getNumContainedTypes() != 0) {
1385 switch (type->getTypeID()) {
1386 case Type::PointerTyID: {
1387 // For the purposes of our Vulkan SPIR-V type system, constant and global
1388 // are conflated.
1389 auto *ptr_ty = cast<PointerType>(type);
1390 unsigned AddrSpace = ptr_ty->getAddressSpace();
1391 if (AddressSpace::Constant == AddrSpace) {
1392 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1393 AddrSpace = AddressSpace::Global;
1394 // The canonical type of __constant is __global unless constants are
1395 // passed in uniform buffers.
1396 auto *GlobalTy =
1397 ptr_ty->getPointerElementType()->getPointerTo(AddrSpace);
1398 return GlobalTy;
1399 }
1400 }
1401 break;
1402 }
1403 case Type::StructTyID: {
1404 SmallVector<Type *, 8> subtypes;
1405 bool changed = false;
1406 for (auto *subtype : type->subtypes()) {
1407 auto canonical = CanonicalType(subtype);
1408 subtypes.push_back(canonical);
1409 if (canonical != subtype) {
1410 changed = true;
1411 }
1412 }
1413 if (changed) {
1414 return StructType::get(type->getContext(), subtypes,
1415 cast<StructType>(type)->isPacked());
1416 }
1417 break;
1418 }
1419 case Type::ArrayTyID: {
1420 auto *elem_ty = type->getArrayElementType();
1421 auto *equiv_elem_ty = CanonicalType(elem_ty);
1422 if (equiv_elem_ty != elem_ty) {
1423 return ArrayType::get(equiv_elem_ty,
1424 cast<ArrayType>(type)->getNumElements());
1425 }
1426 break;
1427 }
1428 case Type::FunctionTyID: {
1429 auto *func_ty = cast<FunctionType>(type);
1430 auto *return_ty = CanonicalType(func_ty->getReturnType());
1431 SmallVector<Type *, 8> params;
1432 for (unsigned i = 0; i < func_ty->getNumParams(); ++i) {
1433 params.push_back(CanonicalType(func_ty->getParamType(i)));
1434 }
1435 return FunctionType::get(return_ty, params, func_ty->isVarArg());
1436 }
1437 default:
1438 break;
1439 }
1440 }
1441
1442 return type;
1443}
1444
alan-baker3f772c02021-06-15 22:18:11 -04001445bool SPIRVProducerPass::PointerRequiresLayout(unsigned aspace) {
1446 if (Option::SpvVersion() >= SPIRVVersion::SPIRV_1_4) {
1447 switch (aspace) {
1448 case AddressSpace::PushConstant:
Kévin Petit85bcee02021-08-03 18:21:30 +01001449 case AddressSpace::Uniform:
alan-baker3f772c02021-06-15 22:18:11 -04001450 case AddressSpace::Global:
1451 case AddressSpace::Constant:
1452 return true;
1453 default:
1454 break;
1455 }
1456 }
1457 return false;
1458}
1459
SJW01901d92020-05-21 08:58:31 -05001460SPIRVID SPIRVProducerPass::getSPIRVType(Type *Ty) {
alan-baker3f772c02021-06-15 22:18:11 -04001461 // Prior to 1.4, layout decorations are more relaxed so we can reuse a laid
1462 // out type in non-laid out storage classes.
1463 bool needs_layout = false;
1464 if (auto ptr_ty = dyn_cast<PointerType>(Ty)) {
1465 needs_layout = PointerRequiresLayout(ptr_ty->getPointerAddressSpace());
1466 }
1467 return getSPIRVType(Ty, needs_layout);
1468}
1469
1470SPIRVID SPIRVProducerPass::getSPIRVType(Type *Ty, bool needs_layout) {
alan-baker448d8522021-08-10 14:54:36 -04001471 // Only pointers, non-opaque structs and arrays should have layout
1472 // decorations.
alan-baker3f772c02021-06-15 22:18:11 -04001473 if (!(isa<PointerType>(Ty) || isa<ArrayType>(Ty) || isa<StructType>(Ty))) {
1474 needs_layout = false;
alan-baker448d8522021-08-10 14:54:36 -04001475 } else if (auto StructTy = dyn_cast<StructType>(Ty)) {
1476 if (StructTy->isOpaque()) {
1477 needs_layout = false;
1478 }
alan-baker3f772c02021-06-15 22:18:11 -04001479 }
1480 // |layout| is the index used for |Ty|'s entry in the type map. Each type
1481 // stores a laid out and non-laid out version of the type.
1482 const unsigned layout = needs_layout ? 1 : 0;
1483
SJWf93f5f32020-05-05 07:27:56 -05001484 auto TI = TypeMap.find(Ty);
1485 if (TI != TypeMap.end()) {
alan-baker3f772c02021-06-15 22:18:11 -04001486 assert(layout < TI->second.size());
1487 if (TI->second[layout].isValid()) {
1488 return TI->second[layout];
1489 }
SJWf93f5f32020-05-05 07:27:56 -05001490 }
1491
alan-bakerc3fd07f2020-10-22 09:48:49 -04001492 auto Canonical = CanonicalType(Ty);
1493 if (Canonical != Ty) {
1494 auto CanonicalTI = TypeMap.find(Canonical);
1495 if (CanonicalTI != TypeMap.end()) {
alan-baker3f772c02021-06-15 22:18:11 -04001496 assert(layout < CanonicalTI->second.size());
1497 if (CanonicalTI->second[layout].isValid()) {
1498 auto id = CanonicalTI->second[layout];
1499 auto &base = TypeMap[Ty];
1500 if (base.empty()) {
1501 base.resize(2);
1502 }
1503 base[layout] = id;
1504 return id;
1505 }
alan-bakerc3fd07f2020-10-22 09:48:49 -04001506 }
1507 }
1508
1509 // Perform the mapping with the canonical type.
1510
SJWf93f5f32020-05-05 07:27:56 -05001511 const auto &DL = module->getDataLayout();
1512
SJW01901d92020-05-21 08:58:31 -05001513 SPIRVID RID;
SJWf93f5f32020-05-05 07:27:56 -05001514
alan-bakerc3fd07f2020-10-22 09:48:49 -04001515 switch (Canonical->getTypeID()) {
SJWf93f5f32020-05-05 07:27:56 -05001516 default: {
alan-bakerc3fd07f2020-10-22 09:48:49 -04001517 Canonical->print(errs());
SJWf93f5f32020-05-05 07:27:56 -05001518 llvm_unreachable("Unsupported type???");
1519 break;
1520 }
1521 case Type::MetadataTyID:
1522 case Type::LabelTyID: {
1523 // Ignore these types.
1524 break;
1525 }
1526 case Type::PointerTyID: {
alan-bakerc3fd07f2020-10-22 09:48:49 -04001527 PointerType *PTy = cast<PointerType>(Canonical);
SJWf93f5f32020-05-05 07:27:56 -05001528 unsigned AddrSpace = PTy->getAddressSpace();
1529
1530 if (AddrSpace != AddressSpace::UniformConstant) {
1531 auto PointeeTy = PTy->getElementType();
1532 if (PointeeTy->isStructTy() &&
1533 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
alan-baker3f772c02021-06-15 22:18:11 -04001534 RID = getSPIRVType(PointeeTy, needs_layout);
SJWf93f5f32020-05-05 07:27:56 -05001535 break;
1536 }
1537 }
1538
SJWf93f5f32020-05-05 07:27:56 -05001539 //
1540 // Generate OpTypePointer.
1541 //
1542
1543 // OpTypePointer
1544 // Ops[0] = Storage Class
1545 // Ops[1] = Element Type ID
1546 SPIRVOperandVec Ops;
1547
alan-baker3f772c02021-06-15 22:18:11 -04001548 Ops << GetStorageClass(AddrSpace)
1549 << getSPIRVType(PTy->getElementType(), needs_layout);
SJWf93f5f32020-05-05 07:27:56 -05001550
1551 RID = addSPIRVInst<kTypes>(spv::OpTypePointer, Ops);
1552 break;
1553 }
1554 case Type::StructTyID: {
alan-bakerc3fd07f2020-10-22 09:48:49 -04001555 StructType *STy = cast<StructType>(Canonical);
SJWf93f5f32020-05-05 07:27:56 -05001556
1557 // Handle sampler type.
1558 if (STy->isOpaque()) {
1559 if (STy->getName().equals("opencl.sampler_t")) {
1560 //
1561 // Generate OpTypeSampler
1562 //
1563 // Empty Ops.
1564
1565 RID = addSPIRVInst<kTypes>(spv::OpTypeSampler);
1566 break;
1567 } else if (STy->getName().startswith("opencl.image1d_ro_t") ||
alan-bakerf6bc8252020-09-23 14:58:55 -04001568 STy->getName().startswith("opencl.image1d_rw_t") ||
SJWf93f5f32020-05-05 07:27:56 -05001569 STy->getName().startswith("opencl.image1d_wo_t") ||
1570 STy->getName().startswith("opencl.image1d_array_ro_t") ||
alan-bakerf6bc8252020-09-23 14:58:55 -04001571 STy->getName().startswith("opencl.image1d_array_rw_t") ||
SJWf93f5f32020-05-05 07:27:56 -05001572 STy->getName().startswith("opencl.image1d_array_wo_t") ||
1573 STy->getName().startswith("opencl.image2d_ro_t") ||
alan-bakerf6bc8252020-09-23 14:58:55 -04001574 STy->getName().startswith("opencl.image2d_rw_t") ||
SJWf93f5f32020-05-05 07:27:56 -05001575 STy->getName().startswith("opencl.image2d_wo_t") ||
1576 STy->getName().startswith("opencl.image2d_array_ro_t") ||
alan-bakerf6bc8252020-09-23 14:58:55 -04001577 STy->getName().startswith("opencl.image2d_array_rw_t") ||
SJWf93f5f32020-05-05 07:27:56 -05001578 STy->getName().startswith("opencl.image2d_array_wo_t") ||
1579 STy->getName().startswith("opencl.image3d_ro_t") ||
alan-bakerf6bc8252020-09-23 14:58:55 -04001580 STy->getName().startswith("opencl.image3d_rw_t") ||
SJWf93f5f32020-05-05 07:27:56 -05001581 STy->getName().startswith("opencl.image3d_wo_t")) {
SJW01901d92020-05-21 08:58:31 -05001582 if (STy->getName().startswith("opencl.image1d_")) {
1583 if (STy->getName().contains(".sampled"))
1584 addCapability(spv::CapabilitySampled1D);
1585 else
1586 addCapability(spv::CapabilityImage1D);
1587 }
1588
SJWf93f5f32020-05-05 07:27:56 -05001589 //
1590 // Generate OpTypeImage
1591 //
1592 // Ops[0] = Sampled Type ID
1593 // Ops[1] = Dim ID
1594 // Ops[2] = Depth (Literal Number)
1595 // Ops[3] = Arrayed (Literal Number)
1596 // Ops[4] = MS (Literal Number)
1597 // Ops[5] = Sampled (Literal Number)
1598 // Ops[6] = Image Format ID
1599 //
1600 SPIRVOperandVec Ops;
1601
SJW01901d92020-05-21 08:58:31 -05001602 SPIRVID SampledTyID;
alan-baker3f772c02021-06-15 22:18:11 -04001603 // None of the sampled types have a layout.
SJWf93f5f32020-05-05 07:27:56 -05001604 if (STy->getName().contains(".float")) {
alan-baker3f772c02021-06-15 22:18:11 -04001605 SampledTyID =
1606 getSPIRVType(Type::getFloatTy(Canonical->getContext()), false);
SJWf93f5f32020-05-05 07:27:56 -05001607 } else if (STy->getName().contains(".uint")) {
alan-baker3f772c02021-06-15 22:18:11 -04001608 SampledTyID =
1609 getSPIRVType(Type::getInt32Ty(Canonical->getContext()), false);
SJWf93f5f32020-05-05 07:27:56 -05001610 } else if (STy->getName().contains(".int")) {
1611 // Generate a signed 32-bit integer if necessary.
1612 if (int32ID == 0) {
1613 SPIRVOperandVec intOps;
SJW01901d92020-05-21 08:58:31 -05001614 intOps << 32 << 1;
SJWf93f5f32020-05-05 07:27:56 -05001615 int32ID = addSPIRVInst<kTypes>(spv::OpTypeInt, intOps);
1616 }
1617 SampledTyID = int32ID;
1618
1619 // Generate a vec4 of the signed int if necessary.
1620 if (v4int32ID == 0) {
1621 SPIRVOperandVec vecOps;
SJW01901d92020-05-21 08:58:31 -05001622 vecOps << int32ID << 4;
SJWf93f5f32020-05-05 07:27:56 -05001623 v4int32ID = addSPIRVInst<kTypes>(spv::OpTypeVector, vecOps);
1624 }
1625 } else {
1626 // This was likely an UndefValue.
alan-baker3f772c02021-06-15 22:18:11 -04001627 SampledTyID =
1628 getSPIRVType(Type::getFloatTy(Canonical->getContext()), false);
SJWf93f5f32020-05-05 07:27:56 -05001629 }
SJW01901d92020-05-21 08:58:31 -05001630 Ops << SampledTyID;
SJWf93f5f32020-05-05 07:27:56 -05001631
1632 spv::Dim DimID = spv::Dim2D;
1633 if (STy->getName().startswith("opencl.image1d_ro_t") ||
alan-bakerf6bc8252020-09-23 14:58:55 -04001634 STy->getName().startswith("opencl.image1d_rw_t") ||
SJWf93f5f32020-05-05 07:27:56 -05001635 STy->getName().startswith("opencl.image1d_wo_t") ||
1636 STy->getName().startswith("opencl.image1d_array_ro_t") ||
alan-bakerf6bc8252020-09-23 14:58:55 -04001637 STy->getName().startswith("opencl.image1d_array_rw_t") ||
SJWf93f5f32020-05-05 07:27:56 -05001638 STy->getName().startswith("opencl.image1d_array_wo_t")) {
1639 DimID = spv::Dim1D;
1640 } else if (STy->getName().startswith("opencl.image3d_ro_t") ||
alan-bakerf6bc8252020-09-23 14:58:55 -04001641 STy->getName().startswith("opencl.image3d_rw_t") ||
SJWf93f5f32020-05-05 07:27:56 -05001642 STy->getName().startswith("opencl.image3d_wo_t")) {
1643 DimID = spv::Dim3D;
1644 }
SJW01901d92020-05-21 08:58:31 -05001645 Ops << DimID;
SJWf93f5f32020-05-05 07:27:56 -05001646
1647 // TODO: Set up Depth.
SJW01901d92020-05-21 08:58:31 -05001648 Ops << 0;
SJWf93f5f32020-05-05 07:27:56 -05001649
1650 uint32_t arrayed = STy->getName().contains("_array_") ? 1 : 0;
SJW01901d92020-05-21 08:58:31 -05001651 Ops << arrayed;
SJWf93f5f32020-05-05 07:27:56 -05001652
1653 // TODO: Set up MS.
SJW01901d92020-05-21 08:58:31 -05001654 Ops << 0;
SJWf93f5f32020-05-05 07:27:56 -05001655
1656 // Set up Sampled.
1657 //
1658 // From Spec
1659 //
1660 // 0 indicates this is only known at run time, not at compile time
1661 // 1 indicates will be used with sampler
1662 // 2 indicates will be used without a sampler (a storage image)
1663 uint32_t Sampled = 1;
1664 if (!STy->getName().contains(".sampled")) {
1665 Sampled = 2;
1666 }
SJW01901d92020-05-21 08:58:31 -05001667 Ops << Sampled;
SJWf93f5f32020-05-05 07:27:56 -05001668
1669 // TODO: Set up Image Format.
SJW01901d92020-05-21 08:58:31 -05001670 Ops << spv::ImageFormatUnknown;
SJWf93f5f32020-05-05 07:27:56 -05001671 RID = addSPIRVInst<kTypes>(spv::OpTypeImage, Ops);
1672
alan-bakerf6bc8252020-09-23 14:58:55 -04001673 // Only need a sampled version of the type if it is used with a sampler.
1674 if (Sampled == 1) {
1675 Ops.clear();
1676 Ops << RID;
alan-bakerc3fd07f2020-10-22 09:48:49 -04001677 getImageTypeMap()[Canonical] =
alan-bakerf6bc8252020-09-23 14:58:55 -04001678 addSPIRVInst<kTypes>(spv::OpTypeSampledImage, Ops);
1679 }
SJWf93f5f32020-05-05 07:27:56 -05001680 break;
1681 }
1682 }
1683
1684 //
1685 // Generate OpTypeStruct
1686 //
1687 // Ops[0] ... Ops[n] = Member IDs
1688 SPIRVOperandVec Ops;
1689
1690 for (auto *EleTy : STy->elements()) {
alan-baker3f772c02021-06-15 22:18:11 -04001691 Ops << getSPIRVType(EleTy, needs_layout);
SJWf93f5f32020-05-05 07:27:56 -05001692 }
1693
1694 RID = addSPIRVInst<kTypes>(spv::OpTypeStruct, Ops);
1695
alan-bakerc3fd07f2020-10-22 09:48:49 -04001696 // Generate OpMemberDecorate unless we are generating it for the canonical
1697 // type.
1698 StructType *canonical = cast<StructType>(CanonicalType(STy));
alan-baker3f772c02021-06-15 22:18:11 -04001699 bool use_layout =
1700 (Option::SpvVersion() < SPIRVVersion::SPIRV_1_4) || needs_layout;
alan-bakerc3fd07f2020-10-22 09:48:49 -04001701 if (TypesNeedingLayout.idFor(STy) &&
alan-baker3f772c02021-06-15 22:18:11 -04001702 (canonical == STy || !TypesNeedingLayout.idFor(canonical)) &&
1703 use_layout) {
SJWf93f5f32020-05-05 07:27:56 -05001704 for (unsigned MemberIdx = 0; MemberIdx < STy->getNumElements();
1705 MemberIdx++) {
1706 // Ops[0] = Structure Type ID
1707 // Ops[1] = Member Index(Literal Number)
1708 // Ops[2] = Decoration (Offset)
1709 // Ops[3] = Byte Offset (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05001710 const auto ByteOffset =
1711 GetExplicitLayoutStructMemberOffset(STy, MemberIdx, DL);
1712
SJW01901d92020-05-21 08:58:31 -05001713 Ops.clear();
1714 Ops << RID << MemberIdx << spv::DecorationOffset << ByteOffset;
SJWf93f5f32020-05-05 07:27:56 -05001715
1716 addSPIRVInst<kAnnotations>(spv::OpMemberDecorate, Ops);
1717 }
1718 }
1719
alan-bakerc3fd07f2020-10-22 09:48:49 -04001720 // Generate OpDecorate unless we are generating it for the canonical type.
1721 if (StructTypesNeedingBlock.idFor(STy) &&
alan-baker3f772c02021-06-15 22:18:11 -04001722 (canonical == STy || !StructTypesNeedingBlock.idFor(canonical)) &&
1723 use_layout) {
SJWf93f5f32020-05-05 07:27:56 -05001724 Ops.clear();
1725 // Use Block decorations with StorageBuffer storage class.
SJW01901d92020-05-21 08:58:31 -05001726 Ops << RID << spv::DecorationBlock;
SJWf93f5f32020-05-05 07:27:56 -05001727
1728 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
1729 }
1730 break;
1731 }
1732 case Type::IntegerTyID: {
alan-bakerc3fd07f2020-10-22 09:48:49 -04001733 uint32_t bit_width =
1734 static_cast<uint32_t>(Canonical->getPrimitiveSizeInBits());
SJWf93f5f32020-05-05 07:27:56 -05001735
alan-bakere2a62752020-07-09 22:53:23 -04001736 if (clspv::Option::Int8Support() && bit_width == 8) {
SJW01901d92020-05-21 08:58:31 -05001737 addCapability(spv::CapabilityInt8);
alan-bakere2a62752020-07-09 22:53:23 -04001738 } else if (bit_width == 16) {
SJW01901d92020-05-21 08:58:31 -05001739 addCapability(spv::CapabilityInt16);
alan-bakere2a62752020-07-09 22:53:23 -04001740 } else if (bit_width == 64) {
SJW01901d92020-05-21 08:58:31 -05001741 addCapability(spv::CapabilityInt64);
1742 }
1743
alan-bakere2a62752020-07-09 22:53:23 -04001744 if (bit_width == 1) {
SJWf93f5f32020-05-05 07:27:56 -05001745 RID = addSPIRVInst<kTypes>(spv::OpTypeBool);
1746 } else {
alan-bakere2a62752020-07-09 22:53:23 -04001747 if (!clspv::Option::Int8Support() && bit_width == 8) {
SJWf93f5f32020-05-05 07:27:56 -05001748 // i8 is added to TypeMap as i32.
alan-baker3f772c02021-06-15 22:18:11 -04001749 RID = getSPIRVType(Type::getIntNTy(Canonical->getContext(), 32), false);
SJWf93f5f32020-05-05 07:27:56 -05001750 } else {
1751 SPIRVOperandVec Ops;
alan-bakere2a62752020-07-09 22:53:23 -04001752 Ops << bit_width << 0 /* not signed */;
SJWf93f5f32020-05-05 07:27:56 -05001753 RID = addSPIRVInst<kTypes>(spv::OpTypeInt, Ops);
1754 }
1755 }
1756 break;
1757 }
1758 case Type::HalfTyID:
1759 case Type::FloatTyID:
1760 case Type::DoubleTyID: {
alan-bakerc3fd07f2020-10-22 09:48:49 -04001761 uint32_t bit_width =
1762 static_cast<uint32_t>(Canonical->getPrimitiveSizeInBits());
alan-bakere2a62752020-07-09 22:53:23 -04001763 if (bit_width == 16) {
SJW01901d92020-05-21 08:58:31 -05001764 addCapability(spv::CapabilityFloat16);
alan-bakere2a62752020-07-09 22:53:23 -04001765 } else if (bit_width == 64) {
SJW01901d92020-05-21 08:58:31 -05001766 addCapability(spv::CapabilityFloat64);
1767 }
1768
SJWf93f5f32020-05-05 07:27:56 -05001769 SPIRVOperandVec Ops;
alan-bakere2a62752020-07-09 22:53:23 -04001770 Ops << bit_width;
SJWf93f5f32020-05-05 07:27:56 -05001771
1772 RID = addSPIRVInst<kTypes>(spv::OpTypeFloat, Ops);
1773 break;
1774 }
1775 case Type::ArrayTyID: {
alan-bakerc3fd07f2020-10-22 09:48:49 -04001776 ArrayType *ArrTy = cast<ArrayType>(Canonical);
SJWf93f5f32020-05-05 07:27:56 -05001777 const uint64_t Length = ArrTy->getArrayNumElements();
1778 if (Length == 0) {
1779 // By convention, map it to a RuntimeArray.
1780
1781 Type *EleTy = ArrTy->getArrayElementType();
1782
1783 //
1784 // Generate OpTypeRuntimeArray.
1785 //
1786 // OpTypeRuntimeArray
1787 // Ops[0] = Element Type ID
1788 SPIRVOperandVec Ops;
alan-baker3f772c02021-06-15 22:18:11 -04001789 Ops << getSPIRVType(EleTy, needs_layout);
SJWf93f5f32020-05-05 07:27:56 -05001790
1791 RID = addSPIRVInst<kTypes>(spv::OpTypeRuntimeArray, Ops);
1792
alan-baker3f772c02021-06-15 22:18:11 -04001793 if (Hack_generate_runtime_array_stride_early &&
1794 (Option::SpvVersion() < SPIRVVersion::SPIRV_1_4 || needs_layout)) {
SJWf93f5f32020-05-05 07:27:56 -05001795 // Generate OpDecorate.
1796
1797 // Ops[0] = Target ID
1798 // Ops[1] = Decoration (ArrayStride)
1799 // Ops[2] = Stride Number(Literal Number)
1800 Ops.clear();
1801
SJW01901d92020-05-21 08:58:31 -05001802 Ops << RID << spv::DecorationArrayStride
1803 << static_cast<uint32_t>(GetTypeAllocSize(EleTy, DL));
SJWf93f5f32020-05-05 07:27:56 -05001804
1805 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
1806 }
1807
1808 } else {
1809
1810 //
1811 // Generate OpConstant and OpTypeArray.
1812 //
1813
1814 //
1815 // Generate OpConstant for array length.
1816 //
1817 // Add constant for length to constant list.
1818 Constant *CstLength =
1819 ConstantInt::get(Type::getInt32Ty(module->getContext()), Length);
SJWf93f5f32020-05-05 07:27:56 -05001820
1821 // Remember to generate ArrayStride later
alan-bakerc3fd07f2020-10-22 09:48:49 -04001822 getTypesNeedingArrayStride().insert(Canonical);
SJWf93f5f32020-05-05 07:27:56 -05001823
1824 //
1825 // Generate OpTypeArray.
1826 //
1827 // Ops[0] = Element Type ID
1828 // Ops[1] = Array Length Constant ID
1829 SPIRVOperandVec Ops;
1830
alan-baker3f772c02021-06-15 22:18:11 -04001831 Ops << getSPIRVType(ArrTy->getElementType(), needs_layout) << CstLength;
SJWf93f5f32020-05-05 07:27:56 -05001832
1833 RID = addSPIRVInst<kTypes>(spv::OpTypeArray, Ops);
1834 }
1835 break;
1836 }
1837 case Type::FixedVectorTyID: {
alan-bakerc3fd07f2020-10-22 09:48:49 -04001838 auto VecTy = cast<VectorType>(Canonical);
SJWf93f5f32020-05-05 07:27:56 -05001839 // <4 x i8> is changed to i32 if i8 is not generally supported.
1840 if (!clspv::Option::Int8Support() &&
1841 VecTy->getElementType() == Type::getInt8Ty(module->getContext())) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001842 if (VecTy->getElementCount().getKnownMinValue() == 4) {
SJWf93f5f32020-05-05 07:27:56 -05001843 RID = getSPIRVType(VecTy->getElementType());
1844 break;
1845 } else {
alan-bakerc3fd07f2020-10-22 09:48:49 -04001846 Canonical->print(errs());
SJWf93f5f32020-05-05 07:27:56 -05001847 llvm_unreachable("Support above i8 vector type");
1848 }
1849 }
1850
1851 // Ops[0] = Component Type ID
1852 // Ops[1] = Component Count (Literal Number)
1853 SPIRVOperandVec Ops;
alan-baker5a8c3be2020-09-09 13:44:26 -04001854 Ops << VecTy->getElementType()
1855 << VecTy->getElementCount().getKnownMinValue();
SJWf93f5f32020-05-05 07:27:56 -05001856
1857 RID = addSPIRVInst<kTypes>(spv::OpTypeVector, Ops);
1858 break;
1859 }
1860 case Type::VoidTyID: {
1861 RID = addSPIRVInst<kTypes>(spv::OpTypeVoid);
1862 break;
1863 }
1864 case Type::FunctionTyID: {
1865 // Generate SPIRV instruction for function type.
alan-bakerc3fd07f2020-10-22 09:48:49 -04001866 FunctionType *FTy = cast<FunctionType>(Canonical);
SJWf93f5f32020-05-05 07:27:56 -05001867
1868 // Ops[0] = Return Type ID
1869 // Ops[1] ... Ops[n] = Parameter Type IDs
1870 SPIRVOperandVec Ops;
1871
1872 // Find SPIRV instruction for return type
SJW01901d92020-05-21 08:58:31 -05001873 Ops << FTy->getReturnType();
SJWf93f5f32020-05-05 07:27:56 -05001874
1875 // Find SPIRV instructions for parameter types
1876 for (unsigned k = 0; k < FTy->getNumParams(); k++) {
1877 // Find SPIRV instruction for parameter type.
1878 auto ParamTy = FTy->getParamType(k);
1879 if (ParamTy->isPointerTy()) {
1880 auto PointeeTy = ParamTy->getPointerElementType();
1881 if (PointeeTy->isStructTy() &&
1882 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1883 ParamTy = PointeeTy;
1884 }
1885 }
1886
Kévin Petit85bcee02021-08-03 18:21:30 +01001887 Ops << getSPIRVType(ParamTy);
SJWf93f5f32020-05-05 07:27:56 -05001888 }
1889
1890 RID = addSPIRVInst<kTypes>(spv::OpTypeFunction, Ops);
1891 break;
1892 }
1893 }
1894
SJW01901d92020-05-21 08:58:31 -05001895 if (RID.isValid()) {
alan-baker3f772c02021-06-15 22:18:11 -04001896 auto &entry = TypeMap[Canonical];
1897 if (entry.empty()) {
1898 entry.resize(2);
1899 }
1900 entry[layout] = RID;
1901
1902 if (Canonical != Ty) {
1903 // Also cache the original type.
1904 auto &base_entry = TypeMap[Ty];
1905 if (base_entry.empty()) {
1906 base_entry.resize(2);
1907 }
1908 base_entry[layout] = RID;
alan-bakerc3fd07f2020-10-22 09:48:49 -04001909 }
SJWf93f5f32020-05-05 07:27:56 -05001910 }
1911 return RID;
David Neto22f144c2017-06-12 14:26:21 -04001912}
1913
SJW806a5d82020-07-15 12:51:38 -05001914SPIRVID SPIRVProducerPass::getSPIRVInt32Constant(uint32_t CstVal) {
1915 Type *i32 = Type::getInt32Ty(module->getContext());
1916 Constant *Cst = ConstantInt::get(i32, CstVal);
1917 return getSPIRVValue(Cst);
1918}
1919
alan-baker1b333b62021-05-31 14:55:32 -04001920SPIRVID SPIRVProducerPass::getSPIRVConstant(Constant *C) {
David Neto22f144c2017-06-12 14:26:21 -04001921 ValueMapType &VMap = getValueMap();
David Neto482550a2018-03-24 05:21:07 -07001922 const bool hack_undef = clspv::Option::HackUndef();
David Neto22f144c2017-06-12 14:26:21 -04001923
alan-baker1b333b62021-05-31 14:55:32 -04001924 // Treat poison as an undef.
1925 auto *Cst = C;
1926 if (isa<PoisonValue>(Cst)) {
1927 Cst = UndefValue::get(Cst->getType());
1928 }
1929
1930 auto VI = VMap.find(Cst);
1931 if (VI != VMap.end()) {
1932 assert(VI->second.isValid());
1933 return VI->second;
1934 }
1935
SJW01901d92020-05-21 08:58:31 -05001936 SPIRVID RID;
David Neto22f144c2017-06-12 14:26:21 -04001937
SJWf93f5f32020-05-05 07:27:56 -05001938 //
1939 // Generate OpConstant.
1940 //
1941 // Ops[0] = Result Type ID
1942 // Ops[1] .. Ops[n] = Values LiteralNumber
1943 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04001944
SJW01901d92020-05-21 08:58:31 -05001945 Ops << Cst->getType();
David Neto22f144c2017-06-12 14:26:21 -04001946
SJWf93f5f32020-05-05 07:27:56 -05001947 std::vector<uint32_t> LiteralNum;
1948 spv::Op Opcode = spv::OpNop;
David Neto22f144c2017-06-12 14:26:21 -04001949
SJWf93f5f32020-05-05 07:27:56 -05001950 if (isa<UndefValue>(Cst)) {
David Neto22f144c2017-06-12 14:26:21 -04001951 // Ops[0] = Result Type ID
SJWf93f5f32020-05-05 07:27:56 -05001952 Opcode = spv::OpUndef;
1953 if (hack_undef && IsTypeNullable(Cst->getType())) {
1954 Opcode = spv::OpConstantNull;
1955 }
1956 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(Cst)) {
alan-bakere2a62752020-07-09 22:53:23 -04001957 unsigned bit_width = CI->getBitWidth();
1958 if (bit_width == 1) {
SJWf93f5f32020-05-05 07:27:56 -05001959 // If the bitwidth of constant is 1, generate OpConstantTrue or
1960 // OpConstantFalse.
1961 if (CI->getZExtValue()) {
1962 // Ops[0] = Result Type ID
1963 Opcode = spv::OpConstantTrue;
David Neto22f144c2017-06-12 14:26:21 -04001964 } else {
SJWf93f5f32020-05-05 07:27:56 -05001965 // Ops[0] = Result Type ID
1966 Opcode = spv::OpConstantFalse;
David Neto22f144c2017-06-12 14:26:21 -04001967 }
SJWf93f5f32020-05-05 07:27:56 -05001968 } else {
1969 auto V = CI->getZExtValue();
1970 LiteralNum.push_back(V & 0xFFFFFFFF);
1971
alan-bakere2a62752020-07-09 22:53:23 -04001972 if (bit_width > 32) {
SJWf93f5f32020-05-05 07:27:56 -05001973 LiteralNum.push_back(V >> 32);
David Neto22f144c2017-06-12 14:26:21 -04001974 }
1975
1976 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04001977
SJW01901d92020-05-21 08:58:31 -05001978 Ops << LiteralNum;
SJWf93f5f32020-05-05 07:27:56 -05001979 }
1980 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Cst)) {
1981 uint64_t FPVal = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1982 Type *CFPTy = CFP->getType();
1983 if (CFPTy->isFloatTy()) {
1984 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
1985 } else if (CFPTy->isDoubleTy()) {
1986 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
1987 LiteralNum.push_back(FPVal >> 32);
1988 } else if (CFPTy->isHalfTy()) {
1989 LiteralNum.push_back(FPVal & 0xFFFF);
1990 } else {
1991 CFPTy->print(errs());
1992 llvm_unreachable("Implement this ConstantFP Type");
1993 }
David Neto22f144c2017-06-12 14:26:21 -04001994
SJWf93f5f32020-05-05 07:27:56 -05001995 Opcode = spv::OpConstant;
David Neto49351ac2017-08-26 17:32:20 -04001996
SJW01901d92020-05-21 08:58:31 -05001997 Ops << LiteralNum;
SJWf93f5f32020-05-05 07:27:56 -05001998 } else if (isa<ConstantDataSequential>(Cst) &&
1999 cast<ConstantDataSequential>(Cst)->isString()) {
2000 Cst->print(errs());
2001 llvm_unreachable("Implement this Constant");
David Neto49351ac2017-08-26 17:32:20 -04002002
SJWf93f5f32020-05-05 07:27:56 -05002003 } else if (const ConstantDataSequential *CDS =
2004 dyn_cast<ConstantDataSequential>(Cst)) {
2005 // Let's convert <4 x i8> constant to int constant specially.
2006 // This case occurs when all the values are specified as constant
2007 // ints.
2008 Type *CstTy = Cst->getType();
2009 if (is4xi8vec(CstTy)) {
SJWf93f5f32020-05-05 07:27:56 -05002010 //
2011 // Generate OpConstant with OpTypeInt 32 0.
2012 //
2013 uint32_t IntValue = 0;
2014 for (unsigned k = 0; k < 4; k++) {
2015 const uint64_t Val = CDS->getElementAsInteger(k);
2016 IntValue = (IntValue << 8) | (Val & 0xffu);
David Neto49351ac2017-08-26 17:32:20 -04002017 }
2018
SJW806a5d82020-07-15 12:51:38 -05002019 RID = getSPIRVInt32Constant(IntValue);
SJWf93f5f32020-05-05 07:27:56 -05002020 } else {
2021
David Neto49351ac2017-08-26 17:32:20 -04002022 // A normal constant-data-sequential case.
David Neto22f144c2017-06-12 14:26:21 -04002023 for (unsigned k = 0; k < CDS->getNumElements(); k++) {
SJW01901d92020-05-21 08:58:31 -05002024 Ops << CDS->getElementAsConstant(k);
David Neto22f144c2017-06-12 14:26:21 -04002025 }
2026
2027 Opcode = spv::OpConstantComposite;
SJWf93f5f32020-05-05 07:27:56 -05002028 }
2029 } else if (const ConstantAggregate *CA = dyn_cast<ConstantAggregate>(Cst)) {
2030 // Let's convert <4 x i8> constant to int constant specially.
2031 // This case occurs when at least one of the values is an undef.
2032 Type *CstTy = Cst->getType();
2033 if (is4xi8vec(CstTy)) {
SJWf93f5f32020-05-05 07:27:56 -05002034 //
2035 // Generate OpConstant with OpTypeInt 32 0.
2036 //
2037 uint32_t IntValue = 0;
2038 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end();
2039 I != E; ++I) {
2040 uint64_t Val = 0;
2041 const Value *CV = *I;
2042 if (auto *CI2 = dyn_cast<ConstantInt>(CV)) {
2043 Val = CI2->getZExtValue();
David Neto22f144c2017-06-12 14:26:21 -04002044 }
SJWf93f5f32020-05-05 07:27:56 -05002045 IntValue = (IntValue << 8) | (Val & 0xffu);
David Neto22f144c2017-06-12 14:26:21 -04002046 }
2047
SJW806a5d82020-07-15 12:51:38 -05002048 RID = getSPIRVInt32Constant(IntValue);
SJWf93f5f32020-05-05 07:27:56 -05002049 } else {
2050
David Neto22f144c2017-06-12 14:26:21 -04002051 // We use a constant composite in SPIR-V for our constant aggregate in
2052 // LLVM.
2053 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002054
2055 for (unsigned k = 0; k < CA->getNumOperands(); k++) {
David Neto22f144c2017-06-12 14:26:21 -04002056 // And add an operand to the composite we are constructing
SJW01901d92020-05-21 08:58:31 -05002057 Ops << CA->getAggregateElement(k);
David Neto22f144c2017-06-12 14:26:21 -04002058 }
David Neto22f144c2017-06-12 14:26:21 -04002059 }
SJWf93f5f32020-05-05 07:27:56 -05002060 } else if (Cst->isNullValue()) {
2061 Opcode = spv::OpConstantNull;
2062 } else {
2063 Cst->print(errs());
2064 llvm_unreachable("Unsupported Constant???");
2065 }
David Neto22f144c2017-06-12 14:26:21 -04002066
SJWf93f5f32020-05-05 07:27:56 -05002067 if (Opcode == spv::OpConstantNull && Cst->getType()->isPointerTy()) {
2068 // Null pointer requires variable pointers.
2069 setVariablePointersCapabilities(Cst->getType()->getPointerAddressSpace());
2070 }
alan-baker5b86ed72019-02-15 08:26:50 -05002071
SJWf93f5f32020-05-05 07:27:56 -05002072 if (RID == 0) {
2073 RID = addSPIRVInst<kConstants>(Opcode, Ops);
2074 }
2075
2076 VMap[Cst] = RID;
2077
2078 return RID;
2079}
2080
2081SPIRVID SPIRVProducerPass::getSPIRVValue(Value *V) {
2082 auto II = ValueMap.find(V);
2083 if (II != ValueMap.end()) {
SJW01901d92020-05-21 08:58:31 -05002084 assert(II->second.isValid());
SJWf93f5f32020-05-05 07:27:56 -05002085 return II->second;
2086 }
2087 if (Constant *Cst = dyn_cast<Constant>(V)) {
2088 return getSPIRVConstant(Cst);
2089 } else {
2090 llvm_unreachable("Variable not found");
2091 }
2092}
2093
SJW77b87ad2020-04-21 14:37:52 -05002094void SPIRVProducerPass::GenerateSamplers() {
alan-baker09cb9802019-12-10 13:16:27 -05002095 SamplerLiteralToIDMap.clear();
David Neto862b7d82018-06-14 18:48:37 -04002096 DenseMap<unsigned, unsigned> SamplerLiteralToDescriptorSetMap;
2097 DenseMap<unsigned, unsigned> SamplerLiteralToBindingMap;
David Neto22f144c2017-06-12 14:26:21 -04002098
David Neto862b7d82018-06-14 18:48:37 -04002099 // We might have samplers in the sampler map that are not used
2100 // in the translation unit. We need to allocate variables
2101 // for them and bindings too.
2102 DenseSet<unsigned> used_bindings;
David Neto22f144c2017-06-12 14:26:21 -04002103
SJW77b87ad2020-04-21 14:37:52 -05002104 auto *var_fn = module->getFunction(clspv::LiteralSamplerFunction());
alan-baker09cb9802019-12-10 13:16:27 -05002105 // Return if there are no literal samplers.
alan-bakerb6b09dc2018-11-08 16:59:28 -05002106 if (!var_fn)
2107 return;
alan-baker09cb9802019-12-10 13:16:27 -05002108
David Neto862b7d82018-06-14 18:48:37 -04002109 for (auto user : var_fn->users()) {
2110 // Populate SamplerLiteralToDescriptorSetMap and
2111 // SamplerLiteralToBindingMap.
2112 //
2113 // Look for calls like
2114 // call %opencl.sampler_t addrspace(2)*
2115 // @clspv.sampler.var.literal(
2116 // i32 descriptor,
2117 // i32 binding,
alan-baker09cb9802019-12-10 13:16:27 -05002118 // i32 (index-into-sampler-map|sampler_mask))
alan-bakerb6b09dc2018-11-08 16:59:28 -05002119 if (auto *call = dyn_cast<CallInst>(user)) {
alan-baker09cb9802019-12-10 13:16:27 -05002120 const auto third_param = static_cast<unsigned>(
alan-bakerb6b09dc2018-11-08 16:59:28 -05002121 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
alan-baker09cb9802019-12-10 13:16:27 -05002122 auto sampler_value = third_param;
2123 if (clspv::Option::UseSamplerMap()) {
alan-baker3f772c02021-06-15 22:18:11 -04002124 auto &sampler_map = *getSamplerMap();
alan-baker09cb9802019-12-10 13:16:27 -05002125 if (third_param >= sampler_map.size()) {
2126 errs() << "Out of bounds index to sampler map: " << third_param;
2127 llvm_unreachable("bad sampler init: out of bounds");
2128 }
2129 sampler_value = sampler_map[third_param].first;
David Neto862b7d82018-06-14 18:48:37 -04002130 }
2131
David Neto862b7d82018-06-14 18:48:37 -04002132 const auto descriptor_set = static_cast<unsigned>(
2133 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
2134 const auto binding = static_cast<unsigned>(
2135 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
2136
2137 SamplerLiteralToDescriptorSetMap[sampler_value] = descriptor_set;
2138 SamplerLiteralToBindingMap[sampler_value] = binding;
2139 used_bindings.insert(binding);
2140 }
2141 }
2142
alan-baker09cb9802019-12-10 13:16:27 -05002143 DenseSet<size_t> seen;
2144 for (auto user : var_fn->users()) {
2145 if (!isa<CallInst>(user))
2146 continue;
2147
2148 auto call = cast<CallInst>(user);
2149 const unsigned third_param = static_cast<unsigned>(
2150 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
2151
2152 // Already allocated a variable for this value.
2153 if (!seen.insert(third_param).second)
2154 continue;
2155
2156 auto sampler_value = third_param;
2157 if (clspv::Option::UseSamplerMap()) {
alan-baker3f772c02021-06-15 22:18:11 -04002158 sampler_value = (*getSamplerMap())[third_param].first;
alan-baker09cb9802019-12-10 13:16:27 -05002159 }
2160
alan-baker448d8522021-08-10 14:54:36 -04002161 // Add literal samplers to each entry point interface as an
2162 // over-approximation.
SJW806a5d82020-07-15 12:51:38 -05002163 auto sampler_var_id = addSPIRVGlobalVariable(
alan-baker448d8522021-08-10 14:54:36 -04002164 getSPIRVType(SamplerTy), spv::StorageClassUniformConstant,
2165 /* InitId = */ SPIRVID(0), /* add_interface = */ true);
David Neto22f144c2017-06-12 14:26:21 -04002166
alan-baker09cb9802019-12-10 13:16:27 -05002167 SamplerLiteralToIDMap[sampler_value] = sampler_var_id;
David Neto22f144c2017-06-12 14:26:21 -04002168
David Neto862b7d82018-06-14 18:48:37 -04002169 unsigned descriptor_set;
2170 unsigned binding;
alan-baker09cb9802019-12-10 13:16:27 -05002171 if (SamplerLiteralToBindingMap.find(sampler_value) ==
alan-bakerb6b09dc2018-11-08 16:59:28 -05002172 SamplerLiteralToBindingMap.end()) {
David Neto862b7d82018-06-14 18:48:37 -04002173 // This sampler is not actually used. Find the next one.
alan-baker7506abb2020-09-10 15:02:55 -04002174 for (binding = 0; used_bindings.count(binding); binding++) {
2175 }
David Neto862b7d82018-06-14 18:48:37 -04002176 descriptor_set = 0; // Literal samplers always use descriptor set 0.
2177 used_bindings.insert(binding);
2178 } else {
alan-baker09cb9802019-12-10 13:16:27 -05002179 descriptor_set = SamplerLiteralToDescriptorSetMap[sampler_value];
2180 binding = SamplerLiteralToBindingMap[sampler_value];
alan-bakercff80152019-06-15 00:38:00 -04002181
alan-baker86ce19c2020-08-05 13:09:19 -04002182 auto import_id = getReflectionImport();
2183 SPIRVOperandVec Ops;
2184 Ops << getSPIRVType(Type::getVoidTy(module->getContext())) << import_id
2185 << reflection::ExtInstLiteralSampler
2186 << getSPIRVInt32Constant(descriptor_set)
2187 << getSPIRVInt32Constant(binding)
2188 << getSPIRVInt32Constant(sampler_value);
2189 addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
David Neto862b7d82018-06-14 18:48:37 -04002190 }
2191
SJW69939d52020-04-16 07:29:07 -05002192 // Ops[0] = Target ID
2193 // Ops[1] = Decoration (DescriptorSet)
2194 // Ops[2] = LiteralNumber according to Decoration
SJW806a5d82020-07-15 12:51:38 -05002195 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05002196 Ops << sampler_var_id << spv::DecorationDescriptorSet << descriptor_set;
David Neto22f144c2017-06-12 14:26:21 -04002197
SJWf93f5f32020-05-05 07:27:56 -05002198 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002199
2200 // Ops[0] = Target ID
2201 // Ops[1] = Decoration (Binding)
2202 // Ops[2] = LiteralNumber according to Decoration
2203 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002204 Ops << sampler_var_id << spv::DecorationBinding << binding;
David Neto22f144c2017-06-12 14:26:21 -04002205
SJWf93f5f32020-05-05 07:27:56 -05002206 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002207 }
David Neto862b7d82018-06-14 18:48:37 -04002208}
David Neto22f144c2017-06-12 14:26:21 -04002209
SJW77b87ad2020-04-21 14:37:52 -05002210void SPIRVProducerPass::GenerateResourceVars() {
David Neto862b7d82018-06-14 18:48:37 -04002211 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04002212
David Neto862b7d82018-06-14 18:48:37 -04002213 // Generate variables. Make one for each of resource var info object.
2214 for (auto *info : ModuleOrderedResourceVars) {
2215 Type *type = info->var_fn->getReturnType();
2216 // Remap the address space for opaque types.
2217 switch (info->arg_kind) {
2218 case clspv::ArgKind::Sampler:
alan-bakerf6bc8252020-09-23 14:58:55 -04002219 case clspv::ArgKind::SampledImage:
2220 case clspv::ArgKind::StorageImage:
David Neto862b7d82018-06-14 18:48:37 -04002221 type = PointerType::get(type->getPointerElementType(),
2222 clspv::AddressSpace::UniformConstant);
2223 break;
2224 default:
2225 break;
2226 }
David Neto22f144c2017-06-12 14:26:21 -04002227
David Neto862b7d82018-06-14 18:48:37 -04002228 const auto sc = GetStorageClassForArgKind(info->arg_kind);
David Neto22f144c2017-06-12 14:26:21 -04002229
SJW806a5d82020-07-15 12:51:38 -05002230 info->var_id = addSPIRVGlobalVariable(getSPIRVType(type), sc);
David Neto862b7d82018-06-14 18:48:37 -04002231
2232 // Map calls to the variable-builtin-function.
2233 for (auto &U : info->var_fn->uses()) {
2234 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
2235 const auto set = unsigned(
2236 dyn_cast<ConstantInt>(call->getOperand(0))->getZExtValue());
2237 const auto binding = unsigned(
2238 dyn_cast<ConstantInt>(call->getOperand(1))->getZExtValue());
2239 if (set == info->descriptor_set && binding == info->binding) {
2240 switch (info->arg_kind) {
2241 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002242 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002243 case clspv::ArgKind::Pod:
alan-baker9b0ec3c2020-04-06 14:45:34 -04002244 case clspv::ArgKind::PodUBO:
2245 case clspv::ArgKind::PodPushConstant:
David Neto862b7d82018-06-14 18:48:37 -04002246 // The call maps to the variable directly.
2247 VMap[call] = info->var_id;
2248 break;
2249 case clspv::ArgKind::Sampler:
alan-bakerf6bc8252020-09-23 14:58:55 -04002250 case clspv::ArgKind::SampledImage:
2251 case clspv::ArgKind::StorageImage:
David Neto862b7d82018-06-14 18:48:37 -04002252 // The call maps to a load we generate later.
2253 ResourceVarDeferredLoadCalls[call] = info->var_id;
2254 break;
2255 default:
2256 llvm_unreachable("Unhandled arg kind");
2257 }
2258 }
David Neto22f144c2017-06-12 14:26:21 -04002259 }
David Neto862b7d82018-06-14 18:48:37 -04002260 }
2261 }
David Neto22f144c2017-06-12 14:26:21 -04002262
David Neto862b7d82018-06-14 18:48:37 -04002263 // Generate associated decorations.
SJWf93f5f32020-05-05 07:27:56 -05002264 SPIRVOperandVec Ops;
David Neto862b7d82018-06-14 18:48:37 -04002265 for (auto *info : ModuleOrderedResourceVars) {
alan-baker9b0ec3c2020-04-06 14:45:34 -04002266 // Push constants don't need descriptor set or binding decorations.
2267 if (info->arg_kind == clspv::ArgKind::PodPushConstant)
2268 continue;
2269
David Neto862b7d82018-06-14 18:48:37 -04002270 // Decorate with DescriptorSet and Binding.
2271 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002272 Ops << info->var_id << spv::DecorationDescriptorSet << info->descriptor_set;
SJWf93f5f32020-05-05 07:27:56 -05002273 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto862b7d82018-06-14 18:48:37 -04002274
2275 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002276 Ops << info->var_id << spv::DecorationBinding << info->binding;
SJWf93f5f32020-05-05 07:27:56 -05002277 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto862b7d82018-06-14 18:48:37 -04002278
alan-bakere9308012019-03-15 10:25:13 -04002279 if (info->coherent) {
2280 // Decorate with Coherent if required for the variable.
2281 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002282 Ops << info->var_id << spv::DecorationCoherent;
SJWf93f5f32020-05-05 07:27:56 -05002283 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
alan-bakere9308012019-03-15 10:25:13 -04002284 }
2285
David Neto862b7d82018-06-14 18:48:37 -04002286 // Generate NonWritable and NonReadable
2287 switch (info->arg_kind) {
2288 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002289 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002290 if (info->var_fn->getReturnType()->getPointerAddressSpace() ==
2291 clspv::AddressSpace::Constant) {
2292 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002293 Ops << info->var_id << spv::DecorationNonWritable;
SJWf93f5f32020-05-05 07:27:56 -05002294 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002295 }
David Neto862b7d82018-06-14 18:48:37 -04002296 break;
alan-bakerf6bc8252020-09-23 14:58:55 -04002297 case clspv::ArgKind::StorageImage: {
2298 auto *type = info->var_fn->getReturnType();
2299 auto *struct_ty = cast<StructType>(type->getPointerElementType());
2300 // TODO(alan-baker): This is conservative. If compiling for OpenCL 2.0 or
2301 // above, the compiler treats all write_only images as read_write images.
2302 if (struct_ty->getName().contains("_wo_t")) {
2303 Ops.clear();
2304 Ops << info->var_id << spv::DecorationNonReadable;
2305 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
2306 }
David Neto862b7d82018-06-14 18:48:37 -04002307 break;
alan-bakerf6bc8252020-09-23 14:58:55 -04002308 }
David Neto862b7d82018-06-14 18:48:37 -04002309 default:
2310 break;
David Neto22f144c2017-06-12 14:26:21 -04002311 }
2312 }
2313}
2314
2315void SPIRVProducerPass::GenerateGlobalVar(GlobalVariable &GV) {
David Neto22f144c2017-06-12 14:26:21 -04002316 ValueMapType &VMap = getValueMap();
SJW01901d92020-05-21 08:58:31 -05002317 std::vector<SPIRVID> &BuiltinDimVec = getBuiltinDimVec();
David Neto85082642018-03-24 06:55:20 -07002318 const DataLayout &DL = GV.getParent()->getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04002319
2320 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
2321 Type *Ty = GV.getType();
2322 PointerType *PTy = cast<PointerType>(Ty);
2323
SJW01901d92020-05-21 08:58:31 -05002324 SPIRVID InitializerID;
David Neto22f144c2017-06-12 14:26:21 -04002325
2326 // Workgroup size is handled differently (it goes into a constant)
2327 if (spv::BuiltInWorkgroupSize == BuiltinType) {
David Neto22f144c2017-06-12 14:26:21 -04002328 uint32_t PrevXDimCst = 0xFFFFFFFF;
2329 uint32_t PrevYDimCst = 0xFFFFFFFF;
2330 uint32_t PrevZDimCst = 0xFFFFFFFF;
alan-baker3b609772020-09-03 19:10:17 -04002331 bool HasMD = true;
David Neto22f144c2017-06-12 14:26:21 -04002332 for (Function &Func : *GV.getParent()) {
2333 if (Func.isDeclaration()) {
2334 continue;
2335 }
2336
2337 // We only need to check kernels.
2338 if (Func.getCallingConv() != CallingConv::SPIR_KERNEL) {
2339 continue;
2340 }
2341
2342 if (const MDNode *MD =
2343 dyn_cast<Function>(&Func)->getMetadata("reqd_work_group_size")) {
2344 uint32_t CurXDimCst = static_cast<uint32_t>(
2345 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
2346 uint32_t CurYDimCst = static_cast<uint32_t>(
2347 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
2348 uint32_t CurZDimCst = static_cast<uint32_t>(
2349 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
2350
2351 if (PrevXDimCst == 0xFFFFFFFF && PrevYDimCst == 0xFFFFFFFF &&
2352 PrevZDimCst == 0xFFFFFFFF) {
2353 PrevXDimCst = CurXDimCst;
2354 PrevYDimCst = CurYDimCst;
2355 PrevZDimCst = CurZDimCst;
2356 } else if (CurXDimCst != PrevXDimCst || CurYDimCst != PrevYDimCst ||
2357 CurZDimCst != PrevZDimCst) {
alan-baker3b609772020-09-03 19:10:17 -04002358 HasMD = false;
2359 continue;
David Neto22f144c2017-06-12 14:26:21 -04002360 } else {
2361 continue;
2362 }
2363
2364 //
2365 // Generate OpConstantComposite.
2366 //
2367 // Ops[0] : Result Type ID
2368 // Ops[1] : Constant size for x dimension.
2369 // Ops[2] : Constant size for y dimension.
2370 // Ops[3] : Constant size for z dimension.
SJWf93f5f32020-05-05 07:27:56 -05002371 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04002372
SJW01901d92020-05-21 08:58:31 -05002373 SPIRVID XDimCstID =
SJWf93f5f32020-05-05 07:27:56 -05002374 getSPIRVValue(mdconst::extract<ConstantInt>(MD->getOperand(0)));
SJW01901d92020-05-21 08:58:31 -05002375 SPIRVID YDimCstID =
SJWf93f5f32020-05-05 07:27:56 -05002376 getSPIRVValue(mdconst::extract<ConstantInt>(MD->getOperand(1)));
SJW01901d92020-05-21 08:58:31 -05002377 SPIRVID ZDimCstID =
SJWf93f5f32020-05-05 07:27:56 -05002378 getSPIRVValue(mdconst::extract<ConstantInt>(MD->getOperand(2)));
David Neto22f144c2017-06-12 14:26:21 -04002379
SJW01901d92020-05-21 08:58:31 -05002380 Ops << Ty->getPointerElementType() << XDimCstID << YDimCstID
2381 << ZDimCstID;
David Neto22f144c2017-06-12 14:26:21 -04002382
SJWf93f5f32020-05-05 07:27:56 -05002383 InitializerID =
2384 addSPIRVInst<kGlobalVariables>(spv::OpConstantComposite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002385 } else {
alan-baker3b609772020-09-03 19:10:17 -04002386 HasMD = false;
David Neto22f144c2017-06-12 14:26:21 -04002387 }
2388 }
2389
2390 // If all kernels do not have metadata for reqd_work_group_size, generate
2391 // OpSpecConstants for x/y/z dimension.
Kévin Petit21c23c62020-04-29 01:38:28 +01002392 if (!HasMD || clspv::Option::NonUniformNDRangeSupported()) {
David Neto22f144c2017-06-12 14:26:21 -04002393 //
2394 // Generate OpSpecConstants for x/y/z dimension.
2395 //
2396 // Ops[0] : Result Type ID
2397 // Ops[1] : Constant size for x/y/z dimension (Literal Number).
David Neto22f144c2017-06-12 14:26:21 -04002398
alan-bakera1be3322020-04-20 12:48:18 -04002399 // Allocate spec constants for workgroup size.
SJW77b87ad2020-04-21 14:37:52 -05002400 clspv::AddWorkgroupSpecConstants(module);
alan-bakera1be3322020-04-20 12:48:18 -04002401
SJWf93f5f32020-05-05 07:27:56 -05002402 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05002403 SPIRVID result_type_id = getSPIRVType(
SJWf93f5f32020-05-05 07:27:56 -05002404 dyn_cast<VectorType>(Ty->getPointerElementType())->getElementType());
David Neto22f144c2017-06-12 14:26:21 -04002405
David Neto257c3892018-04-11 13:19:45 -04002406 // X Dimension
SJW01901d92020-05-21 08:58:31 -05002407 Ops << result_type_id << 1;
2408 SPIRVID XDimCstID = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002409
2410 // Y Dimension
2411 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002412 Ops << result_type_id << 1;
2413 SPIRVID YDimCstID = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002414
2415 // Z Dimension
2416 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002417 Ops << result_type_id << 1;
2418 SPIRVID ZDimCstID = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002419
David Neto257c3892018-04-11 13:19:45 -04002420 BuiltinDimVec.push_back(XDimCstID);
2421 BuiltinDimVec.push_back(YDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002422 BuiltinDimVec.push_back(ZDimCstID);
2423
David Neto22f144c2017-06-12 14:26:21 -04002424 //
2425 // Generate OpSpecConstantComposite.
2426 //
2427 // Ops[0] : Result Type ID
2428 // Ops[1] : Constant size for x dimension.
2429 // Ops[2] : Constant size for y dimension.
2430 // Ops[3] : Constant size for z dimension.
David Neto22f144c2017-06-12 14:26:21 -04002431 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002432 Ops << Ty->getPointerElementType() << XDimCstID << YDimCstID << ZDimCstID;
David Neto22f144c2017-06-12 14:26:21 -04002433
SJWf93f5f32020-05-05 07:27:56 -05002434 InitializerID =
2435 addSPIRVInst<kConstants>(spv::OpSpecConstantComposite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002436 }
alan-bakerbed3a882020-04-21 14:42:41 -04002437 } else if (BuiltinType == spv::BuiltInWorkDim) {
2438 // 1. Generate a specialization constant with a default of 3.
2439 // 2. Allocate and annotate a SpecId for the constant.
2440 // 3. Use the spec constant as the initializer for the variable.
SJWf93f5f32020-05-05 07:27:56 -05002441 SPIRVOperandVec Ops;
alan-bakerbed3a882020-04-21 14:42:41 -04002442
2443 //
2444 // Generate OpSpecConstant.
2445 //
2446 // Ops[0] : Result Type ID
2447 // Ops[1] : Default literal value
alan-bakerbed3a882020-04-21 14:42:41 -04002448
SJW01901d92020-05-21 08:58:31 -05002449 Ops << IntegerType::get(GV.getContext(), 32) << 3;
alan-bakerbed3a882020-04-21 14:42:41 -04002450
SJWf93f5f32020-05-05 07:27:56 -05002451 InitializerID = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
alan-bakerbed3a882020-04-21 14:42:41 -04002452
2453 //
2454 // Generate SpecId decoration.
2455 //
2456 // Ops[0] : target
2457 // Ops[1] : decoration
2458 // Ops[2] : SpecId
Alan Baker75ccc252020-04-21 17:11:52 -04002459 auto spec_id = AllocateSpecConstant(module, SpecConstant::kWorkDim);
alan-bakerbed3a882020-04-21 14:42:41 -04002460 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002461 Ops << InitializerID << spv::DecorationSpecId << spec_id;
alan-bakerbed3a882020-04-21 14:42:41 -04002462
SJWf93f5f32020-05-05 07:27:56 -05002463 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002464 } else if (BuiltinType == spv::BuiltInGlobalOffset) {
2465 // 1. Generate a spec constant with a default of {0, 0, 0}.
2466 // 2. Allocate and annotate SpecIds for the constants.
2467 // 3. Use the spec constant as the initializer for the variable.
SJWf93f5f32020-05-05 07:27:56 -05002468 SPIRVOperandVec Ops;
alan-bakere1996972020-05-04 08:38:12 -04002469
2470 //
2471 // Generate OpSpecConstant for each dimension.
2472 //
2473 // Ops[0] : Result Type ID
2474 // Ops[1] : Default literal value
2475 //
SJW01901d92020-05-21 08:58:31 -05002476 Ops << IntegerType::get(GV.getContext(), 32) << 0;
2477 SPIRVID x_id = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002478
alan-bakere1996972020-05-04 08:38:12 -04002479 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002480 Ops << IntegerType::get(GV.getContext(), 32) << 0;
2481 SPIRVID y_id = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002482
alan-bakere1996972020-05-04 08:38:12 -04002483 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002484 Ops << IntegerType::get(GV.getContext(), 32) << 0;
2485 SPIRVID z_id = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002486
2487 //
2488 // Generate SpecId decoration for each dimension.
2489 //
2490 // Ops[0] : target
2491 // Ops[1] : decoration
2492 // Ops[2] : SpecId
2493 //
2494 auto spec_id = AllocateSpecConstant(module, SpecConstant::kGlobalOffsetX);
2495 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002496 Ops << x_id << spv::DecorationSpecId << spec_id;
SJWf93f5f32020-05-05 07:27:56 -05002497 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002498
2499 spec_id = AllocateSpecConstant(module, SpecConstant::kGlobalOffsetY);
2500 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002501 Ops << y_id << spv::DecorationSpecId << spec_id;
SJWf93f5f32020-05-05 07:27:56 -05002502 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002503
2504 spec_id = AllocateSpecConstant(module, SpecConstant::kGlobalOffsetZ);
2505 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002506 Ops << z_id << spv::DecorationSpecId << spec_id;
SJWf93f5f32020-05-05 07:27:56 -05002507 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002508
2509 //
2510 // Generate OpSpecConstantComposite.
2511 //
2512 // Ops[0] : type id
2513 // Ops[1..n-1] : elements
2514 //
alan-bakere1996972020-05-04 08:38:12 -04002515 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002516 Ops << GV.getType()->getPointerElementType() << x_id << y_id << z_id;
SJWf93f5f32020-05-05 07:27:56 -05002517 InitializerID = addSPIRVInst<kConstants>(spv::OpSpecConstantComposite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002518 }
2519
David Neto85082642018-03-24 06:55:20 -07002520 const auto AS = PTy->getAddressSpace();
SJW806a5d82020-07-15 12:51:38 -05002521 const auto spvSC = GetStorageClass(AS);
David Neto22f144c2017-06-12 14:26:21 -04002522
David Neto85082642018-03-24 06:55:20 -07002523 const bool module_scope_constant_external_init =
David Neto862b7d82018-06-14 18:48:37 -04002524 (AS == AddressSpace::Constant) && GV.hasInitializer() &&
David Neto85082642018-03-24 06:55:20 -07002525 clspv::Option::ModuleConstantsInStorageBuffer();
2526
Kévin Petit23d5f182019-08-13 16:21:29 +01002527 if (GV.hasInitializer()) {
2528 auto GVInit = GV.getInitializer();
2529 if (!isa<UndefValue>(GVInit) && !module_scope_constant_external_init) {
SJWf93f5f32020-05-05 07:27:56 -05002530 InitializerID = getSPIRVValue(GVInit);
David Neto85082642018-03-24 06:55:20 -07002531 }
2532 }
Kévin Petit23d5f182019-08-13 16:21:29 +01002533
alan-baker3f772c02021-06-15 22:18:11 -04002534 // All private, module private, and local global variables can be added to
2535 // interfaces conservatively.
2536 const bool interface =
2537 (AS == AddressSpace::Private || AS == AddressSpace::ModuleScopePrivate ||
2538 AS == AddressSpace::Local);
SJW806a5d82020-07-15 12:51:38 -05002539 SPIRVID var_id =
alan-baker3f772c02021-06-15 22:18:11 -04002540 addSPIRVGlobalVariable(getSPIRVType(Ty), spvSC, InitializerID, interface);
David Neto85082642018-03-24 06:55:20 -07002541
SJWf93f5f32020-05-05 07:27:56 -05002542 VMap[&GV] = var_id;
David Neto22f144c2017-06-12 14:26:21 -04002543
alan-bakere1996972020-05-04 08:38:12 -04002544 auto IsOpenCLBuiltin = [](spv::BuiltIn builtin) {
2545 return builtin == spv::BuiltInWorkDim ||
2546 builtin == spv::BuiltInGlobalOffset;
2547 };
2548
alan-bakere1996972020-05-04 08:38:12 -04002549 // If we have a builtin (not an OpenCL builtin).
2550 if (spv::BuiltInMax != BuiltinType && !IsOpenCLBuiltin(BuiltinType)) {
David Neto22f144c2017-06-12 14:26:21 -04002551 //
2552 // Generate OpDecorate.
2553 //
2554 // DOps[0] = Target ID
2555 // DOps[1] = Decoration (Builtin)
2556 // DOps[2] = BuiltIn ID
SJW01901d92020-05-21 08:58:31 -05002557 SPIRVID ResultID;
David Neto22f144c2017-06-12 14:26:21 -04002558
2559 // WorkgroupSize is different, we decorate the constant composite that has
2560 // its value, rather than the variable that we use to access the value.
2561 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2562 ResultID = InitializerID;
David Netoa60b00b2017-09-15 16:34:09 -04002563 // Save both the value and variable IDs for later.
2564 WorkgroupSizeValueID = InitializerID;
SJWf93f5f32020-05-05 07:27:56 -05002565 WorkgroupSizeVarID = getSPIRVValue(&GV);
David Neto22f144c2017-06-12 14:26:21 -04002566 } else {
SJWf93f5f32020-05-05 07:27:56 -05002567 ResultID = getSPIRVValue(&GV);
David Neto22f144c2017-06-12 14:26:21 -04002568 }
2569
SJW806a5d82020-07-15 12:51:38 -05002570 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05002571 Ops << ResultID << spv::DecorationBuiltIn << BuiltinType;
David Neto22f144c2017-06-12 14:26:21 -04002572
SJW01901d92020-05-21 08:58:31 -05002573 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto85082642018-03-24 06:55:20 -07002574 } else if (module_scope_constant_external_init) {
2575 // This module scope constant is initialized from a storage buffer with data
2576 // provided by the host at binding 0 of the next descriptor set.
SJW77b87ad2020-04-21 14:37:52 -05002577 const uint32_t descriptor_set = TakeDescriptorIndex(module);
David Neto85082642018-03-24 06:55:20 -07002578
alan-baker86ce19c2020-08-05 13:09:19 -04002579 // Emit the intializer as a reflection instruction.
David Neto85082642018-03-24 06:55:20 -07002580 // Use "kind,buffer" to indicate storage buffer. We might want to expand
2581 // that later to other types, like uniform buffer.
alan-bakerf5e5f692018-11-27 08:33:24 -05002582 std::string hexbytes;
2583 llvm::raw_string_ostream str(hexbytes);
2584 clspv::ConstantEmitter(DL, str).Emit(GV.getInitializer());
alan-baker86ce19c2020-08-05 13:09:19 -04002585
2586 // Reflection instruction for constant data.
2587 SPIRVOperandVec Ops;
2588 auto data_id = addSPIRVInst<kDebug>(spv::OpString, str.str().c_str());
2589 Ops << getSPIRVType(Type::getVoidTy(module->getContext()))
2590 << getReflectionImport() << reflection::ExtInstConstantDataStorageBuffer
2591 << getSPIRVInt32Constant(descriptor_set) << getSPIRVInt32Constant(0)
2592 << data_id;
2593 addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
David Neto85082642018-03-24 06:55:20 -07002594
David Neto85082642018-03-24 06:55:20 -07002595 // OpDecorate %var DescriptorSet <descriptor_set>
alan-baker86ce19c2020-08-05 13:09:19 -04002596 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002597 Ops << var_id << spv::DecorationDescriptorSet << descriptor_set;
2598 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
SJW69939d52020-04-16 07:29:07 -05002599
2600 // OpDecorate %var Binding <binding>
SJW01901d92020-05-21 08:58:31 -05002601 Ops.clear();
2602 Ops << var_id << spv::DecorationBinding << 0;
2603 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Netoc6f3ab22018-04-06 18:02:31 -04002604 }
2605}
2606
David Neto22f144c2017-06-12 14:26:21 -04002607void SPIRVProducerPass::GenerateFuncPrologue(Function &F) {
David Neto22f144c2017-06-12 14:26:21 -04002608 ValueMapType &VMap = getValueMap();
2609 EntryPointVecType &EntryPoints = getEntryPointVec();
David Neto22f144c2017-06-12 14:26:21 -04002610 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
2611 auto &GlobalConstArgSet = getGlobalConstArgSet();
2612
2613 FunctionType *FTy = F.getFunctionType();
2614
2615 //
David Neto22f144c2017-06-12 14:26:21 -04002616 // Generate OPFunction.
2617 //
2618
2619 // FOps[0] : Result Type ID
2620 // FOps[1] : Function Control
2621 // FOps[2] : Function Type ID
SJWf93f5f32020-05-05 07:27:56 -05002622 SPIRVOperandVec FOps;
David Neto22f144c2017-06-12 14:26:21 -04002623
2624 // Find SPIRV instruction for return type.
SJW01901d92020-05-21 08:58:31 -05002625 FOps << FTy->getReturnType();
David Neto22f144c2017-06-12 14:26:21 -04002626
2627 // Check function attributes for SPIRV Function Control.
2628 uint32_t FuncControl = spv::FunctionControlMaskNone;
2629 if (F.hasFnAttribute(Attribute::AlwaysInline)) {
2630 FuncControl |= spv::FunctionControlInlineMask;
2631 }
2632 if (F.hasFnAttribute(Attribute::NoInline)) {
2633 FuncControl |= spv::FunctionControlDontInlineMask;
2634 }
2635 // TODO: Check llvm attribute for Function Control Pure.
2636 if (F.hasFnAttribute(Attribute::ReadOnly)) {
2637 FuncControl |= spv::FunctionControlPureMask;
2638 }
2639 // TODO: Check llvm attribute for Function Control Const.
2640 if (F.hasFnAttribute(Attribute::ReadNone)) {
2641 FuncControl |= spv::FunctionControlConstMask;
2642 }
2643
SJW01901d92020-05-21 08:58:31 -05002644 FOps << FuncControl;
David Neto22f144c2017-06-12 14:26:21 -04002645
SJW01901d92020-05-21 08:58:31 -05002646 SPIRVID FTyID;
David Neto22f144c2017-06-12 14:26:21 -04002647 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
2648 SmallVector<Type *, 4> NewFuncParamTys;
2649 FunctionType *NewFTy =
2650 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
SJWf93f5f32020-05-05 07:27:56 -05002651 FTyID = getSPIRVType(NewFTy);
David Neto22f144c2017-06-12 14:26:21 -04002652 } else {
David Neto9ed8e2f2018-03-24 06:47:24 -07002653 // Handle regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04002654 if (GlobalConstFuncTyMap.count(FTy)) {
SJWf93f5f32020-05-05 07:27:56 -05002655 FTyID = getSPIRVType(GlobalConstFuncTyMap[FTy].first);
David Neto22f144c2017-06-12 14:26:21 -04002656 } else {
SJWf93f5f32020-05-05 07:27:56 -05002657 FTyID = getSPIRVType(FTy);
David Neto22f144c2017-06-12 14:26:21 -04002658 }
2659 }
2660
SJW01901d92020-05-21 08:58:31 -05002661 FOps << FTyID;
David Neto22f144c2017-06-12 14:26:21 -04002662
SJWf93f5f32020-05-05 07:27:56 -05002663 // Generate SPIRV instruction for function.
2664 SPIRVID FID = addSPIRVInst(spv::OpFunction, FOps);
2665 VMap[&F] = FID;
David Neto22f144c2017-06-12 14:26:21 -04002666
SJWf93f5f32020-05-05 07:27:56 -05002667 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
2668 EntryPoints.push_back(std::make_pair(&F, FID));
2669 }
David Neto22f144c2017-06-12 14:26:21 -04002670
David Neto482550a2018-03-24 05:21:07 -07002671 if (clspv::Option::ShowIDs()) {
SJW01901d92020-05-21 08:58:31 -05002672 errs() << "Function " << F.getName() << " is " << FID.get() << "\n";
David Netob05675d2018-02-16 12:37:49 -05002673 }
David Neto22f144c2017-06-12 14:26:21 -04002674
2675 //
2676 // Generate OpFunctionParameter for Normal function.
2677 //
David Neto22f144c2017-06-12 14:26:21 -04002678 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
alan-bakere9308012019-03-15 10:25:13 -04002679
David Neto22f144c2017-06-12 14:26:21 -04002680 // Iterate Argument for name instead of param type from function type.
2681 unsigned ArgIdx = 0;
2682 for (Argument &Arg : F.args()) {
David Neto22f144c2017-06-12 14:26:21 -04002683 // ParamOps[0] : Result Type ID
SJW01901d92020-05-21 08:58:31 -05002684 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04002685
2686 // Find SPIRV instruction for parameter type.
SJW01901d92020-05-21 08:58:31 -05002687 SPIRVID ParamTyID = getSPIRVType(Arg.getType());
David Neto22f144c2017-06-12 14:26:21 -04002688 if (PointerType *PTy = dyn_cast<PointerType>(Arg.getType())) {
2689 if (GlobalConstFuncTyMap.count(FTy)) {
2690 if (ArgIdx == GlobalConstFuncTyMap[FTy].second) {
2691 Type *EleTy = PTy->getPointerElementType();
2692 Type *ArgTy =
2693 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
SJWf93f5f32020-05-05 07:27:56 -05002694 ParamTyID = getSPIRVType(ArgTy);
David Neto22f144c2017-06-12 14:26:21 -04002695 GlobalConstArgSet.insert(&Arg);
2696 }
2697 }
2698 }
SJW01901d92020-05-21 08:58:31 -05002699 Ops << ParamTyID;
David Neto22f144c2017-06-12 14:26:21 -04002700
2701 // Generate SPIRV instruction for parameter.
SJW01901d92020-05-21 08:58:31 -05002702 SPIRVID param_id = addSPIRVInst(spv::OpFunctionParameter, Ops);
SJWf93f5f32020-05-05 07:27:56 -05002703 VMap[&Arg] = param_id;
2704
2705 if (CalledWithCoherentResource(Arg)) {
2706 // If the arg is passed a coherent resource ever, then decorate this
2707 // parameter with Coherent too.
SJW01901d92020-05-21 08:58:31 -05002708 Ops.clear();
2709 Ops << param_id << spv::DecorationCoherent;
2710 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
SJWf93f5f32020-05-05 07:27:56 -05002711 }
David Neto22f144c2017-06-12 14:26:21 -04002712
2713 ArgIdx++;
2714 }
2715 }
2716}
2717
SJW77b87ad2020-04-21 14:37:52 -05002718void SPIRVProducerPass::GenerateModuleInfo() {
David Neto22f144c2017-06-12 14:26:21 -04002719 EntryPointVecType &EntryPoints = getEntryPointVec();
SJW806a5d82020-07-15 12:51:38 -05002720 auto &EntryPointInterfaces = getEntryPointInterfacesList();
SJW01901d92020-05-21 08:58:31 -05002721 std::vector<SPIRVID> &BuiltinDimVec = getBuiltinDimVec();
David Neto22f144c2017-06-12 14:26:21 -04002722
SJWf93f5f32020-05-05 07:27:56 -05002723 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04002724
SJW01901d92020-05-21 08:58:31 -05002725 for (auto Capability : CapabilitySet) {
David Neto22f144c2017-06-12 14:26:21 -04002726 //
SJW01901d92020-05-21 08:58:31 -05002727 // Generate OpCapability
David Neto22f144c2017-06-12 14:26:21 -04002728 //
2729 // Ops[0] = Capability
SJW01901d92020-05-21 08:58:31 -05002730 addSPIRVInst<kCapabilities>(spv::OpCapability, Capability);
alan-baker5b86ed72019-02-15 08:26:50 -05002731 }
2732
alan-baker3f772c02021-06-15 22:18:11 -04002733 // Storage buffer and variable pointer extensions were made core in SPIR-V
2734 // 1.3.
2735 if (SpvVersion() < SPIRVVersion::SPIRV_1_3) {
David Neto22f144c2017-06-12 14:26:21 -04002736 //
2737 // Generate OpExtension.
2738 //
2739 // Ops[0] = Name (Literal String)
2740 //
SJWf93f5f32020-05-05 07:27:56 -05002741 addSPIRVInst<kExtensions>(spv::OpExtension,
2742 "SPV_KHR_storage_buffer_storage_class");
David Neto22f144c2017-06-12 14:26:21 -04002743
alan-baker3f772c02021-06-15 22:18:11 -04002744 if (hasVariablePointers() || hasVariablePointersStorageBuffer()) {
2745 //
2746 // Generate OpExtension.
2747 //
2748 // Ops[0] = Name (Literal String)
2749 //
2750 addSPIRVInst<kExtensions>(spv::OpExtension, "SPV_KHR_variable_pointers");
2751 }
David Neto22f144c2017-06-12 14:26:21 -04002752 }
2753
2754 //
2755 // Generate OpMemoryModel
2756 //
2757 // Memory model for Vulkan will always be GLSL450.
2758
2759 // Ops[0] = Addressing Model
2760 // Ops[1] = Memory Model
2761 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002762 Ops << spv::AddressingModelLogical << spv::MemoryModelGLSL450;
David Neto22f144c2017-06-12 14:26:21 -04002763
SJWf93f5f32020-05-05 07:27:56 -05002764 addSPIRVInst<kMemoryModel>(spv::OpMemoryModel, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002765
2766 //
2767 // Generate OpEntryPoint
2768 //
2769 for (auto EntryPoint : EntryPoints) {
2770 // Ops[0] = Execution Model
2771 // Ops[1] = EntryPoint ID
2772 // Ops[2] = Name (Literal String)
2773 // ...
2774 //
2775 // TODO: Do we need to consider Interface ID for forward references???
2776 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05002777 const StringRef &name = EntryPoint.first->getName();
SJW01901d92020-05-21 08:58:31 -05002778 Ops << spv::ExecutionModelGLCompute << EntryPoint.second << name;
David Neto22f144c2017-06-12 14:26:21 -04002779
SJW806a5d82020-07-15 12:51:38 -05002780 for (auto &Interface : EntryPointInterfaces) {
SJW01901d92020-05-21 08:58:31 -05002781 Ops << Interface;
David Neto22f144c2017-06-12 14:26:21 -04002782 }
2783
alan-baker3f772c02021-06-15 22:18:11 -04002784 // Starting in SPIR-V 1.4, all statically used global variables must be
2785 // included in the interface. Private and statically-sized workgroup
2786 // variables are added to all entry points. Kernel arguments are handled
2787 // here.
2788 if (SpvVersion() >= SPIRVVersion::SPIRV_1_4) {
2789 auto *F = dyn_cast<Function>(EntryPoint.first);
2790 assert(F);
2791 assert(F->getCallingConv() == CallingConv::SPIR_KERNEL);
2792
2793 auto &resource_var_at_index = FunctionToResourceVarsMap[F];
2794 for (auto *info : resource_var_at_index) {
2795 if (info) {
2796 Ops << info->var_id;
2797 }
2798 }
2799
Kévin Petit85bcee02021-08-03 18:21:30 +01002800 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
2801 auto *V = module->getGlobalVariable(
2802 clspv::ClusteredConstantsVariableName(), true);
2803 if (V) {
2804 Ops << getValueMap()[V];
2805 }
2806 }
2807
alan-baker3f772c02021-06-15 22:18:11 -04002808 auto local_spec_id_md =
2809 module->getNamedMetadata(clspv::LocalSpecIdMetadataName());
2810 if (local_spec_id_md) {
2811 for (auto spec_id_op : local_spec_id_md->operands()) {
2812 if (dyn_cast<Function>(
2813 dyn_cast<ValueAsMetadata>(spec_id_op->getOperand(0))
2814 ->getValue()) == F) {
2815 int64_t spec_id =
2816 mdconst::extract<ConstantInt>(spec_id_op->getOperand(2))
2817 ->getSExtValue();
2818 if (spec_id > 0) {
2819 auto &info = LocalSpecIdInfoMap[spec_id];
2820 Ops << info.variable_id;
2821 }
2822 }
2823 }
2824 }
2825
2826 // If the kernel uses the global push constant interface it will not be
2827 // covered by the resource variable iteration above.
2828 if (GetPodArgsImpl(*F) == PodArgImpl::kGlobalPushConstant) {
2829 auto *PC =
2830 module->getGlobalVariable(clspv::PushConstantsVariableName());
2831 assert(PC);
2832 Ops << getValueMap()[PC];
2833 }
2834 }
2835
SJWf93f5f32020-05-05 07:27:56 -05002836 addSPIRVInst<kEntryPoints>(spv::OpEntryPoint, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002837 }
2838
alan-baker3b609772020-09-03 19:10:17 -04002839 if (BuiltinDimVec.empty()) {
2840 for (auto EntryPoint : EntryPoints) {
2841 const MDNode *MD = dyn_cast<Function>(EntryPoint.first)
2842 ->getMetadata("reqd_work_group_size");
2843 if ((MD != nullptr) && !clspv::Option::NonUniformNDRangeSupported()) {
2844 //
2845 // Generate OpExecutionMode
2846 //
David Neto22f144c2017-06-12 14:26:21 -04002847
alan-baker3b609772020-09-03 19:10:17 -04002848 // Ops[0] = Entry Point ID
2849 // Ops[1] = Execution Mode
2850 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
2851 Ops.clear();
2852 Ops << EntryPoint.second << spv::ExecutionModeLocalSize;
2853
2854 uint32_t XDim = static_cast<uint32_t>(
2855 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
2856 uint32_t YDim = static_cast<uint32_t>(
2857 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
2858 uint32_t ZDim = static_cast<uint32_t>(
2859 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
2860
2861 Ops << XDim << YDim << ZDim;
2862
2863 addSPIRVInst<kExecutionModes>(spv::OpExecutionMode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002864 }
David Neto22f144c2017-06-12 14:26:21 -04002865 }
2866 }
2867
2868 //
2869 // Generate OpSource.
2870 //
2871 // Ops[0] = SourceLanguage ID
2872 // Ops[1] = Version (LiteralNum)
2873 //
SJW01901d92020-05-21 08:58:31 -05002874 uint32_t LangID = spv::SourceLanguageUnknown;
2875 uint32_t LangVer = 0;
Kévin Petitf0515712020-01-07 18:29:20 +00002876 switch (clspv::Option::Language()) {
2877 case clspv::Option::SourceLanguage::OpenCL_C_10:
SJW01901d92020-05-21 08:58:31 -05002878 LangID = spv::SourceLanguageOpenCL_C;
2879 LangVer = 100;
Kévin Petitf0515712020-01-07 18:29:20 +00002880 break;
2881 case clspv::Option::SourceLanguage::OpenCL_C_11:
SJW01901d92020-05-21 08:58:31 -05002882 LangID = spv::SourceLanguageOpenCL_C;
2883 LangVer = 110;
Kévin Petitf0515712020-01-07 18:29:20 +00002884 break;
2885 case clspv::Option::SourceLanguage::OpenCL_C_12:
SJW01901d92020-05-21 08:58:31 -05002886 LangID = spv::SourceLanguageOpenCL_C;
2887 LangVer = 120;
Kévin Petitf0515712020-01-07 18:29:20 +00002888 break;
2889 case clspv::Option::SourceLanguage::OpenCL_C_20:
SJW01901d92020-05-21 08:58:31 -05002890 LangID = spv::SourceLanguageOpenCL_C;
2891 LangVer = 200;
Kévin Petitf0515712020-01-07 18:29:20 +00002892 break;
Kévin Petit77838ff2020-10-19 18:54:51 +01002893 case clspv::Option::SourceLanguage::OpenCL_C_30:
2894 LangID = spv::SourceLanguageOpenCL_C;
2895 LangVer = 300;
2896 break;
Kévin Petitf0515712020-01-07 18:29:20 +00002897 case clspv::Option::SourceLanguage::OpenCL_CPP:
SJW01901d92020-05-21 08:58:31 -05002898 LangID = spv::SourceLanguageOpenCL_CPP;
2899 LangVer = 100;
Kévin Petitf0515712020-01-07 18:29:20 +00002900 break;
2901 default:
Kévin Petitf0515712020-01-07 18:29:20 +00002902 break;
Kévin Petit0fc88042019-04-09 23:25:02 +01002903 }
David Neto22f144c2017-06-12 14:26:21 -04002904
SJW01901d92020-05-21 08:58:31 -05002905 Ops.clear();
2906 Ops << LangID << LangVer;
SJWf93f5f32020-05-05 07:27:56 -05002907 addSPIRVInst<kDebug>(spv::OpSource, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002908
2909 if (!BuiltinDimVec.empty()) {
2910 //
2911 // Generate OpDecorates for x/y/z dimension.
2912 //
2913 // Ops[0] = Target ID
2914 // Ops[1] = Decoration (SpecId)
David Neto257c3892018-04-11 13:19:45 -04002915 // Ops[2] = Specialization Constant ID (Literal Number)
David Neto22f144c2017-06-12 14:26:21 -04002916
2917 // X Dimension
2918 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002919 Ops << BuiltinDimVec[0] << spv::DecorationSpecId << 0;
SJWf93f5f32020-05-05 07:27:56 -05002920 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002921
2922 // Y Dimension
2923 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002924 Ops << BuiltinDimVec[1] << spv::DecorationSpecId << 1;
SJWf93f5f32020-05-05 07:27:56 -05002925 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002926
2927 // Z Dimension
2928 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002929 Ops << BuiltinDimVec[2] << spv::DecorationSpecId << 2;
SJWf93f5f32020-05-05 07:27:56 -05002930 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002931 }
2932}
2933
David Netob6e2e062018-04-25 10:32:06 -04002934void SPIRVProducerPass::GenerateEntryPointInitialStores() {
2935 // Work around a driver bug. Initializers on Private variables might not
2936 // work. So the start of the kernel should store the initializer value to the
2937 // variables. Yes, *every* entry point pays this cost if *any* entry point
2938 // uses this builtin. At this point I judge this to be an acceptable tradeoff
2939 // of complexity vs. runtime, for a broken driver.
alan-bakerb6b09dc2018-11-08 16:59:28 -05002940 // TODO(dneto): Remove this at some point once fixed drivers are widely
2941 // available.
SJW01901d92020-05-21 08:58:31 -05002942 if (WorkgroupSizeVarID.isValid()) {
2943 assert(WorkgroupSizeValueID.isValid());
David Netob6e2e062018-04-25 10:32:06 -04002944
SJWf93f5f32020-05-05 07:27:56 -05002945 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05002946 Ops << WorkgroupSizeVarID << WorkgroupSizeValueID;
David Netob6e2e062018-04-25 10:32:06 -04002947
SJWf93f5f32020-05-05 07:27:56 -05002948 addSPIRVInst(spv::OpStore, Ops);
David Netob6e2e062018-04-25 10:32:06 -04002949 }
2950}
2951
David Neto22f144c2017-06-12 14:26:21 -04002952void SPIRVProducerPass::GenerateFuncBody(Function &F) {
David Neto22f144c2017-06-12 14:26:21 -04002953 ValueMapType &VMap = getValueMap();
2954
David Netob6e2e062018-04-25 10:32:06 -04002955 const bool IsKernel = F.getCallingConv() == CallingConv::SPIR_KERNEL;
David Neto22f144c2017-06-12 14:26:21 -04002956
2957 for (BasicBlock &BB : F) {
2958 // Register BasicBlock to ValueMap.
David Neto22f144c2017-06-12 14:26:21 -04002959
2960 //
2961 // Generate OpLabel for Basic Block.
2962 //
SJWf93f5f32020-05-05 07:27:56 -05002963 VMap[&BB] = addSPIRVInst(spv::OpLabel);
David Neto22f144c2017-06-12 14:26:21 -04002964
David Neto6dcd4712017-06-23 11:06:47 -04002965 // OpVariable instructions must come first.
2966 for (Instruction &I : BB) {
alan-baker5b86ed72019-02-15 08:26:50 -05002967 if (auto *alloca = dyn_cast<AllocaInst>(&I)) {
2968 // Allocating a pointer requires variable pointers.
2969 if (alloca->getAllocatedType()->isPointerTy()) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002970 setVariablePointersCapabilities(
2971 alloca->getAllocatedType()->getPointerAddressSpace());
alan-baker5b86ed72019-02-15 08:26:50 -05002972 }
David Neto6dcd4712017-06-23 11:06:47 -04002973 GenerateInstruction(I);
2974 }
2975 }
2976
David Neto22f144c2017-06-12 14:26:21 -04002977 if (&BB == &F.getEntryBlock() && IsKernel) {
David Netob6e2e062018-04-25 10:32:06 -04002978 if (clspv::Option::HackInitializers()) {
2979 GenerateEntryPointInitialStores();
2980 }
David Neto22f144c2017-06-12 14:26:21 -04002981 }
2982
2983 for (Instruction &I : BB) {
David Neto6dcd4712017-06-23 11:06:47 -04002984 if (!isa<AllocaInst>(I)) {
2985 GenerateInstruction(I);
2986 }
David Neto22f144c2017-06-12 14:26:21 -04002987 }
2988 }
2989}
2990
2991spv::Op SPIRVProducerPass::GetSPIRVCmpOpcode(CmpInst *I) {
2992 const std::map<CmpInst::Predicate, spv::Op> Map = {
2993 {CmpInst::ICMP_EQ, spv::OpIEqual},
2994 {CmpInst::ICMP_NE, spv::OpINotEqual},
2995 {CmpInst::ICMP_UGT, spv::OpUGreaterThan},
2996 {CmpInst::ICMP_UGE, spv::OpUGreaterThanEqual},
2997 {CmpInst::ICMP_ULT, spv::OpULessThan},
2998 {CmpInst::ICMP_ULE, spv::OpULessThanEqual},
2999 {CmpInst::ICMP_SGT, spv::OpSGreaterThan},
3000 {CmpInst::ICMP_SGE, spv::OpSGreaterThanEqual},
3001 {CmpInst::ICMP_SLT, spv::OpSLessThan},
3002 {CmpInst::ICMP_SLE, spv::OpSLessThanEqual},
3003 {CmpInst::FCMP_OEQ, spv::OpFOrdEqual},
3004 {CmpInst::FCMP_OGT, spv::OpFOrdGreaterThan},
3005 {CmpInst::FCMP_OGE, spv::OpFOrdGreaterThanEqual},
3006 {CmpInst::FCMP_OLT, spv::OpFOrdLessThan},
3007 {CmpInst::FCMP_OLE, spv::OpFOrdLessThanEqual},
3008 {CmpInst::FCMP_ONE, spv::OpFOrdNotEqual},
3009 {CmpInst::FCMP_UEQ, spv::OpFUnordEqual},
3010 {CmpInst::FCMP_UGT, spv::OpFUnordGreaterThan},
3011 {CmpInst::FCMP_UGE, spv::OpFUnordGreaterThanEqual},
3012 {CmpInst::FCMP_ULT, spv::OpFUnordLessThan},
3013 {CmpInst::FCMP_ULE, spv::OpFUnordLessThanEqual},
3014 {CmpInst::FCMP_UNE, spv::OpFUnordNotEqual}};
3015
3016 assert(0 != Map.count(I->getPredicate()));
3017
3018 return Map.at(I->getPredicate());
3019}
3020
3021spv::Op SPIRVProducerPass::GetSPIRVCastOpcode(Instruction &I) {
3022 const std::map<unsigned, spv::Op> Map{
3023 {Instruction::Trunc, spv::OpUConvert},
3024 {Instruction::ZExt, spv::OpUConvert},
3025 {Instruction::SExt, spv::OpSConvert},
3026 {Instruction::FPToUI, spv::OpConvertFToU},
3027 {Instruction::FPToSI, spv::OpConvertFToS},
3028 {Instruction::UIToFP, spv::OpConvertUToF},
3029 {Instruction::SIToFP, spv::OpConvertSToF},
3030 {Instruction::FPTrunc, spv::OpFConvert},
3031 {Instruction::FPExt, spv::OpFConvert},
3032 {Instruction::BitCast, spv::OpBitcast}};
3033
3034 assert(0 != Map.count(I.getOpcode()));
3035
3036 return Map.at(I.getOpcode());
3037}
3038
3039spv::Op SPIRVProducerPass::GetSPIRVBinaryOpcode(Instruction &I) {
Kévin Petit24272b62018-10-18 19:16:12 +00003040 if (I.getType()->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003041 switch (I.getOpcode()) {
3042 default:
3043 break;
3044 case Instruction::Or:
3045 return spv::OpLogicalOr;
3046 case Instruction::And:
3047 return spv::OpLogicalAnd;
3048 case Instruction::Xor:
3049 return spv::OpLogicalNotEqual;
3050 }
3051 }
3052
alan-bakerb6b09dc2018-11-08 16:59:28 -05003053 const std::map<unsigned, spv::Op> Map{
David Neto22f144c2017-06-12 14:26:21 -04003054 {Instruction::Add, spv::OpIAdd},
3055 {Instruction::FAdd, spv::OpFAdd},
3056 {Instruction::Sub, spv::OpISub},
3057 {Instruction::FSub, spv::OpFSub},
3058 {Instruction::Mul, spv::OpIMul},
3059 {Instruction::FMul, spv::OpFMul},
3060 {Instruction::UDiv, spv::OpUDiv},
3061 {Instruction::SDiv, spv::OpSDiv},
3062 {Instruction::FDiv, spv::OpFDiv},
3063 {Instruction::URem, spv::OpUMod},
3064 {Instruction::SRem, spv::OpSRem},
3065 {Instruction::FRem, spv::OpFRem},
3066 {Instruction::Or, spv::OpBitwiseOr},
3067 {Instruction::Xor, spv::OpBitwiseXor},
3068 {Instruction::And, spv::OpBitwiseAnd},
3069 {Instruction::Shl, spv::OpShiftLeftLogical},
3070 {Instruction::LShr, spv::OpShiftRightLogical},
3071 {Instruction::AShr, spv::OpShiftRightArithmetic}};
3072
3073 assert(0 != Map.count(I.getOpcode()));
3074
3075 return Map.at(I.getOpcode());
3076}
3077
SJW806a5d82020-07-15 12:51:38 -05003078SPIRVID SPIRVProducerPass::getSPIRVBuiltin(spv::BuiltIn BID,
3079 spv::Capability Cap) {
3080 SPIRVID RID;
3081
3082 auto ii = BuiltinConstantMap.find(BID);
3083
3084 if (ii != BuiltinConstantMap.end()) {
3085 return ii->second;
3086 } else {
SJW806a5d82020-07-15 12:51:38 -05003087 addCapability(Cap);
3088
3089 Type *type = PointerType::get(IntegerType::get(module->getContext(), 32),
3090 AddressSpace::Input);
3091
3092 RID = addSPIRVGlobalVariable(getSPIRVType(type), spv::StorageClassInput);
3093
3094 BuiltinConstantMap[BID] = RID;
3095
3096 //
3097 // Generate OpDecorate.
3098 //
3099 // Ops[0] : target
3100 // Ops[1] : decoration
3101 // Ops[2] : SpecId
3102 SPIRVOperandVec Ops;
3103 Ops << RID << spv::DecorationBuiltIn << static_cast<int>(BID);
3104
3105 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
3106 }
3107
3108 return RID;
3109}
3110
3111SPIRVID
3112SPIRVProducerPass::GenerateClspvInstruction(CallInst *Call,
3113 const FunctionInfo &FuncInfo) {
3114 SPIRVID RID;
3115
3116 switch (FuncInfo.getType()) {
3117 case Builtins::kClspvCompositeConstruct:
3118 RID = addSPIRVPlaceholder(Call);
3119 break;
3120 case Builtins::kClspvResource: {
3121 if (ResourceVarDeferredLoadCalls.count(Call) && Call->hasNUsesOrMore(1)) {
3122 // Generate an OpLoad
3123 SPIRVOperandVec Ops;
3124
3125 Ops << Call->getType()->getPointerElementType()
3126 << ResourceVarDeferredLoadCalls[Call];
3127
3128 RID = addSPIRVInst(spv::OpLoad, Ops);
3129
3130 } else {
3131 // This maps to an OpVariable we've already generated.
3132 // No code is generated for the call.
3133 }
3134 break;
3135 }
3136 case Builtins::kClspvLocal: {
3137 // Don't codegen an instruction here, but instead map this call directly
3138 // to the workgroup variable id.
3139 int spec_id = static_cast<int>(
3140 cast<ConstantInt>(Call->getOperand(0))->getSExtValue());
3141 const auto &info = LocalSpecIdInfoMap[spec_id];
3142 RID = info.variable_id;
3143 break;
3144 }
3145 case Builtins::kClspvSamplerVarLiteral: {
3146 // Sampler initializers become a load of the corresponding sampler.
3147 // Map this to a load from the variable.
3148 const auto third_param = static_cast<unsigned>(
3149 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue());
3150 auto sampler_value = third_param;
3151 if (clspv::Option::UseSamplerMap()) {
alan-baker3f772c02021-06-15 22:18:11 -04003152 sampler_value = (*getSamplerMap())[third_param].first;
SJW806a5d82020-07-15 12:51:38 -05003153 }
3154
3155 // Generate an OpLoad
3156 SPIRVOperandVec Ops;
3157
3158 Ops << SamplerTy->getPointerElementType()
3159 << SamplerLiteralToIDMap[sampler_value];
3160
3161 RID = addSPIRVInst(spv::OpLoad, Ops);
3162 break;
3163 }
3164 case Builtins::kSpirvAtomicXor: {
3165 // Handle SPIR-V intrinsics
3166 SPIRVOperandVec Ops;
3167
3168 if (!Call->getType()->isVoidTy()) {
3169 Ops << Call->getType();
3170 }
3171
3172 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
3173 Ops << Call->getArgOperand(i);
3174 }
3175
3176 RID = addSPIRVInst(spv::OpAtomicXor, Ops);
3177 break;
3178 }
3179 case Builtins::kSpirvOp: {
3180 // Handle SPIR-V intrinsics
3181 auto *arg0 = dyn_cast<ConstantInt>(Call->getArgOperand(0));
3182 spv::Op opcode = static_cast<spv::Op>(arg0->getZExtValue());
3183 if (opcode != spv::OpNop) {
3184 SPIRVOperandVec Ops;
3185
3186 if (!Call->getType()->isVoidTy()) {
3187 Ops << Call->getType();
3188 }
3189
3190 for (unsigned i = 1; i < Call->getNumArgOperands(); i++) {
3191 Ops << Call->getArgOperand(i);
3192 }
3193
3194 RID = addSPIRVInst(opcode, Ops);
3195 }
3196 break;
3197 }
3198 case Builtins::kSpirvCopyMemory: {
3199 //
3200 // Generate OpCopyMemory.
3201 //
3202
3203 // Ops[0] = Dst ID
3204 // Ops[1] = Src ID
3205 // Ops[2] = Memory Access
3206 // Ops[3] = Alignment
3207
alan-baker3f772c02021-06-15 22:18:11 -04003208 const auto volatile_arg = SpvVersion() >= SPIRVVersion::SPIRV_1_4 ? 4 : 3;
3209 auto IsVolatile = dyn_cast<ConstantInt>(Call->getArgOperand(volatile_arg))
3210 ->getZExtValue() != 0;
SJW806a5d82020-07-15 12:51:38 -05003211
3212 auto VolatileMemoryAccess = (IsVolatile) ? spv::MemoryAccessVolatileMask
3213 : spv::MemoryAccessMaskNone;
3214
3215 auto MemoryAccess = VolatileMemoryAccess | spv::MemoryAccessAlignedMask;
3216
alan-baker3f772c02021-06-15 22:18:11 -04003217 auto DstAlignment =
SJW806a5d82020-07-15 12:51:38 -05003218 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
alan-baker3f772c02021-06-15 22:18:11 -04003219 auto SrcAlignment = DstAlignment;
3220 if (SpvVersion() >= SPIRVVersion::SPIRV_1_4) {
3221 SrcAlignment =
3222 dyn_cast<ConstantInt>(Call->getArgOperand(3))->getZExtValue();
3223 }
SJW806a5d82020-07-15 12:51:38 -05003224
alan-baker3f772c02021-06-15 22:18:11 -04003225 // OpCopyMemory only works if the pointer element type are the same id. If
3226 // we are generating code for SPIR-V 1.4 or later, this may not be the
3227 // case.
3228 auto dst = Call->getArgOperand(0);
3229 auto src = Call->getArgOperand(1);
3230 auto dst_layout =
3231 PointerRequiresLayout(dst->getType()->getPointerAddressSpace());
3232 auto src_layout =
3233 PointerRequiresLayout(src->getType()->getPointerAddressSpace());
3234 auto dst_id =
3235 getSPIRVType(dst->getType()->getPointerElementType(), dst_layout);
3236 auto src_id =
3237 getSPIRVType(src->getType()->getPointerElementType(), src_layout);
SJW806a5d82020-07-15 12:51:38 -05003238 SPIRVOperandVec Ops;
alan-baker3f772c02021-06-15 22:18:11 -04003239 if (dst_id.get() != src_id.get()) {
3240 assert(Option::SpvVersion() >= SPIRVVersion::SPIRV_1_4);
3241 // Types differ so generate:
3242 // OpLoad
3243 // OpCopyLogical
3244 // OpStore
3245 auto load_type_id =
3246 getSPIRVType(src->getType()->getPointerElementType(), src_layout);
3247 Ops << load_type_id << src << MemoryAccess
3248 << static_cast<uint32_t>(SrcAlignment);
3249 auto load = addSPIRVInst(spv::OpLoad, Ops);
SJW806a5d82020-07-15 12:51:38 -05003250
alan-baker3f772c02021-06-15 22:18:11 -04003251 auto copy_type_id =
3252 getSPIRVType(dst->getType()->getPointerElementType(), dst_layout);
3253 Ops.clear();
3254 Ops << copy_type_id << load;
3255 auto copy = addSPIRVInst(spv::OpCopyLogical, Ops);
3256
3257 Ops.clear();
3258 Ops << dst << copy << MemoryAccess << static_cast<uint32_t>(DstAlignment);
3259 RID = addSPIRVInst(spv::OpStore, Ops);
3260 } else {
3261 Ops << dst << src << MemoryAccess << static_cast<uint32_t>(DstAlignment);
3262 if (SpvVersion() >= SPIRVVersion::SPIRV_1_4) {
3263 Ops << MemoryAccess << static_cast<uint32_t>(SrcAlignment);
3264 }
3265
3266 RID = addSPIRVInst(spv::OpCopyMemory, Ops);
3267 }
SJW806a5d82020-07-15 12:51:38 -05003268 break;
3269 }
3270 default:
3271 llvm_unreachable("Unknown CLSPV Instruction");
3272 break;
3273 }
3274 return RID;
3275}
3276
3277SPIRVID
3278SPIRVProducerPass::GenerateImageInstruction(CallInst *Call,
3279 const FunctionInfo &FuncInfo) {
3280 SPIRVID RID;
3281
alan-baker3f772c02021-06-15 22:18:11 -04003282 auto GetExtendMask = [this](Type *sample_type,
3283 bool is_int_image) -> uint32_t {
3284 if (SpvVersion() >= SPIRVVersion::SPIRV_1_4 &&
3285 sample_type->getScalarType()->isIntegerTy()) {
3286 if (is_int_image)
3287 return spv::ImageOperandsSignExtendMask;
3288 else
3289 return spv::ImageOperandsZeroExtendMask;
3290 }
3291 return 0;
3292 };
3293
SJW806a5d82020-07-15 12:51:38 -05003294 LLVMContext &Context = module->getContext();
3295 switch (FuncInfo.getType()) {
3296 case Builtins::kReadImagef:
3297 case Builtins::kReadImageh:
3298 case Builtins::kReadImagei:
3299 case Builtins::kReadImageui: {
3300 // read_image is converted to OpSampledImage and OpImageSampleExplicitLod.
3301 // Additionally, OpTypeSampledImage is generated.
alan-bakerf6bc8252020-09-23 14:58:55 -04003302 const auto image_ty = Call->getArgOperand(0)->getType();
SJW806a5d82020-07-15 12:51:38 -05003303 const auto &pi = FuncInfo.getParameter(1);
3304 if (pi.isSampler()) {
3305 //
3306 // Generate OpSampledImage.
3307 //
3308 // Ops[0] = Result Type ID
3309 // Ops[1] = Image ID
3310 // Ops[2] = Sampler ID
3311 //
3312 SPIRVOperandVec Ops;
3313
3314 Value *Image = Call->getArgOperand(0);
3315 Value *Sampler = Call->getArgOperand(1);
3316 Value *Coordinate = Call->getArgOperand(2);
3317
3318 TypeMapType &OpImageTypeMap = getImageTypeMap();
3319 Type *ImageTy = Image->getType()->getPointerElementType();
3320 SPIRVID ImageTyID = OpImageTypeMap[ImageTy];
3321
3322 Ops << ImageTyID << Image << Sampler;
3323
3324 SPIRVID SampledImageID = addSPIRVInst(spv::OpSampledImage, Ops);
3325
3326 //
3327 // Generate OpImageSampleExplicitLod.
3328 //
3329 // Ops[0] = Result Type ID
3330 // Ops[1] = Sampled Image ID
3331 // Ops[2] = Coordinate ID
3332 // Ops[3] = Image Operands Type ID
3333 // Ops[4] ... Ops[n] = Operands ID
3334 //
3335 Ops.clear();
3336
3337 const bool is_int_image = IsIntImageType(Image->getType());
3338 SPIRVID result_type;
3339 if (is_int_image) {
3340 result_type = v4int32ID;
3341 } else {
3342 result_type = getSPIRVType(Call->getType());
3343 }
3344
alan-baker3f772c02021-06-15 22:18:11 -04003345 uint32_t mask = spv::ImageOperandsLodMask |
3346 GetExtendMask(Call->getType(), is_int_image);
SJW806a5d82020-07-15 12:51:38 -05003347 Constant *CstFP0 = ConstantFP::get(Context, APFloat(0.0f));
alan-baker3f772c02021-06-15 22:18:11 -04003348 Ops << result_type << SampledImageID << Coordinate << mask << CstFP0;
SJW806a5d82020-07-15 12:51:38 -05003349
3350 RID = addSPIRVInst(spv::OpImageSampleExplicitLod, Ops);
3351
3352 if (is_int_image) {
3353 // Generate the bitcast.
3354 Ops.clear();
3355 Ops << Call->getType() << RID;
3356 RID = addSPIRVInst(spv::OpBitcast, Ops);
3357 }
alan-bakerf6bc8252020-09-23 14:58:55 -04003358 } else if (IsStorageImageType(image_ty)) {
3359 // read_image on a storage image is mapped to OpImageRead.
3360 Value *Image = Call->getArgOperand(0);
3361 Value *Coordinate = Call->getArgOperand(1);
3362
3363 //
3364 // Generate OpImageRead
3365 //
3366 // Ops[0] = Result Type ID
3367 // Ops[1] = Image ID
3368 // Ops[2] = Coordinate
3369 // No optional image operands.
3370 //
3371 SPIRVOperandVec Ops;
3372
3373 const bool is_int_image = IsIntImageType(Image->getType());
3374 SPIRVID result_type;
3375 if (is_int_image) {
3376 result_type = v4int32ID;
3377 } else {
3378 result_type = getSPIRVType(Call->getType());
3379 }
3380
3381 Ops << result_type << Image << Coordinate;
alan-baker3f772c02021-06-15 22:18:11 -04003382 uint32_t mask = GetExtendMask(Call->getType(), is_int_image);
3383 if (mask != 0)
3384 Ops << mask;
alan-bakerf6bc8252020-09-23 14:58:55 -04003385 RID = addSPIRVInst(spv::OpImageRead, Ops);
3386
3387 if (is_int_image) {
3388 // Generate the bitcast.
3389 Ops.clear();
3390 Ops << Call->getType() << RID;
3391 RID = addSPIRVInst(spv::OpBitcast, Ops);
3392 }
3393
3394 // OpImageRead requires StorageImageReadWithoutFormat.
3395 addCapability(spv::CapabilityStorageImageReadWithoutFormat);
SJW806a5d82020-07-15 12:51:38 -05003396 } else {
alan-bakerf6bc8252020-09-23 14:58:55 -04003397 // read_image on a sampled image (without a sampler) is mapped to
3398 // OpImageFetch.
SJW806a5d82020-07-15 12:51:38 -05003399 Value *Image = Call->getArgOperand(0);
3400 Value *Coordinate = Call->getArgOperand(1);
3401
3402 //
3403 // Generate OpImageFetch
3404 //
3405 // Ops[0] = Result Type ID
3406 // Ops[1] = Image ID
3407 // Ops[2] = Coordinate ID
3408 // Ops[3] = Lod
3409 // Ops[4] = 0
3410 //
3411 SPIRVOperandVec Ops;
3412
3413 const bool is_int_image = IsIntImageType(Image->getType());
3414 SPIRVID result_type;
3415 if (is_int_image) {
3416 result_type = v4int32ID;
3417 } else {
3418 result_type = getSPIRVType(Call->getType());
3419 }
3420
alan-baker3f772c02021-06-15 22:18:11 -04003421 uint32_t mask = spv::ImageOperandsLodMask |
3422 GetExtendMask(Call->getType(), is_int_image);
3423 Ops << result_type << Image << Coordinate << mask
SJW806a5d82020-07-15 12:51:38 -05003424 << getSPIRVInt32Constant(0);
3425
3426 RID = addSPIRVInst(spv::OpImageFetch, Ops);
3427
3428 if (is_int_image) {
3429 // Generate the bitcast.
3430 Ops.clear();
3431 Ops << Call->getType() << RID;
3432 RID = addSPIRVInst(spv::OpBitcast, Ops);
3433 }
3434 }
3435 break;
3436 }
3437
3438 case Builtins::kWriteImagef:
3439 case Builtins::kWriteImageh:
3440 case Builtins::kWriteImagei:
3441 case Builtins::kWriteImageui: {
3442 // write_image is mapped to OpImageWrite.
3443 //
3444 // Generate OpImageWrite.
3445 //
3446 // Ops[0] = Image ID
3447 // Ops[1] = Coordinate ID
3448 // Ops[2] = Texel ID
3449 // Ops[3] = (Optional) Image Operands Type (Literal Number)
3450 // Ops[4] ... Ops[n] = (Optional) Operands ID
3451 //
3452 SPIRVOperandVec Ops;
3453
3454 Value *Image = Call->getArgOperand(0);
3455 Value *Coordinate = Call->getArgOperand(1);
3456 Value *Texel = Call->getArgOperand(2);
3457
3458 SPIRVID TexelID = getSPIRVValue(Texel);
3459
3460 const bool is_int_image = IsIntImageType(Image->getType());
3461 if (is_int_image) {
3462 // Generate a bitcast to v4int and use it as the texel value.
3463 Ops << v4int32ID << TexelID;
3464 TexelID = addSPIRVInst(spv::OpBitcast, Ops);
3465 Ops.clear();
3466 }
3467 Ops << Image << Coordinate << TexelID;
alan-baker3f772c02021-06-15 22:18:11 -04003468 uint32_t mask = GetExtendMask(Texel->getType(), is_int_image);
3469 if (mask != 0)
3470 Ops << mask;
SJW806a5d82020-07-15 12:51:38 -05003471 RID = addSPIRVInst(spv::OpImageWrite, Ops);
alan-bakerf6bc8252020-09-23 14:58:55 -04003472
3473 // Image writes require StorageImageWriteWithoutFormat.
3474 addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
SJW806a5d82020-07-15 12:51:38 -05003475 break;
3476 }
3477
3478 case Builtins::kGetImageHeight:
3479 case Builtins::kGetImageWidth:
3480 case Builtins::kGetImageDepth:
3481 case Builtins::kGetImageDim: {
3482 // get_image_* is mapped to OpImageQuerySize or OpImageQuerySizeLod
3483 addCapability(spv::CapabilityImageQuery);
3484
3485 //
3486 // Generate OpImageQuerySize[Lod]
3487 //
3488 // Ops[0] = Image ID
3489 //
3490 // Result type has components equal to the dimensionality of the image,
3491 // plus 1 if the image is arrayed.
3492 //
3493 // %sizes = OpImageQuerySize[Lod] %uint[2|3|4] %im [%uint_0]
3494 SPIRVOperandVec Ops;
3495
3496 // Implement:
3497 // %sizes = OpImageQuerySize[Lod] %uint[2|3|4] %im [%uint_0]
3498 SPIRVID SizesTypeID;
3499
3500 Value *Image = Call->getArgOperand(0);
3501 const uint32_t dim = ImageDimensionality(Image->getType());
3502 const uint32_t components =
3503 dim + (IsArrayImageType(Image->getType()) ? 1 : 0);
3504 if (components == 1) {
3505 SizesTypeID = getSPIRVType(Type::getInt32Ty(Context));
3506 } else {
3507 SizesTypeID = getSPIRVType(
3508 FixedVectorType::get(Type::getInt32Ty(Context), components));
3509 }
3510 Ops << SizesTypeID << Image;
3511 spv::Op query_opcode = spv::OpImageQuerySize;
3512 if (IsSampledImageType(Image->getType())) {
3513 query_opcode = spv::OpImageQuerySizeLod;
3514 // Need explicit 0 for Lod operand.
3515 Ops << getSPIRVInt32Constant(0);
3516 }
3517
3518 RID = addSPIRVInst(query_opcode, Ops);
3519
3520 // May require an extra instruction to create the appropriate result of
3521 // the builtin function.
3522 if (FuncInfo.getType() == Builtins::kGetImageDim) {
3523 if (dim == 3) {
3524 // get_image_dim returns an int4 for 3D images.
3525 //
3526
3527 // Implement:
3528 // %result = OpCompositeConstruct %uint4 %sizes %uint_0
3529 Ops.clear();
3530 Ops << FixedVectorType::get(Type::getInt32Ty(Context), 4) << RID
3531 << getSPIRVInt32Constant(0);
3532
3533 RID = addSPIRVInst(spv::OpCompositeConstruct, Ops);
3534 } else if (dim != components) {
3535 // get_image_dim return an int2 regardless of the arrayedness of the
3536 // image. If the image is arrayed an element must be dropped from the
3537 // query result.
3538 //
3539
3540 // Implement:
3541 // %result = OpVectorShuffle %uint2 %sizes %sizes 0 1
3542 Ops.clear();
3543 Ops << FixedVectorType::get(Type::getInt32Ty(Context), 2) << RID << RID
3544 << 0 << 1;
3545
3546 RID = addSPIRVInst(spv::OpVectorShuffle, Ops);
3547 }
3548 } else if (components > 1) {
3549 // Implement:
3550 // %result = OpCompositeExtract %uint %sizes <component number>
3551 Ops.clear();
3552 Ops << Call->getType() << RID;
3553
3554 uint32_t component = 0;
3555 if (FuncInfo.getType() == Builtins::kGetImageHeight)
3556 component = 1;
3557 else if (FuncInfo.getType() == Builtins::kGetImageDepth)
3558 component = 2;
3559 Ops << component;
3560
3561 RID = addSPIRVInst(spv::OpCompositeExtract, Ops);
3562 }
3563 break;
3564 }
3565 default:
3566 llvm_unreachable("Unsupported Image builtin");
3567 }
3568
3569 return RID;
3570}
3571
3572SPIRVID
3573SPIRVProducerPass::GenerateSubgroupInstruction(CallInst *Call,
3574 const FunctionInfo &FuncInfo) {
3575 SPIRVID RID;
3576
3577 // requires SPIRV version 1.3 or greater
3578 if (SpvVersion() != SPIRVVersion::SPIRV_1_3) {
3579 // llvm_unreachable("SubGroups extension requires SPIRV 1.3 or greater");
3580 // TODO(sjw): error out gracefully
3581 }
3582
3583 auto loadBuiltin = [this, Call](spv::BuiltIn spvBI,
3584 spv::Capability spvCap =
3585 spv::CapabilityGroupNonUniform) {
3586 SPIRVOperandVec Ops;
3587 Ops << Call->getType() << this->getSPIRVBuiltin(spvBI, spvCap);
3588
3589 return addSPIRVInst(spv::OpLoad, Ops);
3590 };
3591
3592 spv::Op op = spv::OpNop;
3593 switch (FuncInfo.getType()) {
3594 case Builtins::kGetSubGroupSize:
3595 return loadBuiltin(spv::BuiltInSubgroupSize);
3596 case Builtins::kGetNumSubGroups:
3597 return loadBuiltin(spv::BuiltInNumSubgroups);
3598 case Builtins::kGetSubGroupId:
3599 return loadBuiltin(spv::BuiltInSubgroupId);
3600 case Builtins::kGetSubGroupLocalId:
3601 return loadBuiltin(spv::BuiltInSubgroupLocalInvocationId);
3602
3603 case Builtins::kSubGroupBroadcast:
3604 if (SpvVersion() < SPIRVVersion::SPIRV_1_5 &&
3605 !dyn_cast<ConstantInt>(Call->getOperand(1))) {
3606 llvm_unreachable("sub_group_broadcast requires constant lane Id for "
3607 "SPIRV version < 1.5");
3608 }
3609 addCapability(spv::CapabilityGroupNonUniformBallot);
3610 op = spv::OpGroupNonUniformBroadcast;
3611 break;
3612
3613 case Builtins::kSubGroupAll:
3614 addCapability(spv::CapabilityGroupNonUniformVote);
3615 op = spv::OpGroupNonUniformAll;
3616 break;
3617 case Builtins::kSubGroupAny:
3618 addCapability(spv::CapabilityGroupNonUniformVote);
3619 op = spv::OpGroupNonUniformAny;
3620 break;
3621 case Builtins::kSubGroupReduceAdd:
3622 case Builtins::kSubGroupScanExclusiveAdd:
3623 case Builtins::kSubGroupScanInclusiveAdd: {
3624 addCapability(spv::CapabilityGroupNonUniformArithmetic);
3625 if (FuncInfo.getParameter(0).type_id == Type::IntegerTyID) {
3626 op = spv::OpGroupNonUniformIAdd;
3627 } else {
3628 op = spv::OpGroupNonUniformFAdd;
3629 }
3630 break;
3631 }
3632 case Builtins::kSubGroupReduceMin:
3633 case Builtins::kSubGroupScanExclusiveMin:
3634 case Builtins::kSubGroupScanInclusiveMin: {
3635 addCapability(spv::CapabilityGroupNonUniformArithmetic);
3636 auto &param = FuncInfo.getParameter(0);
3637 if (param.type_id == Type::IntegerTyID) {
3638 op = param.is_signed ? spv::OpGroupNonUniformSMin
3639 : spv::OpGroupNonUniformUMin;
3640 } else {
3641 op = spv::OpGroupNonUniformFMin;
3642 }
3643 break;
3644 }
3645 case Builtins::kSubGroupReduceMax:
3646 case Builtins::kSubGroupScanExclusiveMax:
3647 case Builtins::kSubGroupScanInclusiveMax: {
3648 addCapability(spv::CapabilityGroupNonUniformArithmetic);
3649 auto &param = FuncInfo.getParameter(0);
3650 if (param.type_id == Type::IntegerTyID) {
3651 op = param.is_signed ? spv::OpGroupNonUniformSMax
3652 : spv::OpGroupNonUniformUMax;
3653 } else {
3654 op = spv::OpGroupNonUniformFMax;
3655 }
3656 break;
3657 }
3658
3659 case Builtins::kGetEnqueuedNumSubGroups:
3660 // TODO(sjw): requires CapabilityKernel (incompatible with Shader)
3661 case Builtins::kGetMaxSubGroupSize:
3662 // TODO(sjw): use SpecConstant, capability Kernel (incompatible with Shader)
3663 case Builtins::kSubGroupBarrier:
3664 case Builtins::kSubGroupReserveReadPipe:
3665 case Builtins::kSubGroupReserveWritePipe:
3666 case Builtins::kSubGroupCommitReadPipe:
3667 case Builtins::kSubGroupCommitWritePipe:
3668 case Builtins::kGetKernelSubGroupCountForNdrange:
3669 case Builtins::kGetKernelMaxSubGroupSizeForNdrange:
3670 default:
3671 Call->print(errs());
3672 llvm_unreachable("Unsupported sub_group operation");
3673 break;
3674 }
3675
3676 assert(op != spv::OpNop);
3677
3678 SPIRVOperandVec Operands;
3679
3680 //
3681 // Generate OpGroupNonUniform*
3682 //
3683 // Ops[0] = Result Type ID
3684 // Ops[1] = ScopeSubgroup
3685 // Ops[2] = Value ID
3686 // Ops[3] = Local ID
3687
3688 // The result type.
3689 Operands << Call->getType();
3690
3691 // Subgroup Scope
3692 Operands << getSPIRVInt32Constant(spv::ScopeSubgroup);
3693
3694 switch (FuncInfo.getType()) {
3695 case Builtins::kSubGroupReduceAdd:
3696 case Builtins::kSubGroupReduceMin:
3697 case Builtins::kSubGroupReduceMax:
3698 Operands << spv::GroupOperationReduce;
3699 break;
3700 case Builtins::kSubGroupScanExclusiveAdd:
3701 case Builtins::kSubGroupScanExclusiveMin:
3702 case Builtins::kSubGroupScanExclusiveMax:
3703 Operands << spv::GroupOperationExclusiveScan;
3704 break;
3705 case Builtins::kSubGroupScanInclusiveAdd:
3706 case Builtins::kSubGroupScanInclusiveMin:
3707 case Builtins::kSubGroupScanInclusiveMax:
3708 Operands << spv::GroupOperationInclusiveScan;
3709 break;
3710 default:
3711 break;
3712 }
3713
3714 for (Use &use : Call->arg_operands()) {
3715 Operands << use.get();
3716 }
3717
3718 return addSPIRVInst(op, Operands);
3719}
3720
3721SPIRVID SPIRVProducerPass::GenerateInstructionFromCall(CallInst *Call) {
3722 LLVMContext &Context = module->getContext();
3723
3724 auto &func_info = Builtins::Lookup(Call->getCalledFunction());
3725 auto func_type = func_info.getType();
3726
3727 if (BUILTIN_IN_GROUP(func_type, Clspv)) {
3728 return GenerateClspvInstruction(Call, func_info);
3729 } else if (BUILTIN_IN_GROUP(func_type, Image)) {
3730 return GenerateImageInstruction(Call, func_info);
3731 } else if (BUILTIN_IN_GROUP(func_type, SubgroupsKHR)) {
3732 return GenerateSubgroupInstruction(Call, func_info);
3733 }
3734
3735 SPIRVID RID;
3736
alan-baker5f2e88e2020-12-07 15:24:04 -05003737 switch (Call->getCalledFunction()->getIntrinsicID()) {
3738 case Intrinsic::ctlz: {
3739 // Implement as 31 - FindUMsb. Ignore the second operand of llvm.ctlz.
3740 SPIRVOperandVec Ops;
3741 Ops << Call->getType() << getOpExtInstImportID()
3742 << glsl::ExtInst::ExtInstFindUMsb << Call->getArgOperand(0);
3743 auto find_msb = addSPIRVInst(spv::OpExtInst, Ops);
3744
3745 Constant *thirty_one = ConstantInt::get(
3746 Call->getType(), Call->getType()->getScalarSizeInBits() - 1);
3747 Ops.clear();
3748 Ops << Call->getType() << thirty_one << find_msb;
3749 return addSPIRVInst(spv::OpISub, Ops);
3750 }
3751 case Intrinsic::cttz: {
3752 // Implement as:
3753 // lsb = FindILsb x
3754 // res = lsb == -1 ? width : lsb
3755 //
3756 // Ignore the second operand of llvm.cttz.
3757 SPIRVOperandVec Ops;
3758 Ops << Call->getType() << getOpExtInstImportID()
3759 << glsl::ExtInst::ExtInstFindILsb << Call->getArgOperand(0);
3760 auto find_lsb = addSPIRVInst(spv::OpExtInst, Ops);
3761
3762 auto neg_one = Constant::getAllOnesValue(Call->getType());
3763 auto i1_ty = Call->getType()->getWithNewBitWidth(1);
3764 auto width = ConstantInt::get(Call->getType(),
3765 Call->getType()->getScalarSizeInBits());
3766
3767 Ops.clear();
3768 Ops << i1_ty << find_lsb << neg_one;
3769 auto cmp = addSPIRVInst(spv::OpIEqual, Ops);
3770
3771 Ops.clear();
3772 Ops << Call->getType() << cmp << width << find_lsb;
3773 return addSPIRVInst(spv::OpSelect, Ops);
3774 }
3775
3776 default:
3777 break;
3778 }
3779
SJW806a5d82020-07-15 12:51:38 -05003780 switch (func_type) {
3781 case Builtins::kPopcount: {
3782 //
3783 // Generate OpBitCount
3784 //
3785 // Ops[0] = Result Type ID
3786 // Ops[1] = Base ID
3787 SPIRVOperandVec Ops;
3788 Ops << Call->getType() << Call->getOperand(0);
3789
3790 RID = addSPIRVInst(spv::OpBitCount, Ops);
3791 break;
3792 }
3793 default: {
3794 glsl::ExtInst EInst = getDirectOrIndirectExtInstEnum(func_info);
3795
alan-baker5f2e88e2020-12-07 15:24:04 -05003796 // Do not replace functions with implementations.
3797 if (EInst && Call->getCalledFunction()->isDeclaration()) {
SJW806a5d82020-07-15 12:51:38 -05003798 SPIRVID ExtInstImportID = getOpExtInstImportID();
3799
3800 //
3801 // Generate OpExtInst.
3802 //
3803
3804 // Ops[0] = Result Type ID
3805 // Ops[1] = Set ID (OpExtInstImport ID)
3806 // Ops[2] = Instruction Number (Literal Number)
3807 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
3808 SPIRVOperandVec Ops;
3809
3810 Ops << Call->getType() << ExtInstImportID << EInst;
3811
3812 for (auto &use : Call->arg_operands()) {
3813 Ops << use.get();
3814 }
3815
3816 RID = addSPIRVInst(spv::OpExtInst, Ops);
3817
3818 const auto IndirectExtInst = getIndirectExtInstEnum(func_info);
3819 if (IndirectExtInst != kGlslExtInstBad) {
SJW806a5d82020-07-15 12:51:38 -05003820 // Generate one more instruction that uses the result of the extended
3821 // instruction. Its result id is one more than the id of the
3822 // extended instruction.
3823 auto generate_extra_inst = [this, &Context, &Call,
3824 &RID](spv::Op opcode, Constant *constant) {
3825 //
3826 // Generate instruction like:
3827 // result = opcode constant <extinst-result>
3828 //
3829 // Ops[0] = Result Type ID
3830 // Ops[1] = Operand 0 ;; the constant, suitably splatted
3831 // Ops[2] = Operand 1 ;; the result of the extended instruction
3832 SPIRVOperandVec Ops;
3833
3834 Type *resultTy = Call->getType();
3835
3836 if (auto *vectorTy = dyn_cast<VectorType>(resultTy)) {
alan-baker931253b2020-08-20 17:15:38 -04003837 constant =
3838 ConstantVector::getSplat(vectorTy->getElementCount(), constant);
SJW806a5d82020-07-15 12:51:38 -05003839 }
3840 Ops << resultTy << constant << RID;
3841
3842 RID = addSPIRVInst(opcode, Ops);
3843 };
3844
SJW806a5d82020-07-15 12:51:38 -05003845 switch (IndirectExtInst) {
SJW806a5d82020-07-15 12:51:38 -05003846 case glsl::ExtInstAcos: // Implementing acospi
3847 case glsl::ExtInstAsin: // Implementing asinpi
3848 case glsl::ExtInstAtan: // Implementing atanpi
3849 case glsl::ExtInstAtan2: // Implementing atan2pi
3850 generate_extra_inst(
3851 spv::OpFMul,
alan-bakercc2bafb2020-11-02 08:30:18 -05003852 ConstantFP::get(Call->getType()->getScalarType(), kOneOverPi));
SJW806a5d82020-07-15 12:51:38 -05003853 break;
3854
3855 default:
3856 assert(false && "internally inconsistent");
3857 }
3858 }
3859 } else {
Pedro Olsen Ferreira208d1e72021-06-17 19:24:48 +01003860 switch (Call->getIntrinsicID()) {
3861 // These LLVM intrinsics have no SPV equivalent.
3862 // Because they are optimiser hints, we can safely discard them.
3863 case Intrinsic::experimental_noalias_scope_decl:
3864 break;
3865 default:
3866 // A real function call (not builtin)
3867 // Call instruction is deferred because it needs function's ID.
3868 RID = addSPIRVPlaceholder(Call);
3869 break;
3870 }
SJW806a5d82020-07-15 12:51:38 -05003871 }
3872
3873 break;
3874 }
3875 }
3876
3877 return RID;
3878}
3879
David Neto22f144c2017-06-12 14:26:21 -04003880void SPIRVProducerPass::GenerateInstruction(Instruction &I) {
David Neto22f144c2017-06-12 14:26:21 -04003881 ValueMapType &VMap = getValueMap();
SJW806a5d82020-07-15 12:51:38 -05003882 LLVMContext &Context = module->getContext();
David Neto22f144c2017-06-12 14:26:21 -04003883
SJW806a5d82020-07-15 12:51:38 -05003884 SPIRVID RID;
David Neto22f144c2017-06-12 14:26:21 -04003885
3886 switch (I.getOpcode()) {
3887 default: {
3888 if (Instruction::isCast(I.getOpcode())) {
3889 //
3890 // Generate SPIRV instructions for cast operators.
3891 //
3892
David Netod2de94a2017-08-28 17:27:47 -04003893 auto Ty = I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003894 auto OpTy = I.getOperand(0)->getType();
David Netod2de94a2017-08-28 17:27:47 -04003895 auto toI8 = Ty == Type::getInt8Ty(Context);
3896 auto fromI32 = OpTy == Type::getInt32Ty(Context);
James Price757dea82021-01-11 13:42:39 -05003897 // Handle zext, sext, uitofp, and sitofp with i1 type specially.
David Neto22f144c2017-06-12 14:26:21 -04003898 if ((I.getOpcode() == Instruction::ZExt ||
3899 I.getOpcode() == Instruction::SExt ||
James Price757dea82021-01-11 13:42:39 -05003900 I.getOpcode() == Instruction::UIToFP ||
3901 I.getOpcode() == Instruction::SIToFP) &&
alan-bakerb6b09dc2018-11-08 16:59:28 -05003902 OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003903 //
3904 // Generate OpSelect.
3905 //
3906
3907 // Ops[0] = Result Type ID
3908 // Ops[1] = Condition ID
3909 // Ops[2] = True Constant ID
3910 // Ops[3] = False Constant ID
SJWf93f5f32020-05-05 07:27:56 -05003911 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04003912
SJW01901d92020-05-21 08:58:31 -05003913 Ops << I.getType() << I.getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04003914
David Neto22f144c2017-06-12 14:26:21 -04003915 if (I.getOpcode() == Instruction::ZExt) {
SJW01901d92020-05-21 08:58:31 -05003916 Ops << ConstantInt::get(I.getType(), 1);
David Neto22f144c2017-06-12 14:26:21 -04003917 } else if (I.getOpcode() == Instruction::SExt) {
SJW01901d92020-05-21 08:58:31 -05003918 Ops << ConstantInt::getSigned(I.getType(), -1);
James Price757dea82021-01-11 13:42:39 -05003919 } else if (I.getOpcode() == Instruction::UIToFP) {
James Price96bd3d92020-11-23 09:01:57 -05003920 Ops << ConstantFP::get(I.getType(), 1.0);
James Price757dea82021-01-11 13:42:39 -05003921 } else if (I.getOpcode() == Instruction::SIToFP) {
3922 Ops << ConstantFP::get(I.getType(), -1.0);
David Neto22f144c2017-06-12 14:26:21 -04003923 }
David Neto22f144c2017-06-12 14:26:21 -04003924
David Neto22f144c2017-06-12 14:26:21 -04003925 if (I.getOpcode() == Instruction::ZExt) {
SJW01901d92020-05-21 08:58:31 -05003926 Ops << Constant::getNullValue(I.getType());
David Neto22f144c2017-06-12 14:26:21 -04003927 } else if (I.getOpcode() == Instruction::SExt) {
SJW01901d92020-05-21 08:58:31 -05003928 Ops << Constant::getNullValue(I.getType());
David Neto22f144c2017-06-12 14:26:21 -04003929 } else {
James Price96bd3d92020-11-23 09:01:57 -05003930 Ops << ConstantFP::get(I.getType(), 0.0);
David Neto22f144c2017-06-12 14:26:21 -04003931 }
David Neto22f144c2017-06-12 14:26:21 -04003932
SJWf93f5f32020-05-05 07:27:56 -05003933 RID = addSPIRVInst(spv::OpSelect, Ops);
alan-bakerb39c8262019-03-08 14:03:37 -05003934 } else if (!clspv::Option::Int8Support() &&
3935 I.getOpcode() == Instruction::Trunc && fromI32 && toI8) {
David Netod2de94a2017-08-28 17:27:47 -04003936 // The SPIR-V target type is a 32-bit int. Keep only the bottom
3937 // 8 bits.
3938 // Before:
3939 // %result = trunc i32 %a to i8
3940 // After
3941 // %result = OpBitwiseAnd %uint %a %uint_255
3942
SJWf93f5f32020-05-05 07:27:56 -05003943 SPIRVOperandVec Ops;
David Netod2de94a2017-08-28 17:27:47 -04003944
SJW806a5d82020-07-15 12:51:38 -05003945 Ops << OpTy << I.getOperand(0) << getSPIRVInt32Constant(255);
David Netod2de94a2017-08-28 17:27:47 -04003946
SJWf93f5f32020-05-05 07:27:56 -05003947 RID = addSPIRVInst(spv::OpBitwiseAnd, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003948 } else {
3949 // Ops[0] = Result Type ID
3950 // Ops[1] = Source Value ID
SJWf93f5f32020-05-05 07:27:56 -05003951 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04003952
SJW01901d92020-05-21 08:58:31 -05003953 Ops << I.getType() << I.getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04003954
SJWf93f5f32020-05-05 07:27:56 -05003955 RID = addSPIRVInst(GetSPIRVCastOpcode(I), Ops);
David Neto22f144c2017-06-12 14:26:21 -04003956 }
3957 } else if (isa<BinaryOperator>(I)) {
3958 //
3959 // Generate SPIRV instructions for binary operators.
3960 //
3961
3962 // Handle xor with i1 type specially.
3963 if (I.getOpcode() == Instruction::Xor &&
3964 I.getType() == Type::getInt1Ty(Context) &&
Kévin Petit24272b62018-10-18 19:16:12 +00003965 ((isa<ConstantInt>(I.getOperand(0)) &&
3966 !cast<ConstantInt>(I.getOperand(0))->isZero()) ||
3967 (isa<ConstantInt>(I.getOperand(1)) &&
3968 !cast<ConstantInt>(I.getOperand(1))->isZero()))) {
David Neto22f144c2017-06-12 14:26:21 -04003969 //
3970 // Generate OpLogicalNot.
3971 //
3972 // Ops[0] = Result Type ID
3973 // Ops[1] = Operand
SJWf93f5f32020-05-05 07:27:56 -05003974 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04003975
SJW01901d92020-05-21 08:58:31 -05003976 Ops << I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003977
3978 Value *CondV = I.getOperand(0);
3979 if (isa<Constant>(I.getOperand(0))) {
3980 CondV = I.getOperand(1);
3981 }
SJW01901d92020-05-21 08:58:31 -05003982 Ops << CondV;
David Neto22f144c2017-06-12 14:26:21 -04003983
SJWf93f5f32020-05-05 07:27:56 -05003984 RID = addSPIRVInst(spv::OpLogicalNot, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003985 } else {
3986 // Ops[0] = Result Type ID
3987 // Ops[1] = Operand 0
3988 // Ops[2] = Operand 1
SJWf93f5f32020-05-05 07:27:56 -05003989 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04003990
SJW01901d92020-05-21 08:58:31 -05003991 Ops << I.getType() << I.getOperand(0) << I.getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04003992
SJWf93f5f32020-05-05 07:27:56 -05003993 RID = addSPIRVInst(GetSPIRVBinaryOpcode(I), Ops);
David Neto22f144c2017-06-12 14:26:21 -04003994 }
alan-bakerc9c55ae2019-12-02 16:01:27 -05003995 } else if (I.getOpcode() == Instruction::FNeg) {
3996 // The only unary operator.
3997 //
3998 // Ops[0] = Result Type ID
3999 // Ops[1] = Operand 0
SJW01901d92020-05-21 08:58:31 -05004000 SPIRVOperandVec Ops;
alan-bakerc9c55ae2019-12-02 16:01:27 -05004001
SJW01901d92020-05-21 08:58:31 -05004002 Ops << I.getType() << I.getOperand(0);
4003 RID = addSPIRVInst(spv::OpFNegate, Ops);
Marco Antognini68e5c512020-09-09 16:08:57 +01004004 } else if (I.getOpcode() == Instruction::Unreachable) {
4005 RID = addSPIRVInst(spv::OpUnreachable);
David Neto22f144c2017-06-12 14:26:21 -04004006 } else {
4007 I.print(errs());
4008 llvm_unreachable("Unsupported instruction???");
4009 }
4010 break;
4011 }
4012 case Instruction::GetElementPtr: {
4013 auto &GlobalConstArgSet = getGlobalConstArgSet();
4014
4015 //
4016 // Generate OpAccessChain.
4017 //
4018 GetElementPtrInst *GEP = cast<GetElementPtrInst>(&I);
4019
4020 //
4021 // Generate OpAccessChain.
4022 //
4023
4024 // Ops[0] = Result Type ID
4025 // Ops[1] = Base ID
4026 // Ops[2] ... Ops[n] = Indexes ID
SJWf93f5f32020-05-05 07:27:56 -05004027 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004028
alan-bakerb6b09dc2018-11-08 16:59:28 -05004029 PointerType *ResultType = cast<PointerType>(GEP->getType());
David Neto22f144c2017-06-12 14:26:21 -04004030 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate ||
4031 GlobalConstArgSet.count(GEP->getPointerOperand())) {
4032 // Use pointer type with private address space for global constant.
4033 Type *EleTy = I.getType()->getPointerElementType();
David Neto1a1a0582017-07-07 12:01:44 -04004034 ResultType = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
David Neto22f144c2017-06-12 14:26:21 -04004035 }
David Neto257c3892018-04-11 13:19:45 -04004036
SJW01901d92020-05-21 08:58:31 -05004037 Ops << ResultType;
David Neto22f144c2017-06-12 14:26:21 -04004038
David Neto862b7d82018-06-14 18:48:37 -04004039 // Generate the base pointer.
SJW01901d92020-05-21 08:58:31 -05004040 Ops << GEP->getPointerOperand();
David Neto22f144c2017-06-12 14:26:21 -04004041
David Neto862b7d82018-06-14 18:48:37 -04004042 // TODO(dneto): Simplify the following?
David Neto22f144c2017-06-12 14:26:21 -04004043
4044 //
4045 // Follows below rules for gep.
4046 //
David Neto862b7d82018-06-14 18:48:37 -04004047 // 1. If gep's first index is 0 generate OpAccessChain and ignore gep's
4048 // first index.
David Neto22f144c2017-06-12 14:26:21 -04004049 // 2. If gep's first index is not 0, generate OpPtrAccessChain and use gep's
4050 // first index.
4051 // 3. If gep's first index is not constant, generate OpPtrAccessChain and
4052 // use gep's first index.
4053 // 4. If it is not above case 1, 2 and 3, generate OpAccessChain and use
4054 // gep's first index.
4055 //
4056 spv::Op Opcode = spv::OpAccessChain;
4057 unsigned offset = 0;
4058 if (ConstantInt *CstInt = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
David Neto862b7d82018-06-14 18:48:37 -04004059 if (CstInt->getZExtValue() == 0) {
David Neto22f144c2017-06-12 14:26:21 -04004060 offset = 1;
David Neto862b7d82018-06-14 18:48:37 -04004061 } else if (CstInt->getZExtValue() != 0) {
David Neto22f144c2017-06-12 14:26:21 -04004062 Opcode = spv::OpPtrAccessChain;
David Neto22f144c2017-06-12 14:26:21 -04004063 }
David Neto862b7d82018-06-14 18:48:37 -04004064 } else {
David Neto22f144c2017-06-12 14:26:21 -04004065 Opcode = spv::OpPtrAccessChain;
David Neto1a1a0582017-07-07 12:01:44 -04004066 }
4067
4068 if (Opcode == spv::OpPtrAccessChain) {
alan-baker7506abb2020-09-10 15:02:55 -04004069 // Shader validation in the SPIR-V spec requires that the base pointer to
4070 // OpPtrAccessChain (in StorageBuffer storage class) be decorated with
4071 // ArrayStride.
alan-baker5b86ed72019-02-15 08:26:50 -05004072 auto address_space = ResultType->getAddressSpace();
4073 setVariablePointersCapabilities(address_space);
4074 switch (GetStorageClass(address_space)) {
Alan Bakerfcda9482018-10-02 17:09:59 -04004075 case spv::StorageClassStorageBuffer:
David Neto1a1a0582017-07-07 12:01:44 -04004076 // Save the need to generate an ArrayStride decoration. But defer
4077 // generation until later, so we only make one decoration.
alan-baker7506abb2020-09-10 15:02:55 -04004078 getTypesNeedingArrayStride().insert(GEP->getPointerOperandType());
4079 break;
4080 case spv::StorageClassWorkgroup:
Alan Bakerfcda9482018-10-02 17:09:59 -04004081 break;
4082 default:
alan-baker7506abb2020-09-10 15:02:55 -04004083 llvm_unreachable(
4084 "OpPtrAccessChain is not supported for this storage class");
Alan Bakerfcda9482018-10-02 17:09:59 -04004085 break;
David Neto1a1a0582017-07-07 12:01:44 -04004086 }
David Neto22f144c2017-06-12 14:26:21 -04004087 }
4088
4089 for (auto II = GEP->idx_begin() + offset; II != GEP->idx_end(); II++) {
SJW01901d92020-05-21 08:58:31 -05004090 Ops << *II;
David Neto22f144c2017-06-12 14:26:21 -04004091 }
4092
SJWf93f5f32020-05-05 07:27:56 -05004093 RID = addSPIRVInst(Opcode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004094 break;
4095 }
4096 case Instruction::ExtractValue: {
4097 ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
4098 // Ops[0] = Result Type ID
4099 // Ops[1] = Composite ID
4100 // Ops[2] ... Ops[n] = Indexes (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05004101 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004102
SJW01901d92020-05-21 08:58:31 -05004103 Ops << I.getType();
David Neto22f144c2017-06-12 14:26:21 -04004104
SJW01901d92020-05-21 08:58:31 -05004105 Ops << EVI->getAggregateOperand();
David Neto22f144c2017-06-12 14:26:21 -04004106
4107 for (auto &Index : EVI->indices()) {
SJW01901d92020-05-21 08:58:31 -05004108 Ops << Index;
David Neto22f144c2017-06-12 14:26:21 -04004109 }
4110
SJWf93f5f32020-05-05 07:27:56 -05004111 RID = addSPIRVInst(spv::OpCompositeExtract, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004112 break;
4113 }
4114 case Instruction::InsertValue: {
4115 InsertValueInst *IVI = cast<InsertValueInst>(&I);
4116 // Ops[0] = Result Type ID
4117 // Ops[1] = Object ID
4118 // Ops[2] = Composite ID
4119 // Ops[3] ... Ops[n] = Indexes (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05004120 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004121
SJW01901d92020-05-21 08:58:31 -05004122 Ops << I.getType() << IVI->getInsertedValueOperand()
4123 << IVI->getAggregateOperand();
David Neto22f144c2017-06-12 14:26:21 -04004124
4125 for (auto &Index : IVI->indices()) {
SJW01901d92020-05-21 08:58:31 -05004126 Ops << Index;
David Neto22f144c2017-06-12 14:26:21 -04004127 }
4128
SJWf93f5f32020-05-05 07:27:56 -05004129 RID = addSPIRVInst(spv::OpCompositeInsert, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004130 break;
4131 }
4132 case Instruction::Select: {
4133 //
4134 // Generate OpSelect.
4135 //
4136
4137 // Ops[0] = Result Type ID
4138 // Ops[1] = Condition ID
4139 // Ops[2] = True Constant ID
4140 // Ops[3] = False Constant ID
SJWf93f5f32020-05-05 07:27:56 -05004141 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004142
4143 // Find SPIRV instruction for parameter type.
4144 auto Ty = I.getType();
4145 if (Ty->isPointerTy()) {
4146 auto PointeeTy = Ty->getPointerElementType();
4147 if (PointeeTy->isStructTy() &&
4148 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
4149 Ty = PointeeTy;
alan-baker5b86ed72019-02-15 08:26:50 -05004150 } else {
4151 // Selecting between pointers requires variable pointers.
4152 setVariablePointersCapabilities(Ty->getPointerAddressSpace());
4153 if (!hasVariablePointers() && !selectFromSameObject(&I)) {
SJW01901d92020-05-21 08:58:31 -05004154 setVariablePointers();
alan-baker5b86ed72019-02-15 08:26:50 -05004155 }
David Neto22f144c2017-06-12 14:26:21 -04004156 }
4157 }
4158
SJW01901d92020-05-21 08:58:31 -05004159 Ops << Ty << I.getOperand(0) << I.getOperand(1) << I.getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04004160
SJWf93f5f32020-05-05 07:27:56 -05004161 RID = addSPIRVInst(spv::OpSelect, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004162 break;
4163 }
4164 case Instruction::ExtractElement: {
4165 // Handle <4 x i8> type manually.
4166 Type *CompositeTy = I.getOperand(0)->getType();
4167 if (is4xi8vec(CompositeTy)) {
4168 //
4169 // Generate OpShiftRightLogical and OpBitwiseAnd for extractelement with
4170 // <4 x i8>.
4171 //
4172
4173 //
4174 // Generate OpShiftRightLogical
4175 //
4176 // Ops[0] = Result Type ID
4177 // Ops[1] = Operand 0
4178 // Ops[2] = Operand 1
4179 //
SJWf93f5f32020-05-05 07:27:56 -05004180 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004181
SJW01901d92020-05-21 08:58:31 -05004182 Ops << CompositeTy << I.getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04004183
SJW01901d92020-05-21 08:58:31 -05004184 SPIRVID Op1ID = 0;
David Neto22f144c2017-06-12 14:26:21 -04004185 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
4186 // Handle constant index.
SJW806a5d82020-07-15 12:51:38 -05004187 uint32_t Idx = static_cast<uint32_t>(CI->getZExtValue());
4188 Op1ID = getSPIRVInt32Constant(Idx * 8);
David Neto22f144c2017-06-12 14:26:21 -04004189 } else {
4190 // Handle variable index.
SJWf93f5f32020-05-05 07:27:56 -05004191 SPIRVOperandVec TmpOps;
David Neto22f144c2017-06-12 14:26:21 -04004192
SJW806a5d82020-07-15 12:51:38 -05004193 TmpOps << Type::getInt32Ty(Context) << I.getOperand(1)
4194 << getSPIRVInt32Constant(8);
David Neto22f144c2017-06-12 14:26:21 -04004195
SJWf93f5f32020-05-05 07:27:56 -05004196 Op1ID = addSPIRVInst(spv::OpIMul, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04004197 }
SJW01901d92020-05-21 08:58:31 -05004198 Ops << Op1ID;
David Neto22f144c2017-06-12 14:26:21 -04004199
SJW01901d92020-05-21 08:58:31 -05004200 SPIRVID ShiftID = addSPIRVInst(spv::OpShiftRightLogical, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004201
4202 //
4203 // Generate OpBitwiseAnd
4204 //
4205 // Ops[0] = Result Type ID
4206 // Ops[1] = Operand 0
4207 // Ops[2] = Operand 1
4208 //
4209 Ops.clear();
4210
SJW806a5d82020-07-15 12:51:38 -05004211 Ops << CompositeTy << ShiftID << getSPIRVInt32Constant(0xFF);
David Neto22f144c2017-06-12 14:26:21 -04004212
SJWf93f5f32020-05-05 07:27:56 -05004213 RID = addSPIRVInst(spv::OpBitwiseAnd, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004214 break;
4215 }
4216
4217 // Ops[0] = Result Type ID
4218 // Ops[1] = Composite ID
4219 // Ops[2] ... Ops[n] = Indexes (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05004220 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004221
SJW01901d92020-05-21 08:58:31 -05004222 Ops << I.getType() << I.getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04004223
4224 spv::Op Opcode = spv::OpCompositeExtract;
4225 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
SJW01901d92020-05-21 08:58:31 -05004226 Ops << static_cast<uint32_t>(CI->getZExtValue());
David Neto22f144c2017-06-12 14:26:21 -04004227 } else {
SJW01901d92020-05-21 08:58:31 -05004228 Ops << I.getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04004229 Opcode = spv::OpVectorExtractDynamic;
4230 }
4231
SJWf93f5f32020-05-05 07:27:56 -05004232 RID = addSPIRVInst(Opcode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004233 break;
4234 }
4235 case Instruction::InsertElement: {
4236 // Handle <4 x i8> type manually.
4237 Type *CompositeTy = I.getOperand(0)->getType();
4238 if (is4xi8vec(CompositeTy)) {
SJW806a5d82020-07-15 12:51:38 -05004239 SPIRVID CstFFID = getSPIRVInt32Constant(0xFF);
David Neto22f144c2017-06-12 14:26:21 -04004240
SJW01901d92020-05-21 08:58:31 -05004241 SPIRVID ShiftAmountID = 0;
David Neto22f144c2017-06-12 14:26:21 -04004242 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
4243 // Handle constant index.
SJW806a5d82020-07-15 12:51:38 -05004244 uint32_t Idx = static_cast<uint32_t>(CI->getZExtValue());
4245 ShiftAmountID = getSPIRVInt32Constant(Idx * 8);
David Neto22f144c2017-06-12 14:26:21 -04004246 } else {
4247 // Handle variable index.
SJWf93f5f32020-05-05 07:27:56 -05004248 SPIRVOperandVec TmpOps;
David Neto22f144c2017-06-12 14:26:21 -04004249
SJW806a5d82020-07-15 12:51:38 -05004250 TmpOps << Type::getInt32Ty(Context) << I.getOperand(2)
4251 << getSPIRVInt32Constant(8);
David Neto22f144c2017-06-12 14:26:21 -04004252
SJWf93f5f32020-05-05 07:27:56 -05004253 ShiftAmountID = addSPIRVInst(spv::OpIMul, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04004254 }
4255
4256 //
4257 // Generate mask operations.
4258 //
4259
4260 // ShiftLeft mask according to index of insertelement.
SJWf93f5f32020-05-05 07:27:56 -05004261 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004262
SJW01901d92020-05-21 08:58:31 -05004263 Ops << CompositeTy << CstFFID << ShiftAmountID;
David Neto22f144c2017-06-12 14:26:21 -04004264
SJW01901d92020-05-21 08:58:31 -05004265 SPIRVID MaskID = addSPIRVInst(spv::OpShiftLeftLogical, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004266
4267 // Inverse mask.
4268 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05004269 Ops << CompositeTy << MaskID;
David Neto22f144c2017-06-12 14:26:21 -04004270
SJW01901d92020-05-21 08:58:31 -05004271 SPIRVID InvMaskID = addSPIRVInst(spv::OpNot, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004272
4273 // Apply mask.
4274 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05004275 Ops << CompositeTy << I.getOperand(0) << InvMaskID;
David Neto22f144c2017-06-12 14:26:21 -04004276
SJW01901d92020-05-21 08:58:31 -05004277 SPIRVID OrgValID = addSPIRVInst(spv::OpBitwiseAnd, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004278
4279 // Create correct value according to index of insertelement.
4280 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05004281 Ops << CompositeTy << I.getOperand(1) << ShiftAmountID;
David Neto22f144c2017-06-12 14:26:21 -04004282
SJW01901d92020-05-21 08:58:31 -05004283 SPIRVID InsertValID = addSPIRVInst(spv::OpShiftLeftLogical, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004284
4285 // Insert value to original value.
4286 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05004287 Ops << CompositeTy << OrgValID << InsertValID;
David Neto22f144c2017-06-12 14:26:21 -04004288
SJWf93f5f32020-05-05 07:27:56 -05004289 RID = addSPIRVInst(spv::OpBitwiseOr, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004290 break;
4291 }
4292
SJWf93f5f32020-05-05 07:27:56 -05004293 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004294
James Priced26efea2018-06-09 23:28:32 +01004295 // Ops[0] = Result Type ID
SJW01901d92020-05-21 08:58:31 -05004296 Ops << I.getType();
David Neto22f144c2017-06-12 14:26:21 -04004297
4298 spv::Op Opcode = spv::OpCompositeInsert;
4299 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
David Neto257c3892018-04-11 13:19:45 -04004300 const auto value = CI->getZExtValue();
4301 assert(value <= UINT32_MAX);
James Priced26efea2018-06-09 23:28:32 +01004302 // Ops[1] = Object ID
4303 // Ops[2] = Composite ID
4304 // Ops[3] ... Ops[n] = Indexes (Literal Number)
SJW01901d92020-05-21 08:58:31 -05004305 Ops << I.getOperand(1) << I.getOperand(0) << static_cast<uint32_t>(value);
David Neto22f144c2017-06-12 14:26:21 -04004306 } else {
James Priced26efea2018-06-09 23:28:32 +01004307 // Ops[1] = Composite ID
4308 // Ops[2] = Object ID
4309 // Ops[3] ... Ops[n] = Indexes (Literal Number)
SJW01901d92020-05-21 08:58:31 -05004310 Ops << I.getOperand(0) << I.getOperand(1) << I.getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04004311 Opcode = spv::OpVectorInsertDynamic;
4312 }
4313
SJWf93f5f32020-05-05 07:27:56 -05004314 RID = addSPIRVInst(Opcode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004315 break;
4316 }
4317 case Instruction::ShuffleVector: {
4318 // Ops[0] = Result Type ID
4319 // Ops[1] = Vector 1 ID
4320 // Ops[2] = Vector 2 ID
4321 // Ops[3] ... Ops[n] = Components (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05004322 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004323
SJW01901d92020-05-21 08:58:31 -05004324 Ops << I.getType() << I.getOperand(0) << I.getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04004325
alan-bakerc9666712020-04-01 16:31:21 -04004326 auto shuffle = cast<ShuffleVectorInst>(&I);
4327 SmallVector<int, 4> mask;
4328 shuffle->getShuffleMask(mask);
4329 for (auto i : mask) {
4330 if (i == UndefMaskElem) {
4331 if (clspv::Option::HackUndef())
4332 // Use 0 instead of undef.
SJW01901d92020-05-21 08:58:31 -05004333 Ops << 0;
alan-bakerc9666712020-04-01 16:31:21 -04004334 else
4335 // Undef for shuffle in SPIR-V.
SJW01901d92020-05-21 08:58:31 -05004336 Ops << 0xffffffff;
David Neto22f144c2017-06-12 14:26:21 -04004337 } else {
SJW01901d92020-05-21 08:58:31 -05004338 Ops << i;
David Neto22f144c2017-06-12 14:26:21 -04004339 }
4340 }
4341
SJWf93f5f32020-05-05 07:27:56 -05004342 RID = addSPIRVInst(spv::OpVectorShuffle, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004343 break;
4344 }
4345 case Instruction::ICmp:
4346 case Instruction::FCmp: {
4347 CmpInst *CmpI = cast<CmpInst>(&I);
4348
David Netod4ca2e62017-07-06 18:47:35 -04004349 // Pointer equality is invalid.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004350 Type *ArgTy = CmpI->getOperand(0)->getType();
David Netod4ca2e62017-07-06 18:47:35 -04004351 if (isa<PointerType>(ArgTy)) {
4352 CmpI->print(errs());
alan-baker21574d32020-01-29 16:00:31 -05004353 std::string name = I.getParent()->getParent()->getName().str();
David Netod4ca2e62017-07-06 18:47:35 -04004354 errs()
4355 << "\nPointer equality test is not supported by SPIR-V for Vulkan, "
4356 << "in function " << name << "\n";
4357 llvm_unreachable("Pointer equality check is invalid");
4358 break;
4359 }
4360
SJWf93f5f32020-05-05 07:27:56 -05004361 SPIRVOperandVec Ops;
alan-baker15106572020-11-06 15:08:10 -05004362 if (CmpI->getPredicate() == CmpInst::FCMP_ORD ||
4363 CmpI->getPredicate() == CmpInst::FCMP_UNO) {
4364 // Implement ordered and unordered comparisons are OpIsNan instructions.
4365 // Optimize the constants to simplify the resulting code.
4366 auto lhs = CmpI->getOperand(0);
4367 auto rhs = CmpI->getOperand(1);
4368 auto const_lhs = dyn_cast_or_null<Constant>(lhs);
4369 auto const_rhs = dyn_cast_or_null<Constant>(rhs);
4370 if ((const_lhs && const_lhs->isNaN()) ||
4371 (const_rhs && const_rhs->isNaN())) {
4372 // Result is a constant, false of ordered, true for unordered.
4373 if (CmpI->getPredicate() == CmpInst::FCMP_ORD) {
4374 RID = getSPIRVConstant(ConstantInt::getFalse(CmpI->getType()));
4375 } else {
4376 RID = getSPIRVConstant(ConstantInt::getTrue(CmpI->getType()));
4377 }
4378 break;
4379 }
4380 SPIRVID lhs_id;
4381 SPIRVID rhs_id;
4382 if (!const_lhs) {
4383 // Generate OpIsNan for the lhs.
4384 Ops.clear();
4385 Ops << CmpI->getType() << lhs;
4386 lhs_id = addSPIRVInst(spv::OpIsNan, Ops);
4387 }
4388 if (!const_rhs) {
4389 // Generate OpIsNan for the rhs.
4390 Ops.clear();
4391 Ops << CmpI->getType() << rhs;
4392 rhs_id = addSPIRVInst(spv::OpIsNan, Ops);
4393 }
4394 if (lhs_id.isValid() && rhs_id.isValid()) {
4395 // Or the results for the lhs and rhs.
4396 Ops.clear();
4397 Ops << CmpI->getType() << lhs_id << rhs_id;
4398 RID = addSPIRVInst(spv::OpLogicalOr, Ops);
4399 } else {
4400 RID = lhs_id.isValid() ? lhs_id : rhs_id;
4401 }
4402 if (CmpI->getPredicate() == CmpInst::FCMP_ORD) {
4403 // For ordered comparisons, invert the intermediate result.
4404 Ops.clear();
4405 Ops << CmpI->getType() << RID;
4406 RID = addSPIRVInst(spv::OpLogicalNot, Ops);
4407 }
4408 break;
4409 } else {
4410 // Remaining comparisons map directly to SPIR-V opcodes.
4411 // Ops[0] = Result Type ID
4412 // Ops[1] = Operand 1 ID
4413 // Ops[2] = Operand 2 ID
4414 Ops << CmpI->getType() << CmpI->getOperand(0) << CmpI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04004415
alan-baker15106572020-11-06 15:08:10 -05004416 spv::Op Opcode = GetSPIRVCmpOpcode(CmpI);
4417 RID = addSPIRVInst(Opcode, Ops);
4418 }
David Neto22f144c2017-06-12 14:26:21 -04004419 break;
4420 }
4421 case Instruction::Br: {
SJW88ed5fe2020-05-11 12:40:57 -05004422 // Branch instruction is deferred because it needs label's ID.
4423 BasicBlock *BrBB = I.getParent();
4424 if (ContinueBlocks.count(BrBB) || MergeBlocks.count(BrBB)) {
4425 // Placeholder for Merge operation
4426 RID = addSPIRVPlaceholder(&I);
4427 }
4428 RID = addSPIRVPlaceholder(&I);
David Neto22f144c2017-06-12 14:26:21 -04004429 break;
4430 }
4431 case Instruction::Switch: {
4432 I.print(errs());
4433 llvm_unreachable("Unsupported instruction???");
4434 break;
4435 }
4436 case Instruction::IndirectBr: {
4437 I.print(errs());
4438 llvm_unreachable("Unsupported instruction???");
4439 break;
4440 }
4441 case Instruction::PHI: {
SJW88ed5fe2020-05-11 12:40:57 -05004442 // PHI instruction is deferred because it needs label's ID.
4443 RID = addSPIRVPlaceholder(&I);
David Neto22f144c2017-06-12 14:26:21 -04004444 break;
4445 }
4446 case Instruction::Alloca: {
4447 //
4448 // Generate OpVariable.
4449 //
4450 // Ops[0] : Result Type ID
4451 // Ops[1] : Storage Class
SJWf93f5f32020-05-05 07:27:56 -05004452 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004453
SJW01901d92020-05-21 08:58:31 -05004454 Ops << I.getType() << spv::StorageClassFunction;
David Neto22f144c2017-06-12 14:26:21 -04004455
SJWf93f5f32020-05-05 07:27:56 -05004456 RID = addSPIRVInst(spv::OpVariable, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004457 break;
4458 }
4459 case Instruction::Load: {
4460 LoadInst *LD = cast<LoadInst>(&I);
4461 //
4462 // Generate OpLoad.
4463 //
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04004464
alan-baker5b86ed72019-02-15 08:26:50 -05004465 if (LD->getType()->isPointerTy()) {
4466 // Loading a pointer requires variable pointers.
4467 setVariablePointersCapabilities(LD->getType()->getPointerAddressSpace());
4468 }
David Neto22f144c2017-06-12 14:26:21 -04004469
SJW01901d92020-05-21 08:58:31 -05004470 SPIRVID PointerID = getSPIRVValue(LD->getPointerOperand());
David Netoa60b00b2017-09-15 16:34:09 -04004471 // This is a hack to work around what looks like a driver bug.
4472 // When we're loading from the special variable holding the WorkgroupSize
David Neto0a2f98d2017-09-15 19:38:40 -04004473 // builtin value, use an OpBitWiseAnd of the value's ID rather than
4474 // generating a load.
David Neto66cfe642018-03-24 06:13:56 -07004475 // TODO(dneto): Remove this awful hack once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -04004476 if (PointerID == WorkgroupSizeVarID) {
David Neto0a2f98d2017-09-15 19:38:40 -04004477 // Generate a bitwise-and of the original value with itself.
4478 // We should have been able to get away with just an OpCopyObject,
4479 // but we need something more complex to get past certain driver bugs.
4480 // This is ridiculous, but necessary.
4481 // TODO(dneto): Revisit this once drivers fix their bugs.
4482
SJWf93f5f32020-05-05 07:27:56 -05004483 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05004484 Ops << LD->getType() << WorkgroupSizeValueID << WorkgroupSizeValueID;
David Neto0a2f98d2017-09-15 19:38:40 -04004485
SJWf93f5f32020-05-05 07:27:56 -05004486 RID = addSPIRVInst(spv::OpBitwiseAnd, Ops);
David Netoa60b00b2017-09-15 16:34:09 -04004487 break;
4488 }
4489
4490 // This is the normal path. Generate a load.
4491
David Neto22f144c2017-06-12 14:26:21 -04004492 // Ops[0] = Result Type ID
4493 // Ops[1] = Pointer ID
4494 // Ops[2] ... Ops[n] = Optional Memory Access
4495 //
4496 // TODO: Do we need to implement Optional Memory Access???
David Neto0a2f98d2017-09-15 19:38:40 -04004497
alan-baker3f772c02021-06-15 22:18:11 -04004498 auto ptr = LD->getPointerOperand();
4499 auto ptr_ty = ptr->getType();
4500 SPIRVID result_type_id;
4501 if (LD->getType()->isPointerTy()) {
4502 result_type_id = getSPIRVType(LD->getType());
4503 } else {
4504 auto layout = PointerRequiresLayout(ptr_ty->getPointerAddressSpace());
4505 result_type_id = getSPIRVType(LD->getType(), layout);
4506 }
SJWf93f5f32020-05-05 07:27:56 -05004507 SPIRVOperandVec Ops;
alan-baker3f772c02021-06-15 22:18:11 -04004508 Ops << result_type_id << ptr;
David Neto22f144c2017-06-12 14:26:21 -04004509
SJWf93f5f32020-05-05 07:27:56 -05004510 RID = addSPIRVInst(spv::OpLoad, Ops);
alan-baker3f772c02021-06-15 22:18:11 -04004511
4512 auto no_layout_id = getSPIRVType(LD->getType());
4513 if (Option::SpvVersion() >= SPIRVVersion::SPIRV_1_4 &&
4514 no_layout_id.get() != result_type_id.get()) {
4515 // Generate an OpCopyLogical to convert from the laid out type to a
4516 // non-laid out type.
4517 Ops.clear();
4518 Ops << no_layout_id << RID;
4519 RID = addSPIRVInst(spv::OpCopyLogical, Ops);
4520 }
David Neto22f144c2017-06-12 14:26:21 -04004521 break;
4522 }
4523 case Instruction::Store: {
4524 StoreInst *ST = cast<StoreInst>(&I);
4525 //
4526 // Generate OpStore.
4527 //
4528
alan-baker5b86ed72019-02-15 08:26:50 -05004529 if (ST->getValueOperand()->getType()->isPointerTy()) {
4530 // Storing a pointer requires variable pointers.
4531 setVariablePointersCapabilities(
4532 ST->getValueOperand()->getType()->getPointerAddressSpace());
4533 }
4534
alan-baker3f772c02021-06-15 22:18:11 -04004535 SPIRVOperandVec Ops;
4536 auto ptr = ST->getPointerOperand();
4537 auto ptr_ty = ptr->getType();
4538 auto value = ST->getValueOperand();
4539 auto value_ty = value->getType();
4540 auto needs_layout = PointerRequiresLayout(ptr_ty->getPointerAddressSpace());
4541 if (Option::SpvVersion() >= SPIRVVersion::SPIRV_1_4 && needs_layout &&
4542 (value_ty->isArrayTy() || value_ty->isStructTy())) {
4543 // Generate an OpCopyLogical to convert from the non-laid type to the
4544 // laid out type.
4545 Ops << getSPIRVType(value_ty, needs_layout) << value;
4546 RID = addSPIRVInst(spv::OpCopyLogical, Ops);
4547 Ops.clear();
4548 }
4549
David Neto22f144c2017-06-12 14:26:21 -04004550 // Ops[0] = Pointer ID
4551 // Ops[1] = Object ID
4552 // Ops[2] ... Ops[n] = Optional Memory Access (later???)
4553 //
4554 // TODO: Do we need to implement Optional Memory Access???
alan-baker3f772c02021-06-15 22:18:11 -04004555 Ops << ST->getPointerOperand();
4556 if (RID.isValid()) {
4557 Ops << RID;
4558 } else {
4559 Ops << ST->getValueOperand();
4560 }
SJWf93f5f32020-05-05 07:27:56 -05004561 RID = addSPIRVInst(spv::OpStore, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004562 break;
4563 }
4564 case Instruction::AtomicCmpXchg: {
4565 I.print(errs());
4566 llvm_unreachable("Unsupported instruction???");
4567 break;
4568 }
4569 case Instruction::AtomicRMW: {
Neil Henning39672102017-09-29 14:33:13 +01004570 AtomicRMWInst *AtomicRMW = dyn_cast<AtomicRMWInst>(&I);
4571
4572 spv::Op opcode;
4573
4574 switch (AtomicRMW->getOperation()) {
4575 default:
4576 I.print(errs());
4577 llvm_unreachable("Unsupported instruction???");
4578 case llvm::AtomicRMWInst::Add:
4579 opcode = spv::OpAtomicIAdd;
4580 break;
4581 case llvm::AtomicRMWInst::Sub:
4582 opcode = spv::OpAtomicISub;
4583 break;
4584 case llvm::AtomicRMWInst::Xchg:
4585 opcode = spv::OpAtomicExchange;
4586 break;
4587 case llvm::AtomicRMWInst::Min:
4588 opcode = spv::OpAtomicSMin;
4589 break;
4590 case llvm::AtomicRMWInst::Max:
4591 opcode = spv::OpAtomicSMax;
4592 break;
4593 case llvm::AtomicRMWInst::UMin:
4594 opcode = spv::OpAtomicUMin;
4595 break;
4596 case llvm::AtomicRMWInst::UMax:
4597 opcode = spv::OpAtomicUMax;
4598 break;
4599 case llvm::AtomicRMWInst::And:
4600 opcode = spv::OpAtomicAnd;
4601 break;
4602 case llvm::AtomicRMWInst::Or:
4603 opcode = spv::OpAtomicOr;
4604 break;
4605 case llvm::AtomicRMWInst::Xor:
4606 opcode = spv::OpAtomicXor;
4607 break;
4608 }
4609
4610 //
4611 // Generate OpAtomic*.
4612 //
SJWf93f5f32020-05-05 07:27:56 -05004613 SPIRVOperandVec Ops;
Neil Henning39672102017-09-29 14:33:13 +01004614
SJW01901d92020-05-21 08:58:31 -05004615 Ops << I.getType() << AtomicRMW->getPointerOperand();
Neil Henning39672102017-09-29 14:33:13 +01004616
SJW806a5d82020-07-15 12:51:38 -05004617 const auto ConstantScopeDevice = getSPIRVInt32Constant(spv::ScopeDevice);
SJW01901d92020-05-21 08:58:31 -05004618 Ops << ConstantScopeDevice;
Neil Henning39672102017-09-29 14:33:13 +01004619
SJW806a5d82020-07-15 12:51:38 -05004620 const auto ConstantMemorySemantics =
4621 getSPIRVInt32Constant(spv::MemorySemanticsUniformMemoryMask |
4622 spv::MemorySemanticsSequentiallyConsistentMask);
SJW01901d92020-05-21 08:58:31 -05004623 Ops << ConstantMemorySemantics << AtomicRMW->getValOperand();
Neil Henning39672102017-09-29 14:33:13 +01004624
SJWf93f5f32020-05-05 07:27:56 -05004625 RID = addSPIRVInst(opcode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004626 break;
4627 }
4628 case Instruction::Fence: {
4629 I.print(errs());
4630 llvm_unreachable("Unsupported instruction???");
4631 break;
4632 }
4633 case Instruction::Call: {
4634 CallInst *Call = dyn_cast<CallInst>(&I);
SJW806a5d82020-07-15 12:51:38 -05004635 RID = GenerateInstructionFromCall(Call);
David Neto22f144c2017-06-12 14:26:21 -04004636 break;
4637 }
4638 case Instruction::Ret: {
4639 unsigned NumOps = I.getNumOperands();
4640 if (NumOps == 0) {
4641 //
4642 // Generate OpReturn.
4643 //
SJWf93f5f32020-05-05 07:27:56 -05004644 RID = addSPIRVInst(spv::OpReturn);
David Neto22f144c2017-06-12 14:26:21 -04004645 } else {
4646 //
4647 // Generate OpReturnValue.
4648 //
4649
4650 // Ops[0] = Return Value ID
SJWf93f5f32020-05-05 07:27:56 -05004651 SPIRVOperandVec Ops;
David Neto257c3892018-04-11 13:19:45 -04004652
SJW01901d92020-05-21 08:58:31 -05004653 Ops << I.getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04004654
SJWf93f5f32020-05-05 07:27:56 -05004655 RID = addSPIRVInst(spv::OpReturnValue, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004656 break;
4657 }
4658 break;
4659 }
4660 }
SJWf93f5f32020-05-05 07:27:56 -05004661
4662 // Register Instruction to ValueMap.
SJW01901d92020-05-21 08:58:31 -05004663 if (RID.isValid()) {
SJWf93f5f32020-05-05 07:27:56 -05004664 VMap[&I] = RID;
4665 }
David Neto22f144c2017-06-12 14:26:21 -04004666}
4667
4668void SPIRVProducerPass::GenerateFuncEpilogue() {
David Neto22f144c2017-06-12 14:26:21 -04004669 //
4670 // Generate OpFunctionEnd
4671 //
SJWf93f5f32020-05-05 07:27:56 -05004672 addSPIRVInst(spv::OpFunctionEnd);
David Neto22f144c2017-06-12 14:26:21 -04004673}
4674
4675bool SPIRVProducerPass::is4xi8vec(Type *Ty) const {
alan-bakerb39c8262019-03-08 14:03:37 -05004676 // Don't specialize <4 x i8> if i8 is generally supported.
4677 if (clspv::Option::Int8Support())
4678 return false;
4679
David Neto22f144c2017-06-12 14:26:21 -04004680 LLVMContext &Context = Ty->getContext();
James Pricecf53df42020-04-20 14:41:24 -04004681 if (auto VecTy = dyn_cast<VectorType>(Ty)) {
4682 if (VecTy->getElementType() == Type::getInt8Ty(Context) &&
alan-baker5a8c3be2020-09-09 13:44:26 -04004683 VecTy->getElementCount().getKnownMinValue() == 4) {
David Neto22f144c2017-06-12 14:26:21 -04004684 return true;
4685 }
4686 }
4687
4688 return false;
4689}
4690
4691void SPIRVProducerPass::HandleDeferredInstruction() {
David Neto22f144c2017-06-12 14:26:21 -04004692 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
4693
SJW88ed5fe2020-05-11 12:40:57 -05004694 for (size_t i = 0; i < DeferredInsts.size(); ++i) {
4695 Value *Inst = DeferredInsts[i].first;
4696 SPIRVInstruction *Placeholder = DeferredInsts[i].second;
4697 SPIRVOperandVec Operands;
4698
4699 auto nextDeferred = [&i, &Inst, &DeferredInsts, &Placeholder]() {
4700 ++i;
4701 assert(DeferredInsts.size() > i);
4702 assert(Inst == DeferredInsts[i].first);
4703 Placeholder = DeferredInsts[i].second;
4704 };
David Neto22f144c2017-06-12 14:26:21 -04004705
4706 if (BranchInst *Br = dyn_cast<BranchInst>(Inst)) {
alan-baker06cad652019-12-03 17:56:47 -05004707 // Check whether this branch needs to be preceeded by merge instruction.
David Neto22f144c2017-06-12 14:26:21 -04004708 BasicBlock *BrBB = Br->getParent();
alan-baker06cad652019-12-03 17:56:47 -05004709 if (ContinueBlocks.count(BrBB)) {
David Neto22f144c2017-06-12 14:26:21 -04004710 //
4711 // Generate OpLoopMerge.
4712 //
4713 // Ops[0] = Merge Block ID
4714 // Ops[1] = Continue Target ID
4715 // Ops[2] = Selection Control
SJWf93f5f32020-05-05 07:27:56 -05004716 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004717
SJW01901d92020-05-21 08:58:31 -05004718 Ops << MergeBlocks[BrBB] << ContinueBlocks[BrBB]
4719 << spv::LoopControlMaskNone;
David Neto22f144c2017-06-12 14:26:21 -04004720
SJW88ed5fe2020-05-11 12:40:57 -05004721 replaceSPIRVInst(Placeholder, spv::OpLoopMerge, Ops);
4722
4723 nextDeferred();
4724
alan-baker06cad652019-12-03 17:56:47 -05004725 } else if (MergeBlocks.count(BrBB)) {
4726 //
4727 // Generate OpSelectionMerge.
4728 //
4729 // Ops[0] = Merge Block ID
4730 // Ops[1] = Selection Control
SJWf93f5f32020-05-05 07:27:56 -05004731 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004732
alan-baker06cad652019-12-03 17:56:47 -05004733 auto MergeBB = MergeBlocks[BrBB];
SJW01901d92020-05-21 08:58:31 -05004734 Ops << MergeBB << spv::SelectionControlMaskNone;
David Neto22f144c2017-06-12 14:26:21 -04004735
SJW88ed5fe2020-05-11 12:40:57 -05004736 replaceSPIRVInst(Placeholder, spv::OpSelectionMerge, Ops);
4737
4738 nextDeferred();
David Neto22f144c2017-06-12 14:26:21 -04004739 }
4740
4741 if (Br->isConditional()) {
4742 //
4743 // Generate OpBranchConditional.
4744 //
4745 // Ops[0] = Condition ID
4746 // Ops[1] = True Label ID
4747 // Ops[2] = False Label ID
4748 // Ops[3] ... Ops[n] = Branch weights (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05004749 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004750
SJW01901d92020-05-21 08:58:31 -05004751 Ops << Br->getCondition() << Br->getSuccessor(0) << Br->getSuccessor(1);
David Neto22f144c2017-06-12 14:26:21 -04004752
SJW88ed5fe2020-05-11 12:40:57 -05004753 replaceSPIRVInst(Placeholder, spv::OpBranchConditional, Ops);
4754
David Neto22f144c2017-06-12 14:26:21 -04004755 } else {
4756 //
4757 // Generate OpBranch.
4758 //
4759 // Ops[0] = Target Label ID
SJWf93f5f32020-05-05 07:27:56 -05004760 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004761
SJW01901d92020-05-21 08:58:31 -05004762 Ops << Br->getSuccessor(0);
David Neto22f144c2017-06-12 14:26:21 -04004763
SJW88ed5fe2020-05-11 12:40:57 -05004764 replaceSPIRVInst(Placeholder, spv::OpBranch, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004765 }
4766 } else if (PHINode *PHI = dyn_cast<PHINode>(Inst)) {
alan-baker5ed87542020-03-23 11:05:22 -04004767 if (PHI->getType()->isPointerTy() && !IsSamplerType(PHI->getType()) &&
4768 !IsImageType(PHI->getType())) {
alan-baker5b86ed72019-02-15 08:26:50 -05004769 // OpPhi on pointers requires variable pointers.
4770 setVariablePointersCapabilities(
4771 PHI->getType()->getPointerAddressSpace());
4772 if (!hasVariablePointers() && !selectFromSameObject(PHI)) {
SJW01901d92020-05-21 08:58:31 -05004773 setVariablePointers();
alan-baker5b86ed72019-02-15 08:26:50 -05004774 }
4775 }
4776
David Neto22f144c2017-06-12 14:26:21 -04004777 //
4778 // Generate OpPhi.
4779 //
4780 // Ops[0] = Result Type ID
4781 // Ops[1] ... Ops[n] = (Variable ID, Parent ID) pairs
SJWf93f5f32020-05-05 07:27:56 -05004782 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004783
SJW01901d92020-05-21 08:58:31 -05004784 Ops << PHI->getType();
David Neto22f144c2017-06-12 14:26:21 -04004785
SJW88ed5fe2020-05-11 12:40:57 -05004786 for (unsigned j = 0; j < PHI->getNumIncomingValues(); j++) {
SJW01901d92020-05-21 08:58:31 -05004787 Ops << PHI->getIncomingValue(j) << PHI->getIncomingBlock(j);
David Neto22f144c2017-06-12 14:26:21 -04004788 }
4789
SJW88ed5fe2020-05-11 12:40:57 -05004790 replaceSPIRVInst(Placeholder, spv::OpPhi, Ops);
4791
David Neto22f144c2017-06-12 14:26:21 -04004792 } else if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
4793 Function *Callee = Call->getCalledFunction();
David Neto3fbb4072017-10-16 11:28:14 -04004794 auto callee_name = Callee->getName();
David Neto22f144c2017-06-12 14:26:21 -04004795
SJW61531372020-06-09 07:31:08 -05004796 if (Builtins::Lookup(Callee) == Builtins::kClspvCompositeConstruct) {
David Netoab03f432017-11-03 17:00:44 -04004797 // Generate an OpCompositeConstruct
SJWf93f5f32020-05-05 07:27:56 -05004798 SPIRVOperandVec Ops;
David Netoab03f432017-11-03 17:00:44 -04004799
4800 // The result type.
SJW01901d92020-05-21 08:58:31 -05004801 Ops << Call->getType();
David Netoab03f432017-11-03 17:00:44 -04004802
4803 for (Use &use : Call->arg_operands()) {
SJW01901d92020-05-21 08:58:31 -05004804 Ops << use.get();
David Netoab03f432017-11-03 17:00:44 -04004805 }
4806
SJW88ed5fe2020-05-11 12:40:57 -05004807 replaceSPIRVInst(Placeholder, spv::OpCompositeConstruct, Ops);
David Netoab03f432017-11-03 17:00:44 -04004808
David Neto22f144c2017-06-12 14:26:21 -04004809 } else {
alan-baker5b86ed72019-02-15 08:26:50 -05004810 if (Call->getType()->isPointerTy()) {
4811 // Functions returning pointers require variable pointers.
4812 setVariablePointersCapabilities(
4813 Call->getType()->getPointerAddressSpace());
4814 }
4815
David Neto22f144c2017-06-12 14:26:21 -04004816 //
4817 // Generate OpFunctionCall.
4818 //
4819
4820 // Ops[0] = Result Type ID
4821 // Ops[1] = Callee Function ID
4822 // Ops[2] ... Ops[n] = Argument 0, ... , Argument n
SJWf93f5f32020-05-05 07:27:56 -05004823 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004824
SJW01901d92020-05-21 08:58:31 -05004825 Ops << Call->getType();
David Neto22f144c2017-06-12 14:26:21 -04004826
SJW01901d92020-05-21 08:58:31 -05004827 SPIRVID CalleeID = getSPIRVValue(Callee);
SJW806a5d82020-07-15 12:51:38 -05004828 if (!CalleeID.isValid()) {
David Neto43568eb2017-10-13 18:25:25 -04004829 errs() << "Can't translate function call. Missing builtin? "
David Neto862b7d82018-06-14 18:48:37 -04004830 << callee_name << " in: " << *Call << "\n";
David Neto43568eb2017-10-13 18:25:25 -04004831 // TODO(dneto): Can we error out? Enabling this llvm_unreachable
4832 // causes an infinite loop. Instead, go ahead and generate
4833 // the bad function call. A validator will catch the 0-Id.
4834 // llvm_unreachable("Can't translate function call");
4835 }
David Neto22f144c2017-06-12 14:26:21 -04004836
SJW01901d92020-05-21 08:58:31 -05004837 Ops << CalleeID;
David Neto22f144c2017-06-12 14:26:21 -04004838
David Neto22f144c2017-06-12 14:26:21 -04004839 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
SJW88ed5fe2020-05-11 12:40:57 -05004840 for (unsigned j = 0; j < CalleeFTy->getNumParams(); j++) {
4841 auto *operand = Call->getOperand(j);
alan-bakerd4d50652019-12-03 17:17:15 -05004842 auto *operand_type = operand->getType();
4843 // Images and samplers can be passed as function parameters without
4844 // variable pointers.
4845 if (operand_type->isPointerTy() && !IsImageType(operand_type) &&
4846 !IsSamplerType(operand_type)) {
alan-baker5b86ed72019-02-15 08:26:50 -05004847 auto sc =
4848 GetStorageClass(operand->getType()->getPointerAddressSpace());
4849 if (sc == spv::StorageClassStorageBuffer) {
4850 // Passing SSBO by reference requires variable pointers storage
4851 // buffer.
SJW01901d92020-05-21 08:58:31 -05004852 setVariablePointersStorageBuffer();
alan-baker5b86ed72019-02-15 08:26:50 -05004853 } else if (sc == spv::StorageClassWorkgroup) {
4854 // Workgroup references require variable pointers if they are not
4855 // memory object declarations.
4856 if (auto *operand_call = dyn_cast<CallInst>(operand)) {
4857 // Workgroup accessor represents a variable reference.
SJW61531372020-06-09 07:31:08 -05004858 if (Builtins::Lookup(operand_call->getCalledFunction()) !=
4859 Builtins::kClspvLocal)
SJW01901d92020-05-21 08:58:31 -05004860 setVariablePointers();
alan-baker5b86ed72019-02-15 08:26:50 -05004861 } else {
4862 // Arguments are function parameters.
4863 if (!isa<Argument>(operand))
SJW01901d92020-05-21 08:58:31 -05004864 setVariablePointers();
alan-baker5b86ed72019-02-15 08:26:50 -05004865 }
4866 }
4867 }
SJW01901d92020-05-21 08:58:31 -05004868 Ops << operand;
David Neto22f144c2017-06-12 14:26:21 -04004869 }
4870
SJW88ed5fe2020-05-11 12:40:57 -05004871 replaceSPIRVInst(Placeholder, spv::OpFunctionCall, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004872 }
4873 }
4874 }
4875}
4876
SJW77b87ad2020-04-21 14:37:52 -05004877void SPIRVProducerPass::HandleDeferredDecorations() {
4878 const auto &DL = module->getDataLayout();
alan-baker5a8c3be2020-09-09 13:44:26 -04004879 if (getTypesNeedingArrayStride().empty()) {
David Neto1a1a0582017-07-07 12:01:44 -04004880 return;
David Netoc6f3ab22018-04-06 18:02:31 -04004881 }
David Neto1a1a0582017-07-07 12:01:44 -04004882
David Netoc6f3ab22018-04-06 18:02:31 -04004883 // Insert ArrayStride decorations on pointer types, due to OpPtrAccessChain
4884 // instructions we generated earlier.
alan-bakerc3fd07f2020-10-22 09:48:49 -04004885 DenseSet<uint32_t> seen;
David Neto85082642018-03-24 06:55:20 -07004886 for (auto *type : getTypesNeedingArrayStride()) {
alan-baker3f772c02021-06-15 22:18:11 -04004887 auto TI = TypeMap.find(type);
4888 unsigned index = SpvVersion() < SPIRVVersion::SPIRV_1_4 ? 0 : 1;
4889 assert(TI != TypeMap.end());
4890 assert(index < TI->second.size());
4891 if (!TI->second[index].isValid())
4892 continue;
4893
4894 auto id = TI->second[index];
alan-bakerc3fd07f2020-10-22 09:48:49 -04004895 if (!seen.insert(id.get()).second)
4896 continue;
4897
David Neto85082642018-03-24 06:55:20 -07004898 Type *elemTy = nullptr;
4899 if (auto *ptrTy = dyn_cast<PointerType>(type)) {
4900 elemTy = ptrTy->getElementType();
alan-bakerb6b09dc2018-11-08 16:59:28 -05004901 } else if (auto *arrayTy = dyn_cast<ArrayType>(type)) {
alan-baker8eb435a2020-04-08 00:42:06 -04004902 elemTy = arrayTy->getElementType();
4903 } else if (auto *vecTy = dyn_cast<VectorType>(type)) {
4904 elemTy = vecTy->getElementType();
David Neto85082642018-03-24 06:55:20 -07004905 } else {
4906 errs() << "Unhandled strided type " << *type << "\n";
4907 llvm_unreachable("Unhandled strided type");
4908 }
David Neto1a1a0582017-07-07 12:01:44 -04004909
4910 // Ops[0] = Target ID
4911 // Ops[1] = Decoration (ArrayStride)
4912 // Ops[2] = Stride number (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05004913 SPIRVOperandVec Ops;
David Neto1a1a0582017-07-07 12:01:44 -04004914
David Neto85082642018-03-24 06:55:20 -07004915 // Same as DL.getIndexedOffsetInType( elemTy, { 1 } );
Alan Bakerfcda9482018-10-02 17:09:59 -04004916 const uint32_t stride = static_cast<uint32_t>(GetTypeAllocSize(elemTy, DL));
David Neto257c3892018-04-11 13:19:45 -04004917
alan-bakerc3fd07f2020-10-22 09:48:49 -04004918 Ops << id << spv::DecorationArrayStride << stride;
David Neto1a1a0582017-07-07 12:01:44 -04004919
SJWf93f5f32020-05-05 07:27:56 -05004920 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Netoc6f3ab22018-04-06 18:02:31 -04004921 }
David Neto1a1a0582017-07-07 12:01:44 -04004922}
4923
SJW61531372020-06-09 07:31:08 -05004924glsl::ExtInst
4925SPIRVProducerPass::getExtInstEnum(const Builtins::FunctionInfo &func_info) {
SJW61531372020-06-09 07:31:08 -05004926 switch (func_info.getType()) {
SJW2c317da2020-03-23 07:39:13 -05004927 case Builtins::kClamp: {
SJW61531372020-06-09 07:31:08 -05004928 auto param_type = func_info.getParameter(0);
SJW2c317da2020-03-23 07:39:13 -05004929 if (param_type.type_id == Type::FloatTyID) {
alan-bakerecc9c942020-12-07 13:13:32 -05004930 return glsl::ExtInst::ExtInstNClamp;
SJW2c317da2020-03-23 07:39:13 -05004931 }
4932 return param_type.is_signed ? glsl::ExtInst::ExtInstSClamp
4933 : glsl::ExtInst::ExtInstUClamp;
4934 }
4935 case Builtins::kMax: {
SJW61531372020-06-09 07:31:08 -05004936 auto param_type = func_info.getParameter(0);
SJW2c317da2020-03-23 07:39:13 -05004937 if (param_type.type_id == Type::FloatTyID) {
4938 return glsl::ExtInst::ExtInstFMax;
4939 }
4940 return param_type.is_signed ? glsl::ExtInst::ExtInstSMax
4941 : glsl::ExtInst::ExtInstUMax;
4942 }
4943 case Builtins::kMin: {
SJW61531372020-06-09 07:31:08 -05004944 auto param_type = func_info.getParameter(0);
SJW2c317da2020-03-23 07:39:13 -05004945 if (param_type.type_id == Type::FloatTyID) {
4946 return glsl::ExtInst::ExtInstFMin;
4947 }
4948 return param_type.is_signed ? glsl::ExtInst::ExtInstSMin
4949 : glsl::ExtInst::ExtInstUMin;
4950 }
4951 case Builtins::kAbs:
4952 return glsl::ExtInst::ExtInstSAbs;
4953 case Builtins::kFmax:
Marco Antognini55d51862020-07-21 17:50:07 +01004954 return glsl::ExtInst::ExtInstNMax;
SJW2c317da2020-03-23 07:39:13 -05004955 case Builtins::kFmin:
Marco Antognini55d51862020-07-21 17:50:07 +01004956 return glsl::ExtInst::ExtInstNMin;
SJW2c317da2020-03-23 07:39:13 -05004957 case Builtins::kDegrees:
4958 return glsl::ExtInst::ExtInstDegrees;
4959 case Builtins::kRadians:
4960 return glsl::ExtInst::ExtInstRadians;
4961 case Builtins::kMix:
4962 return glsl::ExtInst::ExtInstFMix;
4963 case Builtins::kAcos:
4964 case Builtins::kAcospi:
4965 return glsl::ExtInst::ExtInstAcos;
4966 case Builtins::kAcosh:
4967 return glsl::ExtInst::ExtInstAcosh;
4968 case Builtins::kAsin:
4969 case Builtins::kAsinpi:
4970 return glsl::ExtInst::ExtInstAsin;
4971 case Builtins::kAsinh:
4972 return glsl::ExtInst::ExtInstAsinh;
4973 case Builtins::kAtan:
4974 case Builtins::kAtanpi:
4975 return glsl::ExtInst::ExtInstAtan;
4976 case Builtins::kAtanh:
4977 return glsl::ExtInst::ExtInstAtanh;
4978 case Builtins::kAtan2:
4979 case Builtins::kAtan2pi:
4980 return glsl::ExtInst::ExtInstAtan2;
4981 case Builtins::kCeil:
4982 return glsl::ExtInst::ExtInstCeil;
4983 case Builtins::kSin:
4984 case Builtins::kHalfSin:
4985 case Builtins::kNativeSin:
4986 return glsl::ExtInst::ExtInstSin;
4987 case Builtins::kSinh:
4988 return glsl::ExtInst::ExtInstSinh;
4989 case Builtins::kCos:
4990 case Builtins::kHalfCos:
4991 case Builtins::kNativeCos:
4992 return glsl::ExtInst::ExtInstCos;
4993 case Builtins::kCosh:
4994 return glsl::ExtInst::ExtInstCosh;
4995 case Builtins::kTan:
4996 case Builtins::kHalfTan:
4997 case Builtins::kNativeTan:
4998 return glsl::ExtInst::ExtInstTan;
4999 case Builtins::kTanh:
5000 return glsl::ExtInst::ExtInstTanh;
5001 case Builtins::kExp:
5002 case Builtins::kHalfExp:
5003 case Builtins::kNativeExp:
5004 return glsl::ExtInst::ExtInstExp;
5005 case Builtins::kExp2:
5006 case Builtins::kHalfExp2:
5007 case Builtins::kNativeExp2:
5008 return glsl::ExtInst::ExtInstExp2;
5009 case Builtins::kLog:
5010 case Builtins::kHalfLog:
5011 case Builtins::kNativeLog:
5012 return glsl::ExtInst::ExtInstLog;
5013 case Builtins::kLog2:
5014 case Builtins::kHalfLog2:
5015 case Builtins::kNativeLog2:
5016 return glsl::ExtInst::ExtInstLog2;
5017 case Builtins::kFabs:
5018 return glsl::ExtInst::ExtInstFAbs;
5019 case Builtins::kFma:
5020 return glsl::ExtInst::ExtInstFma;
5021 case Builtins::kFloor:
5022 return glsl::ExtInst::ExtInstFloor;
5023 case Builtins::kLdexp:
5024 return glsl::ExtInst::ExtInstLdexp;
5025 case Builtins::kPow:
5026 case Builtins::kPowr:
5027 case Builtins::kHalfPowr:
5028 case Builtins::kNativePowr:
5029 return glsl::ExtInst::ExtInstPow;
James Price38553362020-09-03 18:30:40 -04005030 case Builtins::kRint:
5031 return glsl::ExtInst::ExtInstRoundEven;
SJW2c317da2020-03-23 07:39:13 -05005032 case Builtins::kRound:
5033 return glsl::ExtInst::ExtInstRound;
5034 case Builtins::kSqrt:
5035 case Builtins::kHalfSqrt:
5036 case Builtins::kNativeSqrt:
5037 return glsl::ExtInst::ExtInstSqrt;
5038 case Builtins::kRsqrt:
5039 case Builtins::kHalfRsqrt:
5040 case Builtins::kNativeRsqrt:
5041 return glsl::ExtInst::ExtInstInverseSqrt;
5042 case Builtins::kTrunc:
5043 return glsl::ExtInst::ExtInstTrunc;
5044 case Builtins::kFrexp:
5045 return glsl::ExtInst::ExtInstFrexp;
SJW61531372020-06-09 07:31:08 -05005046 case Builtins::kClspvFract:
SJW2c317da2020-03-23 07:39:13 -05005047 case Builtins::kFract:
5048 return glsl::ExtInst::ExtInstFract;
5049 case Builtins::kSign:
5050 return glsl::ExtInst::ExtInstFSign;
5051 case Builtins::kLength:
5052 case Builtins::kFastLength:
5053 return glsl::ExtInst::ExtInstLength;
5054 case Builtins::kDistance:
5055 case Builtins::kFastDistance:
5056 return glsl::ExtInst::ExtInstDistance;
5057 case Builtins::kStep:
5058 return glsl::ExtInst::ExtInstStep;
5059 case Builtins::kSmoothstep:
5060 return glsl::ExtInst::ExtInstSmoothStep;
5061 case Builtins::kCross:
5062 return glsl::ExtInst::ExtInstCross;
5063 case Builtins::kNormalize:
5064 case Builtins::kFastNormalize:
5065 return glsl::ExtInst::ExtInstNormalize;
SJW61531372020-06-09 07:31:08 -05005066 case Builtins::kSpirvPack:
5067 return glsl::ExtInst::ExtInstPackHalf2x16;
5068 case Builtins::kSpirvUnpack:
5069 return glsl::ExtInst::ExtInstUnpackHalf2x16;
SJW2c317da2020-03-23 07:39:13 -05005070 default:
5071 break;
5072 }
5073
alan-baker5f2e88e2020-12-07 15:24:04 -05005074 // TODO: improve this by checking the intrinsic id.
SJW61531372020-06-09 07:31:08 -05005075 if (func_info.getName().find("llvm.fmuladd.") == 0) {
5076 return glsl::ExtInst::ExtInstFma;
5077 }
alan-baker5f2e88e2020-12-07 15:24:04 -05005078 if (func_info.getName().find("llvm.sqrt.") == 0) {
5079 return glsl::ExtInst::ExtInstSqrt;
5080 }
5081 if (func_info.getName().find("llvm.trunc.") == 0) {
5082 return glsl::ExtInst::ExtInstTrunc;
5083 }
5084 if (func_info.getName().find("llvm.ctlz.") == 0) {
5085 return glsl::ExtInst::ExtInstFindUMsb;
5086 }
5087 if (func_info.getName().find("llvm.cttz.") == 0) {
5088 return glsl::ExtInst::ExtInstFindILsb;
5089 }
alan-baker3e0de472020-12-08 15:57:17 -05005090 if (func_info.getName().find("llvm.ceil.") == 0) {
5091 return glsl::ExtInst::ExtInstCeil;
5092 }
5093 if (func_info.getName().find("llvm.rint.") == 0) {
5094 return glsl::ExtInst::ExtInstRoundEven;
5095 }
5096 if (func_info.getName().find("llvm.fabs.") == 0) {
5097 return glsl::ExtInst::ExtInstFAbs;
5098 }
5099 if (func_info.getName().find("llvm.floor.") == 0) {
5100 return glsl::ExtInst::ExtInstFloor;
5101 }
5102 if (func_info.getName().find("llvm.sin.") == 0) {
5103 return glsl::ExtInst::ExtInstSin;
5104 }
5105 if (func_info.getName().find("llvm.cos.") == 0) {
5106 return glsl::ExtInst::ExtInstCos;
5107 }
alan-baker8b968112020-12-15 15:53:29 -05005108 if (func_info.getName().find("llvm.exp.") == 0) {
5109 return glsl::ExtInst::ExtInstExp;
5110 }
5111 if (func_info.getName().find("llvm.log.") == 0) {
5112 return glsl::ExtInst::ExtInstLog;
5113 }
5114 if (func_info.getName().find("llvm.pow.") == 0) {
5115 return glsl::ExtInst::ExtInstPow;
5116 }
James Price8cc3bb12021-05-05 10:20:58 -04005117 if (func_info.getName().find("llvm.smax.") == 0) {
5118 return glsl::ExtInst::ExtInstSMax;
5119 }
5120 if (func_info.getName().find("llvm.smin.") == 0) {
5121 return glsl::ExtInst::ExtInstSMin;
5122 }
Kévin Petit0c0c3882021-07-27 17:01:14 +01005123 if (func_info.getName().find("llvm.umax.") == 0) {
5124 return glsl::ExtInst::ExtInstUMax;
5125 }
5126 if (func_info.getName().find("llvm.umin.") == 0) {
5127 return glsl::ExtInst::ExtInstUMin;
5128 }
SJW61531372020-06-09 07:31:08 -05005129 return kGlslExtInstBad;
David Neto3fbb4072017-10-16 11:28:14 -04005130}
5131
SJW61531372020-06-09 07:31:08 -05005132glsl::ExtInst SPIRVProducerPass::getIndirectExtInstEnum(
5133 const Builtins::FunctionInfo &func_info) {
5134 switch (func_info.getType()) {
SJW2c317da2020-03-23 07:39:13 -05005135 case Builtins::kAcospi:
5136 return glsl::ExtInst::ExtInstAcos;
5137 case Builtins::kAsinpi:
5138 return glsl::ExtInst::ExtInstAsin;
5139 case Builtins::kAtanpi:
5140 return glsl::ExtInst::ExtInstAtan;
5141 case Builtins::kAtan2pi:
5142 return glsl::ExtInst::ExtInstAtan2;
5143 default:
5144 break;
5145 }
5146 return kGlslExtInstBad;
David Neto3fbb4072017-10-16 11:28:14 -04005147}
5148
SJW61531372020-06-09 07:31:08 -05005149glsl::ExtInst SPIRVProducerPass::getDirectOrIndirectExtInstEnum(
5150 const Builtins::FunctionInfo &func_info) {
5151 auto direct = getExtInstEnum(func_info);
David Neto3fbb4072017-10-16 11:28:14 -04005152 if (direct != kGlslExtInstBad)
5153 return direct;
SJW61531372020-06-09 07:31:08 -05005154 return getIndirectExtInstEnum(func_info);
David Neto22f144c2017-06-12 14:26:21 -04005155}
5156
David Neto22f144c2017-06-12 14:26:21 -04005157void SPIRVProducerPass::WriteOneWord(uint32_t Word) {
David Neto0676e6f2017-07-11 18:47:44 -04005158 binaryOut->write(reinterpret_cast<const char *>(&Word), sizeof(uint32_t));
David Neto22f144c2017-06-12 14:26:21 -04005159}
5160
SJW88ed5fe2020-05-11 12:40:57 -05005161void SPIRVProducerPass::WriteResultID(const SPIRVInstruction &Inst) {
SJW01901d92020-05-21 08:58:31 -05005162 WriteOneWord(Inst.getResultID().get());
David Neto22f144c2017-06-12 14:26:21 -04005163}
5164
SJW88ed5fe2020-05-11 12:40:57 -05005165void SPIRVProducerPass::WriteWordCountAndOpcode(const SPIRVInstruction &Inst) {
David Neto22f144c2017-06-12 14:26:21 -04005166 // High 16 bit : Word Count
5167 // Low 16 bit : Opcode
SJW88ed5fe2020-05-11 12:40:57 -05005168 uint32_t Word = Inst.getOpcode();
5169 const uint32_t count = Inst.getWordCount();
David Netoee2660d2018-06-28 16:31:29 -04005170 if (count > 65535) {
5171 errs() << "Word count limit of 65535 exceeded: " << count << "\n";
5172 llvm_unreachable("Word count too high");
5173 }
SJW88ed5fe2020-05-11 12:40:57 -05005174 Word |= Inst.getWordCount() << 16;
David Neto22f144c2017-06-12 14:26:21 -04005175 WriteOneWord(Word);
5176}
5177
SJW88ed5fe2020-05-11 12:40:57 -05005178void SPIRVProducerPass::WriteOperand(const SPIRVOperand &Op) {
5179 SPIRVOperandType OpTy = Op.getType();
David Neto22f144c2017-06-12 14:26:21 -04005180 switch (OpTy) {
5181 default: {
5182 llvm_unreachable("Unsupported SPIRV Operand Type???");
5183 break;
5184 }
5185 case SPIRVOperandType::NUMBERID: {
SJW88ed5fe2020-05-11 12:40:57 -05005186 WriteOneWord(Op.getNumID());
David Neto22f144c2017-06-12 14:26:21 -04005187 break;
5188 }
5189 case SPIRVOperandType::LITERAL_STRING: {
SJW88ed5fe2020-05-11 12:40:57 -05005190 std::string Str = Op.getLiteralStr();
David Neto22f144c2017-06-12 14:26:21 -04005191 const char *Data = Str.c_str();
5192 size_t WordSize = Str.size() / 4;
5193 for (unsigned Idx = 0; Idx < WordSize; Idx++) {
5194 WriteOneWord(*reinterpret_cast<const uint32_t *>(&Data[4 * Idx]));
5195 }
5196
5197 uint32_t Remainder = Str.size() % 4;
5198 uint32_t LastWord = 0;
5199 if (Remainder) {
5200 for (unsigned Idx = 0; Idx < Remainder; Idx++) {
5201 LastWord |= Data[4 * WordSize + Idx] << 8 * Idx;
5202 }
5203 }
5204
5205 WriteOneWord(LastWord);
5206 break;
5207 }
SJW88ed5fe2020-05-11 12:40:57 -05005208 case SPIRVOperandType::LITERAL_WORD: {
5209 WriteOneWord(Op.getLiteralNum()[0]);
5210 break;
5211 }
5212 case SPIRVOperandType::LITERAL_DWORD: {
5213 WriteOneWord(Op.getLiteralNum()[0]);
5214 WriteOneWord(Op.getLiteralNum()[1]);
David Neto22f144c2017-06-12 14:26:21 -04005215 break;
5216 }
5217 }
5218}
5219
5220void SPIRVProducerPass::WriteSPIRVBinary() {
SJW69939d52020-04-16 07:29:07 -05005221 for (int i = 0; i < kSectionCount; ++i) {
5222 WriteSPIRVBinary(SPIRVSections[i]);
5223 }
5224}
5225
5226void SPIRVProducerPass::WriteSPIRVBinary(SPIRVInstructionList &SPIRVInstList) {
SJW88ed5fe2020-05-11 12:40:57 -05005227 for (const auto &Inst : SPIRVInstList) {
5228 const auto &Ops = Inst.getOperands();
5229 spv::Op Opcode = static_cast<spv::Op>(Inst.getOpcode());
David Neto22f144c2017-06-12 14:26:21 -04005230
5231 switch (Opcode) {
5232 default: {
David Neto5c22a252018-03-15 16:07:41 -04005233 errs() << "Unsupported SPIR-V instruction opcode " << int(Opcode) << "\n";
David Neto22f144c2017-06-12 14:26:21 -04005234 llvm_unreachable("Unsupported SPIRV instruction");
5235 break;
5236 }
Marco Antognini68e5c512020-09-09 16:08:57 +01005237 case spv::OpUnreachable:
David Neto22f144c2017-06-12 14:26:21 -04005238 case spv::OpCapability:
5239 case spv::OpExtension:
5240 case spv::OpMemoryModel:
5241 case spv::OpEntryPoint:
5242 case spv::OpExecutionMode:
5243 case spv::OpSource:
5244 case spv::OpDecorate:
5245 case spv::OpMemberDecorate:
5246 case spv::OpBranch:
5247 case spv::OpBranchConditional:
5248 case spv::OpSelectionMerge:
5249 case spv::OpLoopMerge:
5250 case spv::OpStore:
5251 case spv::OpImageWrite:
5252 case spv::OpReturnValue:
5253 case spv::OpControlBarrier:
5254 case spv::OpMemoryBarrier:
5255 case spv::OpReturn:
5256 case spv::OpFunctionEnd:
alan-baker4986eff2020-10-29 13:38:00 -04005257 case spv::OpCopyMemory:
5258 case spv::OpAtomicStore: {
David Neto22f144c2017-06-12 14:26:21 -04005259 WriteWordCountAndOpcode(Inst);
5260 for (uint32_t i = 0; i < Ops.size(); i++) {
5261 WriteOperand(Ops[i]);
5262 }
5263 break;
5264 }
5265 case spv::OpTypeBool:
5266 case spv::OpTypeVoid:
5267 case spv::OpTypeSampler:
5268 case spv::OpLabel:
5269 case spv::OpExtInstImport:
5270 case spv::OpTypePointer:
5271 case spv::OpTypeRuntimeArray:
5272 case spv::OpTypeStruct:
5273 case spv::OpTypeImage:
5274 case spv::OpTypeSampledImage:
5275 case spv::OpTypeInt:
5276 case spv::OpTypeFloat:
5277 case spv::OpTypeArray:
5278 case spv::OpTypeVector:
alan-baker86ce19c2020-08-05 13:09:19 -04005279 case spv::OpTypeFunction:
5280 case spv::OpString: {
David Neto22f144c2017-06-12 14:26:21 -04005281 WriteWordCountAndOpcode(Inst);
5282 WriteResultID(Inst);
5283 for (uint32_t i = 0; i < Ops.size(); i++) {
5284 WriteOperand(Ops[i]);
5285 }
5286 break;
5287 }
5288 case spv::OpFunction:
5289 case spv::OpFunctionParameter:
5290 case spv::OpAccessChain:
5291 case spv::OpPtrAccessChain:
5292 case spv::OpInBoundsAccessChain:
5293 case spv::OpUConvert:
5294 case spv::OpSConvert:
5295 case spv::OpConvertFToU:
5296 case spv::OpConvertFToS:
5297 case spv::OpConvertUToF:
5298 case spv::OpConvertSToF:
5299 case spv::OpFConvert:
5300 case spv::OpConvertPtrToU:
5301 case spv::OpConvertUToPtr:
5302 case spv::OpBitcast:
alan-bakerc9c55ae2019-12-02 16:01:27 -05005303 case spv::OpFNegate:
David Neto22f144c2017-06-12 14:26:21 -04005304 case spv::OpIAdd:
alan-bakera52b7312020-10-26 08:58:51 -04005305 case spv::OpIAddCarry:
David Neto22f144c2017-06-12 14:26:21 -04005306 case spv::OpFAdd:
5307 case spv::OpISub:
alan-baker3f1bf492020-11-05 09:07:36 -05005308 case spv::OpISubBorrow:
David Neto22f144c2017-06-12 14:26:21 -04005309 case spv::OpFSub:
5310 case spv::OpIMul:
5311 case spv::OpFMul:
5312 case spv::OpUDiv:
5313 case spv::OpSDiv:
5314 case spv::OpFDiv:
5315 case spv::OpUMod:
5316 case spv::OpSRem:
5317 case spv::OpFRem:
Kévin Petit8a560882019-03-21 15:24:34 +00005318 case spv::OpUMulExtended:
5319 case spv::OpSMulExtended:
David Neto22f144c2017-06-12 14:26:21 -04005320 case spv::OpBitwiseOr:
5321 case spv::OpBitwiseXor:
5322 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04005323 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04005324 case spv::OpShiftLeftLogical:
5325 case spv::OpShiftRightLogical:
5326 case spv::OpShiftRightArithmetic:
5327 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04005328 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04005329 case spv::OpCompositeExtract:
5330 case spv::OpVectorExtractDynamic:
5331 case spv::OpCompositeInsert:
alan-baker3f772c02021-06-15 22:18:11 -04005332 case spv::OpCopyLogical:
David Neto0a2f98d2017-09-15 19:38:40 -04005333 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04005334 case spv::OpVectorInsertDynamic:
5335 case spv::OpVectorShuffle:
5336 case spv::OpIEqual:
5337 case spv::OpINotEqual:
5338 case spv::OpUGreaterThan:
5339 case spv::OpUGreaterThanEqual:
5340 case spv::OpULessThan:
5341 case spv::OpULessThanEqual:
5342 case spv::OpSGreaterThan:
5343 case spv::OpSGreaterThanEqual:
5344 case spv::OpSLessThan:
5345 case spv::OpSLessThanEqual:
5346 case spv::OpFOrdEqual:
5347 case spv::OpFOrdGreaterThan:
5348 case spv::OpFOrdGreaterThanEqual:
5349 case spv::OpFOrdLessThan:
5350 case spv::OpFOrdLessThanEqual:
5351 case spv::OpFOrdNotEqual:
5352 case spv::OpFUnordEqual:
5353 case spv::OpFUnordGreaterThan:
5354 case spv::OpFUnordGreaterThanEqual:
5355 case spv::OpFUnordLessThan:
5356 case spv::OpFUnordLessThanEqual:
5357 case spv::OpFUnordNotEqual:
5358 case spv::OpExtInst:
5359 case spv::OpIsInf:
5360 case spv::OpIsNan:
5361 case spv::OpAny:
5362 case spv::OpAll:
5363 case spv::OpUndef:
5364 case spv::OpConstantNull:
5365 case spv::OpLogicalOr:
5366 case spv::OpLogicalAnd:
5367 case spv::OpLogicalNot:
5368 case spv::OpLogicalNotEqual:
5369 case spv::OpConstantComposite:
5370 case spv::OpSpecConstantComposite:
5371 case spv::OpConstantTrue:
5372 case spv::OpConstantFalse:
5373 case spv::OpConstant:
5374 case spv::OpSpecConstant:
5375 case spv::OpVariable:
5376 case spv::OpFunctionCall:
5377 case spv::OpSampledImage:
alan-baker75090e42020-02-20 11:21:04 -05005378 case spv::OpImageFetch:
alan-bakerf6bc8252020-09-23 14:58:55 -04005379 case spv::OpImageRead:
David Neto22f144c2017-06-12 14:26:21 -04005380 case spv::OpImageSampleExplicitLod:
David Neto5c22a252018-03-15 16:07:41 -04005381 case spv::OpImageQuerySize:
alan-bakerce179f12019-12-06 19:02:22 -05005382 case spv::OpImageQuerySizeLod:
David Neto22f144c2017-06-12 14:26:21 -04005383 case spv::OpSelect:
5384 case spv::OpPhi:
5385 case spv::OpLoad:
alan-baker4986eff2020-10-29 13:38:00 -04005386 case spv::OpAtomicLoad:
David Neto22f144c2017-06-12 14:26:21 -04005387 case spv::OpAtomicIAdd:
5388 case spv::OpAtomicISub:
5389 case spv::OpAtomicExchange:
5390 case spv::OpAtomicIIncrement:
5391 case spv::OpAtomicIDecrement:
5392 case spv::OpAtomicCompareExchange:
5393 case spv::OpAtomicUMin:
5394 case spv::OpAtomicSMin:
5395 case spv::OpAtomicUMax:
5396 case spv::OpAtomicSMax:
5397 case spv::OpAtomicAnd:
5398 case spv::OpAtomicOr:
5399 case spv::OpAtomicXor:
SJW806a5d82020-07-15 12:51:38 -05005400 case spv::OpDot:
5401 case spv::OpGroupNonUniformAll:
5402 case spv::OpGroupNonUniformAny:
5403 case spv::OpGroupNonUniformBroadcast:
5404 case spv::OpGroupNonUniformIAdd:
5405 case spv::OpGroupNonUniformFAdd:
5406 case spv::OpGroupNonUniformSMin:
5407 case spv::OpGroupNonUniformUMin:
5408 case spv::OpGroupNonUniformFMin:
5409 case spv::OpGroupNonUniformSMax:
5410 case spv::OpGroupNonUniformUMax:
5411 case spv::OpGroupNonUniformFMax: {
David Neto22f144c2017-06-12 14:26:21 -04005412 WriteWordCountAndOpcode(Inst);
5413 WriteOperand(Ops[0]);
5414 WriteResultID(Inst);
5415 for (uint32_t i = 1; i < Ops.size(); i++) {
5416 WriteOperand(Ops[i]);
5417 }
5418 break;
5419 }
5420 }
5421 }
5422}
Alan Baker9bf93fb2018-08-28 16:59:26 -04005423
alan-bakerb6b09dc2018-11-08 16:59:28 -05005424bool SPIRVProducerPass::IsTypeNullable(const Type *type) const {
Alan Baker9bf93fb2018-08-28 16:59:26 -04005425 switch (type->getTypeID()) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05005426 case Type::HalfTyID:
5427 case Type::FloatTyID:
5428 case Type::DoubleTyID:
5429 case Type::IntegerTyID:
James Price59a1c752020-04-23 23:06:16 -04005430 case Type::FixedVectorTyID:
alan-bakerb6b09dc2018-11-08 16:59:28 -05005431 return true;
5432 case Type::PointerTyID: {
5433 const PointerType *pointer_type = cast<PointerType>(type);
5434 if (pointer_type->getPointerAddressSpace() !=
5435 AddressSpace::UniformConstant) {
5436 auto pointee_type = pointer_type->getPointerElementType();
5437 if (pointee_type->isStructTy() &&
5438 cast<StructType>(pointee_type)->isOpaque()) {
5439 // Images and samplers are not nullable.
5440 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04005441 }
Alan Baker9bf93fb2018-08-28 16:59:26 -04005442 }
alan-bakerb6b09dc2018-11-08 16:59:28 -05005443 return true;
5444 }
5445 case Type::ArrayTyID:
alan-baker8eb435a2020-04-08 00:42:06 -04005446 return IsTypeNullable(type->getArrayElementType());
alan-bakerb6b09dc2018-11-08 16:59:28 -05005447 case Type::StructTyID: {
5448 const StructType *struct_type = cast<StructType>(type);
5449 // Images and samplers are not nullable.
5450 if (struct_type->isOpaque())
Alan Baker9bf93fb2018-08-28 16:59:26 -04005451 return false;
alan-bakerb6b09dc2018-11-08 16:59:28 -05005452 for (const auto element : struct_type->elements()) {
5453 if (!IsTypeNullable(element))
5454 return false;
5455 }
5456 return true;
5457 }
5458 default:
5459 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04005460 }
5461}
Alan Bakerfcda9482018-10-02 17:09:59 -04005462
SJW77b87ad2020-04-21 14:37:52 -05005463void SPIRVProducerPass::PopulateUBOTypeMaps() {
Alan Bakerfcda9482018-10-02 17:09:59 -04005464 if (auto *offsets_md =
SJW77b87ad2020-04-21 14:37:52 -05005465 module->getNamedMetadata(clspv::RemappedTypeOffsetMetadataName())) {
Alan Bakerfcda9482018-10-02 17:09:59 -04005466 // Metdata is stored as key-value pair operands. The first element of each
5467 // operand is the type and the second is a vector of offsets.
5468 for (const auto *operand : offsets_md->operands()) {
5469 const auto *pair = cast<MDTuple>(operand);
5470 auto *type =
5471 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
5472 const auto *offset_vector = cast<MDTuple>(pair->getOperand(1));
5473 std::vector<uint32_t> offsets;
5474 for (const Metadata *offset_md : offset_vector->operands()) {
5475 const auto *constant_md = cast<ConstantAsMetadata>(offset_md);
alan-bakerb6b09dc2018-11-08 16:59:28 -05005476 offsets.push_back(static_cast<uint32_t>(
5477 cast<ConstantInt>(constant_md->getValue())->getZExtValue()));
Alan Bakerfcda9482018-10-02 17:09:59 -04005478 }
5479 RemappedUBOTypeOffsets.insert(std::make_pair(type, offsets));
5480 }
5481 }
5482
5483 if (auto *sizes_md =
SJW77b87ad2020-04-21 14:37:52 -05005484 module->getNamedMetadata(clspv::RemappedTypeSizesMetadataName())) {
Alan Bakerfcda9482018-10-02 17:09:59 -04005485 // Metadata is stored as key-value pair operands. The first element of each
5486 // operand is the type and the second is a triple of sizes: type size in
5487 // bits, store size and alloc size.
5488 for (const auto *operand : sizes_md->operands()) {
5489 const auto *pair = cast<MDTuple>(operand);
5490 auto *type =
5491 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
5492 const auto *size_triple = cast<MDTuple>(pair->getOperand(1));
5493 uint64_t type_size_in_bits =
5494 cast<ConstantInt>(
5495 cast<ConstantAsMetadata>(size_triple->getOperand(0))->getValue())
5496 ->getZExtValue();
5497 uint64_t type_store_size =
5498 cast<ConstantInt>(
5499 cast<ConstantAsMetadata>(size_triple->getOperand(1))->getValue())
5500 ->getZExtValue();
5501 uint64_t type_alloc_size =
5502 cast<ConstantInt>(
5503 cast<ConstantAsMetadata>(size_triple->getOperand(2))->getValue())
5504 ->getZExtValue();
5505 RemappedUBOTypeSizes.insert(std::make_pair(
5506 type, std::make_tuple(type_size_in_bits, type_store_size,
5507 type_alloc_size)));
5508 }
5509 }
5510}
5511
5512uint64_t SPIRVProducerPass::GetTypeSizeInBits(Type *type,
5513 const DataLayout &DL) {
5514 auto iter = RemappedUBOTypeSizes.find(type);
5515 if (iter != RemappedUBOTypeSizes.end()) {
5516 return std::get<0>(iter->second);
5517 }
5518
5519 return DL.getTypeSizeInBits(type);
5520}
5521
Alan Bakerfcda9482018-10-02 17:09:59 -04005522uint64_t SPIRVProducerPass::GetTypeAllocSize(Type *type, const DataLayout &DL) {
5523 auto iter = RemappedUBOTypeSizes.find(type);
5524 if (iter != RemappedUBOTypeSizes.end()) {
5525 return std::get<2>(iter->second);
5526 }
5527
5528 return DL.getTypeAllocSize(type);
5529}
alan-baker5b86ed72019-02-15 08:26:50 -05005530
Kévin Petitbbbda972020-03-03 19:16:31 +00005531uint32_t SPIRVProducerPass::GetExplicitLayoutStructMemberOffset(
5532 StructType *type, unsigned member, const DataLayout &DL) {
5533 const auto StructLayout = DL.getStructLayout(type);
5534 // Search for the correct offsets if this type was remapped.
5535 std::vector<uint32_t> *offsets = nullptr;
5536 auto iter = RemappedUBOTypeOffsets.find(type);
5537 if (iter != RemappedUBOTypeOffsets.end()) {
5538 offsets = &iter->second;
5539 }
5540 auto ByteOffset =
5541 static_cast<uint32_t>(StructLayout->getElementOffset(member));
5542 if (offsets) {
5543 ByteOffset = (*offsets)[member];
5544 }
5545
5546 return ByteOffset;
5547}
5548
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04005549void SPIRVProducerPass::setVariablePointersCapabilities(
5550 unsigned address_space) {
alan-baker5b86ed72019-02-15 08:26:50 -05005551 if (GetStorageClass(address_space) == spv::StorageClassStorageBuffer) {
SJW01901d92020-05-21 08:58:31 -05005552 setVariablePointersStorageBuffer();
alan-baker5b86ed72019-02-15 08:26:50 -05005553 } else {
SJW01901d92020-05-21 08:58:31 -05005554 setVariablePointers();
alan-baker5b86ed72019-02-15 08:26:50 -05005555 }
5556}
5557
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04005558Value *SPIRVProducerPass::GetBasePointer(Value *v) {
alan-baker5b86ed72019-02-15 08:26:50 -05005559 if (auto *gep = dyn_cast<GetElementPtrInst>(v)) {
5560 return GetBasePointer(gep->getPointerOperand());
5561 }
5562
5563 // Conservatively return |v|.
5564 return v;
5565}
5566
5567bool SPIRVProducerPass::sameResource(Value *lhs, Value *rhs) const {
5568 if (auto *lhs_call = dyn_cast<CallInst>(lhs)) {
5569 if (auto *rhs_call = dyn_cast<CallInst>(rhs)) {
alan-baker7506abb2020-09-10 15:02:55 -04005570 const auto &lhs_func_info =
5571 Builtins::Lookup(lhs_call->getCalledFunction());
5572 const auto &rhs_func_info =
5573 Builtins::Lookup(rhs_call->getCalledFunction());
SJW61531372020-06-09 07:31:08 -05005574 if (lhs_func_info.getType() == Builtins::kClspvResource &&
5575 rhs_func_info.getType() == Builtins::kClspvResource) {
alan-baker5b86ed72019-02-15 08:26:50 -05005576 // For resource accessors, match descriptor set and binding.
5577 if (lhs_call->getOperand(0) == rhs_call->getOperand(0) &&
5578 lhs_call->getOperand(1) == rhs_call->getOperand(1))
5579 return true;
SJW61531372020-06-09 07:31:08 -05005580 } else if (lhs_func_info.getType() == Builtins::kClspvLocal &&
5581 rhs_func_info.getType() == Builtins::kClspvLocal) {
alan-baker5b86ed72019-02-15 08:26:50 -05005582 // For workgroup resources, match spec id.
5583 if (lhs_call->getOperand(0) == rhs_call->getOperand(0))
5584 return true;
5585 }
5586 }
5587 }
5588
5589 return false;
5590}
5591
5592bool SPIRVProducerPass::selectFromSameObject(Instruction *inst) {
5593 assert(inst->getType()->isPointerTy());
5594 assert(GetStorageClass(inst->getType()->getPointerAddressSpace()) ==
5595 spv::StorageClassStorageBuffer);
5596 const bool hack_undef = clspv::Option::HackUndef();
5597 if (auto *select = dyn_cast<SelectInst>(inst)) {
5598 auto *true_base = GetBasePointer(select->getTrueValue());
5599 auto *false_base = GetBasePointer(select->getFalseValue());
5600
5601 if (true_base == false_base)
5602 return true;
5603
5604 // If either the true or false operand is a null, then we satisfy the same
5605 // object constraint.
5606 if (auto *true_cst = dyn_cast<Constant>(true_base)) {
5607 if (true_cst->isNullValue() || (hack_undef && isa<UndefValue>(true_base)))
5608 return true;
5609 }
5610
5611 if (auto *false_cst = dyn_cast<Constant>(false_base)) {
5612 if (false_cst->isNullValue() ||
5613 (hack_undef && isa<UndefValue>(false_base)))
5614 return true;
5615 }
5616
5617 if (sameResource(true_base, false_base))
5618 return true;
5619 } else if (auto *phi = dyn_cast<PHINode>(inst)) {
5620 Value *value = nullptr;
5621 bool ok = true;
5622 for (unsigned i = 0; ok && i != phi->getNumIncomingValues(); ++i) {
5623 auto *base = GetBasePointer(phi->getIncomingValue(i));
5624 // Null values satisfy the constraint of selecting of selecting from the
5625 // same object.
5626 if (!value) {
5627 if (auto *cst = dyn_cast<Constant>(base)) {
5628 if (!cst->isNullValue() && !(hack_undef && isa<UndefValue>(base)))
5629 value = base;
5630 } else {
5631 value = base;
5632 }
5633 } else if (base != value) {
5634 if (auto *base_cst = dyn_cast<Constant>(base)) {
5635 if (base_cst->isNullValue() || (hack_undef && isa<UndefValue>(base)))
5636 continue;
5637 }
5638
5639 if (sameResource(value, base))
5640 continue;
5641
5642 // Values don't represent the same base.
5643 ok = false;
5644 }
5645 }
5646
5647 return ok;
5648 }
5649
5650 // Conservatively return false.
5651 return false;
5652}
alan-bakere9308012019-03-15 10:25:13 -04005653
5654bool SPIRVProducerPass::CalledWithCoherentResource(Argument &Arg) {
5655 if (!Arg.getType()->isPointerTy() ||
5656 Arg.getType()->getPointerAddressSpace() != clspv::AddressSpace::Global) {
5657 // Only SSBOs need to be annotated as coherent.
5658 return false;
5659 }
5660
5661 DenseSet<Value *> visited;
5662 std::vector<Value *> stack;
5663 for (auto *U : Arg.getParent()->users()) {
5664 if (auto *call = dyn_cast<CallInst>(U)) {
5665 stack.push_back(call->getOperand(Arg.getArgNo()));
5666 }
5667 }
5668
5669 while (!stack.empty()) {
5670 Value *v = stack.back();
5671 stack.pop_back();
5672
5673 if (!visited.insert(v).second)
5674 continue;
5675
5676 auto *resource_call = dyn_cast<CallInst>(v);
5677 if (resource_call &&
SJW61531372020-06-09 07:31:08 -05005678 Builtins::Lookup(resource_call->getCalledFunction()).getType() ==
5679 Builtins::kClspvResource) {
alan-bakere9308012019-03-15 10:25:13 -04005680 // If this is a resource accessor function, check if the coherent operand
5681 // is set.
5682 const auto coherent =
5683 unsigned(dyn_cast<ConstantInt>(resource_call->getArgOperand(5))
5684 ->getZExtValue());
5685 if (coherent == 1)
5686 return true;
5687 } else if (auto *arg = dyn_cast<Argument>(v)) {
5688 // If this is a function argument, trace through its callers.
alan-bakere98f3f92019-04-08 15:06:36 -04005689 for (auto U : arg->getParent()->users()) {
alan-bakere9308012019-03-15 10:25:13 -04005690 if (auto *call = dyn_cast<CallInst>(U)) {
5691 stack.push_back(call->getOperand(arg->getArgNo()));
5692 }
5693 }
5694 } else if (auto *user = dyn_cast<User>(v)) {
5695 // If this is a user, traverse all operands that could lead to resource
5696 // variables.
5697 for (unsigned i = 0; i != user->getNumOperands(); ++i) {
5698 Value *operand = user->getOperand(i);
5699 if (operand->getType()->isPointerTy() &&
5700 operand->getType()->getPointerAddressSpace() ==
5701 clspv::AddressSpace::Global) {
5702 stack.push_back(operand);
5703 }
5704 }
5705 }
5706 }
5707
5708 // No coherent resource variables encountered.
5709 return false;
5710}
alan-baker06cad652019-12-03 17:56:47 -05005711
SJW77b87ad2020-04-21 14:37:52 -05005712void SPIRVProducerPass::PopulateStructuredCFGMaps() {
alan-baker06cad652019-12-03 17:56:47 -05005713 // First, track loop merges and continues.
5714 DenseSet<BasicBlock *> LoopMergesAndContinues;
SJW77b87ad2020-04-21 14:37:52 -05005715 for (auto &F : *module) {
alan-baker06cad652019-12-03 17:56:47 -05005716 if (F.isDeclaration())
5717 continue;
5718
5719 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
5720 const LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>(F).getLoopInfo();
5721 std::deque<BasicBlock *> order;
5722 DenseSet<BasicBlock *> visited;
5723 clspv::ComputeStructuredOrder(&*F.begin(), &DT, LI, &order, &visited);
5724
5725 for (auto BB : order) {
5726 auto terminator = BB->getTerminator();
5727 auto branch = dyn_cast<BranchInst>(terminator);
5728 if (LI.isLoopHeader(BB)) {
5729 auto L = LI.getLoopFor(BB);
5730 BasicBlock *ContinueBB = nullptr;
5731 BasicBlock *MergeBB = nullptr;
5732
5733 MergeBB = L->getExitBlock();
5734 if (!MergeBB) {
5735 // StructurizeCFG pass converts CFG into triangle shape and the cfg
5736 // has regions with single entry/exit. As a result, loop should not
5737 // have multiple exits.
5738 llvm_unreachable("Loop has multiple exits???");
5739 }
5740
5741 if (L->isLoopLatch(BB)) {
5742 ContinueBB = BB;
5743 } else {
5744 // From SPIR-V spec 2.11, Continue Target must dominate that back-edge
5745 // block.
5746 BasicBlock *Header = L->getHeader();
5747 BasicBlock *Latch = L->getLoopLatch();
5748 for (auto *loop_block : L->blocks()) {
5749 if (loop_block == Header) {
5750 continue;
5751 }
5752
5753 // Check whether block dominates block with back-edge.
5754 // The loop latch is the single block with a back-edge. If it was
5755 // possible, StructurizeCFG made the loop conform to this
5756 // requirement, otherwise |Latch| is a nullptr.
5757 if (DT.dominates(loop_block, Latch)) {
5758 ContinueBB = loop_block;
5759 }
5760 }
5761
5762 if (!ContinueBB) {
5763 llvm_unreachable("Wrong continue block from loop");
5764 }
5765 }
5766
5767 // Record the continue and merge blocks.
5768 MergeBlocks[BB] = MergeBB;
5769 ContinueBlocks[BB] = ContinueBB;
5770 LoopMergesAndContinues.insert(MergeBB);
5771 LoopMergesAndContinues.insert(ContinueBB);
5772 } else if (branch && branch->isConditional()) {
5773 auto L = LI.getLoopFor(BB);
5774 bool HasBackedge = false;
5775 while (L && !HasBackedge) {
5776 if (L->isLoopLatch(BB)) {
5777 HasBackedge = true;
5778 }
5779 L = L->getParentLoop();
5780 }
5781
5782 if (!HasBackedge) {
5783 // Only need a merge if the branch doesn't include a loop break or
5784 // continue.
5785 auto true_bb = branch->getSuccessor(0);
5786 auto false_bb = branch->getSuccessor(1);
5787 if (!LoopMergesAndContinues.count(true_bb) &&
5788 !LoopMergesAndContinues.count(false_bb)) {
5789 // StructurizeCFG pass already manipulated CFG. Just use false block
5790 // of branch instruction as merge block.
5791 MergeBlocks[BB] = false_bb;
5792 }
5793 }
5794 }
5795 }
5796 }
5797}
alan-baker86ce19c2020-08-05 13:09:19 -04005798
5799SPIRVID SPIRVProducerPass::getReflectionImport() {
5800 if (!ReflectionID.isValid()) {
5801 addSPIRVInst<kExtensions>(spv::OpExtension, "SPV_KHR_non_semantic_info");
5802 ReflectionID = addSPIRVInst<kImports>(spv::OpExtInstImport,
5803 "NonSemantic.ClspvReflection.1");
5804 }
5805 return ReflectionID;
5806}
5807
5808void SPIRVProducerPass::GenerateReflection() {
5809 GenerateKernelReflection();
5810 GeneratePushConstantReflection();
5811 GenerateSpecConstantReflection();
5812}
5813
5814void SPIRVProducerPass::GeneratePushConstantReflection() {
5815 if (auto GV = module->getGlobalVariable(clspv::PushConstantsVariableName())) {
5816 auto const &DL = module->getDataLayout();
5817 auto MD = GV->getMetadata(clspv::PushConstantsMetadataName());
5818 auto STy = cast<StructType>(GV->getValueType());
5819
5820 for (unsigned i = 0; i < STy->getNumElements(); i++) {
5821 auto pc = static_cast<clspv::PushConstant>(
5822 mdconst::extract<ConstantInt>(MD->getOperand(i))->getZExtValue());
5823 if (pc == PushConstant::KernelArgument)
5824 continue;
5825
5826 auto memberType = STy->getElementType(i);
5827 auto offset = GetExplicitLayoutStructMemberOffset(STy, i, DL);
Marco Antognini7e338402021-03-15 12:48:37 +00005828#ifndef NDEBUG
alan-baker86ce19c2020-08-05 13:09:19 -04005829 unsigned previousOffset = 0;
5830 if (i > 0) {
5831 previousOffset = GetExplicitLayoutStructMemberOffset(STy, i - 1, DL);
5832 }
alan-baker86ce19c2020-08-05 13:09:19 -04005833 assert(isValidExplicitLayout(*module, STy, i,
5834 spv::StorageClassPushConstant, offset,
5835 previousOffset));
Marco Antognini7e338402021-03-15 12:48:37 +00005836#endif
alan-baker86ce19c2020-08-05 13:09:19 -04005837
5838 reflection::ExtInst pc_inst = reflection::ExtInstMax;
5839 switch (pc) {
5840 case PushConstant::GlobalOffset:
5841 pc_inst = reflection::ExtInstPushConstantGlobalOffset;
5842 break;
5843 case PushConstant::EnqueuedLocalSize:
5844 pc_inst = reflection::ExtInstPushConstantEnqueuedLocalSize;
5845 break;
5846 case PushConstant::GlobalSize:
5847 pc_inst = reflection::ExtInstPushConstantGlobalSize;
5848 break;
5849 case PushConstant::RegionOffset:
5850 pc_inst = reflection::ExtInstPushConstantRegionOffset;
5851 break;
5852 case PushConstant::NumWorkgroups:
5853 pc_inst = reflection::ExtInstPushConstantNumWorkgroups;
5854 break;
5855 case PushConstant::RegionGroupOffset:
5856 pc_inst = reflection::ExtInstPushConstantRegionGroupOffset;
5857 break;
5858 default:
5859 llvm_unreachable("Unhandled push constant");
5860 break;
5861 }
5862
5863 auto import_id = getReflectionImport();
Marco Antognini7e338402021-03-15 12:48:37 +00005864 auto size = static_cast<uint32_t>(GetTypeSizeInBits(memberType, DL)) / 8;
alan-baker86ce19c2020-08-05 13:09:19 -04005865 SPIRVOperandVec Ops;
5866 Ops << getSPIRVType(Type::getVoidTy(module->getContext())) << import_id
5867 << pc_inst << getSPIRVInt32Constant(offset)
5868 << getSPIRVInt32Constant(size);
5869 addSPIRVInst(spv::OpExtInst, Ops);
5870 }
5871 }
5872}
5873
5874void SPIRVProducerPass::GenerateSpecConstantReflection() {
5875 const uint32_t kMax = std::numeric_limits<uint32_t>::max();
5876 uint32_t wgsize_id[3] = {kMax, kMax, kMax};
5877 uint32_t global_offset_id[3] = {kMax, kMax, kMax};
5878 uint32_t work_dim_id = kMax;
5879 for (auto pair : clspv::GetSpecConstants(module)) {
5880 auto kind = pair.first;
5881 auto id = pair.second;
5882
5883 // Local memory size is only used for kernel arguments.
5884 if (kind == SpecConstant::kLocalMemorySize)
5885 continue;
5886
5887 switch (kind) {
5888 case SpecConstant::kWorkgroupSizeX:
5889 wgsize_id[0] = id;
5890 break;
5891 case SpecConstant::kWorkgroupSizeY:
5892 wgsize_id[1] = id;
5893 break;
5894 case SpecConstant::kWorkgroupSizeZ:
5895 wgsize_id[2] = id;
5896 break;
5897 case SpecConstant::kGlobalOffsetX:
5898 global_offset_id[0] = id;
5899 break;
5900 case SpecConstant::kGlobalOffsetY:
5901 global_offset_id[1] = id;
5902 break;
5903 case SpecConstant::kGlobalOffsetZ:
5904 global_offset_id[2] = id;
5905 break;
5906 case SpecConstant::kWorkDim:
5907 work_dim_id = id;
5908 break;
5909 default:
5910 llvm_unreachable("Unhandled spec constant");
5911 }
5912 }
5913
5914 auto import_id = getReflectionImport();
5915 auto void_id = getSPIRVType(Type::getVoidTy(module->getContext()));
5916 SPIRVOperandVec Ops;
5917 if (wgsize_id[0] != kMax) {
5918 assert(wgsize_id[1] != kMax);
5919 assert(wgsize_id[2] != kMax);
5920 Ops.clear();
5921 Ops << void_id << import_id << reflection::ExtInstSpecConstantWorkgroupSize
5922 << getSPIRVInt32Constant(wgsize_id[0])
5923 << getSPIRVInt32Constant(wgsize_id[1])
5924 << getSPIRVInt32Constant(wgsize_id[2]);
5925 addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
5926 }
5927 if (global_offset_id[0] != kMax) {
5928 assert(global_offset_id[1] != kMax);
5929 assert(global_offset_id[2] != kMax);
5930 Ops.clear();
5931 Ops << void_id << import_id << reflection::ExtInstSpecConstantGlobalOffset
5932 << getSPIRVInt32Constant(global_offset_id[0])
5933 << getSPIRVInt32Constant(global_offset_id[1])
5934 << getSPIRVInt32Constant(global_offset_id[2]);
5935 addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
5936 }
5937 if (work_dim_id != kMax) {
5938 Ops.clear();
5939 Ops << void_id << import_id << reflection::ExtInstSpecConstantWorkDim
5940 << getSPIRVInt32Constant(work_dim_id);
5941 addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
5942 }
5943}
5944
5945void SPIRVProducerPass::GenerateKernelReflection() {
5946 const auto &DL = module->getDataLayout();
5947 auto import_id = getReflectionImport();
5948 auto void_id = getSPIRVType(Type::getVoidTy(module->getContext()));
5949
5950 for (auto &F : *module) {
5951 if (F.isDeclaration() || F.getCallingConv() != CallingConv::SPIR_KERNEL) {
5952 continue;
5953 }
5954
5955 // OpString for the kernel name.
5956 auto kernel_name =
5957 addSPIRVInst<kDebug>(spv::OpString, F.getName().str().c_str());
5958
5959 // Kernel declaration
5960 // Ops[0] = void type
5961 // Ops[1] = reflection ext import
5962 // Ops[2] = function id
5963 // Ops[3] = kernel name
5964 SPIRVOperandVec Ops;
5965 Ops << void_id << import_id << reflection::ExtInstKernel << ValueMap[&F]
5966 << kernel_name;
5967 auto kernel_decl = addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
5968
5969 // Generate the required workgroup size property if it was specified.
5970 if (const MDNode *MD = F.getMetadata("reqd_work_group_size")) {
5971 uint32_t CurXDimCst = static_cast<uint32_t>(
5972 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
5973 uint32_t CurYDimCst = static_cast<uint32_t>(
5974 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
5975 uint32_t CurZDimCst = static_cast<uint32_t>(
5976 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
5977
5978 Ops.clear();
5979 Ops << void_id << import_id
5980 << reflection::ExtInstPropertyRequiredWorkgroupSize << kernel_decl
5981 << getSPIRVInt32Constant(CurXDimCst)
5982 << getSPIRVInt32Constant(CurYDimCst)
5983 << getSPIRVInt32Constant(CurZDimCst);
5984 addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
5985 }
5986
5987 auto &resource_var_at_index = FunctionToResourceVarsMap[&F];
5988 auto *func_ty = F.getFunctionType();
5989
5990 // If we've clustered POD arguments, then argument details are in metadata.
5991 // If an argument maps to a resource variable, then get descriptor set and
5992 // binding from the resource variable. Other info comes from the metadata.
5993 const auto *arg_map = F.getMetadata(clspv::KernelArgMapMetadataName());
5994 auto local_spec_id_md =
5995 module->getNamedMetadata(clspv::LocalSpecIdMetadataName());
5996 if (arg_map) {
5997 for (const auto &arg : arg_map->operands()) {
5998 const MDNode *arg_node = dyn_cast<MDNode>(arg.get());
5999 assert(arg_node->getNumOperands() == 6);
6000 const auto name =
6001 dyn_cast<MDString>(arg_node->getOperand(0))->getString();
6002 const auto old_index =
6003 dyn_extract<ConstantInt>(arg_node->getOperand(1))->getZExtValue();
6004 // Remapped argument index
6005 const int new_index = static_cast<int>(
6006 dyn_extract<ConstantInt>(arg_node->getOperand(2))->getSExtValue());
6007 const auto offset =
6008 dyn_extract<ConstantInt>(arg_node->getOperand(3))->getZExtValue();
6009 const auto size =
6010 dyn_extract<ConstantInt>(arg_node->getOperand(4))->getZExtValue();
6011 const auto argKind = clspv::GetArgKindFromName(
6012 dyn_cast<MDString>(arg_node->getOperand(5))->getString().str());
6013
6014 // If this is a local memory argument, find the right spec id for this
6015 // argument.
6016 int64_t spec_id = -1;
6017 if (argKind == clspv::ArgKind::Local) {
6018 for (auto spec_id_arg : local_spec_id_md->operands()) {
6019 if ((&F == dyn_cast<Function>(
6020 dyn_cast<ValueAsMetadata>(spec_id_arg->getOperand(0))
6021 ->getValue())) &&
6022 (static_cast<uint64_t>(new_index) ==
6023 mdconst::extract<ConstantInt>(spec_id_arg->getOperand(1))
6024 ->getZExtValue())) {
6025 spec_id =
6026 mdconst::extract<ConstantInt>(spec_id_arg->getOperand(2))
6027 ->getSExtValue();
6028 break;
6029 }
6030 }
6031 }
6032
6033 // Generate the specific argument instruction.
6034 const uint32_t ordinal = static_cast<uint32_t>(old_index);
6035 const uint32_t arg_offset = static_cast<uint32_t>(offset);
6036 const uint32_t arg_size = static_cast<uint32_t>(size);
6037 uint32_t elem_size = 0;
6038 uint32_t descriptor_set = 0;
6039 uint32_t binding = 0;
6040 if (spec_id > 0) {
6041 elem_size = static_cast<uint32_t>(
6042 GetTypeAllocSize(func_ty->getParamType(unsigned(new_index))
6043 ->getPointerElementType(),
6044 DL));
6045 } else if (new_index >= 0) {
6046 auto *info = resource_var_at_index[new_index];
6047 assert(info);
6048 descriptor_set = info->descriptor_set;
6049 binding = info->binding;
6050 }
6051 AddArgumentReflection(kernel_decl, name.str(), argKind, ordinal,
6052 descriptor_set, binding, arg_offset, arg_size,
6053 static_cast<uint32_t>(spec_id), elem_size);
6054 }
6055 } else {
6056 // There is no argument map.
6057 // Take descriptor info from the resource variable calls.
6058 // Take argument name and size from the arguments list.
6059
6060 SmallVector<Argument *, 4> arguments;
6061 for (auto &arg : F.args()) {
6062 arguments.push_back(&arg);
6063 }
6064
6065 unsigned arg_index = 0;
6066 for (auto *info : resource_var_at_index) {
6067 if (info) {
6068 auto arg = arguments[arg_index];
6069 unsigned arg_size = 0;
6070 if (info->arg_kind == clspv::ArgKind::Pod ||
6071 info->arg_kind == clspv::ArgKind::PodUBO ||
6072 info->arg_kind == clspv::ArgKind::PodPushConstant) {
6073 arg_size =
6074 static_cast<uint32_t>(DL.getTypeStoreSize(arg->getType()));
6075 }
6076
6077 // Local pointer arguments are unused in this case.
6078 // offset, spec_id and elem_size always 0.
6079 AddArgumentReflection(kernel_decl, arg->getName().str(),
6080 info->arg_kind, arg_index, info->descriptor_set,
6081 info->binding, 0, arg_size, 0, 0);
6082 }
6083 arg_index++;
6084 }
6085 // Generate mappings for pointer-to-local arguments.
6086 for (arg_index = 0; arg_index < arguments.size(); ++arg_index) {
6087 Argument *arg = arguments[arg_index];
6088 auto where = LocalArgSpecIds.find(arg);
6089 if (where != LocalArgSpecIds.end()) {
6090 auto &local_arg_info = LocalSpecIdInfoMap[where->second];
6091
6092 // descriptor_set, binding, offset and size are always 0.
6093 AddArgumentReflection(kernel_decl, arg->getName().str(),
6094 ArgKind::Local, arg_index, 0, 0, 0, 0,
6095 static_cast<uint32_t>(local_arg_info.spec_id),
6096 static_cast<uint32_t>(GetTypeAllocSize(
6097 local_arg_info.elem_type, DL)));
6098 }
6099 }
6100 }
6101 }
6102}
6103
6104void SPIRVProducerPass::AddArgumentReflection(
6105 SPIRVID kernel_decl, const std::string &name, clspv::ArgKind arg_kind,
6106 uint32_t ordinal, uint32_t descriptor_set, uint32_t binding,
6107 uint32_t offset, uint32_t size, uint32_t spec_id, uint32_t elem_size) {
6108 // Generate ArgumentInfo for this argument.
6109 // TODO: generate remaining optional operands.
6110 auto import_id = getReflectionImport();
6111 auto arg_name = addSPIRVInst<kDebug>(spv::OpString, name.c_str());
6112 auto void_id = getSPIRVType(Type::getVoidTy(module->getContext()));
6113 SPIRVOperandVec Ops;
6114 Ops << void_id << import_id << reflection::ExtInstArgumentInfo << arg_name;
6115 auto arg_info = addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
6116
6117 Ops.clear();
6118 Ops << void_id << import_id;
6119 reflection::ExtInst ext_inst = reflection::ExtInstMax;
6120 // Determine the extended instruction.
6121 switch (arg_kind) {
6122 case clspv::ArgKind::Buffer:
6123 ext_inst = reflection::ExtInstArgumentStorageBuffer;
6124 break;
6125 case clspv::ArgKind::BufferUBO:
6126 ext_inst = reflection::ExtInstArgumentUniform;
6127 break;
6128 case clspv::ArgKind::Local:
6129 ext_inst = reflection::ExtInstArgumentWorkgroup;
6130 break;
6131 case clspv::ArgKind::Pod:
6132 ext_inst = reflection::ExtInstArgumentPodStorageBuffer;
6133 break;
6134 case clspv::ArgKind::PodUBO:
6135 ext_inst = reflection::ExtInstArgumentPodUniform;
6136 break;
6137 case clspv::ArgKind::PodPushConstant:
6138 ext_inst = reflection::ExtInstArgumentPodPushConstant;
6139 break;
alan-bakerf6bc8252020-09-23 14:58:55 -04006140 case clspv::ArgKind::SampledImage:
alan-baker86ce19c2020-08-05 13:09:19 -04006141 ext_inst = reflection::ExtInstArgumentSampledImage;
6142 break;
alan-bakerf6bc8252020-09-23 14:58:55 -04006143 case clspv::ArgKind::StorageImage:
alan-baker86ce19c2020-08-05 13:09:19 -04006144 ext_inst = reflection::ExtInstArgumentStorageImage;
6145 break;
6146 case clspv::ArgKind::Sampler:
6147 ext_inst = reflection::ExtInstArgumentSampler;
6148 break;
6149 default:
6150 llvm_unreachable("Unhandled argument reflection");
6151 break;
6152 }
6153 Ops << ext_inst << kernel_decl << getSPIRVInt32Constant(ordinal);
6154
6155 // Add descriptor set and binding for applicable arguments.
6156 switch (arg_kind) {
6157 case clspv::ArgKind::Buffer:
6158 case clspv::ArgKind::BufferUBO:
6159 case clspv::ArgKind::Pod:
6160 case clspv::ArgKind::PodUBO:
alan-bakerf6bc8252020-09-23 14:58:55 -04006161 case clspv::ArgKind::SampledImage:
6162 case clspv::ArgKind::StorageImage:
alan-baker86ce19c2020-08-05 13:09:19 -04006163 case clspv::ArgKind::Sampler:
6164 Ops << getSPIRVInt32Constant(descriptor_set)
6165 << getSPIRVInt32Constant(binding);
6166 break;
6167 default:
6168 break;
6169 }
6170
6171 // Add remaining operands for arguments.
6172 switch (arg_kind) {
6173 case clspv::ArgKind::Local:
6174 Ops << getSPIRVInt32Constant(spec_id) << getSPIRVInt32Constant(elem_size);
6175 break;
6176 case clspv::ArgKind::Pod:
6177 case clspv::ArgKind::PodUBO:
6178 case clspv::ArgKind::PodPushConstant:
6179 Ops << getSPIRVInt32Constant(offset) << getSPIRVInt32Constant(size);
6180 break;
6181 default:
6182 break;
6183 }
6184 Ops << arg_info;
6185 addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
6186}