blob: 3ab940a66c6d7ac0f48bbf35fdb5ce3032094f4f [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"
37#include "llvm/IR/Metadata.h"
38#include "llvm/IR/Module.h"
alan-bakerf67468c2019-11-25 15:51:49 -050039#include "llvm/IR/ValueSymbolTable.h"
David Neto118188e2018-08-24 11:27:54 -040040#include "llvm/Pass.h"
41#include "llvm/Support/CommandLine.h"
Kévin Petitbbbda972020-03-03 19:16:31 +000042#include "llvm/Support/MathExtras.h"
David Neto118188e2018-08-24 11:27:54 -040043#include "llvm/Support/raw_ostream.h"
44#include "llvm/Transforms/Utils/Cloning.h"
David Neto22f144c2017-06-12 14:26:21 -040045
SJWf93f5f32020-05-05 07:27:56 -050046// enable spv::HasResultAndType
47#define SPV_ENABLE_UTILITY_CODE
alan-bakere0902602020-03-23 08:43:40 -040048#include "spirv/unified1/spirv.hpp"
David Neto118188e2018-08-24 11:27:54 -040049
David Neto85082642018-03-24 06:55:20 -070050#include "clspv/AddressSpace.h"
David Neto118188e2018-08-24 11:27:54 -040051#include "clspv/Option.h"
alan-baker86ce19c2020-08-05 13:09:19 -040052#include "clspv/PushConstant.h"
53#include "clspv/SpecConstant.h"
David Neto85082642018-03-24 06:55:20 -070054#include "clspv/spirv_c_strings.hpp"
55#include "clspv/spirv_glsl.hpp"
alan-baker86ce19c2020-08-05 13:09:19 -040056#include "clspv/spirv_reflection.hpp"
David Neto22f144c2017-06-12 14:26:21 -040057
David Neto4feb7a42017-10-06 17:29:42 -040058#include "ArgKind.h"
alan-bakerf67468c2019-11-25 15:51:49 -050059#include "Builtins.h"
alan-baker06cad652019-12-03 17:56:47 -050060#include "ComputeStructuredOrder.h"
David Neto85082642018-03-24 06:55:20 -070061#include "ConstantEmitter.h"
Alan Baker202c8c72018-08-13 13:47:44 -040062#include "Constants.h"
David Neto78383442018-06-15 20:31:56 -040063#include "DescriptorCounter.h"
alan-bakerc4579bb2020-04-29 14:15:50 -040064#include "Layout.h"
alan-baker56f7aff2019-05-22 08:06:42 -040065#include "NormalizeGlobalVariable.h"
Diego Novilloa4c44fa2019-04-11 10:56:15 -040066#include "Passes.h"
alan-bakera1be3322020-04-20 12:48:18 -040067#include "SpecConstant.h"
alan-bakerce179f12019-12-06 19:02:22 -050068#include "Types.h"
David Neto48f56a42017-10-06 16:44:25 -040069
David Neto22f144c2017-06-12 14:26:21 -040070#if defined(_MSC_VER)
71#pragma warning(pop)
72#endif
73
74using namespace llvm;
75using namespace clspv;
SJW173c7e92020-03-16 08:44:47 -050076using namespace clspv::Builtins;
SJW806a5d82020-07-15 12:51:38 -050077using namespace clspv::Option;
David Neto156783e2017-07-05 15:39:41 -040078using namespace mdconst;
David Neto22f144c2017-06-12 14:26:21 -040079
80namespace {
David Netocd8ca5f2017-10-02 23:34:11 -040081
David Neto862b7d82018-06-14 18:48:37 -040082cl::opt<bool> ShowResourceVars("show-rv", cl::init(false), cl::Hidden,
83 cl::desc("Show resource variable creation"));
84
alan-baker5ed87542020-03-23 11:05:22 -040085cl::opt<bool>
86 ShowProducerIR("show-producer-ir", cl::init(false), cl::ReallyHidden,
87 cl::desc("Dump the IR at the start of SPIRVProducer"));
88
David Neto862b7d82018-06-14 18:48:37 -040089// These hacks exist to help transition code generation algorithms
90// without making huge noise in detailed test output.
91const bool Hack_generate_runtime_array_stride_early = true;
92
David Neto3fbb4072017-10-16 11:28:14 -040093// The value of 1/pi. This value is from MSDN
94// https://msdn.microsoft.com/en-us/library/4hwaceh6.aspx
95const double kOneOverPi = 0.318309886183790671538;
96const glsl::ExtInst kGlslExtInstBad = static_cast<glsl::ExtInst>(0);
97
alan-baker86ce19c2020-08-05 13:09:19 -040098// SPIRV Module Sections (per 2.4 of the SPIR-V spec)
SJW69939d52020-04-16 07:29:07 -050099// These are used to collect SPIRVInstructions by type on-the-fly.
100enum SPIRVSection {
101 kCapabilities,
102 kExtensions,
103 kImports,
104 kMemoryModel,
105 kEntryPoints,
106 kExecutionModes,
107
108 kDebug,
109 kAnnotations,
110
111 kTypes,
112 kConstants = kTypes,
113 kGlobalVariables,
114
115 kFunctions,
116
alan-baker86ce19c2020-08-05 13:09:19 -0400117 // This is not a section of the SPIR-V spec and should always immediately
118 // precede kSectionCount. It is a convenient place for the embedded
119 // reflection data.
120 kReflection,
SJW69939d52020-04-16 07:29:07 -0500121 kSectionCount
122};
123
SJW01901d92020-05-21 08:58:31 -0500124class SPIRVID {
125 uint32_t id;
126
127public:
128 SPIRVID(uint32_t _id = 0) : id(_id) {}
129 uint32_t get() const { return id; }
130 bool isValid() const { return id != 0; }
131 bool operator==(const SPIRVID &that) const { return id == that.id; }
SJW806a5d82020-07-15 12:51:38 -0500132 bool operator<(const SPIRVID &that) const { return id < that.id; }
SJW01901d92020-05-21 08:58:31 -0500133};
SJWf93f5f32020-05-05 07:27:56 -0500134
SJW88ed5fe2020-05-11 12:40:57 -0500135enum SPIRVOperandType { NUMBERID, LITERAL_WORD, LITERAL_DWORD, LITERAL_STRING };
David Neto22f144c2017-06-12 14:26:21 -0400136
137struct SPIRVOperand {
SJW88ed5fe2020-05-11 12:40:57 -0500138 explicit SPIRVOperand(SPIRVOperandType Ty, uint32_t Num) : Type(Ty) {
139 LiteralNum[0] = Num;
140 }
David Neto22f144c2017-06-12 14:26:21 -0400141 explicit SPIRVOperand(SPIRVOperandType Ty, const char *Str)
142 : Type(Ty), LiteralStr(Str) {}
143 explicit SPIRVOperand(SPIRVOperandType Ty, StringRef Str)
144 : Type(Ty), LiteralStr(Str) {}
SJW88ed5fe2020-05-11 12:40:57 -0500145 explicit SPIRVOperand(ArrayRef<uint32_t> NumVec) {
146 auto sz = NumVec.size();
147 assert(sz >= 1 && sz <= 2);
148 Type = sz == 1 ? LITERAL_WORD : LITERAL_DWORD;
149 LiteralNum[0] = NumVec[0];
150 if (sz == 2) {
151 LiteralNum[1] = NumVec[1];
152 }
153 }
David Neto22f144c2017-06-12 14:26:21 -0400154
alan-baker7506abb2020-09-10 15:02:55 -0400155 SPIRVOperandType getType() const { return Type; }
156 uint32_t getNumID() const { return LiteralNum[0]; }
157 std::string getLiteralStr() const { return LiteralStr; }
158 const uint32_t *getLiteralNum() const { return LiteralNum; }
David Neto22f144c2017-06-12 14:26:21 -0400159
David Neto87846742018-04-11 17:36:22 -0400160 uint32_t GetNumWords() const {
161 switch (Type) {
162 case NUMBERID:
SJW88ed5fe2020-05-11 12:40:57 -0500163 case LITERAL_WORD:
David Neto87846742018-04-11 17:36:22 -0400164 return 1;
SJW88ed5fe2020-05-11 12:40:57 -0500165 case LITERAL_DWORD:
166 return 2;
David Neto87846742018-04-11 17:36:22 -0400167 case LITERAL_STRING:
168 // Account for the terminating null character.
David Netoee2660d2018-06-28 16:31:29 -0400169 return uint32_t((LiteralStr.size() + 4) / 4);
David Neto87846742018-04-11 17:36:22 -0400170 }
171 llvm_unreachable("Unhandled case in SPIRVOperand::GetNumWords()");
172 }
173
David Neto22f144c2017-06-12 14:26:21 -0400174private:
175 SPIRVOperandType Type;
176 std::string LiteralStr;
SJW88ed5fe2020-05-11 12:40:57 -0500177 uint32_t LiteralNum[2];
David Neto22f144c2017-06-12 14:26:21 -0400178};
179
SJW88ed5fe2020-05-11 12:40:57 -0500180typedef SmallVector<SPIRVOperand, 4> SPIRVOperandVec;
David Netoc6f3ab22018-04-06 18:02:31 -0400181
David Neto22f144c2017-06-12 14:26:21 -0400182struct SPIRVInstruction {
SJWf93f5f32020-05-05 07:27:56 -0500183 // Primary constructor must have Opcode, initializes WordCount based on ResID.
184 SPIRVInstruction(spv::Op Opc, SPIRVID ResID = 0)
185 : Opcode(static_cast<uint16_t>(Opc)) {
186 setResult(ResID);
David Neto87846742018-04-11 17:36:22 -0400187 }
David Neto22f144c2017-06-12 14:26:21 -0400188
SJWf93f5f32020-05-05 07:27:56 -0500189 // Creates an instruction with an opcode and no result ID, and with the given
190 // operands. This calls primary constructor to initialize Opcode, WordCount.
191 // Takes ownership of the operands and clears |Ops|.
192 SPIRVInstruction(spv::Op Opc, SPIRVOperandVec &Ops) : SPIRVInstruction(Opc) {
193 setOperands(Ops);
David Netoef5ba2b2019-12-20 08:35:54 -0500194 }
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, SPIRVID ResID, SPIRVOperandVec &Ops)
199 : SPIRVInstruction(Opc, ResID) {
200 setOperands(Ops);
David Netoef5ba2b2019-12-20 08:35:54 -0500201 }
David Netoef5ba2b2019-12-20 08:35:54 -0500202
David Netoee2660d2018-06-28 16:31:29 -0400203 uint32_t getWordCount() const { return WordCount; }
David Neto22f144c2017-06-12 14:26:21 -0400204 uint16_t getOpcode() const { return Opcode; }
SJW88ed5fe2020-05-11 12:40:57 -0500205 SPIRVID getResultID() const { return ResultID; }
206 const SPIRVOperandVec &getOperands() const { return Operands; }
David Neto22f144c2017-06-12 14:26:21 -0400207
208private:
SJW01901d92020-05-21 08:58:31 -0500209 void setResult(SPIRVID ResID = 0) {
210 WordCount = 1 + (ResID.isValid() ? 1 : 0);
SJWf93f5f32020-05-05 07:27:56 -0500211 ResultID = ResID;
212 }
213
214 void setOperands(SPIRVOperandVec &Ops) {
215 assert(Operands.empty());
216 Operands = std::move(Ops);
217 for (auto &opd : Operands) {
SJW88ed5fe2020-05-11 12:40:57 -0500218 WordCount += uint16_t(opd.GetNumWords());
SJWf93f5f32020-05-05 07:27:56 -0500219 }
220 }
221
222private:
David Netoee2660d2018-06-28 16:31:29 -0400223 uint32_t WordCount; // Check the 16-bit bound at code generation time.
David Neto22f144c2017-06-12 14:26:21 -0400224 uint16_t Opcode;
SJW88ed5fe2020-05-11 12:40:57 -0500225 SPIRVID ResultID;
SJWf93f5f32020-05-05 07:27:56 -0500226 SPIRVOperandVec Operands;
David Neto22f144c2017-06-12 14:26:21 -0400227};
228
229struct SPIRVProducerPass final : public ModulePass {
SJW01901d92020-05-21 08:58:31 -0500230 typedef DenseMap<Type *, SPIRVID> TypeMapType;
David Neto22f144c2017-06-12 14:26:21 -0400231 typedef UniqueVector<Type *> TypeList;
SJW88ed5fe2020-05-11 12:40:57 -0500232 typedef DenseMap<Value *, SPIRVID> ValueMapType;
SJW806a5d82020-07-15 12:51:38 -0500233 typedef std::list<SPIRVID> SPIRVIDListType;
SJW01901d92020-05-21 08:58:31 -0500234 typedef std::vector<std::pair<Value *, SPIRVID>> EntryPointVecType;
235 typedef std::set<uint32_t> CapabilitySetType;
SJW88ed5fe2020-05-11 12:40:57 -0500236 typedef std::list<SPIRVInstruction> SPIRVInstructionList;
SJW806a5d82020-07-15 12:51:38 -0500237 typedef std::map<spv::BuiltIn, SPIRVID> BuiltinConstantMapType;
SJW88ed5fe2020-05-11 12:40:57 -0500238 // A vector of pairs, each of which is:
David Neto87846742018-04-11 17:36:22 -0400239 // - the LLVM instruction that we will later generate SPIR-V code for
SJW88ed5fe2020-05-11 12:40:57 -0500240 // - the SPIR-V instruction placeholder that will be replaced
241 typedef std::vector<std::pair<Value *, SPIRVInstruction *>>
David Neto22f144c2017-06-12 14:26:21 -0400242 DeferredInstVecType;
243 typedef DenseMap<FunctionType *, std::pair<FunctionType *, uint32_t>>
244 GlobalConstFuncMapType;
245
David Neto44795152017-07-13 15:45:28 -0400246 explicit SPIRVProducerPass(
alan-bakerf5e5f692018-11-27 08:33:24 -0500247 raw_pwrite_stream &out,
alan-baker00e7a582019-06-07 12:54:21 -0400248 ArrayRef<std::pair<unsigned, std::string>> samplerMap,
David Neto44795152017-07-13 15:45:28 -0400249 bool outputCInitList)
SJW01901d92020-05-21 08:58:31 -0500250 : ModulePass(ID), module(nullptr), samplerMap(samplerMap), out(out),
David Neto0676e6f2017-07-11 18:47:44 -0400251 binaryTempOut(binaryTempUnderlyingVector), binaryOut(&out),
David Neto0676e6f2017-07-11 18:47:44 -0400252 outputCInitList(outputCInitList), patchBoundOffset(0), nextID(1),
alan-baker5b86ed72019-02-15 08:26:50 -0500253 OpExtInstImportID(0), HasVariablePointersStorageBuffer(false),
254 HasVariablePointers(false), SamplerTy(nullptr), WorkgroupSizeValueID(0),
SJW01901d92020-05-21 08:58:31 -0500255 WorkgroupSizeVarID(0) {
256 addCapability(spv::CapabilityShader);
257 Ptr = this;
258 }
David Neto22f144c2017-06-12 14:26:21 -0400259
James Price11010dc2019-12-19 13:53:09 -0500260 virtual ~SPIRVProducerPass() {
James Price11010dc2019-12-19 13:53:09 -0500261 }
262
David Neto22f144c2017-06-12 14:26:21 -0400263 void getAnalysisUsage(AnalysisUsage &AU) const override {
264 AU.addRequired<DominatorTreeWrapperPass>();
265 AU.addRequired<LoopInfoWrapperPass>();
266 }
267
268 virtual bool runOnModule(Module &module) override;
269
270 // output the SPIR-V header block
271 void outputHeader();
272
273 // patch the SPIR-V header block
274 void patchHeader();
275
SJW01901d92020-05-21 08:58:31 -0500276 CapabilitySetType &getCapabilitySet() { return CapabilitySet; }
David Neto22f144c2017-06-12 14:26:21 -0400277 TypeMapType &getImageTypeMap() { return ImageTypeMap; }
alan-baker7506abb2020-09-10 15:02:55 -0400278 TypeList &getTypeList() { return Types; }
David Neto22f144c2017-06-12 14:26:21 -0400279 ValueMapType &getValueMap() { return ValueMap; }
SJW69939d52020-04-16 07:29:07 -0500280 SPIRVInstructionList &getSPIRVInstList(SPIRVSection Section) {
281 return SPIRVSections[Section];
282 };
alan-baker7506abb2020-09-10 15:02:55 -0400283 EntryPointVecType &getEntryPointVec() { return EntryPointVec; }
284 DeferredInstVecType &getDeferredInstVec() { return DeferredInstVec; }
SJW806a5d82020-07-15 12:51:38 -0500285 SPIRVIDListType &getEntryPointInterfacesList() {
286 return EntryPointInterfacesList;
alan-baker7506abb2020-09-10 15:02:55 -0400287 }
SJW01901d92020-05-21 08:58:31 -0500288 SPIRVID getOpExtInstImportID();
alan-baker7506abb2020-09-10 15:02:55 -0400289 std::vector<SPIRVID> &getBuiltinDimVec() { return BuiltinDimensionVec; }
SJW2c317da2020-03-23 07:39:13 -0500290
alan-baker5b86ed72019-02-15 08:26:50 -0500291 bool hasVariablePointersStorageBuffer() {
292 return HasVariablePointersStorageBuffer;
293 }
SJW01901d92020-05-21 08:58:31 -0500294 void setVariablePointersStorageBuffer() {
295 if (!HasVariablePointersStorageBuffer) {
296 addCapability(spv::CapabilityVariablePointersStorageBuffer);
297 HasVariablePointersStorageBuffer = true;
298 }
alan-baker5b86ed72019-02-15 08:26:50 -0500299 }
alan-baker7506abb2020-09-10 15:02:55 -0400300 bool hasVariablePointers() { return HasVariablePointers; }
SJW01901d92020-05-21 08:58:31 -0500301 void setVariablePointers() {
302 if (!HasVariablePointers) {
303 addCapability(spv::CapabilityVariablePointers);
304 HasVariablePointers = true;
305 }
alan-baker7506abb2020-09-10 15:02:55 -0400306 }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500307 ArrayRef<std::pair<unsigned, std::string>> &getSamplerMap() {
308 return samplerMap;
309 }
David Neto22f144c2017-06-12 14:26:21 -0400310 GlobalConstFuncMapType &getGlobalConstFuncTypeMap() {
311 return GlobalConstFuncTypeMap;
312 }
313 SmallPtrSet<Value *, 16> &getGlobalConstArgSet() {
314 return GlobalConstArgumentSet;
315 }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500316 TypeList &getTypesNeedingArrayStride() { return TypesNeedingArrayStride; }
David Neto22f144c2017-06-12 14:26:21 -0400317
SJW77b87ad2020-04-21 14:37:52 -0500318 void GenerateLLVMIRInfo();
alan-bakerb6b09dc2018-11-08 16:59:28 -0500319 // Populate GlobalConstFuncTypeMap. Also, if module-scope __constant will
320 // *not* be converted to a storage buffer, replace each such global variable
321 // with one in the storage class expecgted by SPIR-V.
SJW77b87ad2020-04-21 14:37:52 -0500322 void FindGlobalConstVars();
David Neto862b7d82018-06-14 18:48:37 -0400323 // Populate ResourceVarInfoList, FunctionToResourceVarsMap, and
324 // ModuleOrderedResourceVars.
SJW77b87ad2020-04-21 14:37:52 -0500325 void FindResourceVars();
David Neto22f144c2017-06-12 14:26:21 -0400326 void FindTypePerGlobalVar(GlobalVariable &GV);
327 void FindTypePerFunc(Function &F);
SJW77b87ad2020-04-21 14:37:52 -0500328 void FindTypesForSamplerMap();
329 void FindTypesForResourceVars();
alan-bakerb6b09dc2018-11-08 16:59:28 -0500330 // Inserts |Ty| and relevant sub-types into the |Types| member, indicating
331 // that |Ty| and its subtypes will need a corresponding SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400332 void FindType(Type *Ty);
SJWf93f5f32020-05-05 07:27:56 -0500333
334 // Lookup or create Types, Constants.
335 // Returns SPIRVID once it has been created.
336 SPIRVID getSPIRVType(Type *Ty);
337 SPIRVID getSPIRVConstant(Constant *Cst);
SJW806a5d82020-07-15 12:51:38 -0500338 SPIRVID getSPIRVInt32Constant(uint32_t CstVal);
SJWf93f5f32020-05-05 07:27:56 -0500339 // Lookup SPIRVID of llvm::Value, may create Constant.
340 SPIRVID getSPIRVValue(Value *V);
341
SJW806a5d82020-07-15 12:51:38 -0500342 SPIRVID getSPIRVBuiltin(spv::BuiltIn BID, spv::Capability Cap);
343
David Neto19a1bad2017-08-25 15:01:41 -0400344 // Generates instructions for SPIR-V types corresponding to the LLVM types
345 // saved in the |Types| member. A type follows its subtypes. IDs are
346 // allocated sequentially starting with the current value of nextID, and
347 // with a type following its subtypes. Also updates nextID to just beyond
348 // the last generated ID.
SJW77b87ad2020-04-21 14:37:52 -0500349 void GenerateSPIRVTypes();
SJW77b87ad2020-04-21 14:37:52 -0500350 void GenerateModuleInfo();
David Neto22f144c2017-06-12 14:26:21 -0400351 void GenerateGlobalVar(GlobalVariable &GV);
SJW77b87ad2020-04-21 14:37:52 -0500352 void GenerateWorkgroupVars();
alan-baker86ce19c2020-08-05 13:09:19 -0400353 // Generate reflection instructions for resource variables associated with
David Neto862b7d82018-06-14 18:48:37 -0400354 // arguments to F.
SJW77b87ad2020-04-21 14:37:52 -0500355 void GenerateSamplers();
David Neto862b7d82018-06-14 18:48:37 -0400356 // Generate OpVariables for %clspv.resource.var.* calls.
SJW77b87ad2020-04-21 14:37:52 -0500357 void GenerateResourceVars();
David Neto22f144c2017-06-12 14:26:21 -0400358 void GenerateFuncPrologue(Function &F);
359 void GenerateFuncBody(Function &F);
David Netob6e2e062018-04-25 10:32:06 -0400360 void GenerateEntryPointInitialStores();
David Neto22f144c2017-06-12 14:26:21 -0400361 spv::Op GetSPIRVCmpOpcode(CmpInst *CmpI);
362 spv::Op GetSPIRVCastOpcode(Instruction &I);
363 spv::Op GetSPIRVBinaryOpcode(Instruction &I);
SJW806a5d82020-07-15 12:51:38 -0500364 SPIRVID GenerateClspvInstruction(CallInst *Call,
365 const FunctionInfo &FuncInfo);
366 SPIRVID GenerateImageInstruction(CallInst *Call,
367 const FunctionInfo &FuncInfo);
368 SPIRVID GenerateSubgroupInstruction(CallInst *Call,
369 const FunctionInfo &FuncInfo);
370 SPIRVID GenerateInstructionFromCall(CallInst *Call);
David Neto22f144c2017-06-12 14:26:21 -0400371 void GenerateInstruction(Instruction &I);
372 void GenerateFuncEpilogue();
373 void HandleDeferredInstruction();
SJW77b87ad2020-04-21 14:37:52 -0500374 void HandleDeferredDecorations();
David Neto22f144c2017-06-12 14:26:21 -0400375 bool is4xi8vec(Type *Ty) const;
376 spv::StorageClass GetStorageClass(unsigned AddrSpace) const;
David Neto862b7d82018-06-14 18:48:37 -0400377 spv::StorageClass GetStorageClassForArgKind(clspv::ArgKind arg_kind) const;
David Neto22f144c2017-06-12 14:26:21 -0400378 spv::BuiltIn GetBuiltin(StringRef globalVarName) const;
David Neto3fbb4072017-10-16 11:28:14 -0400379 // Returns the GLSL extended instruction enum that the given function
380 // call maps to. If none, then returns the 0 value, i.e. GLSLstd4580Bad.
SJW61531372020-06-09 07:31:08 -0500381 glsl::ExtInst getExtInstEnum(const Builtins::FunctionInfo &func_info);
David Neto3fbb4072017-10-16 11:28:14 -0400382 // Returns the GLSL extended instruction enum indirectly used by the given
383 // function. That is, to implement the given function, we use an extended
384 // instruction plus one more instruction. If none, then returns the 0 value,
385 // i.e. GLSLstd4580Bad.
SJW61531372020-06-09 07:31:08 -0500386 glsl::ExtInst getIndirectExtInstEnum(const Builtins::FunctionInfo &func_info);
David Neto3fbb4072017-10-16 11:28:14 -0400387 // Returns the single GLSL extended instruction used directly or
388 // indirectly by the given function call.
SJW61531372020-06-09 07:31:08 -0500389 glsl::ExtInst
390 getDirectOrIndirectExtInstEnum(const Builtins::FunctionInfo &func_info);
David Neto22f144c2017-06-12 14:26:21 -0400391 void WriteOneWord(uint32_t Word);
SJW88ed5fe2020-05-11 12:40:57 -0500392 void WriteResultID(const SPIRVInstruction &Inst);
393 void WriteWordCountAndOpcode(const SPIRVInstruction &Inst);
394 void WriteOperand(const SPIRVOperand &Op);
David Neto22f144c2017-06-12 14:26:21 -0400395 void WriteSPIRVBinary();
SJW69939d52020-04-16 07:29:07 -0500396 void WriteSPIRVBinary(SPIRVInstructionList &SPIRVInstList);
David Neto22f144c2017-06-12 14:26:21 -0400397
Alan Baker9bf93fb2018-08-28 16:59:26 -0400398 // Returns true if |type| is compatible with OpConstantNull.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500399 bool IsTypeNullable(const Type *type) const;
Alan Baker9bf93fb2018-08-28 16:59:26 -0400400
Alan Bakerfcda9482018-10-02 17:09:59 -0400401 // Populate UBO remapped type maps.
SJW77b87ad2020-04-21 14:37:52 -0500402 void PopulateUBOTypeMaps();
Alan Bakerfcda9482018-10-02 17:09:59 -0400403
alan-baker06cad652019-12-03 17:56:47 -0500404 // Populate the merge and continue block maps.
SJW77b87ad2020-04-21 14:37:52 -0500405 void PopulateStructuredCFGMaps();
alan-baker06cad652019-12-03 17:56:47 -0500406
Alan Bakerfcda9482018-10-02 17:09:59 -0400407 // Wrapped methods of DataLayout accessors. If |type| was remapped for UBOs,
408 // uses the internal map, otherwise it falls back on the data layout.
409 uint64_t GetTypeSizeInBits(Type *type, const DataLayout &DL);
410 uint64_t GetTypeStoreSize(Type *type, const DataLayout &DL);
411 uint64_t GetTypeAllocSize(Type *type, const DataLayout &DL);
Kévin Petitbbbda972020-03-03 19:16:31 +0000412 uint32_t GetExplicitLayoutStructMemberOffset(StructType *type,
413 unsigned member,
414 const DataLayout &DL);
Alan Bakerfcda9482018-10-02 17:09:59 -0400415
alan-baker5b86ed72019-02-15 08:26:50 -0500416 // Returns the base pointer of |v|.
417 Value *GetBasePointer(Value *v);
418
SJW01901d92020-05-21 08:58:31 -0500419 // Add Capability if not already (e.g. CapabilityGroupNonUniformBroadcast)
420 void addCapability(uint32_t c) { CapabilitySet.emplace(c); }
421
alan-baker5b86ed72019-02-15 08:26:50 -0500422 // Sets |HasVariablePointersStorageBuffer| or |HasVariablePointers| base on
423 // |address_space|.
424 void setVariablePointersCapabilities(unsigned address_space);
425
426 // Returns true if |lhs| and |rhs| represent the same resource or workgroup
427 // variable.
428 bool sameResource(Value *lhs, Value *rhs) const;
429
430 // Returns true if |inst| is phi or select that selects from the same
431 // structure (or null).
432 bool selectFromSameObject(Instruction *inst);
433
alan-bakere9308012019-03-15 10:25:13 -0400434 // Returns true if |Arg| is called with a coherent resource.
435 bool CalledWithCoherentResource(Argument &Arg);
436
SJWf93f5f32020-05-05 07:27:56 -0500437 //
438 // Primary interface for adding SPIRVInstructions to a SPIRVSection.
439 template <enum SPIRVSection TSection = kFunctions>
440 SPIRVID addSPIRVInst(spv::Op Opcode, SPIRVOperandVec &Operands) {
441 bool has_result, has_result_type;
442 spv::HasResultAndType(Opcode, &has_result, &has_result_type);
443 SPIRVID RID = has_result ? incrNextID() : 0;
SJW88ed5fe2020-05-11 12:40:57 -0500444 SPIRVSections[TSection].emplace_back(Opcode, RID, Operands);
SJWf93f5f32020-05-05 07:27:56 -0500445 return RID;
446 }
447 template <enum SPIRVSection TSection = kFunctions>
448 SPIRVID addSPIRVInst(spv::Op Op) {
449 SPIRVOperandVec Ops;
450 return addSPIRVInst<TSection>(Op, Ops);
451 }
452 template <enum SPIRVSection TSection = kFunctions>
453 SPIRVID addSPIRVInst(spv::Op Op, uint32_t V) {
454 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -0500455 Ops.emplace_back(LITERAL_WORD, V);
SJWf93f5f32020-05-05 07:27:56 -0500456 return addSPIRVInst<TSection>(Op, Ops);
457 }
458 template <enum SPIRVSection TSection = kFunctions>
459 SPIRVID addSPIRVInst(spv::Op Op, const char *V) {
460 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -0500461 Ops.emplace_back(LITERAL_STRING, V);
SJWf93f5f32020-05-05 07:27:56 -0500462 return addSPIRVInst<TSection>(Op, Ops);
463 }
464
SJW88ed5fe2020-05-11 12:40:57 -0500465 //
466 // Add placeholder for llvm::Value that references future values.
467 // Must have result ID just in case final SPIRVInstruction requires.
468 SPIRVID addSPIRVPlaceholder(Value *I) {
469 SPIRVID RID = incrNextID();
470 SPIRVOperandVec Ops;
471 SPIRVSections[kFunctions].emplace_back(spv::OpExtInst, RID, Ops);
472 DeferredInstVec.push_back({I, &SPIRVSections[kFunctions].back()});
473 return RID;
474 }
475 // Replace placeholder with actual SPIRVInstruction on the final pass
476 // (HandleDeferredInstruction).
477 SPIRVID replaceSPIRVInst(SPIRVInstruction *I, spv::Op Opcode,
478 SPIRVOperandVec &Operands) {
479 bool has_result, has_result_type;
480 spv::HasResultAndType(Opcode, &has_result, &has_result_type);
481 SPIRVID RID = has_result ? I->getResultID() : 0;
482 *I = SPIRVInstruction(Opcode, RID, Operands);
483 return RID;
484 }
485
SJW806a5d82020-07-15 12:51:38 -0500486 //
487 // Add global variable and capture entry point interface
488 SPIRVID addSPIRVGlobalVariable(const SPIRVID &TypeID, spv::StorageClass SC,
489 const SPIRVID &InitID = SPIRVID());
490
alan-baker86ce19c2020-08-05 13:09:19 -0400491 SPIRVID getReflectionImport();
492 void GenerateReflection();
493 void GenerateKernelReflection();
494 void GeneratePushConstantReflection();
495 void GenerateSpecConstantReflection();
496 void AddArgumentReflection(SPIRVID kernel_decl, const std::string &name,
497 clspv::ArgKind arg_kind, uint32_t ordinal,
498 uint32_t descriptor_set, uint32_t binding,
499 uint32_t offset, uint32_t size, uint32_t spec_id,
500 uint32_t elem_size);
501
David Neto22f144c2017-06-12 14:26:21 -0400502private:
503 static char ID;
SJW77b87ad2020-04-21 14:37:52 -0500504
505 Module *module;
506
SJW01901d92020-05-21 08:58:31 -0500507 // Set of Capabilities required
508 CapabilitySetType CapabilitySet;
509
SJW806a5d82020-07-15 12:51:38 -0500510 // Map from clspv::BuiltinType to SPIRV Global Variable
511 BuiltinConstantMapType BuiltinConstantMap;
512
David Neto44795152017-07-13 15:45:28 -0400513 ArrayRef<std::pair<unsigned, std::string>> samplerMap;
David Neto22f144c2017-06-12 14:26:21 -0400514 raw_pwrite_stream &out;
David Neto0676e6f2017-07-11 18:47:44 -0400515
516 // TODO(dneto): Wouldn't it be better to always just emit a binary, and then
517 // convert to other formats on demand?
518
519 // When emitting a C initialization list, the WriteSPIRVBinary method
520 // will actually write its words to this vector via binaryTempOut.
521 SmallVector<char, 100> binaryTempUnderlyingVector;
522 raw_svector_ostream binaryTempOut;
523
524 // Binary output writes to this stream, which might be |out| or
525 // |binaryTempOut|. It's the latter when we really want to write a C
526 // initializer list.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400527 raw_pwrite_stream *binaryOut;
David Neto0676e6f2017-07-11 18:47:44 -0400528 const bool outputCInitList; // If true, output look like {0x7023, ... , 5}
David Neto22f144c2017-06-12 14:26:21 -0400529 uint64_t patchBoundOffset;
530 uint32_t nextID;
531
SJWf93f5f32020-05-05 07:27:56 -0500532 SPIRVID incrNextID() { return nextID++; }
533
alan-bakerf67468c2019-11-25 15:51:49 -0500534 // ID for OpTypeInt 32 1.
SJW01901d92020-05-21 08:58:31 -0500535 SPIRVID int32ID;
alan-bakerf67468c2019-11-25 15:51:49 -0500536 // ID for OpTypeVector %int 4.
SJW01901d92020-05-21 08:58:31 -0500537 SPIRVID v4int32ID;
alan-bakerf67468c2019-11-25 15:51:49 -0500538
David Neto19a1bad2017-08-25 15:01:41 -0400539 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400540 TypeMapType TypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400541 // Maps an LLVM image type to its SPIR-V ID.
David Neto22f144c2017-06-12 14:26:21 -0400542 TypeMapType ImageTypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400543 // A unique-vector of LLVM types that map to a SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400544 TypeList Types;
David Neto19a1bad2017-08-25 15:01:41 -0400545 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400546 ValueMapType ValueMap;
SJW69939d52020-04-16 07:29:07 -0500547 SPIRVInstructionList SPIRVSections[kSectionCount];
David Neto862b7d82018-06-14 18:48:37 -0400548
David Neto22f144c2017-06-12 14:26:21 -0400549 EntryPointVecType EntryPointVec;
550 DeferredInstVecType DeferredInstVec;
SJW806a5d82020-07-15 12:51:38 -0500551 SPIRVIDListType EntryPointInterfacesList;
SJW01901d92020-05-21 08:58:31 -0500552 SPIRVID OpExtInstImportID;
553 std::vector<SPIRVID> BuiltinDimensionVec;
alan-baker5b86ed72019-02-15 08:26:50 -0500554 bool HasVariablePointersStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -0400555 bool HasVariablePointers;
556 Type *SamplerTy;
SJW01901d92020-05-21 08:58:31 -0500557 DenseMap<unsigned, SPIRVID> SamplerLiteralToIDMap;
David Netoc77d9e22018-03-24 06:30:28 -0700558
559 // If a function F has a pointer-to-__constant parameter, then this variable
David Neto9ed8e2f2018-03-24 06:47:24 -0700560 // will map F's type to (G, index of the parameter), where in a first phase
561 // G is F's type. During FindTypePerFunc, G will be changed to F's type
562 // but replacing the pointer-to-constant parameter with
563 // pointer-to-ModuleScopePrivate.
David Netoc77d9e22018-03-24 06:30:28 -0700564 // TODO(dneto): This doesn't seem general enough? A function might have
565 // more than one such parameter.
David Neto22f144c2017-06-12 14:26:21 -0400566 GlobalConstFuncMapType GlobalConstFuncTypeMap;
567 SmallPtrSet<Value *, 16> GlobalConstArgumentSet;
David Neto1a1a0582017-07-07 12:01:44 -0400568 // An ordered set of pointer types of Base arguments to OpPtrAccessChain,
David Neto85082642018-03-24 06:55:20 -0700569 // or array types, and which point into transparent memory (StorageBuffer
570 // storage class). These will require an ArrayStride decoration.
David Neto1a1a0582017-07-07 12:01:44 -0400571 // See SPV_KHR_variable_pointers rev 13.
David Neto85082642018-03-24 06:55:20 -0700572 TypeList TypesNeedingArrayStride;
David Netoa60b00b2017-09-15 16:34:09 -0400573
574 // This is truly ugly, but works around what look like driver bugs.
575 // For get_local_size, an earlier part of the flow has created a module-scope
576 // variable in Private address space to hold the value for the workgroup
577 // size. Its intializer is a uint3 value marked as builtin WorkgroupSize.
578 // When this is present, save the IDs of the initializer value and variable
579 // in these two variables. We only ever do a vector load from it, and
580 // when we see one of those, substitute just the value of the intializer.
581 // This mimics what Glslang does, and that's what drivers are used to.
David Neto66cfe642018-03-24 06:13:56 -0700582 // TODO(dneto): Remove this once drivers are fixed.
SJW01901d92020-05-21 08:58:31 -0500583 SPIRVID WorkgroupSizeValueID;
584 SPIRVID WorkgroupSizeVarID;
David Neto26aaf622017-10-23 18:11:53 -0400585
David Neto862b7d82018-06-14 18:48:37 -0400586 // Bookkeeping for mapping kernel arguments to resource variables.
587 struct ResourceVarInfo {
588 ResourceVarInfo(int index_arg, unsigned set_arg, unsigned binding_arg,
alan-bakere9308012019-03-15 10:25:13 -0400589 Function *fn, clspv::ArgKind arg_kind_arg, int coherent_arg)
David Neto862b7d82018-06-14 18:48:37 -0400590 : index(index_arg), descriptor_set(set_arg), binding(binding_arg),
alan-bakere9308012019-03-15 10:25:13 -0400591 var_fn(fn), arg_kind(arg_kind_arg), coherent(coherent_arg),
David Neto862b7d82018-06-14 18:48:37 -0400592 addr_space(fn->getReturnType()->getPointerAddressSpace()) {}
593 const int index; // Index into ResourceVarInfoList
594 const unsigned descriptor_set;
595 const unsigned binding;
596 Function *const var_fn; // The @clspv.resource.var.* function.
597 const clspv::ArgKind arg_kind;
alan-bakere9308012019-03-15 10:25:13 -0400598 const int coherent;
David Neto862b7d82018-06-14 18:48:37 -0400599 const unsigned addr_space; // The LLVM address space
600 // The SPIR-V ID of the OpVariable. Not populated at construction time.
SJW01901d92020-05-21 08:58:31 -0500601 SPIRVID var_id;
David Neto862b7d82018-06-14 18:48:37 -0400602 };
603 // A list of resource var info. Each one correponds to a module-scope
604 // resource variable we will have to create. Resource var indices are
605 // indices into this vector.
606 SmallVector<std::unique_ptr<ResourceVarInfo>, 8> ResourceVarInfoList;
607 // This is a vector of pointers of all the resource vars, but ordered by
608 // kernel function, and then by argument.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500609 UniqueVector<ResourceVarInfo *> ModuleOrderedResourceVars;
David Neto862b7d82018-06-14 18:48:37 -0400610 // Map a function to the ordered list of resource variables it uses, one for
611 // each argument. If an argument does not use a resource variable, it
612 // will have a null pointer entry.
613 using FunctionToResourceVarsMapType =
614 DenseMap<Function *, SmallVector<ResourceVarInfo *, 8>>;
615 FunctionToResourceVarsMapType FunctionToResourceVarsMap;
616
617 // What LLVM types map to SPIR-V types needing layout? These are the
618 // arrays and structures supporting storage buffers and uniform buffers.
619 TypeList TypesNeedingLayout;
620 // What LLVM struct types map to a SPIR-V struct type with Block decoration?
621 UniqueVector<StructType *> StructTypesNeedingBlock;
622 // For a call that represents a load from an opaque type (samplers, images),
623 // map it to the variable id it should load from.
SJW01901d92020-05-21 08:58:31 -0500624 DenseMap<CallInst *, SPIRVID> ResourceVarDeferredLoadCalls;
David Neto85082642018-03-24 06:55:20 -0700625
David Netoc6f3ab22018-04-06 18:02:31 -0400626 // An ordered list of the kernel arguments of type pointer-to-local.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500627 using LocalArgList = SmallVector<Argument *, 8>;
David Netoc6f3ab22018-04-06 18:02:31 -0400628 LocalArgList LocalArgs;
629 // Information about a pointer-to-local argument.
630 struct LocalArgInfo {
631 // The SPIR-V ID of the array variable.
SJW01901d92020-05-21 08:58:31 -0500632 SPIRVID variable_id;
David Netoc6f3ab22018-04-06 18:02:31 -0400633 // The element type of the
alan-bakerb6b09dc2018-11-08 16:59:28 -0500634 Type *elem_type;
David Netoc6f3ab22018-04-06 18:02:31 -0400635 // The ID of the array type.
SJW01901d92020-05-21 08:58:31 -0500636 SPIRVID array_size_id;
David Netoc6f3ab22018-04-06 18:02:31 -0400637 // The ID of the array type.
SJW01901d92020-05-21 08:58:31 -0500638 SPIRVID array_type_id;
David Netoc6f3ab22018-04-06 18:02:31 -0400639 // The ID of the pointer to the array type.
SJW01901d92020-05-21 08:58:31 -0500640 SPIRVID ptr_array_type_id;
David Netoc6f3ab22018-04-06 18:02:31 -0400641 // The specialization constant ID of the array size.
642 int spec_id;
643 };
Alan Baker202c8c72018-08-13 13:47:44 -0400644 // A mapping from Argument to its assigned SpecId.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500645 DenseMap<const Argument *, int> LocalArgSpecIds;
Alan Baker202c8c72018-08-13 13:47:44 -0400646 // A mapping from SpecId to its LocalArgInfo.
647 DenseMap<int, LocalArgInfo> LocalSpecIdInfoMap;
Alan Bakerfcda9482018-10-02 17:09:59 -0400648 // A mapping from a remapped type to its real offsets.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500649 DenseMap<Type *, std::vector<uint32_t>> RemappedUBOTypeOffsets;
Alan Bakerfcda9482018-10-02 17:09:59 -0400650 // A mapping from a remapped type to its real sizes.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500651 DenseMap<Type *, std::tuple<uint64_t, uint64_t, uint64_t>>
652 RemappedUBOTypeSizes;
alan-baker06cad652019-12-03 17:56:47 -0500653
654 // Maps basic block to its merge block.
655 DenseMap<BasicBlock *, BasicBlock *> MergeBlocks;
656 // Maps basic block to its continue block.
657 DenseMap<BasicBlock *, BasicBlock *> ContinueBlocks;
SJW01901d92020-05-21 08:58:31 -0500658
alan-baker86ce19c2020-08-05 13:09:19 -0400659 SPIRVID ReflectionID;
660 DenseMap<Function *, SPIRVID> KernelDeclarations;
661
SJW01901d92020-05-21 08:58:31 -0500662public:
663 static SPIRVProducerPass *Ptr;
David Neto22f144c2017-06-12 14:26:21 -0400664};
665
666char SPIRVProducerPass::ID;
SJW01901d92020-05-21 08:58:31 -0500667SPIRVProducerPass *SPIRVProducerPass::Ptr = nullptr;
David Netoc6f3ab22018-04-06 18:02:31 -0400668
alan-bakerb6b09dc2018-11-08 16:59:28 -0500669} // namespace
David Neto22f144c2017-06-12 14:26:21 -0400670
671namespace clspv {
alan-baker86ce19c2020-08-05 13:09:19 -0400672ModulePass *
673createSPIRVProducerPass(raw_pwrite_stream &out,
674 ArrayRef<std::pair<unsigned, std::string>> samplerMap,
675 bool outputCInitList) {
676 return new SPIRVProducerPass(out, samplerMap, outputCInitList);
David Neto22f144c2017-06-12 14:26:21 -0400677}
David Netoc2c368d2017-06-30 16:50:17 -0400678} // namespace clspv
David Neto22f144c2017-06-12 14:26:21 -0400679
SJW01901d92020-05-21 08:58:31 -0500680namespace {
681SPIRVOperandVec &operator<<(SPIRVOperandVec &list, uint32_t num) {
682 list.emplace_back(LITERAL_WORD, num);
683 return list;
684}
685
686SPIRVOperandVec &operator<<(SPIRVOperandVec &list, int32_t num) {
687 list.emplace_back(LITERAL_WORD, static_cast<uint32_t>(num));
688 return list;
689}
690
691SPIRVOperandVec &operator<<(SPIRVOperandVec &list, ArrayRef<uint32_t> num_vec) {
692 list.emplace_back(num_vec);
693 return list;
694}
695
696SPIRVOperandVec &operator<<(SPIRVOperandVec &list, StringRef str) {
697 list.emplace_back(LITERAL_STRING, str);
698 return list;
699}
700
701SPIRVOperandVec &operator<<(SPIRVOperandVec &list, Type *t) {
702 list.emplace_back(NUMBERID, SPIRVProducerPass::Ptr->getSPIRVType(t).get());
703 return list;
704}
705
706SPIRVOperandVec &operator<<(SPIRVOperandVec &list, Value *v) {
707 list.emplace_back(NUMBERID, SPIRVProducerPass::Ptr->getSPIRVValue(v).get());
708 return list;
709}
710
SJW806a5d82020-07-15 12:51:38 -0500711SPIRVOperandVec &operator<<(SPIRVOperandVec &list, const SPIRVID &v) {
SJW01901d92020-05-21 08:58:31 -0500712 list.emplace_back(NUMBERID, v.get());
713 return list;
714}
715} // namespace
716
SJW77b87ad2020-04-21 14:37:52 -0500717bool SPIRVProducerPass::runOnModule(Module &M) {
SJW01901d92020-05-21 08:58:31 -0500718 // TODO(sjw): Need to reset all data members for each Module, or better
719 // yet create a new SPIRVProducer for every module.. For now only
720 // allow 1 call.
721 assert(module == nullptr);
SJW77b87ad2020-04-21 14:37:52 -0500722 module = &M;
alan-baker5ed87542020-03-23 11:05:22 -0400723 if (ShowProducerIR) {
SJW77b87ad2020-04-21 14:37:52 -0500724 llvm::outs() << *module << "\n";
alan-baker5ed87542020-03-23 11:05:22 -0400725 }
David Neto0676e6f2017-07-11 18:47:44 -0400726 binaryOut = outputCInitList ? &binaryTempOut : &out;
727
SJW77b87ad2020-04-21 14:37:52 -0500728 PopulateUBOTypeMaps();
729 PopulateStructuredCFGMaps();
Alan Bakerfcda9482018-10-02 17:09:59 -0400730
David Neto22f144c2017-06-12 14:26:21 -0400731 // SPIR-V always begins with its header information
732 outputHeader();
733
734 // Gather information from the LLVM IR that we require.
SJW77b87ad2020-04-21 14:37:52 -0500735 GenerateLLVMIRInfo();
David Neto22f144c2017-06-12 14:26:21 -0400736
David Neto22f144c2017-06-12 14:26:21 -0400737 // Collect information on global variables too.
SJW77b87ad2020-04-21 14:37:52 -0500738 for (GlobalVariable &GV : module->globals()) {
David Neto22f144c2017-06-12 14:26:21 -0400739 // If the GV is one of our special __spirv_* variables, remove the
740 // initializer as it was only placed there to force LLVM to not throw the
741 // value away.
Kévin Petitbbbda972020-03-03 19:16:31 +0000742 if (GV.getName().startswith("__spirv_") ||
743 GV.getAddressSpace() == clspv::AddressSpace::PushConstant) {
David Neto22f144c2017-06-12 14:26:21 -0400744 GV.setInitializer(nullptr);
745 }
746
747 // Collect types' information from global variable.
748 FindTypePerGlobalVar(GV);
David Neto22f144c2017-06-12 14:26:21 -0400749 }
750
David Neto22f144c2017-06-12 14:26:21 -0400751 // Generate SPIRV instructions for types.
SJW77b87ad2020-04-21 14:37:52 -0500752 GenerateSPIRVTypes();
David Neto22f144c2017-06-12 14:26:21 -0400753
alan-baker09cb9802019-12-10 13:16:27 -0500754 // Generate literal samplers if necessary.
SJW77b87ad2020-04-21 14:37:52 -0500755 GenerateSamplers();
David Neto22f144c2017-06-12 14:26:21 -0400756
757 // Generate SPIRV variables.
SJW77b87ad2020-04-21 14:37:52 -0500758 for (GlobalVariable &GV : module->globals()) {
David Neto22f144c2017-06-12 14:26:21 -0400759 GenerateGlobalVar(GV);
760 }
SJW77b87ad2020-04-21 14:37:52 -0500761 GenerateResourceVars();
762 GenerateWorkgroupVars();
David Neto22f144c2017-06-12 14:26:21 -0400763
764 // Generate SPIRV instructions for each function.
SJW77b87ad2020-04-21 14:37:52 -0500765 for (Function &F : *module) {
David Neto22f144c2017-06-12 14:26:21 -0400766 if (F.isDeclaration()) {
767 continue;
768 }
769
770 // Generate Function Prologue.
771 GenerateFuncPrologue(F);
772
773 // Generate SPIRV instructions for function body.
774 GenerateFuncBody(F);
775
776 // Generate Function Epilogue.
777 GenerateFuncEpilogue();
778 }
779
780 HandleDeferredInstruction();
SJW77b87ad2020-04-21 14:37:52 -0500781 HandleDeferredDecorations();
alan-bakera1be3322020-04-20 12:48:18 -0400782
David Neto22f144c2017-06-12 14:26:21 -0400783 // Generate SPIRV module information.
SJW77b87ad2020-04-21 14:37:52 -0500784 GenerateModuleInfo();
David Neto22f144c2017-06-12 14:26:21 -0400785
alan-baker86ce19c2020-08-05 13:09:19 -0400786 // Generate embedded reflection information.
787 GenerateReflection();
788
alan-baker00e7a582019-06-07 12:54:21 -0400789 WriteSPIRVBinary();
David Neto22f144c2017-06-12 14:26:21 -0400790
791 // We need to patch the SPIR-V header to set bound correctly.
792 patchHeader();
David Neto0676e6f2017-07-11 18:47:44 -0400793
794 if (outputCInitList) {
795 bool first = true;
David Neto0676e6f2017-07-11 18:47:44 -0400796 std::ostringstream os;
797
David Neto57fb0b92017-08-04 15:35:09 -0400798 auto emit_word = [&os, &first](uint32_t word) {
David Neto0676e6f2017-07-11 18:47:44 -0400799 if (!first)
David Neto57fb0b92017-08-04 15:35:09 -0400800 os << ",\n";
801 os << word;
David Neto0676e6f2017-07-11 18:47:44 -0400802 first = false;
803 };
804
805 os << "{";
David Neto57fb0b92017-08-04 15:35:09 -0400806 const std::string str(binaryTempOut.str());
807 for (unsigned i = 0; i < str.size(); i += 4) {
808 const uint32_t a = static_cast<unsigned char>(str[i]);
809 const uint32_t b = static_cast<unsigned char>(str[i + 1]);
810 const uint32_t c = static_cast<unsigned char>(str[i + 2]);
811 const uint32_t d = static_cast<unsigned char>(str[i + 3]);
812 emit_word(a | (b << 8) | (c << 16) | (d << 24));
David Neto0676e6f2017-07-11 18:47:44 -0400813 }
814 os << "}\n";
815 out << os.str();
816 }
817
David Neto22f144c2017-06-12 14:26:21 -0400818 return false;
819}
820
821void SPIRVProducerPass::outputHeader() {
alan-baker00e7a582019-06-07 12:54:21 -0400822 binaryOut->write(reinterpret_cast<const char *>(&spv::MagicNumber),
823 sizeof(spv::MagicNumber));
SJW806a5d82020-07-15 12:51:38 -0500824 uint32_t minor = 0;
825 if (SpvVersion() == SPIRVVersion::SPIRV_1_3) {
826 minor = 3;
827 }
828 uint32_t version = (1 << 16) | (minor << 8);
829 binaryOut->write(reinterpret_cast<const char *>(&version), sizeof(version));
David Neto22f144c2017-06-12 14:26:21 -0400830
alan-baker0c18ab02019-06-12 10:23:21 -0400831 // use Google's vendor ID
832 const uint32_t vendor = 21 << 16;
alan-baker00e7a582019-06-07 12:54:21 -0400833 binaryOut->write(reinterpret_cast<const char *>(&vendor), sizeof(vendor));
David Neto22f144c2017-06-12 14:26:21 -0400834
alan-baker00e7a582019-06-07 12:54:21 -0400835 // we record where we need to come back to and patch in the bound value
836 patchBoundOffset = binaryOut->tell();
David Neto22f144c2017-06-12 14:26:21 -0400837
alan-baker00e7a582019-06-07 12:54:21 -0400838 // output a bad bound for now
839 binaryOut->write(reinterpret_cast<const char *>(&nextID), sizeof(nextID));
David Neto22f144c2017-06-12 14:26:21 -0400840
alan-baker00e7a582019-06-07 12:54:21 -0400841 // output the schema (reserved for use and must be 0)
842 const uint32_t schema = 0;
843 binaryOut->write(reinterpret_cast<const char *>(&schema), sizeof(schema));
David Neto22f144c2017-06-12 14:26:21 -0400844}
845
846void SPIRVProducerPass::patchHeader() {
alan-baker00e7a582019-06-07 12:54:21 -0400847 // for a binary we just write the value of nextID over bound
848 binaryOut->pwrite(reinterpret_cast<char *>(&nextID), sizeof(nextID),
849 patchBoundOffset);
David Neto22f144c2017-06-12 14:26:21 -0400850}
851
SJW77b87ad2020-04-21 14:37:52 -0500852void SPIRVProducerPass::GenerateLLVMIRInfo() {
David Neto22f144c2017-06-12 14:26:21 -0400853 // This function generates LLVM IR for function such as global variable for
854 // argument, constant and pointer type for argument access. These information
855 // is artificial one because we need Vulkan SPIR-V output. This function is
856 // executed ahead of FindType and FindConstant.
David Neto22f144c2017-06-12 14:26:21 -0400857
SJW77b87ad2020-04-21 14:37:52 -0500858 FindGlobalConstVars();
David Neto5c22a252018-03-15 16:07:41 -0400859
SJW77b87ad2020-04-21 14:37:52 -0500860 FindResourceVars();
David Neto22f144c2017-06-12 14:26:21 -0400861
862 bool HasWorkGroupBuiltin = false;
SJW77b87ad2020-04-21 14:37:52 -0500863 for (GlobalVariable &GV : module->globals()) {
David Neto22f144c2017-06-12 14:26:21 -0400864 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
865 if (spv::BuiltInWorkgroupSize == BuiltinType) {
866 HasWorkGroupBuiltin = true;
867 }
868 }
869
SJW77b87ad2020-04-21 14:37:52 -0500870 FindTypesForSamplerMap();
871 FindTypesForResourceVars();
David Neto22f144c2017-06-12 14:26:21 -0400872}
873
SJW77b87ad2020-04-21 14:37:52 -0500874void SPIRVProducerPass::FindGlobalConstVars() {
875 clspv::NormalizeGlobalVariables(*module);
876 const DataLayout &DL = module->getDataLayout();
alan-baker56f7aff2019-05-22 08:06:42 -0400877
David Neto862b7d82018-06-14 18:48:37 -0400878 SmallVector<GlobalVariable *, 8> GVList;
879 SmallVector<GlobalVariable *, 8> DeadGVList;
SJW77b87ad2020-04-21 14:37:52 -0500880 for (GlobalVariable &GV : module->globals()) {
David Neto862b7d82018-06-14 18:48:37 -0400881 if (GV.getType()->getAddressSpace() == AddressSpace::Constant) {
882 if (GV.use_empty()) {
883 DeadGVList.push_back(&GV);
884 } else {
885 GVList.push_back(&GV);
886 }
887 }
888 }
889
890 // Remove dead global __constant variables.
891 for (auto GV : DeadGVList) {
892 GV->eraseFromParent();
893 }
894 DeadGVList.clear();
895
896 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
897 // For now, we only support a single storage buffer.
alan-baker7506abb2020-09-10 15:02:55 -0400898 if (!GVList.empty()) {
David Neto862b7d82018-06-14 18:48:37 -0400899 assert(GVList.size() == 1);
900 const auto *GV = GVList[0];
901 const auto constants_byte_size =
Alan Bakerfcda9482018-10-02 17:09:59 -0400902 (GetTypeSizeInBits(GV->getInitializer()->getType(), DL)) / 8;
David Neto862b7d82018-06-14 18:48:37 -0400903 const size_t kConstantMaxSize = 65536;
904 if (constants_byte_size > kConstantMaxSize) {
905 outs() << "Max __constant capacity of " << kConstantMaxSize
906 << " bytes exceeded: " << constants_byte_size << " bytes used\n";
907 llvm_unreachable("Max __constant capacity exceeded");
908 }
909 }
910 } else {
911 // Change global constant variable's address space to ModuleScopePrivate.
912 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
913 for (auto GV : GVList) {
914 // Create new gv with ModuleScopePrivate address space.
915 Type *NewGVTy = GV->getType()->getPointerElementType();
916 GlobalVariable *NewGV = new GlobalVariable(
SJW77b87ad2020-04-21 14:37:52 -0500917 *module, NewGVTy, false, GV->getLinkage(), GV->getInitializer(), "",
David Neto862b7d82018-06-14 18:48:37 -0400918 nullptr, GV->getThreadLocalMode(), AddressSpace::ModuleScopePrivate);
919 NewGV->takeName(GV);
920
921 const SmallVector<User *, 8> GVUsers(GV->user_begin(), GV->user_end());
922 SmallVector<User *, 8> CandidateUsers;
923
924 auto record_called_function_type_as_user =
925 [&GlobalConstFuncTyMap](Value *gv, CallInst *call) {
926 // Find argument index.
927 unsigned index = 0;
928 for (unsigned i = 0; i < call->getNumArgOperands(); i++) {
929 if (gv == call->getOperand(i)) {
930 // TODO(dneto): Should we break here?
931 index = i;
932 }
933 }
934
935 // Record function type with global constant.
936 GlobalConstFuncTyMap[call->getFunctionType()] =
937 std::make_pair(call->getFunctionType(), index);
938 };
939
940 for (User *GVU : GVUsers) {
941 if (CallInst *Call = dyn_cast<CallInst>(GVU)) {
942 record_called_function_type_as_user(GV, Call);
943 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(GVU)) {
944 // Check GEP users.
945 for (User *GEPU : GEP->users()) {
946 if (CallInst *GEPCall = dyn_cast<CallInst>(GEPU)) {
947 record_called_function_type_as_user(GEP, GEPCall);
948 }
949 }
950 }
951
952 CandidateUsers.push_back(GVU);
953 }
954
955 for (User *U : CandidateUsers) {
956 // Update users of gv with new gv.
alan-bakered80f572019-02-11 17:28:26 -0500957 if (!isa<Constant>(U)) {
958 // #254: Can't change operands of a constant, but this shouldn't be
959 // something that sticks around in the module.
960 U->replaceUsesOfWith(GV, NewGV);
961 }
David Neto862b7d82018-06-14 18:48:37 -0400962 }
963
964 // Delete original gv.
965 GV->eraseFromParent();
966 }
967 }
968}
969
SJW77b87ad2020-04-21 14:37:52 -0500970void SPIRVProducerPass::FindResourceVars() {
David Neto862b7d82018-06-14 18:48:37 -0400971 ResourceVarInfoList.clear();
972 FunctionToResourceVarsMap.clear();
973 ModuleOrderedResourceVars.reset();
974 // Normally, there is one resource variable per clspv.resource.var.*
975 // function, since that is unique'd by arg type and index. By design,
976 // we can share these resource variables across kernels because all
977 // kernels use the same descriptor set.
978 //
979 // But if the user requested distinct descriptor sets per kernel, then
980 // the descriptor allocator has made different (set,binding) pairs for
981 // the same (type,arg_index) pair. Since we can decorate a resource
982 // variable with only exactly one DescriptorSet and Binding, we are
983 // forced in this case to make distinct resource variables whenever
Kévin Petitbbbda972020-03-03 19:16:31 +0000984 // the same clspv.resource.var.X function is seen with disintct
David Neto862b7d82018-06-14 18:48:37 -0400985 // (set,binding) values.
986 const bool always_distinct_sets =
987 clspv::Option::DistinctKernelDescriptorSets();
SJW77b87ad2020-04-21 14:37:52 -0500988 for (Function &F : *module) {
David Neto862b7d82018-06-14 18:48:37 -0400989 // Rely on the fact the resource var functions have a stable ordering
990 // in the module.
SJW61531372020-06-09 07:31:08 -0500991 if (Builtins::Lookup(&F) == Builtins::kClspvResource) {
David Neto862b7d82018-06-14 18:48:37 -0400992 // Find all calls to this function with distinct set and binding pairs.
993 // Save them in ResourceVarInfoList.
994
995 // Determine uniqueness of the (set,binding) pairs only withing this
996 // one resource-var builtin function.
997 using SetAndBinding = std::pair<unsigned, unsigned>;
998 // Maps set and binding to the resource var info.
999 DenseMap<SetAndBinding, ResourceVarInfo *> set_and_binding_map;
1000 bool first_use = true;
1001 for (auto &U : F.uses()) {
1002 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
1003 const auto set = unsigned(
1004 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
1005 const auto binding = unsigned(
1006 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
1007 const auto arg_kind = clspv::ArgKind(
1008 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
1009 const auto arg_index = unsigned(
1010 dyn_cast<ConstantInt>(call->getArgOperand(3))->getZExtValue());
alan-bakere9308012019-03-15 10:25:13 -04001011 const auto coherent = unsigned(
1012 dyn_cast<ConstantInt>(call->getArgOperand(5))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04001013
1014 // Find or make the resource var info for this combination.
1015 ResourceVarInfo *rv = nullptr;
1016 if (always_distinct_sets) {
1017 // Make a new resource var any time we see a different
1018 // (set,binding) pair.
1019 SetAndBinding key{set, binding};
1020 auto where = set_and_binding_map.find(key);
1021 if (where == set_and_binding_map.end()) {
alan-baker7506abb2020-09-10 15:02:55 -04001022 rv = new ResourceVarInfo(
1023 static_cast<int>(ResourceVarInfoList.size()), set, binding,
1024 &F, arg_kind, coherent);
David Neto862b7d82018-06-14 18:48:37 -04001025 ResourceVarInfoList.emplace_back(rv);
1026 set_and_binding_map[key] = rv;
1027 } else {
1028 rv = where->second;
1029 }
1030 } else {
1031 // The default is to make exactly one resource for each
1032 // clspv.resource.var.* function.
1033 if (first_use) {
1034 first_use = false;
alan-baker7506abb2020-09-10 15:02:55 -04001035 rv = new ResourceVarInfo(
1036 static_cast<int>(ResourceVarInfoList.size()), set, binding,
1037 &F, arg_kind, coherent);
David Neto862b7d82018-06-14 18:48:37 -04001038 ResourceVarInfoList.emplace_back(rv);
1039 } else {
1040 rv = ResourceVarInfoList.back().get();
1041 }
1042 }
1043
1044 // Now populate FunctionToResourceVarsMap.
1045 auto &mapping =
1046 FunctionToResourceVarsMap[call->getParent()->getParent()];
1047 while (mapping.size() <= arg_index) {
1048 mapping.push_back(nullptr);
1049 }
1050 mapping[arg_index] = rv;
1051 }
1052 }
1053 }
1054 }
1055
1056 // Populate ModuleOrderedResourceVars.
SJW77b87ad2020-04-21 14:37:52 -05001057 for (Function &F : *module) {
David Neto862b7d82018-06-14 18:48:37 -04001058 auto where = FunctionToResourceVarsMap.find(&F);
1059 if (where != FunctionToResourceVarsMap.end()) {
1060 for (auto &rv : where->second) {
1061 if (rv != nullptr) {
1062 ModuleOrderedResourceVars.insert(rv);
1063 }
1064 }
1065 }
1066 }
1067 if (ShowResourceVars) {
1068 for (auto *info : ModuleOrderedResourceVars) {
1069 outs() << "MORV index " << info->index << " (" << info->descriptor_set
1070 << "," << info->binding << ") " << *(info->var_fn->getReturnType())
1071 << "\n";
1072 }
1073 }
1074}
1075
David Neto22f144c2017-06-12 14:26:21 -04001076void SPIRVProducerPass::FindTypePerGlobalVar(GlobalVariable &GV) {
1077 // Investigate global variable's type.
1078 FindType(GV.getType());
1079}
1080
1081void SPIRVProducerPass::FindTypePerFunc(Function &F) {
1082 // Investigate function's type.
1083 FunctionType *FTy = F.getFunctionType();
1084
1085 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
1086 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
David Neto9ed8e2f2018-03-24 06:47:24 -07001087 // Handle a regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04001088 if (GlobalConstFuncTyMap.count(FTy)) {
1089 uint32_t GVCstArgIdx = GlobalConstFuncTypeMap[FTy].second;
1090 SmallVector<Type *, 4> NewFuncParamTys;
1091 for (unsigned i = 0; i < FTy->getNumParams(); i++) {
1092 Type *ParamTy = FTy->getParamType(i);
1093 if (i == GVCstArgIdx) {
1094 Type *EleTy = ParamTy->getPointerElementType();
1095 ParamTy = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1096 }
1097
1098 NewFuncParamTys.push_back(ParamTy);
1099 }
1100
1101 FunctionType *NewFTy =
1102 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1103 GlobalConstFuncTyMap[FTy] = std::make_pair(NewFTy, GVCstArgIdx);
1104 FTy = NewFTy;
1105 }
1106
1107 FindType(FTy);
1108 } else {
1109 // As kernel functions do not have parameters, create new function type and
1110 // add it to type map.
1111 SmallVector<Type *, 4> NewFuncParamTys;
1112 FunctionType *NewFTy =
1113 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1114 FindType(NewFTy);
1115 }
1116
1117 // Investigate instructions' type in function body.
1118 for (BasicBlock &BB : F) {
1119 for (Instruction &I : BB) {
1120 if (isa<ShuffleVectorInst>(I)) {
1121 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1122 // Ignore type for mask of shuffle vector instruction.
1123 if (i == 2) {
1124 continue;
1125 }
1126
1127 Value *Op = I.getOperand(i);
1128 if (!isa<MetadataAsValue>(Op)) {
1129 FindType(Op->getType());
1130 }
1131 }
1132
1133 FindType(I.getType());
1134 continue;
1135 }
1136
David Neto862b7d82018-06-14 18:48:37 -04001137 CallInst *Call = dyn_cast<CallInst>(&I);
1138
SJW61531372020-06-09 07:31:08 -05001139 if (Call) {
1140 auto &func_info = Builtins::Lookup(Call->getCalledFunction());
1141 if (func_info.getType() == Builtins::kClspvResource ||
1142 func_info.getType() == Builtins::kClspvLocal) {
1143 // This is a fake call representing access to a resource/workgroup
1144 // variable. We handle that elsewhere.
1145 continue;
1146 }
Alan Baker202c8c72018-08-13 13:47:44 -04001147 }
1148
alan-bakerf083bed2020-01-29 08:15:42 -05001149 // #497: InsertValue and ExtractValue map to OpCompositeInsert and
1150 // OpCompositeExtract which takes literal values for indices. As a result
1151 // don't map the type of indices.
1152 if (I.getOpcode() == Instruction::ExtractValue) {
1153 FindType(I.getOperand(0)->getType());
1154 continue;
1155 }
1156 if (I.getOpcode() == Instruction::InsertValue) {
1157 FindType(I.getOperand(0)->getType());
1158 FindType(I.getOperand(1)->getType());
1159 continue;
1160 }
1161
1162 // #497: InsertElement and ExtractElement map to OpCompositeExtract if
1163 // the index is a constant. In such a case don't map the index type.
1164 if (I.getOpcode() == Instruction::ExtractElement) {
1165 FindType(I.getOperand(0)->getType());
1166 Value *op1 = I.getOperand(1);
1167 if (!isa<Constant>(op1) || isa<GlobalValue>(op1)) {
1168 FindType(op1->getType());
1169 }
1170 continue;
1171 }
1172 if (I.getOpcode() == Instruction::InsertElement) {
1173 FindType(I.getOperand(0)->getType());
1174 FindType(I.getOperand(1)->getType());
1175 Value *op2 = I.getOperand(2);
1176 if (!isa<Constant>(op2) || isa<GlobalValue>(op2)) {
1177 FindType(op2->getType());
1178 }
1179 continue;
1180 }
1181
David Neto22f144c2017-06-12 14:26:21 -04001182 // Work through the operands of the instruction.
1183 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1184 Value *const Op = I.getOperand(i);
1185 // If any of the operands is a constant, find the type!
1186 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1187 FindType(Op->getType());
1188 }
1189 }
1190
1191 for (Use &Op : I.operands()) {
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001192 if (isa<CallInst>(&I)) {
David Neto22f144c2017-06-12 14:26:21 -04001193 // Avoid to check call instruction's type.
1194 break;
1195 }
Alan Baker202c8c72018-08-13 13:47:44 -04001196 if (CallInst *OpCall = dyn_cast<CallInst>(Op)) {
SJW61531372020-06-09 07:31:08 -05001197 if (Builtins::Lookup(OpCall->getCalledFunction()) ==
1198 Builtins::kClspvLocal) {
Alan Baker202c8c72018-08-13 13:47:44 -04001199 // This is a fake call representing access to a workgroup variable.
1200 // We handle that elsewhere.
1201 continue;
1202 }
1203 }
David Neto22f144c2017-06-12 14:26:21 -04001204 if (!isa<MetadataAsValue>(&Op)) {
1205 FindType(Op->getType());
1206 continue;
1207 }
1208 }
1209
David Neto22f144c2017-06-12 14:26:21 -04001210 // We don't want to track the type of this call as we are going to replace
1211 // it.
SJW61531372020-06-09 07:31:08 -05001212 if (Call && Builtins::Lookup(Call->getCalledFunction()) ==
1213 Builtins::kClspvSamplerVarLiteral) {
David Neto22f144c2017-06-12 14:26:21 -04001214 continue;
1215 }
1216
1217 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
1218 // If gep's base operand has ModuleScopePrivate address space, make gep
1219 // return ModuleScopePrivate address space.
1220 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate) {
1221 // Add pointer type with private address space for global constant to
1222 // type list.
1223 Type *EleTy = I.getType()->getPointerElementType();
1224 Type *NewPTy =
1225 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1226
1227 FindType(NewPTy);
1228 continue;
1229 }
1230 }
1231
1232 FindType(I.getType());
1233 }
1234 }
1235}
1236
SJW77b87ad2020-04-21 14:37:52 -05001237void SPIRVProducerPass::FindTypesForSamplerMap() {
David Neto862b7d82018-06-14 18:48:37 -04001238 // If we are using a sampler map, find the type of the sampler.
SJW77b87ad2020-04-21 14:37:52 -05001239 if (module->getFunction(clspv::LiteralSamplerFunction()) ||
alan-baker7506abb2020-09-10 15:02:55 -04001240 !getSamplerMap().empty()) {
SJW77b87ad2020-04-21 14:37:52 -05001241 auto SamplerStructTy = module->getTypeByName("opencl.sampler_t");
David Neto862b7d82018-06-14 18:48:37 -04001242 if (!SamplerStructTy) {
SJW77b87ad2020-04-21 14:37:52 -05001243 SamplerStructTy =
1244 StructType::create(module->getContext(), "opencl.sampler_t");
David Neto862b7d82018-06-14 18:48:37 -04001245 }
1246
1247 SamplerTy = SamplerStructTy->getPointerTo(AddressSpace::UniformConstant);
1248
1249 FindType(SamplerTy);
1250 }
1251}
1252
SJW77b87ad2020-04-21 14:37:52 -05001253void SPIRVProducerPass::FindTypesForResourceVars() {
David Neto862b7d82018-06-14 18:48:37 -04001254 // Record types so they are generated.
1255 TypesNeedingLayout.reset();
1256 StructTypesNeedingBlock.reset();
1257
1258 // To match older clspv codegen, generate the float type first if required
1259 // for images.
1260 for (const auto *info : ModuleOrderedResourceVars) {
1261 if (info->arg_kind == clspv::ArgKind::ReadOnlyImage ||
1262 info->arg_kind == clspv::ArgKind::WriteOnlyImage) {
alan-bakerf67468c2019-11-25 15:51:49 -05001263 if (IsIntImageType(info->var_fn->getReturnType())) {
1264 // Nothing for now...
1265 } else if (IsUintImageType(info->var_fn->getReturnType())) {
SJW77b87ad2020-04-21 14:37:52 -05001266 FindType(Type::getInt32Ty(module->getContext()));
alan-bakerf67468c2019-11-25 15:51:49 -05001267 }
1268
1269 // We need "float" either for the sampled type or for the Lod operand.
SJW77b87ad2020-04-21 14:37:52 -05001270 FindType(Type::getFloatTy(module->getContext()));
David Neto862b7d82018-06-14 18:48:37 -04001271 }
1272 }
1273
1274 for (const auto *info : ModuleOrderedResourceVars) {
1275 Type *type = info->var_fn->getReturnType();
1276
1277 switch (info->arg_kind) {
1278 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04001279 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04001280 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1281 StructTypesNeedingBlock.insert(sty);
1282 } else {
1283 errs() << *type << "\n";
1284 llvm_unreachable("Buffer arguments must map to structures!");
1285 }
1286 break;
1287 case clspv::ArgKind::Pod:
alan-baker9b0ec3c2020-04-06 14:45:34 -04001288 case clspv::ArgKind::PodUBO:
1289 case clspv::ArgKind::PodPushConstant:
David Neto862b7d82018-06-14 18:48:37 -04001290 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1291 StructTypesNeedingBlock.insert(sty);
1292 } else {
1293 errs() << *type << "\n";
1294 llvm_unreachable("POD arguments must map to structures!");
1295 }
1296 break;
1297 case clspv::ArgKind::ReadOnlyImage:
1298 case clspv::ArgKind::WriteOnlyImage:
1299 case clspv::ArgKind::Sampler:
1300 // Sampler and image types map to the pointee type but
1301 // in the uniform constant address space.
1302 type = PointerType::get(type->getPointerElementType(),
1303 clspv::AddressSpace::UniformConstant);
1304 break;
1305 default:
1306 break;
1307 }
1308
1309 // The converted type is the type of the OpVariable we will generate.
1310 // If the pointee type is an array of size zero, FindType will convert it
1311 // to a runtime array.
1312 FindType(type);
1313 }
1314
alan-bakerdcd97412019-09-16 15:32:30 -04001315 // If module constants are clustered in a storage buffer then that struct
1316 // needs layout decorations.
1317 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
SJW77b87ad2020-04-21 14:37:52 -05001318 for (GlobalVariable &GV : module->globals()) {
alan-bakerdcd97412019-09-16 15:32:30 -04001319 PointerType *PTy = cast<PointerType>(GV.getType());
1320 const auto AS = PTy->getAddressSpace();
1321 const bool module_scope_constant_external_init =
1322 (AS == AddressSpace::Constant) && GV.hasInitializer();
1323 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
1324 if (module_scope_constant_external_init &&
1325 spv::BuiltInMax == BuiltinType) {
1326 StructTypesNeedingBlock.insert(
1327 cast<StructType>(PTy->getPointerElementType()));
1328 }
1329 }
1330 }
1331
SJW77b87ad2020-04-21 14:37:52 -05001332 for (const GlobalVariable &GV : module->globals()) {
Kévin Petitbbbda972020-03-03 19:16:31 +00001333 if (GV.getAddressSpace() == clspv::AddressSpace::PushConstant) {
1334 auto Ty = cast<PointerType>(GV.getType())->getPointerElementType();
1335 assert(Ty->isStructTy() && "Push constants have to be structures.");
1336 auto STy = cast<StructType>(Ty);
1337 StructTypesNeedingBlock.insert(STy);
1338 }
1339 }
1340
David Neto862b7d82018-06-14 18:48:37 -04001341 // Traverse the arrays and structures underneath each Block, and
1342 // mark them as needing layout.
1343 std::vector<Type *> work_list(StructTypesNeedingBlock.begin(),
1344 StructTypesNeedingBlock.end());
1345 while (!work_list.empty()) {
1346 Type *type = work_list.back();
1347 work_list.pop_back();
1348 TypesNeedingLayout.insert(type);
1349 switch (type->getTypeID()) {
1350 case Type::ArrayTyID:
1351 work_list.push_back(type->getArrayElementType());
1352 if (!Hack_generate_runtime_array_stride_early) {
1353 // Remember this array type for deferred decoration.
1354 TypesNeedingArrayStride.insert(type);
1355 }
1356 break;
1357 case Type::StructTyID:
1358 for (auto *elem_ty : cast<StructType>(type)->elements()) {
1359 work_list.push_back(elem_ty);
1360 }
1361 default:
1362 // This type and its contained types don't get layout.
1363 break;
1364 }
1365 }
1366}
1367
SJWf93f5f32020-05-05 07:27:56 -05001368void SPIRVProducerPass::GenerateWorkgroupVars() {
Alan Baker202c8c72018-08-13 13:47:44 -04001369 // The SpecId assignment for pointer-to-local arguments is recorded in
1370 // module-level metadata. Translate that information into local argument
1371 // information.
SJWf93f5f32020-05-05 07:27:56 -05001372 LLVMContext &Context = module->getContext();
SJW77b87ad2020-04-21 14:37:52 -05001373 NamedMDNode *nmd = module->getNamedMetadata(clspv::LocalSpecIdMetadataName());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001374 if (!nmd)
1375 return;
Alan Baker202c8c72018-08-13 13:47:44 -04001376 for (auto operand : nmd->operands()) {
1377 MDTuple *tuple = cast<MDTuple>(operand);
1378 ValueAsMetadata *fn_md = cast<ValueAsMetadata>(tuple->getOperand(0));
1379 Function *func = cast<Function>(fn_md->getValue());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001380 ConstantAsMetadata *arg_index_md =
1381 cast<ConstantAsMetadata>(tuple->getOperand(1));
1382 int arg_index = static_cast<int>(
1383 cast<ConstantInt>(arg_index_md->getValue())->getSExtValue());
1384 Argument *arg = &*(func->arg_begin() + arg_index);
Alan Baker202c8c72018-08-13 13:47:44 -04001385
1386 ConstantAsMetadata *spec_id_md =
1387 cast<ConstantAsMetadata>(tuple->getOperand(2));
alan-bakerb6b09dc2018-11-08 16:59:28 -05001388 int spec_id = static_cast<int>(
1389 cast<ConstantInt>(spec_id_md->getValue())->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04001390
Alan Baker202c8c72018-08-13 13:47:44 -04001391 LocalArgSpecIds[arg] = spec_id;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001392 if (LocalSpecIdInfoMap.count(spec_id))
1393 continue;
Alan Baker202c8c72018-08-13 13:47:44 -04001394
SJWf93f5f32020-05-05 07:27:56 -05001395 // Generate the spec constant.
1396 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05001397 Ops << Type::getInt32Ty(Context) << 1;
SJWf93f5f32020-05-05 07:27:56 -05001398 SPIRVID ArraySizeID = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
Alan Baker202c8c72018-08-13 13:47:44 -04001399
SJWf93f5f32020-05-05 07:27:56 -05001400 // Generate the array type.
1401 Type *ElemTy = arg->getType()->getPointerElementType();
1402 Ops.clear();
1403 // The element type must have been created.
SJW01901d92020-05-21 08:58:31 -05001404 Ops << ElemTy << ArraySizeID;
SJWf93f5f32020-05-05 07:27:56 -05001405
1406 SPIRVID ArrayTypeID = addSPIRVInst<kTypes>(spv::OpTypeArray, Ops);
1407
1408 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05001409 Ops << spv::StorageClassWorkgroup << ArrayTypeID;
SJWf93f5f32020-05-05 07:27:56 -05001410 SPIRVID PtrArrayTypeID = addSPIRVInst<kTypes>(spv::OpTypePointer, Ops);
1411
1412 // Generate OpVariable.
1413 //
1414 // Ops[0] : Result Type ID
1415 // Ops[1] : Storage Class
SJW806a5d82020-07-15 12:51:38 -05001416 SPIRVID VariableID =
1417 addSPIRVGlobalVariable(PtrArrayTypeID, spv::StorageClassWorkgroup);
SJWf93f5f32020-05-05 07:27:56 -05001418
1419 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05001420 Ops << ArraySizeID << spv::DecorationSpecId << spec_id;
SJWf93f5f32020-05-05 07:27:56 -05001421 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
1422
1423 LocalArgInfo info{VariableID, ElemTy, ArraySizeID,
1424 ArrayTypeID, PtrArrayTypeID, spec_id};
1425 LocalSpecIdInfoMap[spec_id] = info;
Alan Baker202c8c72018-08-13 13:47:44 -04001426 }
1427}
1428
David Neto22f144c2017-06-12 14:26:21 -04001429void SPIRVProducerPass::FindType(Type *Ty) {
1430 TypeList &TyList = getTypeList();
1431
1432 if (0 != TyList.idFor(Ty)) {
1433 return;
1434 }
1435
1436 if (Ty->isPointerTy()) {
1437 auto AddrSpace = Ty->getPointerAddressSpace();
1438 if ((AddressSpace::Constant == AddrSpace) ||
1439 (AddressSpace::Global == AddrSpace)) {
1440 auto PointeeTy = Ty->getPointerElementType();
1441
1442 if (PointeeTy->isStructTy() &&
1443 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1444 FindType(PointeeTy);
1445 auto ActualPointerTy =
1446 PointeeTy->getPointerTo(AddressSpace::UniformConstant);
1447 FindType(ActualPointerTy);
1448 return;
1449 }
1450 }
1451 }
1452
David Neto862b7d82018-06-14 18:48:37 -04001453 // By convention, LLVM array type with 0 elements will map to
1454 // OpTypeRuntimeArray. Otherwise, it will map to OpTypeArray, which
1455 // has a constant number of elements. We need to support type of the
1456 // constant.
1457 if (auto *arrayTy = dyn_cast<ArrayType>(Ty)) {
1458 if (arrayTy->getNumElements() > 0) {
1459 LLVMContext &Context = Ty->getContext();
1460 FindType(Type::getInt32Ty(Context));
1461 }
David Neto22f144c2017-06-12 14:26:21 -04001462 }
1463
1464 for (Type *SubTy : Ty->subtypes()) {
1465 FindType(SubTy);
1466 }
1467
1468 TyList.insert(Ty);
1469}
1470
David Neto22f144c2017-06-12 14:26:21 -04001471spv::StorageClass SPIRVProducerPass::GetStorageClass(unsigned AddrSpace) const {
1472 switch (AddrSpace) {
1473 default:
1474 llvm_unreachable("Unsupported OpenCL address space");
1475 case AddressSpace::Private:
1476 return spv::StorageClassFunction;
1477 case AddressSpace::Global:
David Neto22f144c2017-06-12 14:26:21 -04001478 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001479 case AddressSpace::Constant:
1480 return clspv::Option::ConstantArgsInUniformBuffer()
1481 ? spv::StorageClassUniform
1482 : spv::StorageClassStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -04001483 case AddressSpace::Input:
1484 return spv::StorageClassInput;
1485 case AddressSpace::Local:
1486 return spv::StorageClassWorkgroup;
1487 case AddressSpace::UniformConstant:
1488 return spv::StorageClassUniformConstant;
David Neto9ed8e2f2018-03-24 06:47:24 -07001489 case AddressSpace::Uniform:
David Netoe439d702018-03-23 13:14:08 -07001490 return spv::StorageClassUniform;
David Neto22f144c2017-06-12 14:26:21 -04001491 case AddressSpace::ModuleScopePrivate:
1492 return spv::StorageClassPrivate;
Kévin Petitbbbda972020-03-03 19:16:31 +00001493 case AddressSpace::PushConstant:
1494 return spv::StorageClassPushConstant;
David Neto22f144c2017-06-12 14:26:21 -04001495 }
1496}
1497
David Neto862b7d82018-06-14 18:48:37 -04001498spv::StorageClass
1499SPIRVProducerPass::GetStorageClassForArgKind(clspv::ArgKind arg_kind) const {
1500 switch (arg_kind) {
1501 case clspv::ArgKind::Buffer:
1502 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001503 case clspv::ArgKind::BufferUBO:
1504 return spv::StorageClassUniform;
David Neto862b7d82018-06-14 18:48:37 -04001505 case clspv::ArgKind::Pod:
alan-baker9b0ec3c2020-04-06 14:45:34 -04001506 return spv::StorageClassStorageBuffer;
1507 case clspv::ArgKind::PodUBO:
1508 return spv::StorageClassUniform;
1509 case clspv::ArgKind::PodPushConstant:
1510 return spv::StorageClassPushConstant;
David Neto862b7d82018-06-14 18:48:37 -04001511 case clspv::ArgKind::Local:
1512 return spv::StorageClassWorkgroup;
1513 case clspv::ArgKind::ReadOnlyImage:
1514 case clspv::ArgKind::WriteOnlyImage:
1515 case clspv::ArgKind::Sampler:
1516 return spv::StorageClassUniformConstant;
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001517 default:
1518 llvm_unreachable("Unsupported storage class for argument kind");
David Neto862b7d82018-06-14 18:48:37 -04001519 }
1520}
1521
David Neto22f144c2017-06-12 14:26:21 -04001522spv::BuiltIn SPIRVProducerPass::GetBuiltin(StringRef Name) const {
1523 return StringSwitch<spv::BuiltIn>(Name)
1524 .Case("__spirv_GlobalInvocationId", spv::BuiltInGlobalInvocationId)
1525 .Case("__spirv_LocalInvocationId", spv::BuiltInLocalInvocationId)
1526 .Case("__spirv_WorkgroupSize", spv::BuiltInWorkgroupSize)
1527 .Case("__spirv_NumWorkgroups", spv::BuiltInNumWorkgroups)
1528 .Case("__spirv_WorkgroupId", spv::BuiltInWorkgroupId)
alan-bakerbed3a882020-04-21 14:42:41 -04001529 .Case("__spirv_WorkDim", spv::BuiltInWorkDim)
alan-bakere1996972020-05-04 08:38:12 -04001530 .Case("__spirv_GlobalOffset", spv::BuiltInGlobalOffset)
David Neto22f144c2017-06-12 14:26:21 -04001531 .Default(spv::BuiltInMax);
1532}
1533
SJW01901d92020-05-21 08:58:31 -05001534SPIRVID SPIRVProducerPass::getOpExtInstImportID() {
1535 if (OpExtInstImportID == 0) {
1536 //
1537 // Generate OpExtInstImport.
1538 //
1539 // Ops[0] ... Ops[n] = Name (Literal String)
David Neto22f144c2017-06-12 14:26:21 -04001540
SJW01901d92020-05-21 08:58:31 -05001541 OpExtInstImportID =
1542 addSPIRVInst<kImports>(spv::OpExtInstImport, "GLSL.std.450");
1543 }
1544 return OpExtInstImportID;
SJWf93f5f32020-05-05 07:27:56 -05001545}
1546
SJW806a5d82020-07-15 12:51:38 -05001547SPIRVID SPIRVProducerPass::addSPIRVGlobalVariable(const SPIRVID &TypeID,
1548 spv::StorageClass SC,
1549 const SPIRVID &InitID) {
1550 // Generate OpVariable.
1551 //
1552 // Ops[0] : Result Type ID
1553 // Ops[1] : Storage Class
1554 // Ops[2] : Initialization Value ID (optional)
1555
1556 SPIRVOperandVec Ops;
1557 Ops << TypeID << SC;
1558 if (InitID.isValid()) {
1559 Ops << InitID;
1560 }
1561
1562 SPIRVID VID = addSPIRVInst<kGlobalVariables>(spv::OpVariable, Ops);
1563
1564 if (SC == spv::StorageClassInput) {
1565 getEntryPointInterfacesList().push_back(VID);
1566 }
1567
1568 return VID;
1569}
1570
SJW01901d92020-05-21 08:58:31 -05001571SPIRVID SPIRVProducerPass::getSPIRVType(Type *Ty) {
SJWf93f5f32020-05-05 07:27:56 -05001572 auto TI = TypeMap.find(Ty);
1573 if (TI != TypeMap.end()) {
SJW01901d92020-05-21 08:58:31 -05001574 assert(TI->second.isValid());
SJWf93f5f32020-05-05 07:27:56 -05001575 return TI->second;
1576 }
1577
1578 const auto &DL = module->getDataLayout();
1579
SJW01901d92020-05-21 08:58:31 -05001580 SPIRVID RID;
SJWf93f5f32020-05-05 07:27:56 -05001581
1582 switch (Ty->getTypeID()) {
1583 default: {
1584 Ty->print(errs());
1585 llvm_unreachable("Unsupported type???");
1586 break;
1587 }
1588 case Type::MetadataTyID:
1589 case Type::LabelTyID: {
1590 // Ignore these types.
1591 break;
1592 }
1593 case Type::PointerTyID: {
1594 PointerType *PTy = cast<PointerType>(Ty);
1595 unsigned AddrSpace = PTy->getAddressSpace();
1596
1597 if (AddrSpace != AddressSpace::UniformConstant) {
1598 auto PointeeTy = PTy->getElementType();
1599 if (PointeeTy->isStructTy() &&
1600 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1601 // TODO(sjw): assert always an image?
1602 RID = getSPIRVType(PointeeTy);
1603 break;
1604 }
1605 }
1606
1607 // For the purposes of our Vulkan SPIR-V type system, constant and global
1608 // are conflated.
1609 if (AddressSpace::Constant == AddrSpace) {
1610 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1611 AddrSpace = AddressSpace::Global;
1612 // Check to see if we already created this type (for instance, if we
1613 // had a constant <type>* and a global <type>*, the type would be
1614 // created by one of these types, and shared by both).
1615 auto GlobalTy = PTy->getPointerElementType()->getPointerTo(AddrSpace);
1616 if (0 < TypeMap.count(GlobalTy)) {
1617 RID = TypeMap[GlobalTy];
1618 break;
1619 }
1620 }
1621 } else if (AddressSpace::Global == AddrSpace) {
1622 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1623 AddrSpace = AddressSpace::Constant;
1624
1625 // Check to see if we already created this type (for instance, if we
1626 // had a constant <type>* and a global <type>*, the type would be
1627 // created by one of these types, and shared by both).
1628 auto ConstantTy = PTy->getPointerElementType()->getPointerTo(AddrSpace);
1629 if (0 < TypeMap.count(ConstantTy)) {
1630 RID = TypeMap[ConstantTy];
1631 break;
1632 }
1633 }
1634 }
1635
1636 //
1637 // Generate OpTypePointer.
1638 //
1639
1640 // OpTypePointer
1641 // Ops[0] = Storage Class
1642 // Ops[1] = Element Type ID
1643 SPIRVOperandVec Ops;
1644
SJW01901d92020-05-21 08:58:31 -05001645 Ops << GetStorageClass(AddrSpace) << PTy->getElementType();
SJWf93f5f32020-05-05 07:27:56 -05001646
1647 RID = addSPIRVInst<kTypes>(spv::OpTypePointer, Ops);
1648 break;
1649 }
1650 case Type::StructTyID: {
1651 StructType *STy = cast<StructType>(Ty);
1652
1653 // Handle sampler type.
1654 if (STy->isOpaque()) {
1655 if (STy->getName().equals("opencl.sampler_t")) {
1656 //
1657 // Generate OpTypeSampler
1658 //
1659 // Empty Ops.
1660
1661 RID = addSPIRVInst<kTypes>(spv::OpTypeSampler);
1662 break;
1663 } else if (STy->getName().startswith("opencl.image1d_ro_t") ||
1664 STy->getName().startswith("opencl.image1d_wo_t") ||
1665 STy->getName().startswith("opencl.image1d_array_ro_t") ||
1666 STy->getName().startswith("opencl.image1d_array_wo_t") ||
1667 STy->getName().startswith("opencl.image2d_ro_t") ||
1668 STy->getName().startswith("opencl.image2d_wo_t") ||
1669 STy->getName().startswith("opencl.image2d_array_ro_t") ||
1670 STy->getName().startswith("opencl.image2d_array_wo_t") ||
1671 STy->getName().startswith("opencl.image3d_ro_t") ||
1672 STy->getName().startswith("opencl.image3d_wo_t")) {
SJW01901d92020-05-21 08:58:31 -05001673
1674 if (STy->getName().contains("_wo_t")) {
1675 addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
1676 }
1677 if (STy->getName().startswith("opencl.image1d_")) {
1678 if (STy->getName().contains(".sampled"))
1679 addCapability(spv::CapabilitySampled1D);
1680 else
1681 addCapability(spv::CapabilityImage1D);
1682 }
1683
SJWf93f5f32020-05-05 07:27:56 -05001684 //
1685 // Generate OpTypeImage
1686 //
1687 // Ops[0] = Sampled Type ID
1688 // Ops[1] = Dim ID
1689 // Ops[2] = Depth (Literal Number)
1690 // Ops[3] = Arrayed (Literal Number)
1691 // Ops[4] = MS (Literal Number)
1692 // Ops[5] = Sampled (Literal Number)
1693 // Ops[6] = Image Format ID
1694 //
1695 SPIRVOperandVec Ops;
1696
SJW01901d92020-05-21 08:58:31 -05001697 SPIRVID SampledTyID;
SJWf93f5f32020-05-05 07:27:56 -05001698 if (STy->getName().contains(".float")) {
1699 SampledTyID = getSPIRVType(Type::getFloatTy(Ty->getContext()));
1700 } else if (STy->getName().contains(".uint")) {
1701 SampledTyID = getSPIRVType(Type::getInt32Ty(Ty->getContext()));
1702 } else if (STy->getName().contains(".int")) {
1703 // Generate a signed 32-bit integer if necessary.
1704 if (int32ID == 0) {
1705 SPIRVOperandVec intOps;
SJW01901d92020-05-21 08:58:31 -05001706 intOps << 32 << 1;
SJWf93f5f32020-05-05 07:27:56 -05001707 int32ID = addSPIRVInst<kTypes>(spv::OpTypeInt, intOps);
1708 }
1709 SampledTyID = int32ID;
1710
1711 // Generate a vec4 of the signed int if necessary.
1712 if (v4int32ID == 0) {
1713 SPIRVOperandVec vecOps;
SJW01901d92020-05-21 08:58:31 -05001714 vecOps << int32ID << 4;
SJWf93f5f32020-05-05 07:27:56 -05001715 v4int32ID = addSPIRVInst<kTypes>(spv::OpTypeVector, vecOps);
1716 }
1717 } else {
1718 // This was likely an UndefValue.
1719 SampledTyID = getSPIRVType(Type::getFloatTy(Ty->getContext()));
1720 }
SJW01901d92020-05-21 08:58:31 -05001721 Ops << SampledTyID;
SJWf93f5f32020-05-05 07:27:56 -05001722
1723 spv::Dim DimID = spv::Dim2D;
1724 if (STy->getName().startswith("opencl.image1d_ro_t") ||
1725 STy->getName().startswith("opencl.image1d_wo_t") ||
1726 STy->getName().startswith("opencl.image1d_array_ro_t") ||
1727 STy->getName().startswith("opencl.image1d_array_wo_t")) {
1728 DimID = spv::Dim1D;
1729 } else if (STy->getName().startswith("opencl.image3d_ro_t") ||
1730 STy->getName().startswith("opencl.image3d_wo_t")) {
1731 DimID = spv::Dim3D;
1732 }
SJW01901d92020-05-21 08:58:31 -05001733 Ops << DimID;
SJWf93f5f32020-05-05 07:27:56 -05001734
1735 // TODO: Set up Depth.
SJW01901d92020-05-21 08:58:31 -05001736 Ops << 0;
SJWf93f5f32020-05-05 07:27:56 -05001737
1738 uint32_t arrayed = STy->getName().contains("_array_") ? 1 : 0;
SJW01901d92020-05-21 08:58:31 -05001739 Ops << arrayed;
SJWf93f5f32020-05-05 07:27:56 -05001740
1741 // TODO: Set up MS.
SJW01901d92020-05-21 08:58:31 -05001742 Ops << 0;
SJWf93f5f32020-05-05 07:27:56 -05001743
1744 // Set up Sampled.
1745 //
1746 // From Spec
1747 //
1748 // 0 indicates this is only known at run time, not at compile time
1749 // 1 indicates will be used with sampler
1750 // 2 indicates will be used without a sampler (a storage image)
1751 uint32_t Sampled = 1;
1752 if (!STy->getName().contains(".sampled")) {
1753 Sampled = 2;
1754 }
SJW01901d92020-05-21 08:58:31 -05001755 Ops << Sampled;
SJWf93f5f32020-05-05 07:27:56 -05001756
1757 // TODO: Set up Image Format.
SJW01901d92020-05-21 08:58:31 -05001758 Ops << spv::ImageFormatUnknown;
SJWf93f5f32020-05-05 07:27:56 -05001759
1760 RID = addSPIRVInst<kTypes>(spv::OpTypeImage, Ops);
1761
1762 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05001763 Ops << RID;
SJWf93f5f32020-05-05 07:27:56 -05001764
1765 getImageTypeMap()[Ty] =
1766 addSPIRVInst<kTypes>(spv::OpTypeSampledImage, Ops);
1767 break;
1768 }
1769 }
1770
1771 //
1772 // Generate OpTypeStruct
1773 //
1774 // Ops[0] ... Ops[n] = Member IDs
1775 SPIRVOperandVec Ops;
1776
1777 for (auto *EleTy : STy->elements()) {
SJW01901d92020-05-21 08:58:31 -05001778 Ops << EleTy;
SJWf93f5f32020-05-05 07:27:56 -05001779 }
1780
1781 RID = addSPIRVInst<kTypes>(spv::OpTypeStruct, Ops);
1782
1783 // Generate OpMemberDecorate.
1784 if (TypesNeedingLayout.idFor(STy)) {
1785 for (unsigned MemberIdx = 0; MemberIdx < STy->getNumElements();
1786 MemberIdx++) {
1787 // Ops[0] = Structure Type ID
1788 // Ops[1] = Member Index(Literal Number)
1789 // Ops[2] = Decoration (Offset)
1790 // Ops[3] = Byte Offset (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05001791 const auto ByteOffset =
1792 GetExplicitLayoutStructMemberOffset(STy, MemberIdx, DL);
1793
SJW01901d92020-05-21 08:58:31 -05001794 Ops.clear();
1795 Ops << RID << MemberIdx << spv::DecorationOffset << ByteOffset;
SJWf93f5f32020-05-05 07:27:56 -05001796
1797 addSPIRVInst<kAnnotations>(spv::OpMemberDecorate, Ops);
1798 }
1799 }
1800
1801 // Generate OpDecorate.
1802 if (StructTypesNeedingBlock.idFor(STy)) {
1803 Ops.clear();
1804 // Use Block decorations with StorageBuffer storage class.
SJW01901d92020-05-21 08:58:31 -05001805 Ops << RID << spv::DecorationBlock;
SJWf93f5f32020-05-05 07:27:56 -05001806
1807 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
1808 }
1809 break;
1810 }
1811 case Type::IntegerTyID: {
alan-bakere2a62752020-07-09 22:53:23 -04001812 uint32_t bit_width = static_cast<uint32_t>(Ty->getPrimitiveSizeInBits());
SJWf93f5f32020-05-05 07:27:56 -05001813
alan-bakere2a62752020-07-09 22:53:23 -04001814 if (clspv::Option::Int8Support() && bit_width == 8) {
SJW01901d92020-05-21 08:58:31 -05001815 addCapability(spv::CapabilityInt8);
alan-bakere2a62752020-07-09 22:53:23 -04001816 } else if (bit_width == 16) {
SJW01901d92020-05-21 08:58:31 -05001817 addCapability(spv::CapabilityInt16);
alan-bakere2a62752020-07-09 22:53:23 -04001818 } else if (bit_width == 64) {
SJW01901d92020-05-21 08:58:31 -05001819 addCapability(spv::CapabilityInt64);
1820 }
1821
alan-bakere2a62752020-07-09 22:53:23 -04001822 if (bit_width == 1) {
SJWf93f5f32020-05-05 07:27:56 -05001823 RID = addSPIRVInst<kTypes>(spv::OpTypeBool);
1824 } else {
alan-bakere2a62752020-07-09 22:53:23 -04001825 if (!clspv::Option::Int8Support() && bit_width == 8) {
SJWf93f5f32020-05-05 07:27:56 -05001826 // i8 is added to TypeMap as i32.
1827 RID = getSPIRVType(Type::getIntNTy(Ty->getContext(), 32));
1828 } else {
1829 SPIRVOperandVec Ops;
alan-bakere2a62752020-07-09 22:53:23 -04001830 Ops << bit_width << 0 /* not signed */;
SJWf93f5f32020-05-05 07:27:56 -05001831 RID = addSPIRVInst<kTypes>(spv::OpTypeInt, Ops);
1832 }
1833 }
1834 break;
1835 }
1836 case Type::HalfTyID:
1837 case Type::FloatTyID:
1838 case Type::DoubleTyID: {
alan-bakere2a62752020-07-09 22:53:23 -04001839 uint32_t bit_width = static_cast<uint32_t>(Ty->getPrimitiveSizeInBits());
1840 if (bit_width == 16) {
SJW01901d92020-05-21 08:58:31 -05001841 addCapability(spv::CapabilityFloat16);
alan-bakere2a62752020-07-09 22:53:23 -04001842 } else if (bit_width == 64) {
SJW01901d92020-05-21 08:58:31 -05001843 addCapability(spv::CapabilityFloat64);
1844 }
1845
SJWf93f5f32020-05-05 07:27:56 -05001846 SPIRVOperandVec Ops;
alan-bakere2a62752020-07-09 22:53:23 -04001847 Ops << bit_width;
SJWf93f5f32020-05-05 07:27:56 -05001848
1849 RID = addSPIRVInst<kTypes>(spv::OpTypeFloat, Ops);
1850 break;
1851 }
1852 case Type::ArrayTyID: {
1853 ArrayType *ArrTy = cast<ArrayType>(Ty);
1854 const uint64_t Length = ArrTy->getArrayNumElements();
1855 if (Length == 0) {
1856 // By convention, map it to a RuntimeArray.
1857
1858 Type *EleTy = ArrTy->getArrayElementType();
1859
1860 //
1861 // Generate OpTypeRuntimeArray.
1862 //
1863 // OpTypeRuntimeArray
1864 // Ops[0] = Element Type ID
1865 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05001866 Ops << EleTy;
SJWf93f5f32020-05-05 07:27:56 -05001867
1868 RID = addSPIRVInst<kTypes>(spv::OpTypeRuntimeArray, Ops);
1869
1870 if (Hack_generate_runtime_array_stride_early) {
1871 // Generate OpDecorate.
1872
1873 // Ops[0] = Target ID
1874 // Ops[1] = Decoration (ArrayStride)
1875 // Ops[2] = Stride Number(Literal Number)
1876 Ops.clear();
1877
SJW01901d92020-05-21 08:58:31 -05001878 Ops << RID << spv::DecorationArrayStride
1879 << static_cast<uint32_t>(GetTypeAllocSize(EleTy, DL));
SJWf93f5f32020-05-05 07:27:56 -05001880
1881 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
1882 }
1883
1884 } else {
1885
1886 //
1887 // Generate OpConstant and OpTypeArray.
1888 //
1889
1890 //
1891 // Generate OpConstant for array length.
1892 //
1893 // Add constant for length to constant list.
1894 Constant *CstLength =
1895 ConstantInt::get(Type::getInt32Ty(module->getContext()), Length);
SJWf93f5f32020-05-05 07:27:56 -05001896
1897 // Remember to generate ArrayStride later
1898 getTypesNeedingArrayStride().insert(Ty);
1899
1900 //
1901 // Generate OpTypeArray.
1902 //
1903 // Ops[0] = Element Type ID
1904 // Ops[1] = Array Length Constant ID
1905 SPIRVOperandVec Ops;
1906
SJW01901d92020-05-21 08:58:31 -05001907 Ops << ArrTy->getElementType() << CstLength;
SJWf93f5f32020-05-05 07:27:56 -05001908
1909 RID = addSPIRVInst<kTypes>(spv::OpTypeArray, Ops);
1910 }
1911 break;
1912 }
1913 case Type::FixedVectorTyID: {
1914 auto VecTy = cast<VectorType>(Ty);
1915 // <4 x i8> is changed to i32 if i8 is not generally supported.
1916 if (!clspv::Option::Int8Support() &&
1917 VecTy->getElementType() == Type::getInt8Ty(module->getContext())) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001918 if (VecTy->getElementCount().getKnownMinValue() == 4) {
SJWf93f5f32020-05-05 07:27:56 -05001919 RID = getSPIRVType(VecTy->getElementType());
1920 break;
1921 } else {
1922 Ty->print(errs());
1923 llvm_unreachable("Support above i8 vector type");
1924 }
1925 }
1926
1927 // Ops[0] = Component Type ID
1928 // Ops[1] = Component Count (Literal Number)
1929 SPIRVOperandVec Ops;
alan-baker5a8c3be2020-09-09 13:44:26 -04001930 Ops << VecTy->getElementType()
1931 << VecTy->getElementCount().getKnownMinValue();
SJWf93f5f32020-05-05 07:27:56 -05001932
1933 RID = addSPIRVInst<kTypes>(spv::OpTypeVector, Ops);
1934 break;
1935 }
1936 case Type::VoidTyID: {
1937 RID = addSPIRVInst<kTypes>(spv::OpTypeVoid);
1938 break;
1939 }
1940 case Type::FunctionTyID: {
1941 // Generate SPIRV instruction for function type.
1942 FunctionType *FTy = cast<FunctionType>(Ty);
1943
1944 // Ops[0] = Return Type ID
1945 // Ops[1] ... Ops[n] = Parameter Type IDs
1946 SPIRVOperandVec Ops;
1947
1948 // Find SPIRV instruction for return type
SJW01901d92020-05-21 08:58:31 -05001949 Ops << FTy->getReturnType();
SJWf93f5f32020-05-05 07:27:56 -05001950
1951 // Find SPIRV instructions for parameter types
1952 for (unsigned k = 0; k < FTy->getNumParams(); k++) {
1953 // Find SPIRV instruction for parameter type.
1954 auto ParamTy = FTy->getParamType(k);
1955 if (ParamTy->isPointerTy()) {
1956 auto PointeeTy = ParamTy->getPointerElementType();
1957 if (PointeeTy->isStructTy() &&
1958 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1959 ParamTy = PointeeTy;
1960 }
1961 }
1962
SJW01901d92020-05-21 08:58:31 -05001963 Ops << ParamTy;
SJWf93f5f32020-05-05 07:27:56 -05001964 }
1965
1966 RID = addSPIRVInst<kTypes>(spv::OpTypeFunction, Ops);
1967 break;
1968 }
1969 }
1970
SJW01901d92020-05-21 08:58:31 -05001971 if (RID.isValid()) {
SJWf93f5f32020-05-05 07:27:56 -05001972 TypeMap[Ty] = RID;
1973 }
1974 return RID;
David Neto22f144c2017-06-12 14:26:21 -04001975}
1976
SJW77b87ad2020-04-21 14:37:52 -05001977void SPIRVProducerPass::GenerateSPIRVTypes() {
David Neto22f144c2017-06-12 14:26:21 -04001978 for (Type *Ty : getTypeList()) {
SJWf93f5f32020-05-05 07:27:56 -05001979 getSPIRVType(Ty);
David Netoc6f3ab22018-04-06 18:02:31 -04001980 }
David Neto22f144c2017-06-12 14:26:21 -04001981}
1982
SJW806a5d82020-07-15 12:51:38 -05001983SPIRVID SPIRVProducerPass::getSPIRVInt32Constant(uint32_t CstVal) {
1984 Type *i32 = Type::getInt32Ty(module->getContext());
1985 Constant *Cst = ConstantInt::get(i32, CstVal);
1986 return getSPIRVValue(Cst);
1987}
1988
SJWf93f5f32020-05-05 07:27:56 -05001989SPIRVID SPIRVProducerPass::getSPIRVConstant(Constant *Cst) {
David Neto22f144c2017-06-12 14:26:21 -04001990 ValueMapType &VMap = getValueMap();
David Neto482550a2018-03-24 05:21:07 -07001991 const bool hack_undef = clspv::Option::HackUndef();
David Neto22f144c2017-06-12 14:26:21 -04001992
SJW01901d92020-05-21 08:58:31 -05001993 SPIRVID RID;
David Neto22f144c2017-06-12 14:26:21 -04001994
SJWf93f5f32020-05-05 07:27:56 -05001995 //
1996 // Generate OpConstant.
1997 //
1998 // Ops[0] = Result Type ID
1999 // Ops[1] .. Ops[n] = Values LiteralNumber
2000 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04002001
SJW01901d92020-05-21 08:58:31 -05002002 Ops << Cst->getType();
David Neto22f144c2017-06-12 14:26:21 -04002003
SJWf93f5f32020-05-05 07:27:56 -05002004 std::vector<uint32_t> LiteralNum;
2005 spv::Op Opcode = spv::OpNop;
David Neto22f144c2017-06-12 14:26:21 -04002006
SJWf93f5f32020-05-05 07:27:56 -05002007 if (isa<UndefValue>(Cst)) {
David Neto22f144c2017-06-12 14:26:21 -04002008 // Ops[0] = Result Type ID
SJWf93f5f32020-05-05 07:27:56 -05002009 Opcode = spv::OpUndef;
2010 if (hack_undef && IsTypeNullable(Cst->getType())) {
2011 Opcode = spv::OpConstantNull;
2012 }
2013 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(Cst)) {
alan-bakere2a62752020-07-09 22:53:23 -04002014 unsigned bit_width = CI->getBitWidth();
2015 if (bit_width == 1) {
SJWf93f5f32020-05-05 07:27:56 -05002016 // If the bitwidth of constant is 1, generate OpConstantTrue or
2017 // OpConstantFalse.
2018 if (CI->getZExtValue()) {
2019 // Ops[0] = Result Type ID
2020 Opcode = spv::OpConstantTrue;
David Neto22f144c2017-06-12 14:26:21 -04002021 } else {
SJWf93f5f32020-05-05 07:27:56 -05002022 // Ops[0] = Result Type ID
2023 Opcode = spv::OpConstantFalse;
David Neto22f144c2017-06-12 14:26:21 -04002024 }
SJWf93f5f32020-05-05 07:27:56 -05002025 } else {
2026 auto V = CI->getZExtValue();
2027 LiteralNum.push_back(V & 0xFFFFFFFF);
2028
alan-bakere2a62752020-07-09 22:53:23 -04002029 if (bit_width > 32) {
SJWf93f5f32020-05-05 07:27:56 -05002030 LiteralNum.push_back(V >> 32);
David Neto22f144c2017-06-12 14:26:21 -04002031 }
2032
2033 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002034
SJW01901d92020-05-21 08:58:31 -05002035 Ops << LiteralNum;
SJWf93f5f32020-05-05 07:27:56 -05002036 }
2037 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Cst)) {
2038 uint64_t FPVal = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
2039 Type *CFPTy = CFP->getType();
2040 if (CFPTy->isFloatTy()) {
2041 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
2042 } else if (CFPTy->isDoubleTy()) {
2043 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
2044 LiteralNum.push_back(FPVal >> 32);
2045 } else if (CFPTy->isHalfTy()) {
2046 LiteralNum.push_back(FPVal & 0xFFFF);
2047 } else {
2048 CFPTy->print(errs());
2049 llvm_unreachable("Implement this ConstantFP Type");
2050 }
David Neto22f144c2017-06-12 14:26:21 -04002051
SJWf93f5f32020-05-05 07:27:56 -05002052 Opcode = spv::OpConstant;
David Neto49351ac2017-08-26 17:32:20 -04002053
SJW01901d92020-05-21 08:58:31 -05002054 Ops << LiteralNum;
SJWf93f5f32020-05-05 07:27:56 -05002055 } else if (isa<ConstantDataSequential>(Cst) &&
2056 cast<ConstantDataSequential>(Cst)->isString()) {
2057 Cst->print(errs());
2058 llvm_unreachable("Implement this Constant");
David Neto49351ac2017-08-26 17:32:20 -04002059
SJWf93f5f32020-05-05 07:27:56 -05002060 } else if (const ConstantDataSequential *CDS =
2061 dyn_cast<ConstantDataSequential>(Cst)) {
2062 // Let's convert <4 x i8> constant to int constant specially.
2063 // This case occurs when all the values are specified as constant
2064 // ints.
2065 Type *CstTy = Cst->getType();
2066 if (is4xi8vec(CstTy)) {
SJWf93f5f32020-05-05 07:27:56 -05002067 //
2068 // Generate OpConstant with OpTypeInt 32 0.
2069 //
2070 uint32_t IntValue = 0;
2071 for (unsigned k = 0; k < 4; k++) {
2072 const uint64_t Val = CDS->getElementAsInteger(k);
2073 IntValue = (IntValue << 8) | (Val & 0xffu);
David Neto49351ac2017-08-26 17:32:20 -04002074 }
2075
SJW806a5d82020-07-15 12:51:38 -05002076 RID = getSPIRVInt32Constant(IntValue);
SJWf93f5f32020-05-05 07:27:56 -05002077 } else {
2078
David Neto49351ac2017-08-26 17:32:20 -04002079 // A normal constant-data-sequential case.
David Neto22f144c2017-06-12 14:26:21 -04002080 for (unsigned k = 0; k < CDS->getNumElements(); k++) {
SJW01901d92020-05-21 08:58:31 -05002081 Ops << CDS->getElementAsConstant(k);
David Neto22f144c2017-06-12 14:26:21 -04002082 }
2083
2084 Opcode = spv::OpConstantComposite;
SJWf93f5f32020-05-05 07:27:56 -05002085 }
2086 } else if (const ConstantAggregate *CA = dyn_cast<ConstantAggregate>(Cst)) {
2087 // Let's convert <4 x i8> constant to int constant specially.
2088 // This case occurs when at least one of the values is an undef.
2089 Type *CstTy = Cst->getType();
2090 if (is4xi8vec(CstTy)) {
SJWf93f5f32020-05-05 07:27:56 -05002091 //
2092 // Generate OpConstant with OpTypeInt 32 0.
2093 //
2094 uint32_t IntValue = 0;
2095 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end();
2096 I != E; ++I) {
2097 uint64_t Val = 0;
2098 const Value *CV = *I;
2099 if (auto *CI2 = dyn_cast<ConstantInt>(CV)) {
2100 Val = CI2->getZExtValue();
David Neto22f144c2017-06-12 14:26:21 -04002101 }
SJWf93f5f32020-05-05 07:27:56 -05002102 IntValue = (IntValue << 8) | (Val & 0xffu);
David Neto22f144c2017-06-12 14:26:21 -04002103 }
2104
SJW806a5d82020-07-15 12:51:38 -05002105 RID = getSPIRVInt32Constant(IntValue);
SJWf93f5f32020-05-05 07:27:56 -05002106 } else {
2107
David Neto22f144c2017-06-12 14:26:21 -04002108 // We use a constant composite in SPIR-V for our constant aggregate in
2109 // LLVM.
2110 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002111
2112 for (unsigned k = 0; k < CA->getNumOperands(); k++) {
David Neto22f144c2017-06-12 14:26:21 -04002113 // And add an operand to the composite we are constructing
SJW01901d92020-05-21 08:58:31 -05002114 Ops << CA->getAggregateElement(k);
David Neto22f144c2017-06-12 14:26:21 -04002115 }
David Neto22f144c2017-06-12 14:26:21 -04002116 }
SJWf93f5f32020-05-05 07:27:56 -05002117 } else if (Cst->isNullValue()) {
2118 Opcode = spv::OpConstantNull;
2119 } else {
2120 Cst->print(errs());
2121 llvm_unreachable("Unsupported Constant???");
2122 }
David Neto22f144c2017-06-12 14:26:21 -04002123
SJWf93f5f32020-05-05 07:27:56 -05002124 if (Opcode == spv::OpConstantNull && Cst->getType()->isPointerTy()) {
2125 // Null pointer requires variable pointers.
2126 setVariablePointersCapabilities(Cst->getType()->getPointerAddressSpace());
2127 }
alan-baker5b86ed72019-02-15 08:26:50 -05002128
SJWf93f5f32020-05-05 07:27:56 -05002129 if (RID == 0) {
2130 RID = addSPIRVInst<kConstants>(Opcode, Ops);
2131 }
2132
2133 VMap[Cst] = RID;
2134
2135 return RID;
2136}
2137
2138SPIRVID SPIRVProducerPass::getSPIRVValue(Value *V) {
2139 auto II = ValueMap.find(V);
2140 if (II != ValueMap.end()) {
SJW01901d92020-05-21 08:58:31 -05002141 assert(II->second.isValid());
SJWf93f5f32020-05-05 07:27:56 -05002142 return II->second;
2143 }
2144 if (Constant *Cst = dyn_cast<Constant>(V)) {
2145 return getSPIRVConstant(Cst);
2146 } else {
2147 llvm_unreachable("Variable not found");
2148 }
2149}
2150
SJW77b87ad2020-04-21 14:37:52 -05002151void SPIRVProducerPass::GenerateSamplers() {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002152 auto &sampler_map = getSamplerMap();
alan-baker09cb9802019-12-10 13:16:27 -05002153 SamplerLiteralToIDMap.clear();
David Neto862b7d82018-06-14 18:48:37 -04002154 DenseMap<unsigned, unsigned> SamplerLiteralToDescriptorSetMap;
2155 DenseMap<unsigned, unsigned> SamplerLiteralToBindingMap;
David Neto22f144c2017-06-12 14:26:21 -04002156
David Neto862b7d82018-06-14 18:48:37 -04002157 // We might have samplers in the sampler map that are not used
2158 // in the translation unit. We need to allocate variables
2159 // for them and bindings too.
2160 DenseSet<unsigned> used_bindings;
David Neto22f144c2017-06-12 14:26:21 -04002161
SJW77b87ad2020-04-21 14:37:52 -05002162 auto *var_fn = module->getFunction(clspv::LiteralSamplerFunction());
alan-baker09cb9802019-12-10 13:16:27 -05002163 // Return if there are no literal samplers.
alan-bakerb6b09dc2018-11-08 16:59:28 -05002164 if (!var_fn)
2165 return;
alan-baker09cb9802019-12-10 13:16:27 -05002166
David Neto862b7d82018-06-14 18:48:37 -04002167 for (auto user : var_fn->users()) {
2168 // Populate SamplerLiteralToDescriptorSetMap and
2169 // SamplerLiteralToBindingMap.
2170 //
2171 // Look for calls like
2172 // call %opencl.sampler_t addrspace(2)*
2173 // @clspv.sampler.var.literal(
2174 // i32 descriptor,
2175 // i32 binding,
alan-baker09cb9802019-12-10 13:16:27 -05002176 // i32 (index-into-sampler-map|sampler_mask))
alan-bakerb6b09dc2018-11-08 16:59:28 -05002177 if (auto *call = dyn_cast<CallInst>(user)) {
alan-baker09cb9802019-12-10 13:16:27 -05002178 const auto third_param = static_cast<unsigned>(
alan-bakerb6b09dc2018-11-08 16:59:28 -05002179 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
alan-baker09cb9802019-12-10 13:16:27 -05002180 auto sampler_value = third_param;
2181 if (clspv::Option::UseSamplerMap()) {
2182 if (third_param >= sampler_map.size()) {
2183 errs() << "Out of bounds index to sampler map: " << third_param;
2184 llvm_unreachable("bad sampler init: out of bounds");
2185 }
2186 sampler_value = sampler_map[third_param].first;
David Neto862b7d82018-06-14 18:48:37 -04002187 }
2188
David Neto862b7d82018-06-14 18:48:37 -04002189 const auto descriptor_set = static_cast<unsigned>(
2190 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
2191 const auto binding = static_cast<unsigned>(
2192 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
2193
2194 SamplerLiteralToDescriptorSetMap[sampler_value] = descriptor_set;
2195 SamplerLiteralToBindingMap[sampler_value] = binding;
2196 used_bindings.insert(binding);
2197 }
2198 }
2199
alan-baker09cb9802019-12-10 13:16:27 -05002200 DenseSet<size_t> seen;
2201 for (auto user : var_fn->users()) {
2202 if (!isa<CallInst>(user))
2203 continue;
2204
2205 auto call = cast<CallInst>(user);
2206 const unsigned third_param = static_cast<unsigned>(
2207 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
2208
2209 // Already allocated a variable for this value.
2210 if (!seen.insert(third_param).second)
2211 continue;
2212
2213 auto sampler_value = third_param;
2214 if (clspv::Option::UseSamplerMap()) {
2215 sampler_value = sampler_map[third_param].first;
2216 }
2217
SJW806a5d82020-07-15 12:51:38 -05002218 auto sampler_var_id = addSPIRVGlobalVariable(
2219 getSPIRVType(SamplerTy), spv::StorageClassUniformConstant);
David Neto22f144c2017-06-12 14:26:21 -04002220
alan-baker09cb9802019-12-10 13:16:27 -05002221 SamplerLiteralToIDMap[sampler_value] = sampler_var_id;
David Neto22f144c2017-06-12 14:26:21 -04002222
David Neto862b7d82018-06-14 18:48:37 -04002223 unsigned descriptor_set;
2224 unsigned binding;
alan-baker09cb9802019-12-10 13:16:27 -05002225 if (SamplerLiteralToBindingMap.find(sampler_value) ==
alan-bakerb6b09dc2018-11-08 16:59:28 -05002226 SamplerLiteralToBindingMap.end()) {
David Neto862b7d82018-06-14 18:48:37 -04002227 // This sampler is not actually used. Find the next one.
alan-baker7506abb2020-09-10 15:02:55 -04002228 for (binding = 0; used_bindings.count(binding); binding++) {
2229 }
David Neto862b7d82018-06-14 18:48:37 -04002230 descriptor_set = 0; // Literal samplers always use descriptor set 0.
2231 used_bindings.insert(binding);
2232 } else {
alan-baker09cb9802019-12-10 13:16:27 -05002233 descriptor_set = SamplerLiteralToDescriptorSetMap[sampler_value];
2234 binding = SamplerLiteralToBindingMap[sampler_value];
alan-bakercff80152019-06-15 00:38:00 -04002235
alan-baker86ce19c2020-08-05 13:09:19 -04002236 auto import_id = getReflectionImport();
2237 SPIRVOperandVec Ops;
2238 Ops << getSPIRVType(Type::getVoidTy(module->getContext())) << import_id
2239 << reflection::ExtInstLiteralSampler
2240 << getSPIRVInt32Constant(descriptor_set)
2241 << getSPIRVInt32Constant(binding)
2242 << getSPIRVInt32Constant(sampler_value);
2243 addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
David Neto862b7d82018-06-14 18:48:37 -04002244 }
2245
SJW69939d52020-04-16 07:29:07 -05002246 // Ops[0] = Target ID
2247 // Ops[1] = Decoration (DescriptorSet)
2248 // Ops[2] = LiteralNumber according to Decoration
SJW806a5d82020-07-15 12:51:38 -05002249 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05002250 Ops << sampler_var_id << spv::DecorationDescriptorSet << descriptor_set;
David Neto22f144c2017-06-12 14:26:21 -04002251
SJWf93f5f32020-05-05 07:27:56 -05002252 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002253
2254 // Ops[0] = Target ID
2255 // Ops[1] = Decoration (Binding)
2256 // Ops[2] = LiteralNumber according to Decoration
2257 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002258 Ops << sampler_var_id << spv::DecorationBinding << binding;
David Neto22f144c2017-06-12 14:26:21 -04002259
SJWf93f5f32020-05-05 07:27:56 -05002260 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002261 }
David Neto862b7d82018-06-14 18:48:37 -04002262}
David Neto22f144c2017-06-12 14:26:21 -04002263
SJW77b87ad2020-04-21 14:37:52 -05002264void SPIRVProducerPass::GenerateResourceVars() {
David Neto862b7d82018-06-14 18:48:37 -04002265 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04002266
David Neto862b7d82018-06-14 18:48:37 -04002267 // Generate variables. Make one for each of resource var info object.
2268 for (auto *info : ModuleOrderedResourceVars) {
2269 Type *type = info->var_fn->getReturnType();
2270 // Remap the address space for opaque types.
2271 switch (info->arg_kind) {
2272 case clspv::ArgKind::Sampler:
2273 case clspv::ArgKind::ReadOnlyImage:
2274 case clspv::ArgKind::WriteOnlyImage:
2275 type = PointerType::get(type->getPointerElementType(),
2276 clspv::AddressSpace::UniformConstant);
2277 break;
2278 default:
2279 break;
2280 }
David Neto22f144c2017-06-12 14:26:21 -04002281
David Neto862b7d82018-06-14 18:48:37 -04002282 const auto sc = GetStorageClassForArgKind(info->arg_kind);
David Neto22f144c2017-06-12 14:26:21 -04002283
SJW806a5d82020-07-15 12:51:38 -05002284 info->var_id = addSPIRVGlobalVariable(getSPIRVType(type), sc);
David Neto862b7d82018-06-14 18:48:37 -04002285
2286 // Map calls to the variable-builtin-function.
2287 for (auto &U : info->var_fn->uses()) {
2288 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
2289 const auto set = unsigned(
2290 dyn_cast<ConstantInt>(call->getOperand(0))->getZExtValue());
2291 const auto binding = unsigned(
2292 dyn_cast<ConstantInt>(call->getOperand(1))->getZExtValue());
2293 if (set == info->descriptor_set && binding == info->binding) {
2294 switch (info->arg_kind) {
2295 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002296 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002297 case clspv::ArgKind::Pod:
alan-baker9b0ec3c2020-04-06 14:45:34 -04002298 case clspv::ArgKind::PodUBO:
2299 case clspv::ArgKind::PodPushConstant:
David Neto862b7d82018-06-14 18:48:37 -04002300 // The call maps to the variable directly.
2301 VMap[call] = info->var_id;
2302 break;
2303 case clspv::ArgKind::Sampler:
2304 case clspv::ArgKind::ReadOnlyImage:
2305 case clspv::ArgKind::WriteOnlyImage:
2306 // The call maps to a load we generate later.
2307 ResourceVarDeferredLoadCalls[call] = info->var_id;
2308 break;
2309 default:
2310 llvm_unreachable("Unhandled arg kind");
2311 }
2312 }
David Neto22f144c2017-06-12 14:26:21 -04002313 }
David Neto862b7d82018-06-14 18:48:37 -04002314 }
2315 }
David Neto22f144c2017-06-12 14:26:21 -04002316
David Neto862b7d82018-06-14 18:48:37 -04002317 // Generate associated decorations.
SJWf93f5f32020-05-05 07:27:56 -05002318 SPIRVOperandVec Ops;
David Neto862b7d82018-06-14 18:48:37 -04002319 for (auto *info : ModuleOrderedResourceVars) {
alan-baker9b0ec3c2020-04-06 14:45:34 -04002320 // Push constants don't need descriptor set or binding decorations.
2321 if (info->arg_kind == clspv::ArgKind::PodPushConstant)
2322 continue;
2323
David Neto862b7d82018-06-14 18:48:37 -04002324 // Decorate with DescriptorSet and Binding.
2325 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002326 Ops << info->var_id << spv::DecorationDescriptorSet << info->descriptor_set;
SJWf93f5f32020-05-05 07:27:56 -05002327 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto862b7d82018-06-14 18:48:37 -04002328
2329 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002330 Ops << info->var_id << spv::DecorationBinding << info->binding;
SJWf93f5f32020-05-05 07:27:56 -05002331 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto862b7d82018-06-14 18:48:37 -04002332
alan-bakere9308012019-03-15 10:25:13 -04002333 if (info->coherent) {
2334 // Decorate with Coherent if required for the variable.
2335 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002336 Ops << info->var_id << spv::DecorationCoherent;
SJWf93f5f32020-05-05 07:27:56 -05002337 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
alan-bakere9308012019-03-15 10:25:13 -04002338 }
2339
David Neto862b7d82018-06-14 18:48:37 -04002340 // Generate NonWritable and NonReadable
2341 switch (info->arg_kind) {
2342 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002343 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002344 if (info->var_fn->getReturnType()->getPointerAddressSpace() ==
2345 clspv::AddressSpace::Constant) {
2346 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002347 Ops << info->var_id << spv::DecorationNonWritable;
SJWf93f5f32020-05-05 07:27:56 -05002348 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002349 }
David Neto862b7d82018-06-14 18:48:37 -04002350 break;
David Neto862b7d82018-06-14 18:48:37 -04002351 case clspv::ArgKind::WriteOnlyImage:
2352 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002353 Ops << info->var_id << spv::DecorationNonReadable;
SJWf93f5f32020-05-05 07:27:56 -05002354 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto862b7d82018-06-14 18:48:37 -04002355 break;
2356 default:
2357 break;
David Neto22f144c2017-06-12 14:26:21 -04002358 }
2359 }
2360}
2361
2362void SPIRVProducerPass::GenerateGlobalVar(GlobalVariable &GV) {
David Neto22f144c2017-06-12 14:26:21 -04002363 ValueMapType &VMap = getValueMap();
SJW01901d92020-05-21 08:58:31 -05002364 std::vector<SPIRVID> &BuiltinDimVec = getBuiltinDimVec();
David Neto85082642018-03-24 06:55:20 -07002365 const DataLayout &DL = GV.getParent()->getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04002366
2367 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
2368 Type *Ty = GV.getType();
2369 PointerType *PTy = cast<PointerType>(Ty);
2370
SJW01901d92020-05-21 08:58:31 -05002371 SPIRVID InitializerID;
David Neto22f144c2017-06-12 14:26:21 -04002372
2373 // Workgroup size is handled differently (it goes into a constant)
2374 if (spv::BuiltInWorkgroupSize == BuiltinType) {
David Neto22f144c2017-06-12 14:26:21 -04002375 uint32_t PrevXDimCst = 0xFFFFFFFF;
2376 uint32_t PrevYDimCst = 0xFFFFFFFF;
2377 uint32_t PrevZDimCst = 0xFFFFFFFF;
alan-baker3b609772020-09-03 19:10:17 -04002378 bool HasMD = true;
David Neto22f144c2017-06-12 14:26:21 -04002379 for (Function &Func : *GV.getParent()) {
2380 if (Func.isDeclaration()) {
2381 continue;
2382 }
2383
2384 // We only need to check kernels.
2385 if (Func.getCallingConv() != CallingConv::SPIR_KERNEL) {
2386 continue;
2387 }
2388
2389 if (const MDNode *MD =
2390 dyn_cast<Function>(&Func)->getMetadata("reqd_work_group_size")) {
2391 uint32_t CurXDimCst = static_cast<uint32_t>(
2392 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
2393 uint32_t CurYDimCst = static_cast<uint32_t>(
2394 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
2395 uint32_t CurZDimCst = static_cast<uint32_t>(
2396 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
2397
2398 if (PrevXDimCst == 0xFFFFFFFF && PrevYDimCst == 0xFFFFFFFF &&
2399 PrevZDimCst == 0xFFFFFFFF) {
2400 PrevXDimCst = CurXDimCst;
2401 PrevYDimCst = CurYDimCst;
2402 PrevZDimCst = CurZDimCst;
2403 } else if (CurXDimCst != PrevXDimCst || CurYDimCst != PrevYDimCst ||
2404 CurZDimCst != PrevZDimCst) {
alan-baker3b609772020-09-03 19:10:17 -04002405 HasMD = false;
2406 continue;
David Neto22f144c2017-06-12 14:26:21 -04002407 } else {
2408 continue;
2409 }
2410
2411 //
2412 // Generate OpConstantComposite.
2413 //
2414 // Ops[0] : Result Type ID
2415 // Ops[1] : Constant size for x dimension.
2416 // Ops[2] : Constant size for y dimension.
2417 // Ops[3] : Constant size for z dimension.
SJWf93f5f32020-05-05 07:27:56 -05002418 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04002419
SJW01901d92020-05-21 08:58:31 -05002420 SPIRVID XDimCstID =
SJWf93f5f32020-05-05 07:27:56 -05002421 getSPIRVValue(mdconst::extract<ConstantInt>(MD->getOperand(0)));
SJW01901d92020-05-21 08:58:31 -05002422 SPIRVID YDimCstID =
SJWf93f5f32020-05-05 07:27:56 -05002423 getSPIRVValue(mdconst::extract<ConstantInt>(MD->getOperand(1)));
SJW01901d92020-05-21 08:58:31 -05002424 SPIRVID ZDimCstID =
SJWf93f5f32020-05-05 07:27:56 -05002425 getSPIRVValue(mdconst::extract<ConstantInt>(MD->getOperand(2)));
David Neto22f144c2017-06-12 14:26:21 -04002426
SJW01901d92020-05-21 08:58:31 -05002427 Ops << Ty->getPointerElementType() << XDimCstID << YDimCstID
2428 << ZDimCstID;
David Neto22f144c2017-06-12 14:26:21 -04002429
SJWf93f5f32020-05-05 07:27:56 -05002430 InitializerID =
2431 addSPIRVInst<kGlobalVariables>(spv::OpConstantComposite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002432 } else {
alan-baker3b609772020-09-03 19:10:17 -04002433 HasMD = false;
David Neto22f144c2017-06-12 14:26:21 -04002434 }
2435 }
2436
2437 // If all kernels do not have metadata for reqd_work_group_size, generate
2438 // OpSpecConstants for x/y/z dimension.
Kévin Petit21c23c62020-04-29 01:38:28 +01002439 if (!HasMD || clspv::Option::NonUniformNDRangeSupported()) {
David Neto22f144c2017-06-12 14:26:21 -04002440 //
2441 // Generate OpSpecConstants for x/y/z dimension.
2442 //
2443 // Ops[0] : Result Type ID
2444 // Ops[1] : Constant size for x/y/z dimension (Literal Number).
David Neto22f144c2017-06-12 14:26:21 -04002445
alan-bakera1be3322020-04-20 12:48:18 -04002446 // Allocate spec constants for workgroup size.
SJW77b87ad2020-04-21 14:37:52 -05002447 clspv::AddWorkgroupSpecConstants(module);
alan-bakera1be3322020-04-20 12:48:18 -04002448
SJWf93f5f32020-05-05 07:27:56 -05002449 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05002450 SPIRVID result_type_id = getSPIRVType(
SJWf93f5f32020-05-05 07:27:56 -05002451 dyn_cast<VectorType>(Ty->getPointerElementType())->getElementType());
David Neto22f144c2017-06-12 14:26:21 -04002452
David Neto257c3892018-04-11 13:19:45 -04002453 // X Dimension
SJW01901d92020-05-21 08:58:31 -05002454 Ops << result_type_id << 1;
2455 SPIRVID XDimCstID = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002456
2457 // Y Dimension
2458 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002459 Ops << result_type_id << 1;
2460 SPIRVID YDimCstID = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002461
2462 // Z Dimension
2463 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002464 Ops << result_type_id << 1;
2465 SPIRVID ZDimCstID = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002466
David Neto257c3892018-04-11 13:19:45 -04002467 BuiltinDimVec.push_back(XDimCstID);
2468 BuiltinDimVec.push_back(YDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002469 BuiltinDimVec.push_back(ZDimCstID);
2470
David Neto22f144c2017-06-12 14:26:21 -04002471 //
2472 // Generate OpSpecConstantComposite.
2473 //
2474 // Ops[0] : Result Type ID
2475 // Ops[1] : Constant size for x dimension.
2476 // Ops[2] : Constant size for y dimension.
2477 // Ops[3] : Constant size for z dimension.
David Neto22f144c2017-06-12 14:26:21 -04002478 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002479 Ops << Ty->getPointerElementType() << XDimCstID << YDimCstID << ZDimCstID;
David Neto22f144c2017-06-12 14:26:21 -04002480
SJWf93f5f32020-05-05 07:27:56 -05002481 InitializerID =
2482 addSPIRVInst<kConstants>(spv::OpSpecConstantComposite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002483 }
alan-bakerbed3a882020-04-21 14:42:41 -04002484 } else if (BuiltinType == spv::BuiltInWorkDim) {
2485 // 1. Generate a specialization constant with a default of 3.
2486 // 2. Allocate and annotate a SpecId for the constant.
2487 // 3. Use the spec constant as the initializer for the variable.
SJWf93f5f32020-05-05 07:27:56 -05002488 SPIRVOperandVec Ops;
alan-bakerbed3a882020-04-21 14:42:41 -04002489
2490 //
2491 // Generate OpSpecConstant.
2492 //
2493 // Ops[0] : Result Type ID
2494 // Ops[1] : Default literal value
alan-bakerbed3a882020-04-21 14:42:41 -04002495
SJW01901d92020-05-21 08:58:31 -05002496 Ops << IntegerType::get(GV.getContext(), 32) << 3;
alan-bakerbed3a882020-04-21 14:42:41 -04002497
SJWf93f5f32020-05-05 07:27:56 -05002498 InitializerID = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
alan-bakerbed3a882020-04-21 14:42:41 -04002499
2500 //
2501 // Generate SpecId decoration.
2502 //
2503 // Ops[0] : target
2504 // Ops[1] : decoration
2505 // Ops[2] : SpecId
Alan Baker75ccc252020-04-21 17:11:52 -04002506 auto spec_id = AllocateSpecConstant(module, SpecConstant::kWorkDim);
alan-bakerbed3a882020-04-21 14:42:41 -04002507 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002508 Ops << InitializerID << spv::DecorationSpecId << spec_id;
alan-bakerbed3a882020-04-21 14:42:41 -04002509
SJWf93f5f32020-05-05 07:27:56 -05002510 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002511 } else if (BuiltinType == spv::BuiltInGlobalOffset) {
2512 // 1. Generate a spec constant with a default of {0, 0, 0}.
2513 // 2. Allocate and annotate SpecIds for the constants.
2514 // 3. Use the spec constant as the initializer for the variable.
SJWf93f5f32020-05-05 07:27:56 -05002515 SPIRVOperandVec Ops;
alan-bakere1996972020-05-04 08:38:12 -04002516
2517 //
2518 // Generate OpSpecConstant for each dimension.
2519 //
2520 // Ops[0] : Result Type ID
2521 // Ops[1] : Default literal value
2522 //
SJW01901d92020-05-21 08:58:31 -05002523 Ops << IntegerType::get(GV.getContext(), 32) << 0;
2524 SPIRVID x_id = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002525
alan-bakere1996972020-05-04 08:38:12 -04002526 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002527 Ops << IntegerType::get(GV.getContext(), 32) << 0;
2528 SPIRVID y_id = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002529
alan-bakere1996972020-05-04 08:38:12 -04002530 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002531 Ops << IntegerType::get(GV.getContext(), 32) << 0;
2532 SPIRVID z_id = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002533
2534 //
2535 // Generate SpecId decoration for each dimension.
2536 //
2537 // Ops[0] : target
2538 // Ops[1] : decoration
2539 // Ops[2] : SpecId
2540 //
2541 auto spec_id = AllocateSpecConstant(module, SpecConstant::kGlobalOffsetX);
2542 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002543 Ops << x_id << spv::DecorationSpecId << spec_id;
SJWf93f5f32020-05-05 07:27:56 -05002544 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002545
2546 spec_id = AllocateSpecConstant(module, SpecConstant::kGlobalOffsetY);
2547 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002548 Ops << y_id << spv::DecorationSpecId << spec_id;
SJWf93f5f32020-05-05 07:27:56 -05002549 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002550
2551 spec_id = AllocateSpecConstant(module, SpecConstant::kGlobalOffsetZ);
2552 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002553 Ops << z_id << spv::DecorationSpecId << spec_id;
SJWf93f5f32020-05-05 07:27:56 -05002554 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002555
2556 //
2557 // Generate OpSpecConstantComposite.
2558 //
2559 // Ops[0] : type id
2560 // Ops[1..n-1] : elements
2561 //
alan-bakere1996972020-05-04 08:38:12 -04002562 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002563 Ops << GV.getType()->getPointerElementType() << x_id << y_id << z_id;
SJWf93f5f32020-05-05 07:27:56 -05002564 InitializerID = addSPIRVInst<kConstants>(spv::OpSpecConstantComposite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002565 }
2566
David Neto85082642018-03-24 06:55:20 -07002567 const auto AS = PTy->getAddressSpace();
SJW806a5d82020-07-15 12:51:38 -05002568 const auto spvSC = GetStorageClass(AS);
David Neto22f144c2017-06-12 14:26:21 -04002569
David Neto85082642018-03-24 06:55:20 -07002570 const bool module_scope_constant_external_init =
David Neto862b7d82018-06-14 18:48:37 -04002571 (AS == AddressSpace::Constant) && GV.hasInitializer() &&
David Neto85082642018-03-24 06:55:20 -07002572 clspv::Option::ModuleConstantsInStorageBuffer();
2573
Kévin Petit23d5f182019-08-13 16:21:29 +01002574 if (GV.hasInitializer()) {
2575 auto GVInit = GV.getInitializer();
2576 if (!isa<UndefValue>(GVInit) && !module_scope_constant_external_init) {
SJWf93f5f32020-05-05 07:27:56 -05002577 InitializerID = getSPIRVValue(GVInit);
David Neto85082642018-03-24 06:55:20 -07002578 }
2579 }
Kévin Petit23d5f182019-08-13 16:21:29 +01002580
SJW806a5d82020-07-15 12:51:38 -05002581 SPIRVID var_id =
2582 addSPIRVGlobalVariable(getSPIRVType(Ty), spvSC, InitializerID);
David Neto85082642018-03-24 06:55:20 -07002583
SJWf93f5f32020-05-05 07:27:56 -05002584 VMap[&GV] = var_id;
David Neto22f144c2017-06-12 14:26:21 -04002585
alan-bakere1996972020-05-04 08:38:12 -04002586 auto IsOpenCLBuiltin = [](spv::BuiltIn builtin) {
2587 return builtin == spv::BuiltInWorkDim ||
2588 builtin == spv::BuiltInGlobalOffset;
2589 };
2590
alan-bakere1996972020-05-04 08:38:12 -04002591 // If we have a builtin (not an OpenCL builtin).
2592 if (spv::BuiltInMax != BuiltinType && !IsOpenCLBuiltin(BuiltinType)) {
David Neto22f144c2017-06-12 14:26:21 -04002593 //
2594 // Generate OpDecorate.
2595 //
2596 // DOps[0] = Target ID
2597 // DOps[1] = Decoration (Builtin)
2598 // DOps[2] = BuiltIn ID
SJW01901d92020-05-21 08:58:31 -05002599 SPIRVID ResultID;
David Neto22f144c2017-06-12 14:26:21 -04002600
2601 // WorkgroupSize is different, we decorate the constant composite that has
2602 // its value, rather than the variable that we use to access the value.
2603 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2604 ResultID = InitializerID;
David Netoa60b00b2017-09-15 16:34:09 -04002605 // Save both the value and variable IDs for later.
2606 WorkgroupSizeValueID = InitializerID;
SJWf93f5f32020-05-05 07:27:56 -05002607 WorkgroupSizeVarID = getSPIRVValue(&GV);
David Neto22f144c2017-06-12 14:26:21 -04002608 } else {
SJWf93f5f32020-05-05 07:27:56 -05002609 ResultID = getSPIRVValue(&GV);
David Neto22f144c2017-06-12 14:26:21 -04002610 }
2611
SJW806a5d82020-07-15 12:51:38 -05002612 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05002613 Ops << ResultID << spv::DecorationBuiltIn << BuiltinType;
David Neto22f144c2017-06-12 14:26:21 -04002614
SJW01901d92020-05-21 08:58:31 -05002615 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto85082642018-03-24 06:55:20 -07002616 } else if (module_scope_constant_external_init) {
2617 // This module scope constant is initialized from a storage buffer with data
2618 // provided by the host at binding 0 of the next descriptor set.
SJW77b87ad2020-04-21 14:37:52 -05002619 const uint32_t descriptor_set = TakeDescriptorIndex(module);
David Neto85082642018-03-24 06:55:20 -07002620
alan-baker86ce19c2020-08-05 13:09:19 -04002621 // Emit the intializer as a reflection instruction.
David Neto85082642018-03-24 06:55:20 -07002622 // Use "kind,buffer" to indicate storage buffer. We might want to expand
2623 // that later to other types, like uniform buffer.
alan-bakerf5e5f692018-11-27 08:33:24 -05002624 std::string hexbytes;
2625 llvm::raw_string_ostream str(hexbytes);
2626 clspv::ConstantEmitter(DL, str).Emit(GV.getInitializer());
alan-baker86ce19c2020-08-05 13:09:19 -04002627
2628 // Reflection instruction for constant data.
2629 SPIRVOperandVec Ops;
2630 auto data_id = addSPIRVInst<kDebug>(spv::OpString, str.str().c_str());
2631 Ops << getSPIRVType(Type::getVoidTy(module->getContext()))
2632 << getReflectionImport() << reflection::ExtInstConstantDataStorageBuffer
2633 << getSPIRVInt32Constant(descriptor_set) << getSPIRVInt32Constant(0)
2634 << data_id;
2635 addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
David Neto85082642018-03-24 06:55:20 -07002636
David Neto85082642018-03-24 06:55:20 -07002637 // OpDecorate %var DescriptorSet <descriptor_set>
alan-baker86ce19c2020-08-05 13:09:19 -04002638 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002639 Ops << var_id << spv::DecorationDescriptorSet << descriptor_set;
2640 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
SJW69939d52020-04-16 07:29:07 -05002641
2642 // OpDecorate %var Binding <binding>
SJW01901d92020-05-21 08:58:31 -05002643 Ops.clear();
2644 Ops << var_id << spv::DecorationBinding << 0;
2645 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Netoc6f3ab22018-04-06 18:02:31 -04002646 }
2647}
2648
David Neto22f144c2017-06-12 14:26:21 -04002649void SPIRVProducerPass::GenerateFuncPrologue(Function &F) {
David Neto22f144c2017-06-12 14:26:21 -04002650 ValueMapType &VMap = getValueMap();
2651 EntryPointVecType &EntryPoints = getEntryPointVec();
David Neto22f144c2017-06-12 14:26:21 -04002652 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
2653 auto &GlobalConstArgSet = getGlobalConstArgSet();
2654
2655 FunctionType *FTy = F.getFunctionType();
2656
2657 //
David Neto22f144c2017-06-12 14:26:21 -04002658 // Generate OPFunction.
2659 //
2660
2661 // FOps[0] : Result Type ID
2662 // FOps[1] : Function Control
2663 // FOps[2] : Function Type ID
SJWf93f5f32020-05-05 07:27:56 -05002664 SPIRVOperandVec FOps;
David Neto22f144c2017-06-12 14:26:21 -04002665
2666 // Find SPIRV instruction for return type.
SJW01901d92020-05-21 08:58:31 -05002667 FOps << FTy->getReturnType();
David Neto22f144c2017-06-12 14:26:21 -04002668
2669 // Check function attributes for SPIRV Function Control.
2670 uint32_t FuncControl = spv::FunctionControlMaskNone;
2671 if (F.hasFnAttribute(Attribute::AlwaysInline)) {
2672 FuncControl |= spv::FunctionControlInlineMask;
2673 }
2674 if (F.hasFnAttribute(Attribute::NoInline)) {
2675 FuncControl |= spv::FunctionControlDontInlineMask;
2676 }
2677 // TODO: Check llvm attribute for Function Control Pure.
2678 if (F.hasFnAttribute(Attribute::ReadOnly)) {
2679 FuncControl |= spv::FunctionControlPureMask;
2680 }
2681 // TODO: Check llvm attribute for Function Control Const.
2682 if (F.hasFnAttribute(Attribute::ReadNone)) {
2683 FuncControl |= spv::FunctionControlConstMask;
2684 }
2685
SJW01901d92020-05-21 08:58:31 -05002686 FOps << FuncControl;
David Neto22f144c2017-06-12 14:26:21 -04002687
SJW01901d92020-05-21 08:58:31 -05002688 SPIRVID FTyID;
David Neto22f144c2017-06-12 14:26:21 -04002689 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
2690 SmallVector<Type *, 4> NewFuncParamTys;
2691 FunctionType *NewFTy =
2692 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
SJWf93f5f32020-05-05 07:27:56 -05002693 FTyID = getSPIRVType(NewFTy);
David Neto22f144c2017-06-12 14:26:21 -04002694 } else {
David Neto9ed8e2f2018-03-24 06:47:24 -07002695 // Handle regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04002696 if (GlobalConstFuncTyMap.count(FTy)) {
SJWf93f5f32020-05-05 07:27:56 -05002697 FTyID = getSPIRVType(GlobalConstFuncTyMap[FTy].first);
David Neto22f144c2017-06-12 14:26:21 -04002698 } else {
SJWf93f5f32020-05-05 07:27:56 -05002699 FTyID = getSPIRVType(FTy);
David Neto22f144c2017-06-12 14:26:21 -04002700 }
2701 }
2702
SJW01901d92020-05-21 08:58:31 -05002703 FOps << FTyID;
David Neto22f144c2017-06-12 14:26:21 -04002704
SJWf93f5f32020-05-05 07:27:56 -05002705 // Generate SPIRV instruction for function.
2706 SPIRVID FID = addSPIRVInst(spv::OpFunction, FOps);
2707 VMap[&F] = FID;
David Neto22f144c2017-06-12 14:26:21 -04002708
SJWf93f5f32020-05-05 07:27:56 -05002709 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
2710 EntryPoints.push_back(std::make_pair(&F, FID));
2711 }
David Neto22f144c2017-06-12 14:26:21 -04002712
David Neto482550a2018-03-24 05:21:07 -07002713 if (clspv::Option::ShowIDs()) {
SJW01901d92020-05-21 08:58:31 -05002714 errs() << "Function " << F.getName() << " is " << FID.get() << "\n";
David Netob05675d2018-02-16 12:37:49 -05002715 }
David Neto22f144c2017-06-12 14:26:21 -04002716
2717 //
2718 // Generate OpFunctionParameter for Normal function.
2719 //
David Neto22f144c2017-06-12 14:26:21 -04002720 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
alan-bakere9308012019-03-15 10:25:13 -04002721
David Neto22f144c2017-06-12 14:26:21 -04002722 // Iterate Argument for name instead of param type from function type.
2723 unsigned ArgIdx = 0;
2724 for (Argument &Arg : F.args()) {
David Neto22f144c2017-06-12 14:26:21 -04002725 // ParamOps[0] : Result Type ID
SJW01901d92020-05-21 08:58:31 -05002726 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04002727
2728 // Find SPIRV instruction for parameter type.
SJW01901d92020-05-21 08:58:31 -05002729 SPIRVID ParamTyID = getSPIRVType(Arg.getType());
David Neto22f144c2017-06-12 14:26:21 -04002730 if (PointerType *PTy = dyn_cast<PointerType>(Arg.getType())) {
2731 if (GlobalConstFuncTyMap.count(FTy)) {
2732 if (ArgIdx == GlobalConstFuncTyMap[FTy].second) {
2733 Type *EleTy = PTy->getPointerElementType();
2734 Type *ArgTy =
2735 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
SJWf93f5f32020-05-05 07:27:56 -05002736 ParamTyID = getSPIRVType(ArgTy);
David Neto22f144c2017-06-12 14:26:21 -04002737 GlobalConstArgSet.insert(&Arg);
2738 }
2739 }
2740 }
SJW01901d92020-05-21 08:58:31 -05002741 Ops << ParamTyID;
David Neto22f144c2017-06-12 14:26:21 -04002742
2743 // Generate SPIRV instruction for parameter.
SJW01901d92020-05-21 08:58:31 -05002744 SPIRVID param_id = addSPIRVInst(spv::OpFunctionParameter, Ops);
SJWf93f5f32020-05-05 07:27:56 -05002745 VMap[&Arg] = param_id;
2746
2747 if (CalledWithCoherentResource(Arg)) {
2748 // If the arg is passed a coherent resource ever, then decorate this
2749 // parameter with Coherent too.
SJW01901d92020-05-21 08:58:31 -05002750 Ops.clear();
2751 Ops << param_id << spv::DecorationCoherent;
2752 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
SJWf93f5f32020-05-05 07:27:56 -05002753 }
David Neto22f144c2017-06-12 14:26:21 -04002754
2755 ArgIdx++;
2756 }
2757 }
2758}
2759
SJW77b87ad2020-04-21 14:37:52 -05002760void SPIRVProducerPass::GenerateModuleInfo() {
David Neto22f144c2017-06-12 14:26:21 -04002761 EntryPointVecType &EntryPoints = getEntryPointVec();
SJW806a5d82020-07-15 12:51:38 -05002762 auto &EntryPointInterfaces = getEntryPointInterfacesList();
SJW01901d92020-05-21 08:58:31 -05002763 std::vector<SPIRVID> &BuiltinDimVec = getBuiltinDimVec();
David Neto22f144c2017-06-12 14:26:21 -04002764
SJWf93f5f32020-05-05 07:27:56 -05002765 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04002766
SJW01901d92020-05-21 08:58:31 -05002767 for (auto Capability : CapabilitySet) {
David Neto22f144c2017-06-12 14:26:21 -04002768 //
SJW01901d92020-05-21 08:58:31 -05002769 // Generate OpCapability
David Neto22f144c2017-06-12 14:26:21 -04002770 //
2771 // Ops[0] = Capability
SJW01901d92020-05-21 08:58:31 -05002772 addSPIRVInst<kCapabilities>(spv::OpCapability, Capability);
alan-baker5b86ed72019-02-15 08:26:50 -05002773 }
2774
2775 // Always add the storage buffer extension
2776 {
David Neto22f144c2017-06-12 14:26:21 -04002777 //
2778 // Generate OpExtension.
2779 //
2780 // Ops[0] = Name (Literal String)
2781 //
SJWf93f5f32020-05-05 07:27:56 -05002782 addSPIRVInst<kExtensions>(spv::OpExtension,
2783 "SPV_KHR_storage_buffer_storage_class");
alan-baker5b86ed72019-02-15 08:26:50 -05002784 }
David Neto22f144c2017-06-12 14:26:21 -04002785
alan-baker5b86ed72019-02-15 08:26:50 -05002786 if (hasVariablePointers() || hasVariablePointersStorageBuffer()) {
2787 //
2788 // Generate OpExtension.
2789 //
2790 // Ops[0] = Name (Literal String)
2791 //
SJWf93f5f32020-05-05 07:27:56 -05002792 addSPIRVInst<kExtensions>(spv::OpExtension, "SPV_KHR_variable_pointers");
David Neto22f144c2017-06-12 14:26:21 -04002793 }
2794
2795 //
2796 // Generate OpMemoryModel
2797 //
2798 // Memory model for Vulkan will always be GLSL450.
2799
2800 // Ops[0] = Addressing Model
2801 // Ops[1] = Memory Model
2802 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002803 Ops << spv::AddressingModelLogical << spv::MemoryModelGLSL450;
David Neto22f144c2017-06-12 14:26:21 -04002804
SJWf93f5f32020-05-05 07:27:56 -05002805 addSPIRVInst<kMemoryModel>(spv::OpMemoryModel, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002806
2807 //
2808 // Generate OpEntryPoint
2809 //
2810 for (auto EntryPoint : EntryPoints) {
2811 // Ops[0] = Execution Model
2812 // Ops[1] = EntryPoint ID
2813 // Ops[2] = Name (Literal String)
2814 // ...
2815 //
2816 // TODO: Do we need to consider Interface ID for forward references???
2817 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05002818 const StringRef &name = EntryPoint.first->getName();
SJW01901d92020-05-21 08:58:31 -05002819 Ops << spv::ExecutionModelGLCompute << EntryPoint.second << name;
David Neto22f144c2017-06-12 14:26:21 -04002820
SJW806a5d82020-07-15 12:51:38 -05002821 for (auto &Interface : EntryPointInterfaces) {
SJW01901d92020-05-21 08:58:31 -05002822 Ops << Interface;
David Neto22f144c2017-06-12 14:26:21 -04002823 }
2824
SJWf93f5f32020-05-05 07:27:56 -05002825 addSPIRVInst<kEntryPoints>(spv::OpEntryPoint, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002826 }
2827
alan-baker3b609772020-09-03 19:10:17 -04002828 if (BuiltinDimVec.empty()) {
2829 for (auto EntryPoint : EntryPoints) {
2830 const MDNode *MD = dyn_cast<Function>(EntryPoint.first)
2831 ->getMetadata("reqd_work_group_size");
2832 if ((MD != nullptr) && !clspv::Option::NonUniformNDRangeSupported()) {
2833 //
2834 // Generate OpExecutionMode
2835 //
David Neto22f144c2017-06-12 14:26:21 -04002836
alan-baker3b609772020-09-03 19:10:17 -04002837 // Ops[0] = Entry Point ID
2838 // Ops[1] = Execution Mode
2839 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
2840 Ops.clear();
2841 Ops << EntryPoint.second << spv::ExecutionModeLocalSize;
2842
2843 uint32_t XDim = static_cast<uint32_t>(
2844 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
2845 uint32_t YDim = static_cast<uint32_t>(
2846 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
2847 uint32_t ZDim = static_cast<uint32_t>(
2848 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
2849
2850 Ops << XDim << YDim << ZDim;
2851
2852 addSPIRVInst<kExecutionModes>(spv::OpExecutionMode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002853 }
David Neto22f144c2017-06-12 14:26:21 -04002854 }
2855 }
2856
2857 //
2858 // Generate OpSource.
2859 //
2860 // Ops[0] = SourceLanguage ID
2861 // Ops[1] = Version (LiteralNum)
2862 //
SJW01901d92020-05-21 08:58:31 -05002863 uint32_t LangID = spv::SourceLanguageUnknown;
2864 uint32_t LangVer = 0;
Kévin Petitf0515712020-01-07 18:29:20 +00002865 switch (clspv::Option::Language()) {
2866 case clspv::Option::SourceLanguage::OpenCL_C_10:
SJW01901d92020-05-21 08:58:31 -05002867 LangID = spv::SourceLanguageOpenCL_C;
2868 LangVer = 100;
Kévin Petitf0515712020-01-07 18:29:20 +00002869 break;
2870 case clspv::Option::SourceLanguage::OpenCL_C_11:
SJW01901d92020-05-21 08:58:31 -05002871 LangID = spv::SourceLanguageOpenCL_C;
2872 LangVer = 110;
Kévin Petitf0515712020-01-07 18:29:20 +00002873 break;
2874 case clspv::Option::SourceLanguage::OpenCL_C_12:
SJW01901d92020-05-21 08:58:31 -05002875 LangID = spv::SourceLanguageOpenCL_C;
2876 LangVer = 120;
Kévin Petitf0515712020-01-07 18:29:20 +00002877 break;
2878 case clspv::Option::SourceLanguage::OpenCL_C_20:
SJW01901d92020-05-21 08:58:31 -05002879 LangID = spv::SourceLanguageOpenCL_C;
2880 LangVer = 200;
Kévin Petitf0515712020-01-07 18:29:20 +00002881 break;
2882 case clspv::Option::SourceLanguage::OpenCL_CPP:
SJW01901d92020-05-21 08:58:31 -05002883 LangID = spv::SourceLanguageOpenCL_CPP;
2884 LangVer = 100;
Kévin Petitf0515712020-01-07 18:29:20 +00002885 break;
2886 default:
Kévin Petitf0515712020-01-07 18:29:20 +00002887 break;
Kévin Petit0fc88042019-04-09 23:25:02 +01002888 }
David Neto22f144c2017-06-12 14:26:21 -04002889
SJW01901d92020-05-21 08:58:31 -05002890 Ops.clear();
2891 Ops << LangID << LangVer;
SJWf93f5f32020-05-05 07:27:56 -05002892 addSPIRVInst<kDebug>(spv::OpSource, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002893
2894 if (!BuiltinDimVec.empty()) {
2895 //
2896 // Generate OpDecorates for x/y/z dimension.
2897 //
2898 // Ops[0] = Target ID
2899 // Ops[1] = Decoration (SpecId)
David Neto257c3892018-04-11 13:19:45 -04002900 // Ops[2] = Specialization Constant ID (Literal Number)
David Neto22f144c2017-06-12 14:26:21 -04002901
2902 // X Dimension
2903 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002904 Ops << BuiltinDimVec[0] << spv::DecorationSpecId << 0;
SJWf93f5f32020-05-05 07:27:56 -05002905 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002906
2907 // Y Dimension
2908 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002909 Ops << BuiltinDimVec[1] << spv::DecorationSpecId << 1;
SJWf93f5f32020-05-05 07:27:56 -05002910 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002911
2912 // Z Dimension
2913 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002914 Ops << BuiltinDimVec[2] << spv::DecorationSpecId << 2;
SJWf93f5f32020-05-05 07:27:56 -05002915 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002916 }
2917}
2918
David Netob6e2e062018-04-25 10:32:06 -04002919void SPIRVProducerPass::GenerateEntryPointInitialStores() {
2920 // Work around a driver bug. Initializers on Private variables might not
2921 // work. So the start of the kernel should store the initializer value to the
2922 // variables. Yes, *every* entry point pays this cost if *any* entry point
2923 // uses this builtin. At this point I judge this to be an acceptable tradeoff
2924 // of complexity vs. runtime, for a broken driver.
alan-bakerb6b09dc2018-11-08 16:59:28 -05002925 // TODO(dneto): Remove this at some point once fixed drivers are widely
2926 // available.
SJW01901d92020-05-21 08:58:31 -05002927 if (WorkgroupSizeVarID.isValid()) {
2928 assert(WorkgroupSizeValueID.isValid());
David Netob6e2e062018-04-25 10:32:06 -04002929
SJWf93f5f32020-05-05 07:27:56 -05002930 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05002931 Ops << WorkgroupSizeVarID << WorkgroupSizeValueID;
David Netob6e2e062018-04-25 10:32:06 -04002932
SJWf93f5f32020-05-05 07:27:56 -05002933 addSPIRVInst(spv::OpStore, Ops);
David Netob6e2e062018-04-25 10:32:06 -04002934 }
2935}
2936
David Neto22f144c2017-06-12 14:26:21 -04002937void SPIRVProducerPass::GenerateFuncBody(Function &F) {
David Neto22f144c2017-06-12 14:26:21 -04002938 ValueMapType &VMap = getValueMap();
2939
David Netob6e2e062018-04-25 10:32:06 -04002940 const bool IsKernel = F.getCallingConv() == CallingConv::SPIR_KERNEL;
David Neto22f144c2017-06-12 14:26:21 -04002941
2942 for (BasicBlock &BB : F) {
2943 // Register BasicBlock to ValueMap.
David Neto22f144c2017-06-12 14:26:21 -04002944
2945 //
2946 // Generate OpLabel for Basic Block.
2947 //
SJWf93f5f32020-05-05 07:27:56 -05002948 VMap[&BB] = addSPIRVInst(spv::OpLabel);
David Neto22f144c2017-06-12 14:26:21 -04002949
David Neto6dcd4712017-06-23 11:06:47 -04002950 // OpVariable instructions must come first.
2951 for (Instruction &I : BB) {
alan-baker5b86ed72019-02-15 08:26:50 -05002952 if (auto *alloca = dyn_cast<AllocaInst>(&I)) {
2953 // Allocating a pointer requires variable pointers.
2954 if (alloca->getAllocatedType()->isPointerTy()) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002955 setVariablePointersCapabilities(
2956 alloca->getAllocatedType()->getPointerAddressSpace());
alan-baker5b86ed72019-02-15 08:26:50 -05002957 }
David Neto6dcd4712017-06-23 11:06:47 -04002958 GenerateInstruction(I);
2959 }
2960 }
2961
David Neto22f144c2017-06-12 14:26:21 -04002962 if (&BB == &F.getEntryBlock() && IsKernel) {
David Netob6e2e062018-04-25 10:32:06 -04002963 if (clspv::Option::HackInitializers()) {
2964 GenerateEntryPointInitialStores();
2965 }
David Neto22f144c2017-06-12 14:26:21 -04002966 }
2967
2968 for (Instruction &I : BB) {
David Neto6dcd4712017-06-23 11:06:47 -04002969 if (!isa<AllocaInst>(I)) {
2970 GenerateInstruction(I);
2971 }
David Neto22f144c2017-06-12 14:26:21 -04002972 }
2973 }
2974}
2975
2976spv::Op SPIRVProducerPass::GetSPIRVCmpOpcode(CmpInst *I) {
2977 const std::map<CmpInst::Predicate, spv::Op> Map = {
2978 {CmpInst::ICMP_EQ, spv::OpIEqual},
2979 {CmpInst::ICMP_NE, spv::OpINotEqual},
2980 {CmpInst::ICMP_UGT, spv::OpUGreaterThan},
2981 {CmpInst::ICMP_UGE, spv::OpUGreaterThanEqual},
2982 {CmpInst::ICMP_ULT, spv::OpULessThan},
2983 {CmpInst::ICMP_ULE, spv::OpULessThanEqual},
2984 {CmpInst::ICMP_SGT, spv::OpSGreaterThan},
2985 {CmpInst::ICMP_SGE, spv::OpSGreaterThanEqual},
2986 {CmpInst::ICMP_SLT, spv::OpSLessThan},
2987 {CmpInst::ICMP_SLE, spv::OpSLessThanEqual},
2988 {CmpInst::FCMP_OEQ, spv::OpFOrdEqual},
2989 {CmpInst::FCMP_OGT, spv::OpFOrdGreaterThan},
2990 {CmpInst::FCMP_OGE, spv::OpFOrdGreaterThanEqual},
2991 {CmpInst::FCMP_OLT, spv::OpFOrdLessThan},
2992 {CmpInst::FCMP_OLE, spv::OpFOrdLessThanEqual},
2993 {CmpInst::FCMP_ONE, spv::OpFOrdNotEqual},
2994 {CmpInst::FCMP_UEQ, spv::OpFUnordEqual},
2995 {CmpInst::FCMP_UGT, spv::OpFUnordGreaterThan},
2996 {CmpInst::FCMP_UGE, spv::OpFUnordGreaterThanEqual},
2997 {CmpInst::FCMP_ULT, spv::OpFUnordLessThan},
2998 {CmpInst::FCMP_ULE, spv::OpFUnordLessThanEqual},
2999 {CmpInst::FCMP_UNE, spv::OpFUnordNotEqual}};
3000
3001 assert(0 != Map.count(I->getPredicate()));
3002
3003 return Map.at(I->getPredicate());
3004}
3005
3006spv::Op SPIRVProducerPass::GetSPIRVCastOpcode(Instruction &I) {
3007 const std::map<unsigned, spv::Op> Map{
3008 {Instruction::Trunc, spv::OpUConvert},
3009 {Instruction::ZExt, spv::OpUConvert},
3010 {Instruction::SExt, spv::OpSConvert},
3011 {Instruction::FPToUI, spv::OpConvertFToU},
3012 {Instruction::FPToSI, spv::OpConvertFToS},
3013 {Instruction::UIToFP, spv::OpConvertUToF},
3014 {Instruction::SIToFP, spv::OpConvertSToF},
3015 {Instruction::FPTrunc, spv::OpFConvert},
3016 {Instruction::FPExt, spv::OpFConvert},
3017 {Instruction::BitCast, spv::OpBitcast}};
3018
3019 assert(0 != Map.count(I.getOpcode()));
3020
3021 return Map.at(I.getOpcode());
3022}
3023
3024spv::Op SPIRVProducerPass::GetSPIRVBinaryOpcode(Instruction &I) {
Kévin Petit24272b62018-10-18 19:16:12 +00003025 if (I.getType()->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003026 switch (I.getOpcode()) {
3027 default:
3028 break;
3029 case Instruction::Or:
3030 return spv::OpLogicalOr;
3031 case Instruction::And:
3032 return spv::OpLogicalAnd;
3033 case Instruction::Xor:
3034 return spv::OpLogicalNotEqual;
3035 }
3036 }
3037
alan-bakerb6b09dc2018-11-08 16:59:28 -05003038 const std::map<unsigned, spv::Op> Map{
David Neto22f144c2017-06-12 14:26:21 -04003039 {Instruction::Add, spv::OpIAdd},
3040 {Instruction::FAdd, spv::OpFAdd},
3041 {Instruction::Sub, spv::OpISub},
3042 {Instruction::FSub, spv::OpFSub},
3043 {Instruction::Mul, spv::OpIMul},
3044 {Instruction::FMul, spv::OpFMul},
3045 {Instruction::UDiv, spv::OpUDiv},
3046 {Instruction::SDiv, spv::OpSDiv},
3047 {Instruction::FDiv, spv::OpFDiv},
3048 {Instruction::URem, spv::OpUMod},
3049 {Instruction::SRem, spv::OpSRem},
3050 {Instruction::FRem, spv::OpFRem},
3051 {Instruction::Or, spv::OpBitwiseOr},
3052 {Instruction::Xor, spv::OpBitwiseXor},
3053 {Instruction::And, spv::OpBitwiseAnd},
3054 {Instruction::Shl, spv::OpShiftLeftLogical},
3055 {Instruction::LShr, spv::OpShiftRightLogical},
3056 {Instruction::AShr, spv::OpShiftRightArithmetic}};
3057
3058 assert(0 != Map.count(I.getOpcode()));
3059
3060 return Map.at(I.getOpcode());
3061}
3062
SJW806a5d82020-07-15 12:51:38 -05003063SPIRVID SPIRVProducerPass::getSPIRVBuiltin(spv::BuiltIn BID,
3064 spv::Capability Cap) {
3065 SPIRVID RID;
3066
3067 auto ii = BuiltinConstantMap.find(BID);
3068
3069 if (ii != BuiltinConstantMap.end()) {
3070 return ii->second;
3071 } else {
SJW806a5d82020-07-15 12:51:38 -05003072 addCapability(Cap);
3073
3074 Type *type = PointerType::get(IntegerType::get(module->getContext(), 32),
3075 AddressSpace::Input);
3076
3077 RID = addSPIRVGlobalVariable(getSPIRVType(type), spv::StorageClassInput);
3078
3079 BuiltinConstantMap[BID] = RID;
3080
3081 //
3082 // Generate OpDecorate.
3083 //
3084 // Ops[0] : target
3085 // Ops[1] : decoration
3086 // Ops[2] : SpecId
3087 SPIRVOperandVec Ops;
3088 Ops << RID << spv::DecorationBuiltIn << static_cast<int>(BID);
3089
3090 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
3091 }
3092
3093 return RID;
3094}
3095
3096SPIRVID
3097SPIRVProducerPass::GenerateClspvInstruction(CallInst *Call,
3098 const FunctionInfo &FuncInfo) {
3099 SPIRVID RID;
3100
3101 switch (FuncInfo.getType()) {
3102 case Builtins::kClspvCompositeConstruct:
3103 RID = addSPIRVPlaceholder(Call);
3104 break;
3105 case Builtins::kClspvResource: {
3106 if (ResourceVarDeferredLoadCalls.count(Call) && Call->hasNUsesOrMore(1)) {
3107 // Generate an OpLoad
3108 SPIRVOperandVec Ops;
3109
3110 Ops << Call->getType()->getPointerElementType()
3111 << ResourceVarDeferredLoadCalls[Call];
3112
3113 RID = addSPIRVInst(spv::OpLoad, Ops);
3114
3115 } else {
3116 // This maps to an OpVariable we've already generated.
3117 // No code is generated for the call.
3118 }
3119 break;
3120 }
3121 case Builtins::kClspvLocal: {
3122 // Don't codegen an instruction here, but instead map this call directly
3123 // to the workgroup variable id.
3124 int spec_id = static_cast<int>(
3125 cast<ConstantInt>(Call->getOperand(0))->getSExtValue());
3126 const auto &info = LocalSpecIdInfoMap[spec_id];
3127 RID = info.variable_id;
3128 break;
3129 }
3130 case Builtins::kClspvSamplerVarLiteral: {
3131 // Sampler initializers become a load of the corresponding sampler.
3132 // Map this to a load from the variable.
3133 const auto third_param = static_cast<unsigned>(
3134 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue());
3135 auto sampler_value = third_param;
3136 if (clspv::Option::UseSamplerMap()) {
3137 sampler_value = getSamplerMap()[third_param].first;
3138 }
3139
3140 // Generate an OpLoad
3141 SPIRVOperandVec Ops;
3142
3143 Ops << SamplerTy->getPointerElementType()
3144 << SamplerLiteralToIDMap[sampler_value];
3145
3146 RID = addSPIRVInst(spv::OpLoad, Ops);
3147 break;
3148 }
3149 case Builtins::kSpirvAtomicXor: {
3150 // Handle SPIR-V intrinsics
3151 SPIRVOperandVec Ops;
3152
3153 if (!Call->getType()->isVoidTy()) {
3154 Ops << Call->getType();
3155 }
3156
3157 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
3158 Ops << Call->getArgOperand(i);
3159 }
3160
3161 RID = addSPIRVInst(spv::OpAtomicXor, Ops);
3162 break;
3163 }
3164 case Builtins::kSpirvOp: {
3165 // Handle SPIR-V intrinsics
3166 auto *arg0 = dyn_cast<ConstantInt>(Call->getArgOperand(0));
3167 spv::Op opcode = static_cast<spv::Op>(arg0->getZExtValue());
3168 if (opcode != spv::OpNop) {
3169 SPIRVOperandVec Ops;
3170
3171 if (!Call->getType()->isVoidTy()) {
3172 Ops << Call->getType();
3173 }
3174
3175 for (unsigned i = 1; i < Call->getNumArgOperands(); i++) {
3176 Ops << Call->getArgOperand(i);
3177 }
3178
3179 RID = addSPIRVInst(opcode, Ops);
3180 }
3181 break;
3182 }
3183 case Builtins::kSpirvCopyMemory: {
3184 //
3185 // Generate OpCopyMemory.
3186 //
3187
3188 // Ops[0] = Dst ID
3189 // Ops[1] = Src ID
3190 // Ops[2] = Memory Access
3191 // Ops[3] = Alignment
3192
3193 auto IsVolatile =
3194 dyn_cast<ConstantInt>(Call->getArgOperand(3))->getZExtValue() != 0;
3195
3196 auto VolatileMemoryAccess = (IsVolatile) ? spv::MemoryAccessVolatileMask
3197 : spv::MemoryAccessMaskNone;
3198
3199 auto MemoryAccess = VolatileMemoryAccess | spv::MemoryAccessAlignedMask;
3200
3201 auto Alignment =
3202 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
3203
3204 SPIRVOperandVec Ops;
3205 Ops << Call->getArgOperand(0) << Call->getArgOperand(1) << MemoryAccess
3206 << static_cast<uint32_t>(Alignment);
3207
3208 RID = addSPIRVInst(spv::OpCopyMemory, Ops);
3209 break;
3210 }
3211 default:
3212 llvm_unreachable("Unknown CLSPV Instruction");
3213 break;
3214 }
3215 return RID;
3216}
3217
3218SPIRVID
3219SPIRVProducerPass::GenerateImageInstruction(CallInst *Call,
3220 const FunctionInfo &FuncInfo) {
3221 SPIRVID RID;
3222
3223 LLVMContext &Context = module->getContext();
3224 switch (FuncInfo.getType()) {
3225 case Builtins::kReadImagef:
3226 case Builtins::kReadImageh:
3227 case Builtins::kReadImagei:
3228 case Builtins::kReadImageui: {
3229 // read_image is converted to OpSampledImage and OpImageSampleExplicitLod.
3230 // Additionally, OpTypeSampledImage is generated.
3231 const auto &pi = FuncInfo.getParameter(1);
3232 if (pi.isSampler()) {
3233 //
3234 // Generate OpSampledImage.
3235 //
3236 // Ops[0] = Result Type ID
3237 // Ops[1] = Image ID
3238 // Ops[2] = Sampler ID
3239 //
3240 SPIRVOperandVec Ops;
3241
3242 Value *Image = Call->getArgOperand(0);
3243 Value *Sampler = Call->getArgOperand(1);
3244 Value *Coordinate = Call->getArgOperand(2);
3245
3246 TypeMapType &OpImageTypeMap = getImageTypeMap();
3247 Type *ImageTy = Image->getType()->getPointerElementType();
3248 SPIRVID ImageTyID = OpImageTypeMap[ImageTy];
3249
3250 Ops << ImageTyID << Image << Sampler;
3251
3252 SPIRVID SampledImageID = addSPIRVInst(spv::OpSampledImage, Ops);
3253
3254 //
3255 // Generate OpImageSampleExplicitLod.
3256 //
3257 // Ops[0] = Result Type ID
3258 // Ops[1] = Sampled Image ID
3259 // Ops[2] = Coordinate ID
3260 // Ops[3] = Image Operands Type ID
3261 // Ops[4] ... Ops[n] = Operands ID
3262 //
3263 Ops.clear();
3264
3265 const bool is_int_image = IsIntImageType(Image->getType());
3266 SPIRVID result_type;
3267 if (is_int_image) {
3268 result_type = v4int32ID;
3269 } else {
3270 result_type = getSPIRVType(Call->getType());
3271 }
3272
3273 Constant *CstFP0 = ConstantFP::get(Context, APFloat(0.0f));
3274 Ops << result_type << SampledImageID << Coordinate
3275 << spv::ImageOperandsLodMask << CstFP0;
3276
3277 RID = addSPIRVInst(spv::OpImageSampleExplicitLod, Ops);
3278
3279 if (is_int_image) {
3280 // Generate the bitcast.
3281 Ops.clear();
3282 Ops << Call->getType() << RID;
3283 RID = addSPIRVInst(spv::OpBitcast, Ops);
3284 }
3285 } else {
SJW806a5d82020-07-15 12:51:38 -05003286 // read_image (without a sampler) is mapped to OpImageFetch.
3287 Value *Image = Call->getArgOperand(0);
3288 Value *Coordinate = Call->getArgOperand(1);
3289
3290 //
3291 // Generate OpImageFetch
3292 //
3293 // Ops[0] = Result Type ID
3294 // Ops[1] = Image ID
3295 // Ops[2] = Coordinate ID
3296 // Ops[3] = Lod
3297 // Ops[4] = 0
3298 //
3299 SPIRVOperandVec Ops;
3300
3301 const bool is_int_image = IsIntImageType(Image->getType());
3302 SPIRVID result_type;
3303 if (is_int_image) {
3304 result_type = v4int32ID;
3305 } else {
3306 result_type = getSPIRVType(Call->getType());
3307 }
3308
3309 Ops << result_type << Image << Coordinate << spv::ImageOperandsLodMask
3310 << getSPIRVInt32Constant(0);
3311
3312 RID = addSPIRVInst(spv::OpImageFetch, Ops);
3313
3314 if (is_int_image) {
3315 // Generate the bitcast.
3316 Ops.clear();
3317 Ops << Call->getType() << RID;
3318 RID = addSPIRVInst(spv::OpBitcast, Ops);
3319 }
3320 }
3321 break;
3322 }
3323
3324 case Builtins::kWriteImagef:
3325 case Builtins::kWriteImageh:
3326 case Builtins::kWriteImagei:
3327 case Builtins::kWriteImageui: {
3328 // write_image is mapped to OpImageWrite.
3329 //
3330 // Generate OpImageWrite.
3331 //
3332 // Ops[0] = Image ID
3333 // Ops[1] = Coordinate ID
3334 // Ops[2] = Texel ID
3335 // Ops[3] = (Optional) Image Operands Type (Literal Number)
3336 // Ops[4] ... Ops[n] = (Optional) Operands ID
3337 //
3338 SPIRVOperandVec Ops;
3339
3340 Value *Image = Call->getArgOperand(0);
3341 Value *Coordinate = Call->getArgOperand(1);
3342 Value *Texel = Call->getArgOperand(2);
3343
3344 SPIRVID TexelID = getSPIRVValue(Texel);
3345
3346 const bool is_int_image = IsIntImageType(Image->getType());
3347 if (is_int_image) {
3348 // Generate a bitcast to v4int and use it as the texel value.
3349 Ops << v4int32ID << TexelID;
3350 TexelID = addSPIRVInst(spv::OpBitcast, Ops);
3351 Ops.clear();
3352 }
3353 Ops << Image << Coordinate << TexelID;
3354
3355 RID = addSPIRVInst(spv::OpImageWrite, Ops);
3356 break;
3357 }
3358
3359 case Builtins::kGetImageHeight:
3360 case Builtins::kGetImageWidth:
3361 case Builtins::kGetImageDepth:
3362 case Builtins::kGetImageDim: {
3363 // get_image_* is mapped to OpImageQuerySize or OpImageQuerySizeLod
3364 addCapability(spv::CapabilityImageQuery);
3365
3366 //
3367 // Generate OpImageQuerySize[Lod]
3368 //
3369 // Ops[0] = Image ID
3370 //
3371 // Result type has components equal to the dimensionality of the image,
3372 // plus 1 if the image is arrayed.
3373 //
3374 // %sizes = OpImageQuerySize[Lod] %uint[2|3|4] %im [%uint_0]
3375 SPIRVOperandVec Ops;
3376
3377 // Implement:
3378 // %sizes = OpImageQuerySize[Lod] %uint[2|3|4] %im [%uint_0]
3379 SPIRVID SizesTypeID;
3380
3381 Value *Image = Call->getArgOperand(0);
3382 const uint32_t dim = ImageDimensionality(Image->getType());
3383 const uint32_t components =
3384 dim + (IsArrayImageType(Image->getType()) ? 1 : 0);
3385 if (components == 1) {
3386 SizesTypeID = getSPIRVType(Type::getInt32Ty(Context));
3387 } else {
3388 SizesTypeID = getSPIRVType(
3389 FixedVectorType::get(Type::getInt32Ty(Context), components));
3390 }
3391 Ops << SizesTypeID << Image;
3392 spv::Op query_opcode = spv::OpImageQuerySize;
3393 if (IsSampledImageType(Image->getType())) {
3394 query_opcode = spv::OpImageQuerySizeLod;
3395 // Need explicit 0 for Lod operand.
3396 Ops << getSPIRVInt32Constant(0);
3397 }
3398
3399 RID = addSPIRVInst(query_opcode, Ops);
3400
3401 // May require an extra instruction to create the appropriate result of
3402 // the builtin function.
3403 if (FuncInfo.getType() == Builtins::kGetImageDim) {
3404 if (dim == 3) {
3405 // get_image_dim returns an int4 for 3D images.
3406 //
3407
3408 // Implement:
3409 // %result = OpCompositeConstruct %uint4 %sizes %uint_0
3410 Ops.clear();
3411 Ops << FixedVectorType::get(Type::getInt32Ty(Context), 4) << RID
3412 << getSPIRVInt32Constant(0);
3413
3414 RID = addSPIRVInst(spv::OpCompositeConstruct, Ops);
3415 } else if (dim != components) {
3416 // get_image_dim return an int2 regardless of the arrayedness of the
3417 // image. If the image is arrayed an element must be dropped from the
3418 // query result.
3419 //
3420
3421 // Implement:
3422 // %result = OpVectorShuffle %uint2 %sizes %sizes 0 1
3423 Ops.clear();
3424 Ops << FixedVectorType::get(Type::getInt32Ty(Context), 2) << RID << RID
3425 << 0 << 1;
3426
3427 RID = addSPIRVInst(spv::OpVectorShuffle, Ops);
3428 }
3429 } else if (components > 1) {
3430 // Implement:
3431 // %result = OpCompositeExtract %uint %sizes <component number>
3432 Ops.clear();
3433 Ops << Call->getType() << RID;
3434
3435 uint32_t component = 0;
3436 if (FuncInfo.getType() == Builtins::kGetImageHeight)
3437 component = 1;
3438 else if (FuncInfo.getType() == Builtins::kGetImageDepth)
3439 component = 2;
3440 Ops << component;
3441
3442 RID = addSPIRVInst(spv::OpCompositeExtract, Ops);
3443 }
3444 break;
3445 }
3446 default:
3447 llvm_unreachable("Unsupported Image builtin");
3448 }
3449
3450 return RID;
3451}
3452
3453SPIRVID
3454SPIRVProducerPass::GenerateSubgroupInstruction(CallInst *Call,
3455 const FunctionInfo &FuncInfo) {
3456 SPIRVID RID;
3457
3458 // requires SPIRV version 1.3 or greater
3459 if (SpvVersion() != SPIRVVersion::SPIRV_1_3) {
3460 // llvm_unreachable("SubGroups extension requires SPIRV 1.3 or greater");
3461 // TODO(sjw): error out gracefully
3462 }
3463
3464 auto loadBuiltin = [this, Call](spv::BuiltIn spvBI,
3465 spv::Capability spvCap =
3466 spv::CapabilityGroupNonUniform) {
3467 SPIRVOperandVec Ops;
3468 Ops << Call->getType() << this->getSPIRVBuiltin(spvBI, spvCap);
3469
3470 return addSPIRVInst(spv::OpLoad, Ops);
3471 };
3472
3473 spv::Op op = spv::OpNop;
3474 switch (FuncInfo.getType()) {
3475 case Builtins::kGetSubGroupSize:
3476 return loadBuiltin(spv::BuiltInSubgroupSize);
3477 case Builtins::kGetNumSubGroups:
3478 return loadBuiltin(spv::BuiltInNumSubgroups);
3479 case Builtins::kGetSubGroupId:
3480 return loadBuiltin(spv::BuiltInSubgroupId);
3481 case Builtins::kGetSubGroupLocalId:
3482 return loadBuiltin(spv::BuiltInSubgroupLocalInvocationId);
3483
3484 case Builtins::kSubGroupBroadcast:
3485 if (SpvVersion() < SPIRVVersion::SPIRV_1_5 &&
3486 !dyn_cast<ConstantInt>(Call->getOperand(1))) {
3487 llvm_unreachable("sub_group_broadcast requires constant lane Id for "
3488 "SPIRV version < 1.5");
3489 }
3490 addCapability(spv::CapabilityGroupNonUniformBallot);
3491 op = spv::OpGroupNonUniformBroadcast;
3492 break;
3493
3494 case Builtins::kSubGroupAll:
3495 addCapability(spv::CapabilityGroupNonUniformVote);
3496 op = spv::OpGroupNonUniformAll;
3497 break;
3498 case Builtins::kSubGroupAny:
3499 addCapability(spv::CapabilityGroupNonUniformVote);
3500 op = spv::OpGroupNonUniformAny;
3501 break;
3502 case Builtins::kSubGroupReduceAdd:
3503 case Builtins::kSubGroupScanExclusiveAdd:
3504 case Builtins::kSubGroupScanInclusiveAdd: {
3505 addCapability(spv::CapabilityGroupNonUniformArithmetic);
3506 if (FuncInfo.getParameter(0).type_id == Type::IntegerTyID) {
3507 op = spv::OpGroupNonUniformIAdd;
3508 } else {
3509 op = spv::OpGroupNonUniformFAdd;
3510 }
3511 break;
3512 }
3513 case Builtins::kSubGroupReduceMin:
3514 case Builtins::kSubGroupScanExclusiveMin:
3515 case Builtins::kSubGroupScanInclusiveMin: {
3516 addCapability(spv::CapabilityGroupNonUniformArithmetic);
3517 auto &param = FuncInfo.getParameter(0);
3518 if (param.type_id == Type::IntegerTyID) {
3519 op = param.is_signed ? spv::OpGroupNonUniformSMin
3520 : spv::OpGroupNonUniformUMin;
3521 } else {
3522 op = spv::OpGroupNonUniformFMin;
3523 }
3524 break;
3525 }
3526 case Builtins::kSubGroupReduceMax:
3527 case Builtins::kSubGroupScanExclusiveMax:
3528 case Builtins::kSubGroupScanInclusiveMax: {
3529 addCapability(spv::CapabilityGroupNonUniformArithmetic);
3530 auto &param = FuncInfo.getParameter(0);
3531 if (param.type_id == Type::IntegerTyID) {
3532 op = param.is_signed ? spv::OpGroupNonUniformSMax
3533 : spv::OpGroupNonUniformUMax;
3534 } else {
3535 op = spv::OpGroupNonUniformFMax;
3536 }
3537 break;
3538 }
3539
3540 case Builtins::kGetEnqueuedNumSubGroups:
3541 // TODO(sjw): requires CapabilityKernel (incompatible with Shader)
3542 case Builtins::kGetMaxSubGroupSize:
3543 // TODO(sjw): use SpecConstant, capability Kernel (incompatible with Shader)
3544 case Builtins::kSubGroupBarrier:
3545 case Builtins::kSubGroupReserveReadPipe:
3546 case Builtins::kSubGroupReserveWritePipe:
3547 case Builtins::kSubGroupCommitReadPipe:
3548 case Builtins::kSubGroupCommitWritePipe:
3549 case Builtins::kGetKernelSubGroupCountForNdrange:
3550 case Builtins::kGetKernelMaxSubGroupSizeForNdrange:
3551 default:
3552 Call->print(errs());
3553 llvm_unreachable("Unsupported sub_group operation");
3554 break;
3555 }
3556
3557 assert(op != spv::OpNop);
3558
3559 SPIRVOperandVec Operands;
3560
3561 //
3562 // Generate OpGroupNonUniform*
3563 //
3564 // Ops[0] = Result Type ID
3565 // Ops[1] = ScopeSubgroup
3566 // Ops[2] = Value ID
3567 // Ops[3] = Local ID
3568
3569 // The result type.
3570 Operands << Call->getType();
3571
3572 // Subgroup Scope
3573 Operands << getSPIRVInt32Constant(spv::ScopeSubgroup);
3574
3575 switch (FuncInfo.getType()) {
3576 case Builtins::kSubGroupReduceAdd:
3577 case Builtins::kSubGroupReduceMin:
3578 case Builtins::kSubGroupReduceMax:
3579 Operands << spv::GroupOperationReduce;
3580 break;
3581 case Builtins::kSubGroupScanExclusiveAdd:
3582 case Builtins::kSubGroupScanExclusiveMin:
3583 case Builtins::kSubGroupScanExclusiveMax:
3584 Operands << spv::GroupOperationExclusiveScan;
3585 break;
3586 case Builtins::kSubGroupScanInclusiveAdd:
3587 case Builtins::kSubGroupScanInclusiveMin:
3588 case Builtins::kSubGroupScanInclusiveMax:
3589 Operands << spv::GroupOperationInclusiveScan;
3590 break;
3591 default:
3592 break;
3593 }
3594
3595 for (Use &use : Call->arg_operands()) {
3596 Operands << use.get();
3597 }
3598
3599 return addSPIRVInst(op, Operands);
3600}
3601
3602SPIRVID SPIRVProducerPass::GenerateInstructionFromCall(CallInst *Call) {
3603 LLVMContext &Context = module->getContext();
3604
3605 auto &func_info = Builtins::Lookup(Call->getCalledFunction());
3606 auto func_type = func_info.getType();
3607
3608 if (BUILTIN_IN_GROUP(func_type, Clspv)) {
3609 return GenerateClspvInstruction(Call, func_info);
3610 } else if (BUILTIN_IN_GROUP(func_type, Image)) {
3611 return GenerateImageInstruction(Call, func_info);
3612 } else if (BUILTIN_IN_GROUP(func_type, SubgroupsKHR)) {
3613 return GenerateSubgroupInstruction(Call, func_info);
3614 }
3615
3616 SPIRVID RID;
3617
3618 switch (func_type) {
3619 case Builtins::kPopcount: {
3620 //
3621 // Generate OpBitCount
3622 //
3623 // Ops[0] = Result Type ID
3624 // Ops[1] = Base ID
3625 SPIRVOperandVec Ops;
3626 Ops << Call->getType() << Call->getOperand(0);
3627
3628 RID = addSPIRVInst(spv::OpBitCount, Ops);
3629 break;
3630 }
3631 default: {
3632 glsl::ExtInst EInst = getDirectOrIndirectExtInstEnum(func_info);
3633
3634 if (EInst) {
3635 SPIRVID ExtInstImportID = getOpExtInstImportID();
3636
3637 //
3638 // Generate OpExtInst.
3639 //
3640
3641 // Ops[0] = Result Type ID
3642 // Ops[1] = Set ID (OpExtInstImport ID)
3643 // Ops[2] = Instruction Number (Literal Number)
3644 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
3645 SPIRVOperandVec Ops;
3646
3647 Ops << Call->getType() << ExtInstImportID << EInst;
3648
3649 for (auto &use : Call->arg_operands()) {
3650 Ops << use.get();
3651 }
3652
3653 RID = addSPIRVInst(spv::OpExtInst, Ops);
3654
3655 const auto IndirectExtInst = getIndirectExtInstEnum(func_info);
3656 if (IndirectExtInst != kGlslExtInstBad) {
SJW806a5d82020-07-15 12:51:38 -05003657 // Generate one more instruction that uses the result of the extended
3658 // instruction. Its result id is one more than the id of the
3659 // extended instruction.
3660 auto generate_extra_inst = [this, &Context, &Call,
3661 &RID](spv::Op opcode, Constant *constant) {
3662 //
3663 // Generate instruction like:
3664 // result = opcode constant <extinst-result>
3665 //
3666 // Ops[0] = Result Type ID
3667 // Ops[1] = Operand 0 ;; the constant, suitably splatted
3668 // Ops[2] = Operand 1 ;; the result of the extended instruction
3669 SPIRVOperandVec Ops;
3670
3671 Type *resultTy = Call->getType();
3672
3673 if (auto *vectorTy = dyn_cast<VectorType>(resultTy)) {
alan-baker931253b2020-08-20 17:15:38 -04003674 constant =
3675 ConstantVector::getSplat(vectorTy->getElementCount(), constant);
SJW806a5d82020-07-15 12:51:38 -05003676 }
3677 Ops << resultTy << constant << RID;
3678
3679 RID = addSPIRVInst(opcode, Ops);
3680 };
3681
3682 auto IntTy = Type::getInt32Ty(Context);
3683 switch (IndirectExtInst) {
3684 case glsl::ExtInstFindUMsb: // Implementing clz
3685 generate_extra_inst(spv::OpISub, ConstantInt::get(IntTy, 31));
3686 break;
3687 case glsl::ExtInstAcos: // Implementing acospi
3688 case glsl::ExtInstAsin: // Implementing asinpi
3689 case glsl::ExtInstAtan: // Implementing atanpi
3690 case glsl::ExtInstAtan2: // Implementing atan2pi
3691 generate_extra_inst(
3692 spv::OpFMul,
3693 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
3694 break;
3695
3696 default:
3697 assert(false && "internally inconsistent");
3698 }
3699 }
3700 } else {
SJW806a5d82020-07-15 12:51:38 -05003701 // A real function call (not builtin)
3702 // Call instruction is deferred because it needs function's ID.
3703 RID = addSPIRVPlaceholder(Call);
3704 }
3705
3706 break;
3707 }
3708 }
3709
3710 return RID;
3711}
3712
David Neto22f144c2017-06-12 14:26:21 -04003713void SPIRVProducerPass::GenerateInstruction(Instruction &I) {
David Neto22f144c2017-06-12 14:26:21 -04003714 ValueMapType &VMap = getValueMap();
SJW806a5d82020-07-15 12:51:38 -05003715 LLVMContext &Context = module->getContext();
David Neto22f144c2017-06-12 14:26:21 -04003716
SJW806a5d82020-07-15 12:51:38 -05003717 SPIRVID RID;
David Neto22f144c2017-06-12 14:26:21 -04003718
3719 switch (I.getOpcode()) {
3720 default: {
3721 if (Instruction::isCast(I.getOpcode())) {
3722 //
3723 // Generate SPIRV instructions for cast operators.
3724 //
3725
David Netod2de94a2017-08-28 17:27:47 -04003726 auto Ty = I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003727 auto OpTy = I.getOperand(0)->getType();
David Netod2de94a2017-08-28 17:27:47 -04003728 auto toI8 = Ty == Type::getInt8Ty(Context);
3729 auto fromI32 = OpTy == Type::getInt32Ty(Context);
David Neto22f144c2017-06-12 14:26:21 -04003730 // Handle zext, sext and uitofp with i1 type specially.
3731 if ((I.getOpcode() == Instruction::ZExt ||
3732 I.getOpcode() == Instruction::SExt ||
3733 I.getOpcode() == Instruction::UIToFP) &&
alan-bakerb6b09dc2018-11-08 16:59:28 -05003734 OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003735 //
3736 // Generate OpSelect.
3737 //
3738
3739 // Ops[0] = Result Type ID
3740 // Ops[1] = Condition ID
3741 // Ops[2] = True Constant ID
3742 // Ops[3] = False Constant ID
SJWf93f5f32020-05-05 07:27:56 -05003743 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04003744
SJW01901d92020-05-21 08:58:31 -05003745 Ops << I.getType() << I.getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04003746
David Neto22f144c2017-06-12 14:26:21 -04003747 if (I.getOpcode() == Instruction::ZExt) {
SJW01901d92020-05-21 08:58:31 -05003748 Ops << ConstantInt::get(I.getType(), 1);
David Neto22f144c2017-06-12 14:26:21 -04003749 } else if (I.getOpcode() == Instruction::SExt) {
SJW01901d92020-05-21 08:58:31 -05003750 Ops << ConstantInt::getSigned(I.getType(), -1);
David Neto22f144c2017-06-12 14:26:21 -04003751 } else {
SJW01901d92020-05-21 08:58:31 -05003752 Ops << ConstantFP::get(Context, APFloat(1.0f));
David Neto22f144c2017-06-12 14:26:21 -04003753 }
David Neto22f144c2017-06-12 14:26:21 -04003754
David Neto22f144c2017-06-12 14:26:21 -04003755 if (I.getOpcode() == Instruction::ZExt) {
SJW01901d92020-05-21 08:58:31 -05003756 Ops << Constant::getNullValue(I.getType());
David Neto22f144c2017-06-12 14:26:21 -04003757 } else if (I.getOpcode() == Instruction::SExt) {
SJW01901d92020-05-21 08:58:31 -05003758 Ops << Constant::getNullValue(I.getType());
David Neto22f144c2017-06-12 14:26:21 -04003759 } else {
SJW01901d92020-05-21 08:58:31 -05003760 Ops << ConstantFP::get(Context, APFloat(0.0f));
David Neto22f144c2017-06-12 14:26:21 -04003761 }
David Neto22f144c2017-06-12 14:26:21 -04003762
SJWf93f5f32020-05-05 07:27:56 -05003763 RID = addSPIRVInst(spv::OpSelect, Ops);
alan-bakerb39c8262019-03-08 14:03:37 -05003764 } else if (!clspv::Option::Int8Support() &&
3765 I.getOpcode() == Instruction::Trunc && fromI32 && toI8) {
David Netod2de94a2017-08-28 17:27:47 -04003766 // The SPIR-V target type is a 32-bit int. Keep only the bottom
3767 // 8 bits.
3768 // Before:
3769 // %result = trunc i32 %a to i8
3770 // After
3771 // %result = OpBitwiseAnd %uint %a %uint_255
3772
SJWf93f5f32020-05-05 07:27:56 -05003773 SPIRVOperandVec Ops;
David Netod2de94a2017-08-28 17:27:47 -04003774
SJW806a5d82020-07-15 12:51:38 -05003775 Ops << OpTy << I.getOperand(0) << getSPIRVInt32Constant(255);
David Netod2de94a2017-08-28 17:27:47 -04003776
SJWf93f5f32020-05-05 07:27:56 -05003777 RID = addSPIRVInst(spv::OpBitwiseAnd, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003778 } else {
3779 // Ops[0] = Result Type ID
3780 // Ops[1] = Source Value ID
SJWf93f5f32020-05-05 07:27:56 -05003781 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04003782
SJW01901d92020-05-21 08:58:31 -05003783 Ops << I.getType() << I.getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04003784
SJWf93f5f32020-05-05 07:27:56 -05003785 RID = addSPIRVInst(GetSPIRVCastOpcode(I), Ops);
David Neto22f144c2017-06-12 14:26:21 -04003786 }
3787 } else if (isa<BinaryOperator>(I)) {
3788 //
3789 // Generate SPIRV instructions for binary operators.
3790 //
3791
3792 // Handle xor with i1 type specially.
3793 if (I.getOpcode() == Instruction::Xor &&
3794 I.getType() == Type::getInt1Ty(Context) &&
Kévin Petit24272b62018-10-18 19:16:12 +00003795 ((isa<ConstantInt>(I.getOperand(0)) &&
3796 !cast<ConstantInt>(I.getOperand(0))->isZero()) ||
3797 (isa<ConstantInt>(I.getOperand(1)) &&
3798 !cast<ConstantInt>(I.getOperand(1))->isZero()))) {
David Neto22f144c2017-06-12 14:26:21 -04003799 //
3800 // Generate OpLogicalNot.
3801 //
3802 // Ops[0] = Result Type ID
3803 // Ops[1] = Operand
SJWf93f5f32020-05-05 07:27:56 -05003804 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04003805
SJW01901d92020-05-21 08:58:31 -05003806 Ops << I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003807
3808 Value *CondV = I.getOperand(0);
3809 if (isa<Constant>(I.getOperand(0))) {
3810 CondV = I.getOperand(1);
3811 }
SJW01901d92020-05-21 08:58:31 -05003812 Ops << CondV;
David Neto22f144c2017-06-12 14:26:21 -04003813
SJWf93f5f32020-05-05 07:27:56 -05003814 RID = addSPIRVInst(spv::OpLogicalNot, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003815 } else {
3816 // Ops[0] = Result Type ID
3817 // Ops[1] = Operand 0
3818 // Ops[2] = Operand 1
SJWf93f5f32020-05-05 07:27:56 -05003819 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04003820
SJW01901d92020-05-21 08:58:31 -05003821 Ops << I.getType() << I.getOperand(0) << I.getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04003822
SJWf93f5f32020-05-05 07:27:56 -05003823 RID = addSPIRVInst(GetSPIRVBinaryOpcode(I), Ops);
David Neto22f144c2017-06-12 14:26:21 -04003824 }
alan-bakerc9c55ae2019-12-02 16:01:27 -05003825 } else if (I.getOpcode() == Instruction::FNeg) {
3826 // The only unary operator.
3827 //
3828 // Ops[0] = Result Type ID
3829 // Ops[1] = Operand 0
SJW01901d92020-05-21 08:58:31 -05003830 SPIRVOperandVec Ops;
alan-bakerc9c55ae2019-12-02 16:01:27 -05003831
SJW01901d92020-05-21 08:58:31 -05003832 Ops << I.getType() << I.getOperand(0);
3833 RID = addSPIRVInst(spv::OpFNegate, Ops);
Marco Antognini68e5c512020-09-09 16:08:57 +01003834 } else if (I.getOpcode() == Instruction::Unreachable) {
3835 RID = addSPIRVInst(spv::OpUnreachable);
David Neto22f144c2017-06-12 14:26:21 -04003836 } else {
3837 I.print(errs());
3838 llvm_unreachable("Unsupported instruction???");
3839 }
3840 break;
3841 }
3842 case Instruction::GetElementPtr: {
3843 auto &GlobalConstArgSet = getGlobalConstArgSet();
3844
3845 //
3846 // Generate OpAccessChain.
3847 //
3848 GetElementPtrInst *GEP = cast<GetElementPtrInst>(&I);
3849
3850 //
3851 // Generate OpAccessChain.
3852 //
3853
3854 // Ops[0] = Result Type ID
3855 // Ops[1] = Base ID
3856 // Ops[2] ... Ops[n] = Indexes ID
SJWf93f5f32020-05-05 07:27:56 -05003857 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04003858
alan-bakerb6b09dc2018-11-08 16:59:28 -05003859 PointerType *ResultType = cast<PointerType>(GEP->getType());
David Neto22f144c2017-06-12 14:26:21 -04003860 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate ||
3861 GlobalConstArgSet.count(GEP->getPointerOperand())) {
3862 // Use pointer type with private address space for global constant.
3863 Type *EleTy = I.getType()->getPointerElementType();
David Neto1a1a0582017-07-07 12:01:44 -04003864 ResultType = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
David Neto22f144c2017-06-12 14:26:21 -04003865 }
David Neto257c3892018-04-11 13:19:45 -04003866
SJW01901d92020-05-21 08:58:31 -05003867 Ops << ResultType;
David Neto22f144c2017-06-12 14:26:21 -04003868
David Neto862b7d82018-06-14 18:48:37 -04003869 // Generate the base pointer.
SJW01901d92020-05-21 08:58:31 -05003870 Ops << GEP->getPointerOperand();
David Neto22f144c2017-06-12 14:26:21 -04003871
David Neto862b7d82018-06-14 18:48:37 -04003872 // TODO(dneto): Simplify the following?
David Neto22f144c2017-06-12 14:26:21 -04003873
3874 //
3875 // Follows below rules for gep.
3876 //
David Neto862b7d82018-06-14 18:48:37 -04003877 // 1. If gep's first index is 0 generate OpAccessChain and ignore gep's
3878 // first index.
David Neto22f144c2017-06-12 14:26:21 -04003879 // 2. If gep's first index is not 0, generate OpPtrAccessChain and use gep's
3880 // first index.
3881 // 3. If gep's first index is not constant, generate OpPtrAccessChain and
3882 // use gep's first index.
3883 // 4. If it is not above case 1, 2 and 3, generate OpAccessChain and use
3884 // gep's first index.
3885 //
3886 spv::Op Opcode = spv::OpAccessChain;
3887 unsigned offset = 0;
3888 if (ConstantInt *CstInt = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
David Neto862b7d82018-06-14 18:48:37 -04003889 if (CstInt->getZExtValue() == 0) {
David Neto22f144c2017-06-12 14:26:21 -04003890 offset = 1;
David Neto862b7d82018-06-14 18:48:37 -04003891 } else if (CstInt->getZExtValue() != 0) {
David Neto22f144c2017-06-12 14:26:21 -04003892 Opcode = spv::OpPtrAccessChain;
David Neto22f144c2017-06-12 14:26:21 -04003893 }
David Neto862b7d82018-06-14 18:48:37 -04003894 } else {
David Neto22f144c2017-06-12 14:26:21 -04003895 Opcode = spv::OpPtrAccessChain;
David Neto1a1a0582017-07-07 12:01:44 -04003896 }
3897
3898 if (Opcode == spv::OpPtrAccessChain) {
alan-baker7506abb2020-09-10 15:02:55 -04003899 // Shader validation in the SPIR-V spec requires that the base pointer to
3900 // OpPtrAccessChain (in StorageBuffer storage class) be decorated with
3901 // ArrayStride.
alan-baker5b86ed72019-02-15 08:26:50 -05003902 auto address_space = ResultType->getAddressSpace();
3903 setVariablePointersCapabilities(address_space);
3904 switch (GetStorageClass(address_space)) {
Alan Bakerfcda9482018-10-02 17:09:59 -04003905 case spv::StorageClassStorageBuffer:
David Neto1a1a0582017-07-07 12:01:44 -04003906 // Save the need to generate an ArrayStride decoration. But defer
3907 // generation until later, so we only make one decoration.
alan-baker7506abb2020-09-10 15:02:55 -04003908 getTypesNeedingArrayStride().insert(GEP->getPointerOperandType());
3909 break;
3910 case spv::StorageClassWorkgroup:
Alan Bakerfcda9482018-10-02 17:09:59 -04003911 break;
3912 default:
alan-baker7506abb2020-09-10 15:02:55 -04003913 llvm_unreachable(
3914 "OpPtrAccessChain is not supported for this storage class");
Alan Bakerfcda9482018-10-02 17:09:59 -04003915 break;
David Neto1a1a0582017-07-07 12:01:44 -04003916 }
David Neto22f144c2017-06-12 14:26:21 -04003917 }
3918
3919 for (auto II = GEP->idx_begin() + offset; II != GEP->idx_end(); II++) {
SJW01901d92020-05-21 08:58:31 -05003920 Ops << *II;
David Neto22f144c2017-06-12 14:26:21 -04003921 }
3922
SJWf93f5f32020-05-05 07:27:56 -05003923 RID = addSPIRVInst(Opcode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003924 break;
3925 }
3926 case Instruction::ExtractValue: {
3927 ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
3928 // Ops[0] = Result Type ID
3929 // Ops[1] = Composite ID
3930 // Ops[2] ... Ops[n] = Indexes (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05003931 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04003932
SJW01901d92020-05-21 08:58:31 -05003933 Ops << I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003934
SJW01901d92020-05-21 08:58:31 -05003935 Ops << EVI->getAggregateOperand();
David Neto22f144c2017-06-12 14:26:21 -04003936
3937 for (auto &Index : EVI->indices()) {
SJW01901d92020-05-21 08:58:31 -05003938 Ops << Index;
David Neto22f144c2017-06-12 14:26:21 -04003939 }
3940
SJWf93f5f32020-05-05 07:27:56 -05003941 RID = addSPIRVInst(spv::OpCompositeExtract, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003942 break;
3943 }
3944 case Instruction::InsertValue: {
3945 InsertValueInst *IVI = cast<InsertValueInst>(&I);
3946 // Ops[0] = Result Type ID
3947 // Ops[1] = Object ID
3948 // Ops[2] = Composite ID
3949 // Ops[3] ... Ops[n] = Indexes (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05003950 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04003951
SJW01901d92020-05-21 08:58:31 -05003952 Ops << I.getType() << IVI->getInsertedValueOperand()
3953 << IVI->getAggregateOperand();
David Neto22f144c2017-06-12 14:26:21 -04003954
3955 for (auto &Index : IVI->indices()) {
SJW01901d92020-05-21 08:58:31 -05003956 Ops << Index;
David Neto22f144c2017-06-12 14:26:21 -04003957 }
3958
SJWf93f5f32020-05-05 07:27:56 -05003959 RID = addSPIRVInst(spv::OpCompositeInsert, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003960 break;
3961 }
3962 case Instruction::Select: {
3963 //
3964 // Generate OpSelect.
3965 //
3966
3967 // Ops[0] = Result Type ID
3968 // Ops[1] = Condition ID
3969 // Ops[2] = True Constant ID
3970 // Ops[3] = False Constant ID
SJWf93f5f32020-05-05 07:27:56 -05003971 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04003972
3973 // Find SPIRV instruction for parameter type.
3974 auto Ty = I.getType();
3975 if (Ty->isPointerTy()) {
3976 auto PointeeTy = Ty->getPointerElementType();
3977 if (PointeeTy->isStructTy() &&
3978 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
3979 Ty = PointeeTy;
alan-baker5b86ed72019-02-15 08:26:50 -05003980 } else {
3981 // Selecting between pointers requires variable pointers.
3982 setVariablePointersCapabilities(Ty->getPointerAddressSpace());
3983 if (!hasVariablePointers() && !selectFromSameObject(&I)) {
SJW01901d92020-05-21 08:58:31 -05003984 setVariablePointers();
alan-baker5b86ed72019-02-15 08:26:50 -05003985 }
David Neto22f144c2017-06-12 14:26:21 -04003986 }
3987 }
3988
SJW01901d92020-05-21 08:58:31 -05003989 Ops << Ty << I.getOperand(0) << I.getOperand(1) << I.getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04003990
SJWf93f5f32020-05-05 07:27:56 -05003991 RID = addSPIRVInst(spv::OpSelect, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003992 break;
3993 }
3994 case Instruction::ExtractElement: {
3995 // Handle <4 x i8> type manually.
3996 Type *CompositeTy = I.getOperand(0)->getType();
3997 if (is4xi8vec(CompositeTy)) {
3998 //
3999 // Generate OpShiftRightLogical and OpBitwiseAnd for extractelement with
4000 // <4 x i8>.
4001 //
4002
4003 //
4004 // Generate OpShiftRightLogical
4005 //
4006 // Ops[0] = Result Type ID
4007 // Ops[1] = Operand 0
4008 // Ops[2] = Operand 1
4009 //
SJWf93f5f32020-05-05 07:27:56 -05004010 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004011
SJW01901d92020-05-21 08:58:31 -05004012 Ops << CompositeTy << I.getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04004013
SJW01901d92020-05-21 08:58:31 -05004014 SPIRVID Op1ID = 0;
David Neto22f144c2017-06-12 14:26:21 -04004015 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
4016 // Handle constant index.
SJW806a5d82020-07-15 12:51:38 -05004017 uint32_t Idx = static_cast<uint32_t>(CI->getZExtValue());
4018 Op1ID = getSPIRVInt32Constant(Idx * 8);
David Neto22f144c2017-06-12 14:26:21 -04004019 } else {
4020 // Handle variable index.
SJWf93f5f32020-05-05 07:27:56 -05004021 SPIRVOperandVec TmpOps;
David Neto22f144c2017-06-12 14:26:21 -04004022
SJW806a5d82020-07-15 12:51:38 -05004023 TmpOps << Type::getInt32Ty(Context) << I.getOperand(1)
4024 << getSPIRVInt32Constant(8);
David Neto22f144c2017-06-12 14:26:21 -04004025
SJWf93f5f32020-05-05 07:27:56 -05004026 Op1ID = addSPIRVInst(spv::OpIMul, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04004027 }
SJW01901d92020-05-21 08:58:31 -05004028 Ops << Op1ID;
David Neto22f144c2017-06-12 14:26:21 -04004029
SJW01901d92020-05-21 08:58:31 -05004030 SPIRVID ShiftID = addSPIRVInst(spv::OpShiftRightLogical, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004031
4032 //
4033 // Generate OpBitwiseAnd
4034 //
4035 // Ops[0] = Result Type ID
4036 // Ops[1] = Operand 0
4037 // Ops[2] = Operand 1
4038 //
4039 Ops.clear();
4040
SJW806a5d82020-07-15 12:51:38 -05004041 Ops << CompositeTy << ShiftID << getSPIRVInt32Constant(0xFF);
David Neto22f144c2017-06-12 14:26:21 -04004042
SJWf93f5f32020-05-05 07:27:56 -05004043 RID = addSPIRVInst(spv::OpBitwiseAnd, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004044 break;
4045 }
4046
4047 // Ops[0] = Result Type ID
4048 // Ops[1] = Composite ID
4049 // Ops[2] ... Ops[n] = Indexes (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05004050 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004051
SJW01901d92020-05-21 08:58:31 -05004052 Ops << I.getType() << I.getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04004053
4054 spv::Op Opcode = spv::OpCompositeExtract;
4055 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
SJW01901d92020-05-21 08:58:31 -05004056 Ops << static_cast<uint32_t>(CI->getZExtValue());
David Neto22f144c2017-06-12 14:26:21 -04004057 } else {
SJW01901d92020-05-21 08:58:31 -05004058 Ops << I.getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04004059 Opcode = spv::OpVectorExtractDynamic;
4060 }
4061
SJWf93f5f32020-05-05 07:27:56 -05004062 RID = addSPIRVInst(Opcode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004063 break;
4064 }
4065 case Instruction::InsertElement: {
4066 // Handle <4 x i8> type manually.
4067 Type *CompositeTy = I.getOperand(0)->getType();
4068 if (is4xi8vec(CompositeTy)) {
SJW806a5d82020-07-15 12:51:38 -05004069 SPIRVID CstFFID = getSPIRVInt32Constant(0xFF);
David Neto22f144c2017-06-12 14:26:21 -04004070
SJW01901d92020-05-21 08:58:31 -05004071 SPIRVID ShiftAmountID = 0;
David Neto22f144c2017-06-12 14:26:21 -04004072 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
4073 // Handle constant index.
SJW806a5d82020-07-15 12:51:38 -05004074 uint32_t Idx = static_cast<uint32_t>(CI->getZExtValue());
4075 ShiftAmountID = getSPIRVInt32Constant(Idx * 8);
David Neto22f144c2017-06-12 14:26:21 -04004076 } else {
4077 // Handle variable index.
SJWf93f5f32020-05-05 07:27:56 -05004078 SPIRVOperandVec TmpOps;
David Neto22f144c2017-06-12 14:26:21 -04004079
SJW806a5d82020-07-15 12:51:38 -05004080 TmpOps << Type::getInt32Ty(Context) << I.getOperand(2)
4081 << getSPIRVInt32Constant(8);
David Neto22f144c2017-06-12 14:26:21 -04004082
SJWf93f5f32020-05-05 07:27:56 -05004083 ShiftAmountID = addSPIRVInst(spv::OpIMul, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04004084 }
4085
4086 //
4087 // Generate mask operations.
4088 //
4089
4090 // ShiftLeft mask according to index of insertelement.
SJWf93f5f32020-05-05 07:27:56 -05004091 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004092
SJW01901d92020-05-21 08:58:31 -05004093 Ops << CompositeTy << CstFFID << ShiftAmountID;
David Neto22f144c2017-06-12 14:26:21 -04004094
SJW01901d92020-05-21 08:58:31 -05004095 SPIRVID MaskID = addSPIRVInst(spv::OpShiftLeftLogical, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004096
4097 // Inverse mask.
4098 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05004099 Ops << CompositeTy << MaskID;
David Neto22f144c2017-06-12 14:26:21 -04004100
SJW01901d92020-05-21 08:58:31 -05004101 SPIRVID InvMaskID = addSPIRVInst(spv::OpNot, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004102
4103 // Apply mask.
4104 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05004105 Ops << CompositeTy << I.getOperand(0) << InvMaskID;
David Neto22f144c2017-06-12 14:26:21 -04004106
SJW01901d92020-05-21 08:58:31 -05004107 SPIRVID OrgValID = addSPIRVInst(spv::OpBitwiseAnd, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004108
4109 // Create correct value according to index of insertelement.
4110 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05004111 Ops << CompositeTy << I.getOperand(1) << ShiftAmountID;
David Neto22f144c2017-06-12 14:26:21 -04004112
SJW01901d92020-05-21 08:58:31 -05004113 SPIRVID InsertValID = addSPIRVInst(spv::OpShiftLeftLogical, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004114
4115 // Insert value to original value.
4116 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05004117 Ops << CompositeTy << OrgValID << InsertValID;
David Neto22f144c2017-06-12 14:26:21 -04004118
SJWf93f5f32020-05-05 07:27:56 -05004119 RID = addSPIRVInst(spv::OpBitwiseOr, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004120 break;
4121 }
4122
SJWf93f5f32020-05-05 07:27:56 -05004123 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004124
James Priced26efea2018-06-09 23:28:32 +01004125 // Ops[0] = Result Type ID
SJW01901d92020-05-21 08:58:31 -05004126 Ops << I.getType();
David Neto22f144c2017-06-12 14:26:21 -04004127
4128 spv::Op Opcode = spv::OpCompositeInsert;
4129 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
David Neto257c3892018-04-11 13:19:45 -04004130 const auto value = CI->getZExtValue();
4131 assert(value <= UINT32_MAX);
James Priced26efea2018-06-09 23:28:32 +01004132 // Ops[1] = Object ID
4133 // Ops[2] = Composite ID
4134 // Ops[3] ... Ops[n] = Indexes (Literal Number)
SJW01901d92020-05-21 08:58:31 -05004135 Ops << I.getOperand(1) << I.getOperand(0) << static_cast<uint32_t>(value);
David Neto22f144c2017-06-12 14:26:21 -04004136 } else {
James Priced26efea2018-06-09 23:28:32 +01004137 // Ops[1] = Composite ID
4138 // Ops[2] = Object ID
4139 // Ops[3] ... Ops[n] = Indexes (Literal Number)
SJW01901d92020-05-21 08:58:31 -05004140 Ops << I.getOperand(0) << I.getOperand(1) << I.getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04004141 Opcode = spv::OpVectorInsertDynamic;
4142 }
4143
SJWf93f5f32020-05-05 07:27:56 -05004144 RID = addSPIRVInst(Opcode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004145 break;
4146 }
4147 case Instruction::ShuffleVector: {
4148 // Ops[0] = Result Type ID
4149 // Ops[1] = Vector 1 ID
4150 // Ops[2] = Vector 2 ID
4151 // Ops[3] ... Ops[n] = Components (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05004152 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004153
SJW01901d92020-05-21 08:58:31 -05004154 Ops << I.getType() << I.getOperand(0) << I.getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04004155
alan-bakerc9666712020-04-01 16:31:21 -04004156 auto shuffle = cast<ShuffleVectorInst>(&I);
4157 SmallVector<int, 4> mask;
4158 shuffle->getShuffleMask(mask);
4159 for (auto i : mask) {
4160 if (i == UndefMaskElem) {
4161 if (clspv::Option::HackUndef())
4162 // Use 0 instead of undef.
SJW01901d92020-05-21 08:58:31 -05004163 Ops << 0;
alan-bakerc9666712020-04-01 16:31:21 -04004164 else
4165 // Undef for shuffle in SPIR-V.
SJW01901d92020-05-21 08:58:31 -05004166 Ops << 0xffffffff;
David Neto22f144c2017-06-12 14:26:21 -04004167 } else {
SJW01901d92020-05-21 08:58:31 -05004168 Ops << i;
David Neto22f144c2017-06-12 14:26:21 -04004169 }
4170 }
4171
SJWf93f5f32020-05-05 07:27:56 -05004172 RID = addSPIRVInst(spv::OpVectorShuffle, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004173 break;
4174 }
4175 case Instruction::ICmp:
4176 case Instruction::FCmp: {
4177 CmpInst *CmpI = cast<CmpInst>(&I);
4178
David Netod4ca2e62017-07-06 18:47:35 -04004179 // Pointer equality is invalid.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004180 Type *ArgTy = CmpI->getOperand(0)->getType();
David Netod4ca2e62017-07-06 18:47:35 -04004181 if (isa<PointerType>(ArgTy)) {
4182 CmpI->print(errs());
alan-baker21574d32020-01-29 16:00:31 -05004183 std::string name = I.getParent()->getParent()->getName().str();
David Netod4ca2e62017-07-06 18:47:35 -04004184 errs()
4185 << "\nPointer equality test is not supported by SPIR-V for Vulkan, "
4186 << "in function " << name << "\n";
4187 llvm_unreachable("Pointer equality check is invalid");
4188 break;
4189 }
4190
David Neto257c3892018-04-11 13:19:45 -04004191 // Ops[0] = Result Type ID
4192 // Ops[1] = Operand 1 ID
4193 // Ops[2] = Operand 2 ID
SJWf93f5f32020-05-05 07:27:56 -05004194 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004195
SJW01901d92020-05-21 08:58:31 -05004196 Ops << CmpI->getType() << CmpI->getOperand(0) << CmpI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04004197
4198 spv::Op Opcode = GetSPIRVCmpOpcode(CmpI);
SJWf93f5f32020-05-05 07:27:56 -05004199 RID = addSPIRVInst(Opcode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004200 break;
4201 }
4202 case Instruction::Br: {
SJW88ed5fe2020-05-11 12:40:57 -05004203 // Branch instruction is deferred because it needs label's ID.
4204 BasicBlock *BrBB = I.getParent();
4205 if (ContinueBlocks.count(BrBB) || MergeBlocks.count(BrBB)) {
4206 // Placeholder for Merge operation
4207 RID = addSPIRVPlaceholder(&I);
4208 }
4209 RID = addSPIRVPlaceholder(&I);
David Neto22f144c2017-06-12 14:26:21 -04004210 break;
4211 }
4212 case Instruction::Switch: {
4213 I.print(errs());
4214 llvm_unreachable("Unsupported instruction???");
4215 break;
4216 }
4217 case Instruction::IndirectBr: {
4218 I.print(errs());
4219 llvm_unreachable("Unsupported instruction???");
4220 break;
4221 }
4222 case Instruction::PHI: {
SJW88ed5fe2020-05-11 12:40:57 -05004223 // PHI instruction is deferred because it needs label's ID.
4224 RID = addSPIRVPlaceholder(&I);
David Neto22f144c2017-06-12 14:26:21 -04004225 break;
4226 }
4227 case Instruction::Alloca: {
4228 //
4229 // Generate OpVariable.
4230 //
4231 // Ops[0] : Result Type ID
4232 // Ops[1] : Storage Class
SJWf93f5f32020-05-05 07:27:56 -05004233 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004234
SJW01901d92020-05-21 08:58:31 -05004235 Ops << I.getType() << spv::StorageClassFunction;
David Neto22f144c2017-06-12 14:26:21 -04004236
SJWf93f5f32020-05-05 07:27:56 -05004237 RID = addSPIRVInst(spv::OpVariable, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004238 break;
4239 }
4240 case Instruction::Load: {
4241 LoadInst *LD = cast<LoadInst>(&I);
4242 //
4243 // Generate OpLoad.
4244 //
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04004245
alan-baker5b86ed72019-02-15 08:26:50 -05004246 if (LD->getType()->isPointerTy()) {
4247 // Loading a pointer requires variable pointers.
4248 setVariablePointersCapabilities(LD->getType()->getPointerAddressSpace());
4249 }
David Neto22f144c2017-06-12 14:26:21 -04004250
SJW01901d92020-05-21 08:58:31 -05004251 SPIRVID PointerID = getSPIRVValue(LD->getPointerOperand());
David Netoa60b00b2017-09-15 16:34:09 -04004252 // This is a hack to work around what looks like a driver bug.
4253 // When we're loading from the special variable holding the WorkgroupSize
David Neto0a2f98d2017-09-15 19:38:40 -04004254 // builtin value, use an OpBitWiseAnd of the value's ID rather than
4255 // generating a load.
David Neto66cfe642018-03-24 06:13:56 -07004256 // TODO(dneto): Remove this awful hack once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -04004257 if (PointerID == WorkgroupSizeVarID) {
David Neto0a2f98d2017-09-15 19:38:40 -04004258 // Generate a bitwise-and of the original value with itself.
4259 // We should have been able to get away with just an OpCopyObject,
4260 // but we need something more complex to get past certain driver bugs.
4261 // This is ridiculous, but necessary.
4262 // TODO(dneto): Revisit this once drivers fix their bugs.
4263
SJWf93f5f32020-05-05 07:27:56 -05004264 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05004265 Ops << LD->getType() << WorkgroupSizeValueID << WorkgroupSizeValueID;
David Neto0a2f98d2017-09-15 19:38:40 -04004266
SJWf93f5f32020-05-05 07:27:56 -05004267 RID = addSPIRVInst(spv::OpBitwiseAnd, Ops);
David Netoa60b00b2017-09-15 16:34:09 -04004268 break;
4269 }
4270
4271 // This is the normal path. Generate a load.
4272
David Neto22f144c2017-06-12 14:26:21 -04004273 // Ops[0] = Result Type ID
4274 // Ops[1] = Pointer ID
4275 // Ops[2] ... Ops[n] = Optional Memory Access
4276 //
4277 // TODO: Do we need to implement Optional Memory Access???
David Neto0a2f98d2017-09-15 19:38:40 -04004278
SJWf93f5f32020-05-05 07:27:56 -05004279 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05004280 Ops << LD->getType() << LD->getPointerOperand();
David Neto22f144c2017-06-12 14:26:21 -04004281
SJWf93f5f32020-05-05 07:27:56 -05004282 RID = addSPIRVInst(spv::OpLoad, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004283 break;
4284 }
4285 case Instruction::Store: {
4286 StoreInst *ST = cast<StoreInst>(&I);
4287 //
4288 // Generate OpStore.
4289 //
4290
alan-baker5b86ed72019-02-15 08:26:50 -05004291 if (ST->getValueOperand()->getType()->isPointerTy()) {
4292 // Storing a pointer requires variable pointers.
4293 setVariablePointersCapabilities(
4294 ST->getValueOperand()->getType()->getPointerAddressSpace());
4295 }
4296
David Neto22f144c2017-06-12 14:26:21 -04004297 // Ops[0] = Pointer ID
4298 // Ops[1] = Object ID
4299 // Ops[2] ... Ops[n] = Optional Memory Access (later???)
4300 //
4301 // TODO: Do we need to implement Optional Memory Access???
SJWf93f5f32020-05-05 07:27:56 -05004302 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05004303 Ops << ST->getPointerOperand() << ST->getValueOperand();
David Neto22f144c2017-06-12 14:26:21 -04004304
SJWf93f5f32020-05-05 07:27:56 -05004305 RID = addSPIRVInst(spv::OpStore, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004306 break;
4307 }
4308 case Instruction::AtomicCmpXchg: {
4309 I.print(errs());
4310 llvm_unreachable("Unsupported instruction???");
4311 break;
4312 }
4313 case Instruction::AtomicRMW: {
Neil Henning39672102017-09-29 14:33:13 +01004314 AtomicRMWInst *AtomicRMW = dyn_cast<AtomicRMWInst>(&I);
4315
4316 spv::Op opcode;
4317
4318 switch (AtomicRMW->getOperation()) {
4319 default:
4320 I.print(errs());
4321 llvm_unreachable("Unsupported instruction???");
4322 case llvm::AtomicRMWInst::Add:
4323 opcode = spv::OpAtomicIAdd;
4324 break;
4325 case llvm::AtomicRMWInst::Sub:
4326 opcode = spv::OpAtomicISub;
4327 break;
4328 case llvm::AtomicRMWInst::Xchg:
4329 opcode = spv::OpAtomicExchange;
4330 break;
4331 case llvm::AtomicRMWInst::Min:
4332 opcode = spv::OpAtomicSMin;
4333 break;
4334 case llvm::AtomicRMWInst::Max:
4335 opcode = spv::OpAtomicSMax;
4336 break;
4337 case llvm::AtomicRMWInst::UMin:
4338 opcode = spv::OpAtomicUMin;
4339 break;
4340 case llvm::AtomicRMWInst::UMax:
4341 opcode = spv::OpAtomicUMax;
4342 break;
4343 case llvm::AtomicRMWInst::And:
4344 opcode = spv::OpAtomicAnd;
4345 break;
4346 case llvm::AtomicRMWInst::Or:
4347 opcode = spv::OpAtomicOr;
4348 break;
4349 case llvm::AtomicRMWInst::Xor:
4350 opcode = spv::OpAtomicXor;
4351 break;
4352 }
4353
4354 //
4355 // Generate OpAtomic*.
4356 //
SJWf93f5f32020-05-05 07:27:56 -05004357 SPIRVOperandVec Ops;
Neil Henning39672102017-09-29 14:33:13 +01004358
SJW01901d92020-05-21 08:58:31 -05004359 Ops << I.getType() << AtomicRMW->getPointerOperand();
Neil Henning39672102017-09-29 14:33:13 +01004360
SJW806a5d82020-07-15 12:51:38 -05004361 const auto ConstantScopeDevice = getSPIRVInt32Constant(spv::ScopeDevice);
SJW01901d92020-05-21 08:58:31 -05004362 Ops << ConstantScopeDevice;
Neil Henning39672102017-09-29 14:33:13 +01004363
SJW806a5d82020-07-15 12:51:38 -05004364 const auto ConstantMemorySemantics =
4365 getSPIRVInt32Constant(spv::MemorySemanticsUniformMemoryMask |
4366 spv::MemorySemanticsSequentiallyConsistentMask);
SJW01901d92020-05-21 08:58:31 -05004367 Ops << ConstantMemorySemantics << AtomicRMW->getValOperand();
Neil Henning39672102017-09-29 14:33:13 +01004368
SJWf93f5f32020-05-05 07:27:56 -05004369 RID = addSPIRVInst(opcode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004370 break;
4371 }
4372 case Instruction::Fence: {
4373 I.print(errs());
4374 llvm_unreachable("Unsupported instruction???");
4375 break;
4376 }
4377 case Instruction::Call: {
4378 CallInst *Call = dyn_cast<CallInst>(&I);
SJW806a5d82020-07-15 12:51:38 -05004379 RID = GenerateInstructionFromCall(Call);
David Neto22f144c2017-06-12 14:26:21 -04004380 break;
4381 }
4382 case Instruction::Ret: {
4383 unsigned NumOps = I.getNumOperands();
4384 if (NumOps == 0) {
4385 //
4386 // Generate OpReturn.
4387 //
SJWf93f5f32020-05-05 07:27:56 -05004388 RID = addSPIRVInst(spv::OpReturn);
David Neto22f144c2017-06-12 14:26:21 -04004389 } else {
4390 //
4391 // Generate OpReturnValue.
4392 //
4393
4394 // Ops[0] = Return Value ID
SJWf93f5f32020-05-05 07:27:56 -05004395 SPIRVOperandVec Ops;
David Neto257c3892018-04-11 13:19:45 -04004396
SJW01901d92020-05-21 08:58:31 -05004397 Ops << I.getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04004398
SJWf93f5f32020-05-05 07:27:56 -05004399 RID = addSPIRVInst(spv::OpReturnValue, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004400 break;
4401 }
4402 break;
4403 }
4404 }
SJWf93f5f32020-05-05 07:27:56 -05004405
4406 // Register Instruction to ValueMap.
SJW01901d92020-05-21 08:58:31 -05004407 if (RID.isValid()) {
SJWf93f5f32020-05-05 07:27:56 -05004408 VMap[&I] = RID;
4409 }
David Neto22f144c2017-06-12 14:26:21 -04004410}
4411
4412void SPIRVProducerPass::GenerateFuncEpilogue() {
David Neto22f144c2017-06-12 14:26:21 -04004413 //
4414 // Generate OpFunctionEnd
4415 //
SJWf93f5f32020-05-05 07:27:56 -05004416 addSPIRVInst(spv::OpFunctionEnd);
David Neto22f144c2017-06-12 14:26:21 -04004417}
4418
4419bool SPIRVProducerPass::is4xi8vec(Type *Ty) const {
alan-bakerb39c8262019-03-08 14:03:37 -05004420 // Don't specialize <4 x i8> if i8 is generally supported.
4421 if (clspv::Option::Int8Support())
4422 return false;
4423
David Neto22f144c2017-06-12 14:26:21 -04004424 LLVMContext &Context = Ty->getContext();
James Pricecf53df42020-04-20 14:41:24 -04004425 if (auto VecTy = dyn_cast<VectorType>(Ty)) {
4426 if (VecTy->getElementType() == Type::getInt8Ty(Context) &&
alan-baker5a8c3be2020-09-09 13:44:26 -04004427 VecTy->getElementCount().getKnownMinValue() == 4) {
David Neto22f144c2017-06-12 14:26:21 -04004428 return true;
4429 }
4430 }
4431
4432 return false;
4433}
4434
4435void SPIRVProducerPass::HandleDeferredInstruction() {
David Neto22f144c2017-06-12 14:26:21 -04004436 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
4437
SJW88ed5fe2020-05-11 12:40:57 -05004438 for (size_t i = 0; i < DeferredInsts.size(); ++i) {
4439 Value *Inst = DeferredInsts[i].first;
4440 SPIRVInstruction *Placeholder = DeferredInsts[i].second;
4441 SPIRVOperandVec Operands;
4442
4443 auto nextDeferred = [&i, &Inst, &DeferredInsts, &Placeholder]() {
4444 ++i;
4445 assert(DeferredInsts.size() > i);
4446 assert(Inst == DeferredInsts[i].first);
4447 Placeholder = DeferredInsts[i].second;
4448 };
David Neto22f144c2017-06-12 14:26:21 -04004449
4450 if (BranchInst *Br = dyn_cast<BranchInst>(Inst)) {
alan-baker06cad652019-12-03 17:56:47 -05004451 // Check whether this branch needs to be preceeded by merge instruction.
David Neto22f144c2017-06-12 14:26:21 -04004452 BasicBlock *BrBB = Br->getParent();
alan-baker06cad652019-12-03 17:56:47 -05004453 if (ContinueBlocks.count(BrBB)) {
David Neto22f144c2017-06-12 14:26:21 -04004454 //
4455 // Generate OpLoopMerge.
4456 //
4457 // Ops[0] = Merge Block ID
4458 // Ops[1] = Continue Target ID
4459 // Ops[2] = Selection Control
SJWf93f5f32020-05-05 07:27:56 -05004460 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004461
SJW01901d92020-05-21 08:58:31 -05004462 Ops << MergeBlocks[BrBB] << ContinueBlocks[BrBB]
4463 << spv::LoopControlMaskNone;
David Neto22f144c2017-06-12 14:26:21 -04004464
SJW88ed5fe2020-05-11 12:40:57 -05004465 replaceSPIRVInst(Placeholder, spv::OpLoopMerge, Ops);
4466
4467 nextDeferred();
4468
alan-baker06cad652019-12-03 17:56:47 -05004469 } else if (MergeBlocks.count(BrBB)) {
4470 //
4471 // Generate OpSelectionMerge.
4472 //
4473 // Ops[0] = Merge Block ID
4474 // Ops[1] = Selection Control
SJWf93f5f32020-05-05 07:27:56 -05004475 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004476
alan-baker06cad652019-12-03 17:56:47 -05004477 auto MergeBB = MergeBlocks[BrBB];
SJW01901d92020-05-21 08:58:31 -05004478 Ops << MergeBB << spv::SelectionControlMaskNone;
David Neto22f144c2017-06-12 14:26:21 -04004479
SJW88ed5fe2020-05-11 12:40:57 -05004480 replaceSPIRVInst(Placeholder, spv::OpSelectionMerge, Ops);
4481
4482 nextDeferred();
David Neto22f144c2017-06-12 14:26:21 -04004483 }
4484
4485 if (Br->isConditional()) {
4486 //
4487 // Generate OpBranchConditional.
4488 //
4489 // Ops[0] = Condition ID
4490 // Ops[1] = True Label ID
4491 // Ops[2] = False Label ID
4492 // Ops[3] ... Ops[n] = Branch weights (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05004493 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004494
SJW01901d92020-05-21 08:58:31 -05004495 Ops << Br->getCondition() << Br->getSuccessor(0) << Br->getSuccessor(1);
David Neto22f144c2017-06-12 14:26:21 -04004496
SJW88ed5fe2020-05-11 12:40:57 -05004497 replaceSPIRVInst(Placeholder, spv::OpBranchConditional, Ops);
4498
David Neto22f144c2017-06-12 14:26:21 -04004499 } else {
4500 //
4501 // Generate OpBranch.
4502 //
4503 // Ops[0] = Target Label ID
SJWf93f5f32020-05-05 07:27:56 -05004504 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004505
SJW01901d92020-05-21 08:58:31 -05004506 Ops << Br->getSuccessor(0);
David Neto22f144c2017-06-12 14:26:21 -04004507
SJW88ed5fe2020-05-11 12:40:57 -05004508 replaceSPIRVInst(Placeholder, spv::OpBranch, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004509 }
4510 } else if (PHINode *PHI = dyn_cast<PHINode>(Inst)) {
alan-baker5ed87542020-03-23 11:05:22 -04004511 if (PHI->getType()->isPointerTy() && !IsSamplerType(PHI->getType()) &&
4512 !IsImageType(PHI->getType())) {
alan-baker5b86ed72019-02-15 08:26:50 -05004513 // OpPhi on pointers requires variable pointers.
4514 setVariablePointersCapabilities(
4515 PHI->getType()->getPointerAddressSpace());
4516 if (!hasVariablePointers() && !selectFromSameObject(PHI)) {
SJW01901d92020-05-21 08:58:31 -05004517 setVariablePointers();
alan-baker5b86ed72019-02-15 08:26:50 -05004518 }
4519 }
4520
David Neto22f144c2017-06-12 14:26:21 -04004521 //
4522 // Generate OpPhi.
4523 //
4524 // Ops[0] = Result Type ID
4525 // Ops[1] ... Ops[n] = (Variable ID, Parent ID) pairs
SJWf93f5f32020-05-05 07:27:56 -05004526 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004527
SJW01901d92020-05-21 08:58:31 -05004528 Ops << PHI->getType();
David Neto22f144c2017-06-12 14:26:21 -04004529
SJW88ed5fe2020-05-11 12:40:57 -05004530 for (unsigned j = 0; j < PHI->getNumIncomingValues(); j++) {
SJW01901d92020-05-21 08:58:31 -05004531 Ops << PHI->getIncomingValue(j) << PHI->getIncomingBlock(j);
David Neto22f144c2017-06-12 14:26:21 -04004532 }
4533
SJW88ed5fe2020-05-11 12:40:57 -05004534 replaceSPIRVInst(Placeholder, spv::OpPhi, Ops);
4535
David Neto22f144c2017-06-12 14:26:21 -04004536 } else if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
4537 Function *Callee = Call->getCalledFunction();
David Neto3fbb4072017-10-16 11:28:14 -04004538 auto callee_name = Callee->getName();
David Neto22f144c2017-06-12 14:26:21 -04004539
SJW61531372020-06-09 07:31:08 -05004540 if (Builtins::Lookup(Callee) == Builtins::kClspvCompositeConstruct) {
David Netoab03f432017-11-03 17:00:44 -04004541 // Generate an OpCompositeConstruct
SJWf93f5f32020-05-05 07:27:56 -05004542 SPIRVOperandVec Ops;
David Netoab03f432017-11-03 17:00:44 -04004543
4544 // The result type.
SJW01901d92020-05-21 08:58:31 -05004545 Ops << Call->getType();
David Netoab03f432017-11-03 17:00:44 -04004546
4547 for (Use &use : Call->arg_operands()) {
SJW01901d92020-05-21 08:58:31 -05004548 Ops << use.get();
David Netoab03f432017-11-03 17:00:44 -04004549 }
4550
SJW88ed5fe2020-05-11 12:40:57 -05004551 replaceSPIRVInst(Placeholder, spv::OpCompositeConstruct, Ops);
David Netoab03f432017-11-03 17:00:44 -04004552
David Neto22f144c2017-06-12 14:26:21 -04004553 } else {
alan-baker5b86ed72019-02-15 08:26:50 -05004554 if (Call->getType()->isPointerTy()) {
4555 // Functions returning pointers require variable pointers.
4556 setVariablePointersCapabilities(
4557 Call->getType()->getPointerAddressSpace());
4558 }
4559
David Neto22f144c2017-06-12 14:26:21 -04004560 //
4561 // Generate OpFunctionCall.
4562 //
4563
4564 // Ops[0] = Result Type ID
4565 // Ops[1] = Callee Function ID
4566 // Ops[2] ... Ops[n] = Argument 0, ... , Argument n
SJWf93f5f32020-05-05 07:27:56 -05004567 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004568
SJW01901d92020-05-21 08:58:31 -05004569 Ops << Call->getType();
David Neto22f144c2017-06-12 14:26:21 -04004570
SJW01901d92020-05-21 08:58:31 -05004571 SPIRVID CalleeID = getSPIRVValue(Callee);
SJW806a5d82020-07-15 12:51:38 -05004572 if (!CalleeID.isValid()) {
David Neto43568eb2017-10-13 18:25:25 -04004573 errs() << "Can't translate function call. Missing builtin? "
David Neto862b7d82018-06-14 18:48:37 -04004574 << callee_name << " in: " << *Call << "\n";
David Neto43568eb2017-10-13 18:25:25 -04004575 // TODO(dneto): Can we error out? Enabling this llvm_unreachable
4576 // causes an infinite loop. Instead, go ahead and generate
4577 // the bad function call. A validator will catch the 0-Id.
4578 // llvm_unreachable("Can't translate function call");
4579 }
David Neto22f144c2017-06-12 14:26:21 -04004580
SJW01901d92020-05-21 08:58:31 -05004581 Ops << CalleeID;
David Neto22f144c2017-06-12 14:26:21 -04004582
David Neto22f144c2017-06-12 14:26:21 -04004583 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
SJW88ed5fe2020-05-11 12:40:57 -05004584 for (unsigned j = 0; j < CalleeFTy->getNumParams(); j++) {
4585 auto *operand = Call->getOperand(j);
alan-bakerd4d50652019-12-03 17:17:15 -05004586 auto *operand_type = operand->getType();
4587 // Images and samplers can be passed as function parameters without
4588 // variable pointers.
4589 if (operand_type->isPointerTy() && !IsImageType(operand_type) &&
4590 !IsSamplerType(operand_type)) {
alan-baker5b86ed72019-02-15 08:26:50 -05004591 auto sc =
4592 GetStorageClass(operand->getType()->getPointerAddressSpace());
4593 if (sc == spv::StorageClassStorageBuffer) {
4594 // Passing SSBO by reference requires variable pointers storage
4595 // buffer.
SJW01901d92020-05-21 08:58:31 -05004596 setVariablePointersStorageBuffer();
alan-baker5b86ed72019-02-15 08:26:50 -05004597 } else if (sc == spv::StorageClassWorkgroup) {
4598 // Workgroup references require variable pointers if they are not
4599 // memory object declarations.
4600 if (auto *operand_call = dyn_cast<CallInst>(operand)) {
4601 // Workgroup accessor represents a variable reference.
SJW61531372020-06-09 07:31:08 -05004602 if (Builtins::Lookup(operand_call->getCalledFunction()) !=
4603 Builtins::kClspvLocal)
SJW01901d92020-05-21 08:58:31 -05004604 setVariablePointers();
alan-baker5b86ed72019-02-15 08:26:50 -05004605 } else {
4606 // Arguments are function parameters.
4607 if (!isa<Argument>(operand))
SJW01901d92020-05-21 08:58:31 -05004608 setVariablePointers();
alan-baker5b86ed72019-02-15 08:26:50 -05004609 }
4610 }
4611 }
SJW01901d92020-05-21 08:58:31 -05004612 Ops << operand;
David Neto22f144c2017-06-12 14:26:21 -04004613 }
4614
SJW88ed5fe2020-05-11 12:40:57 -05004615 replaceSPIRVInst(Placeholder, spv::OpFunctionCall, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004616 }
4617 }
4618 }
4619}
4620
SJW77b87ad2020-04-21 14:37:52 -05004621void SPIRVProducerPass::HandleDeferredDecorations() {
4622 const auto &DL = module->getDataLayout();
alan-baker5a8c3be2020-09-09 13:44:26 -04004623 if (getTypesNeedingArrayStride().empty()) {
David Neto1a1a0582017-07-07 12:01:44 -04004624 return;
David Netoc6f3ab22018-04-06 18:02:31 -04004625 }
David Neto1a1a0582017-07-07 12:01:44 -04004626
David Netoc6f3ab22018-04-06 18:02:31 -04004627 // Insert ArrayStride decorations on pointer types, due to OpPtrAccessChain
4628 // instructions we generated earlier.
David Neto85082642018-03-24 06:55:20 -07004629 for (auto *type : getTypesNeedingArrayStride()) {
4630 Type *elemTy = nullptr;
4631 if (auto *ptrTy = dyn_cast<PointerType>(type)) {
4632 elemTy = ptrTy->getElementType();
alan-bakerb6b09dc2018-11-08 16:59:28 -05004633 } else if (auto *arrayTy = dyn_cast<ArrayType>(type)) {
alan-baker8eb435a2020-04-08 00:42:06 -04004634 elemTy = arrayTy->getElementType();
4635 } else if (auto *vecTy = dyn_cast<VectorType>(type)) {
4636 elemTy = vecTy->getElementType();
David Neto85082642018-03-24 06:55:20 -07004637 } else {
4638 errs() << "Unhandled strided type " << *type << "\n";
4639 llvm_unreachable("Unhandled strided type");
4640 }
David Neto1a1a0582017-07-07 12:01:44 -04004641
4642 // Ops[0] = Target ID
4643 // Ops[1] = Decoration (ArrayStride)
4644 // Ops[2] = Stride number (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05004645 SPIRVOperandVec Ops;
David Neto1a1a0582017-07-07 12:01:44 -04004646
David Neto85082642018-03-24 06:55:20 -07004647 // Same as DL.getIndexedOffsetInType( elemTy, { 1 } );
Alan Bakerfcda9482018-10-02 17:09:59 -04004648 const uint32_t stride = static_cast<uint32_t>(GetTypeAllocSize(elemTy, DL));
David Neto257c3892018-04-11 13:19:45 -04004649
SJW01901d92020-05-21 08:58:31 -05004650 Ops << type << spv::DecorationArrayStride << stride;
David Neto1a1a0582017-07-07 12:01:44 -04004651
SJWf93f5f32020-05-05 07:27:56 -05004652 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Netoc6f3ab22018-04-06 18:02:31 -04004653 }
David Neto1a1a0582017-07-07 12:01:44 -04004654}
4655
SJW61531372020-06-09 07:31:08 -05004656glsl::ExtInst
4657SPIRVProducerPass::getExtInstEnum(const Builtins::FunctionInfo &func_info) {
SJW61531372020-06-09 07:31:08 -05004658 switch (func_info.getType()) {
SJW2c317da2020-03-23 07:39:13 -05004659 case Builtins::kClamp: {
SJW61531372020-06-09 07:31:08 -05004660 auto param_type = func_info.getParameter(0);
SJW2c317da2020-03-23 07:39:13 -05004661 if (param_type.type_id == Type::FloatTyID) {
4662 return glsl::ExtInst::ExtInstFClamp;
4663 }
4664 return param_type.is_signed ? glsl::ExtInst::ExtInstSClamp
4665 : glsl::ExtInst::ExtInstUClamp;
4666 }
4667 case Builtins::kMax: {
SJW61531372020-06-09 07:31:08 -05004668 auto param_type = func_info.getParameter(0);
SJW2c317da2020-03-23 07:39:13 -05004669 if (param_type.type_id == Type::FloatTyID) {
4670 return glsl::ExtInst::ExtInstFMax;
4671 }
4672 return param_type.is_signed ? glsl::ExtInst::ExtInstSMax
4673 : glsl::ExtInst::ExtInstUMax;
4674 }
4675 case Builtins::kMin: {
SJW61531372020-06-09 07:31:08 -05004676 auto param_type = func_info.getParameter(0);
SJW2c317da2020-03-23 07:39:13 -05004677 if (param_type.type_id == Type::FloatTyID) {
4678 return glsl::ExtInst::ExtInstFMin;
4679 }
4680 return param_type.is_signed ? glsl::ExtInst::ExtInstSMin
4681 : glsl::ExtInst::ExtInstUMin;
4682 }
4683 case Builtins::kAbs:
4684 return glsl::ExtInst::ExtInstSAbs;
4685 case Builtins::kFmax:
Marco Antognini55d51862020-07-21 17:50:07 +01004686 return glsl::ExtInst::ExtInstNMax;
SJW2c317da2020-03-23 07:39:13 -05004687 case Builtins::kFmin:
Marco Antognini55d51862020-07-21 17:50:07 +01004688 return glsl::ExtInst::ExtInstNMin;
SJW2c317da2020-03-23 07:39:13 -05004689 case Builtins::kDegrees:
4690 return glsl::ExtInst::ExtInstDegrees;
4691 case Builtins::kRadians:
4692 return glsl::ExtInst::ExtInstRadians;
4693 case Builtins::kMix:
4694 return glsl::ExtInst::ExtInstFMix;
4695 case Builtins::kAcos:
4696 case Builtins::kAcospi:
4697 return glsl::ExtInst::ExtInstAcos;
4698 case Builtins::kAcosh:
4699 return glsl::ExtInst::ExtInstAcosh;
4700 case Builtins::kAsin:
4701 case Builtins::kAsinpi:
4702 return glsl::ExtInst::ExtInstAsin;
4703 case Builtins::kAsinh:
4704 return glsl::ExtInst::ExtInstAsinh;
4705 case Builtins::kAtan:
4706 case Builtins::kAtanpi:
4707 return glsl::ExtInst::ExtInstAtan;
4708 case Builtins::kAtanh:
4709 return glsl::ExtInst::ExtInstAtanh;
4710 case Builtins::kAtan2:
4711 case Builtins::kAtan2pi:
4712 return glsl::ExtInst::ExtInstAtan2;
4713 case Builtins::kCeil:
4714 return glsl::ExtInst::ExtInstCeil;
4715 case Builtins::kSin:
4716 case Builtins::kHalfSin:
4717 case Builtins::kNativeSin:
4718 return glsl::ExtInst::ExtInstSin;
4719 case Builtins::kSinh:
4720 return glsl::ExtInst::ExtInstSinh;
4721 case Builtins::kCos:
4722 case Builtins::kHalfCos:
4723 case Builtins::kNativeCos:
4724 return glsl::ExtInst::ExtInstCos;
4725 case Builtins::kCosh:
4726 return glsl::ExtInst::ExtInstCosh;
4727 case Builtins::kTan:
4728 case Builtins::kHalfTan:
4729 case Builtins::kNativeTan:
4730 return glsl::ExtInst::ExtInstTan;
4731 case Builtins::kTanh:
4732 return glsl::ExtInst::ExtInstTanh;
4733 case Builtins::kExp:
4734 case Builtins::kHalfExp:
4735 case Builtins::kNativeExp:
4736 return glsl::ExtInst::ExtInstExp;
4737 case Builtins::kExp2:
4738 case Builtins::kHalfExp2:
4739 case Builtins::kNativeExp2:
4740 return glsl::ExtInst::ExtInstExp2;
4741 case Builtins::kLog:
4742 case Builtins::kHalfLog:
4743 case Builtins::kNativeLog:
4744 return glsl::ExtInst::ExtInstLog;
4745 case Builtins::kLog2:
4746 case Builtins::kHalfLog2:
4747 case Builtins::kNativeLog2:
4748 return glsl::ExtInst::ExtInstLog2;
4749 case Builtins::kFabs:
4750 return glsl::ExtInst::ExtInstFAbs;
4751 case Builtins::kFma:
4752 return glsl::ExtInst::ExtInstFma;
4753 case Builtins::kFloor:
4754 return glsl::ExtInst::ExtInstFloor;
4755 case Builtins::kLdexp:
4756 return glsl::ExtInst::ExtInstLdexp;
4757 case Builtins::kPow:
4758 case Builtins::kPowr:
4759 case Builtins::kHalfPowr:
4760 case Builtins::kNativePowr:
4761 return glsl::ExtInst::ExtInstPow;
James Price38553362020-09-03 18:30:40 -04004762 case Builtins::kRint:
4763 return glsl::ExtInst::ExtInstRoundEven;
SJW2c317da2020-03-23 07:39:13 -05004764 case Builtins::kRound:
4765 return glsl::ExtInst::ExtInstRound;
4766 case Builtins::kSqrt:
4767 case Builtins::kHalfSqrt:
4768 case Builtins::kNativeSqrt:
4769 return glsl::ExtInst::ExtInstSqrt;
4770 case Builtins::kRsqrt:
4771 case Builtins::kHalfRsqrt:
4772 case Builtins::kNativeRsqrt:
4773 return glsl::ExtInst::ExtInstInverseSqrt;
4774 case Builtins::kTrunc:
4775 return glsl::ExtInst::ExtInstTrunc;
4776 case Builtins::kFrexp:
4777 return glsl::ExtInst::ExtInstFrexp;
SJW61531372020-06-09 07:31:08 -05004778 case Builtins::kClspvFract:
SJW2c317da2020-03-23 07:39:13 -05004779 case Builtins::kFract:
4780 return glsl::ExtInst::ExtInstFract;
4781 case Builtins::kSign:
4782 return glsl::ExtInst::ExtInstFSign;
4783 case Builtins::kLength:
4784 case Builtins::kFastLength:
4785 return glsl::ExtInst::ExtInstLength;
4786 case Builtins::kDistance:
4787 case Builtins::kFastDistance:
4788 return glsl::ExtInst::ExtInstDistance;
4789 case Builtins::kStep:
4790 return glsl::ExtInst::ExtInstStep;
4791 case Builtins::kSmoothstep:
4792 return glsl::ExtInst::ExtInstSmoothStep;
4793 case Builtins::kCross:
4794 return glsl::ExtInst::ExtInstCross;
4795 case Builtins::kNormalize:
4796 case Builtins::kFastNormalize:
4797 return glsl::ExtInst::ExtInstNormalize;
SJW61531372020-06-09 07:31:08 -05004798 case Builtins::kSpirvPack:
4799 return glsl::ExtInst::ExtInstPackHalf2x16;
4800 case Builtins::kSpirvUnpack:
4801 return glsl::ExtInst::ExtInstUnpackHalf2x16;
SJW2c317da2020-03-23 07:39:13 -05004802 default:
4803 break;
4804 }
4805
SJW61531372020-06-09 07:31:08 -05004806 if (func_info.getName().find("llvm.fmuladd.") == 0) {
4807 return glsl::ExtInst::ExtInstFma;
4808 }
4809 return kGlslExtInstBad;
David Neto3fbb4072017-10-16 11:28:14 -04004810}
4811
SJW61531372020-06-09 07:31:08 -05004812glsl::ExtInst SPIRVProducerPass::getIndirectExtInstEnum(
4813 const Builtins::FunctionInfo &func_info) {
4814 switch (func_info.getType()) {
SJW2c317da2020-03-23 07:39:13 -05004815 case Builtins::kClz:
4816 return glsl::ExtInst::ExtInstFindUMsb;
4817 case Builtins::kAcospi:
4818 return glsl::ExtInst::ExtInstAcos;
4819 case Builtins::kAsinpi:
4820 return glsl::ExtInst::ExtInstAsin;
4821 case Builtins::kAtanpi:
4822 return glsl::ExtInst::ExtInstAtan;
4823 case Builtins::kAtan2pi:
4824 return glsl::ExtInst::ExtInstAtan2;
4825 default:
4826 break;
4827 }
4828 return kGlslExtInstBad;
David Neto3fbb4072017-10-16 11:28:14 -04004829}
4830
SJW61531372020-06-09 07:31:08 -05004831glsl::ExtInst SPIRVProducerPass::getDirectOrIndirectExtInstEnum(
4832 const Builtins::FunctionInfo &func_info) {
4833 auto direct = getExtInstEnum(func_info);
David Neto3fbb4072017-10-16 11:28:14 -04004834 if (direct != kGlslExtInstBad)
4835 return direct;
SJW61531372020-06-09 07:31:08 -05004836 return getIndirectExtInstEnum(func_info);
David Neto22f144c2017-06-12 14:26:21 -04004837}
4838
David Neto22f144c2017-06-12 14:26:21 -04004839void SPIRVProducerPass::WriteOneWord(uint32_t Word) {
David Neto0676e6f2017-07-11 18:47:44 -04004840 binaryOut->write(reinterpret_cast<const char *>(&Word), sizeof(uint32_t));
David Neto22f144c2017-06-12 14:26:21 -04004841}
4842
SJW88ed5fe2020-05-11 12:40:57 -05004843void SPIRVProducerPass::WriteResultID(const SPIRVInstruction &Inst) {
SJW01901d92020-05-21 08:58:31 -05004844 WriteOneWord(Inst.getResultID().get());
David Neto22f144c2017-06-12 14:26:21 -04004845}
4846
SJW88ed5fe2020-05-11 12:40:57 -05004847void SPIRVProducerPass::WriteWordCountAndOpcode(const SPIRVInstruction &Inst) {
David Neto22f144c2017-06-12 14:26:21 -04004848 // High 16 bit : Word Count
4849 // Low 16 bit : Opcode
SJW88ed5fe2020-05-11 12:40:57 -05004850 uint32_t Word = Inst.getOpcode();
4851 const uint32_t count = Inst.getWordCount();
David Netoee2660d2018-06-28 16:31:29 -04004852 if (count > 65535) {
4853 errs() << "Word count limit of 65535 exceeded: " << count << "\n";
4854 llvm_unreachable("Word count too high");
4855 }
SJW88ed5fe2020-05-11 12:40:57 -05004856 Word |= Inst.getWordCount() << 16;
David Neto22f144c2017-06-12 14:26:21 -04004857 WriteOneWord(Word);
4858}
4859
SJW88ed5fe2020-05-11 12:40:57 -05004860void SPIRVProducerPass::WriteOperand(const SPIRVOperand &Op) {
4861 SPIRVOperandType OpTy = Op.getType();
David Neto22f144c2017-06-12 14:26:21 -04004862 switch (OpTy) {
4863 default: {
4864 llvm_unreachable("Unsupported SPIRV Operand Type???");
4865 break;
4866 }
4867 case SPIRVOperandType::NUMBERID: {
SJW88ed5fe2020-05-11 12:40:57 -05004868 WriteOneWord(Op.getNumID());
David Neto22f144c2017-06-12 14:26:21 -04004869 break;
4870 }
4871 case SPIRVOperandType::LITERAL_STRING: {
SJW88ed5fe2020-05-11 12:40:57 -05004872 std::string Str = Op.getLiteralStr();
David Neto22f144c2017-06-12 14:26:21 -04004873 const char *Data = Str.c_str();
4874 size_t WordSize = Str.size() / 4;
4875 for (unsigned Idx = 0; Idx < WordSize; Idx++) {
4876 WriteOneWord(*reinterpret_cast<const uint32_t *>(&Data[4 * Idx]));
4877 }
4878
4879 uint32_t Remainder = Str.size() % 4;
4880 uint32_t LastWord = 0;
4881 if (Remainder) {
4882 for (unsigned Idx = 0; Idx < Remainder; Idx++) {
4883 LastWord |= Data[4 * WordSize + Idx] << 8 * Idx;
4884 }
4885 }
4886
4887 WriteOneWord(LastWord);
4888 break;
4889 }
SJW88ed5fe2020-05-11 12:40:57 -05004890 case SPIRVOperandType::LITERAL_WORD: {
4891 WriteOneWord(Op.getLiteralNum()[0]);
4892 break;
4893 }
4894 case SPIRVOperandType::LITERAL_DWORD: {
4895 WriteOneWord(Op.getLiteralNum()[0]);
4896 WriteOneWord(Op.getLiteralNum()[1]);
David Neto22f144c2017-06-12 14:26:21 -04004897 break;
4898 }
4899 }
4900}
4901
4902void SPIRVProducerPass::WriteSPIRVBinary() {
SJW69939d52020-04-16 07:29:07 -05004903 for (int i = 0; i < kSectionCount; ++i) {
4904 WriteSPIRVBinary(SPIRVSections[i]);
4905 }
4906}
4907
4908void SPIRVProducerPass::WriteSPIRVBinary(SPIRVInstructionList &SPIRVInstList) {
SJW88ed5fe2020-05-11 12:40:57 -05004909 for (const auto &Inst : SPIRVInstList) {
4910 const auto &Ops = Inst.getOperands();
4911 spv::Op Opcode = static_cast<spv::Op>(Inst.getOpcode());
David Neto22f144c2017-06-12 14:26:21 -04004912
4913 switch (Opcode) {
4914 default: {
David Neto5c22a252018-03-15 16:07:41 -04004915 errs() << "Unsupported SPIR-V instruction opcode " << int(Opcode) << "\n";
David Neto22f144c2017-06-12 14:26:21 -04004916 llvm_unreachable("Unsupported SPIRV instruction");
4917 break;
4918 }
Marco Antognini68e5c512020-09-09 16:08:57 +01004919 case spv::OpUnreachable:
David Neto22f144c2017-06-12 14:26:21 -04004920 case spv::OpCapability:
4921 case spv::OpExtension:
4922 case spv::OpMemoryModel:
4923 case spv::OpEntryPoint:
4924 case spv::OpExecutionMode:
4925 case spv::OpSource:
4926 case spv::OpDecorate:
4927 case spv::OpMemberDecorate:
4928 case spv::OpBranch:
4929 case spv::OpBranchConditional:
4930 case spv::OpSelectionMerge:
4931 case spv::OpLoopMerge:
4932 case spv::OpStore:
4933 case spv::OpImageWrite:
4934 case spv::OpReturnValue:
4935 case spv::OpControlBarrier:
4936 case spv::OpMemoryBarrier:
4937 case spv::OpReturn:
4938 case spv::OpFunctionEnd:
4939 case spv::OpCopyMemory: {
4940 WriteWordCountAndOpcode(Inst);
4941 for (uint32_t i = 0; i < Ops.size(); i++) {
4942 WriteOperand(Ops[i]);
4943 }
4944 break;
4945 }
4946 case spv::OpTypeBool:
4947 case spv::OpTypeVoid:
4948 case spv::OpTypeSampler:
4949 case spv::OpLabel:
4950 case spv::OpExtInstImport:
4951 case spv::OpTypePointer:
4952 case spv::OpTypeRuntimeArray:
4953 case spv::OpTypeStruct:
4954 case spv::OpTypeImage:
4955 case spv::OpTypeSampledImage:
4956 case spv::OpTypeInt:
4957 case spv::OpTypeFloat:
4958 case spv::OpTypeArray:
4959 case spv::OpTypeVector:
alan-baker86ce19c2020-08-05 13:09:19 -04004960 case spv::OpTypeFunction:
4961 case spv::OpString: {
David Neto22f144c2017-06-12 14:26:21 -04004962 WriteWordCountAndOpcode(Inst);
4963 WriteResultID(Inst);
4964 for (uint32_t i = 0; i < Ops.size(); i++) {
4965 WriteOperand(Ops[i]);
4966 }
4967 break;
4968 }
4969 case spv::OpFunction:
4970 case spv::OpFunctionParameter:
4971 case spv::OpAccessChain:
4972 case spv::OpPtrAccessChain:
4973 case spv::OpInBoundsAccessChain:
4974 case spv::OpUConvert:
4975 case spv::OpSConvert:
4976 case spv::OpConvertFToU:
4977 case spv::OpConvertFToS:
4978 case spv::OpConvertUToF:
4979 case spv::OpConvertSToF:
4980 case spv::OpFConvert:
4981 case spv::OpConvertPtrToU:
4982 case spv::OpConvertUToPtr:
4983 case spv::OpBitcast:
alan-bakerc9c55ae2019-12-02 16:01:27 -05004984 case spv::OpFNegate:
David Neto22f144c2017-06-12 14:26:21 -04004985 case spv::OpIAdd:
4986 case spv::OpFAdd:
4987 case spv::OpISub:
4988 case spv::OpFSub:
4989 case spv::OpIMul:
4990 case spv::OpFMul:
4991 case spv::OpUDiv:
4992 case spv::OpSDiv:
4993 case spv::OpFDiv:
4994 case spv::OpUMod:
4995 case spv::OpSRem:
4996 case spv::OpFRem:
Kévin Petit8a560882019-03-21 15:24:34 +00004997 case spv::OpUMulExtended:
4998 case spv::OpSMulExtended:
David Neto22f144c2017-06-12 14:26:21 -04004999 case spv::OpBitwiseOr:
5000 case spv::OpBitwiseXor:
5001 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04005002 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04005003 case spv::OpShiftLeftLogical:
5004 case spv::OpShiftRightLogical:
5005 case spv::OpShiftRightArithmetic:
5006 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04005007 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04005008 case spv::OpCompositeExtract:
5009 case spv::OpVectorExtractDynamic:
5010 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04005011 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04005012 case spv::OpVectorInsertDynamic:
5013 case spv::OpVectorShuffle:
5014 case spv::OpIEqual:
5015 case spv::OpINotEqual:
5016 case spv::OpUGreaterThan:
5017 case spv::OpUGreaterThanEqual:
5018 case spv::OpULessThan:
5019 case spv::OpULessThanEqual:
5020 case spv::OpSGreaterThan:
5021 case spv::OpSGreaterThanEqual:
5022 case spv::OpSLessThan:
5023 case spv::OpSLessThanEqual:
5024 case spv::OpFOrdEqual:
5025 case spv::OpFOrdGreaterThan:
5026 case spv::OpFOrdGreaterThanEqual:
5027 case spv::OpFOrdLessThan:
5028 case spv::OpFOrdLessThanEqual:
5029 case spv::OpFOrdNotEqual:
5030 case spv::OpFUnordEqual:
5031 case spv::OpFUnordGreaterThan:
5032 case spv::OpFUnordGreaterThanEqual:
5033 case spv::OpFUnordLessThan:
5034 case spv::OpFUnordLessThanEqual:
5035 case spv::OpFUnordNotEqual:
5036 case spv::OpExtInst:
5037 case spv::OpIsInf:
5038 case spv::OpIsNan:
5039 case spv::OpAny:
5040 case spv::OpAll:
5041 case spv::OpUndef:
5042 case spv::OpConstantNull:
5043 case spv::OpLogicalOr:
5044 case spv::OpLogicalAnd:
5045 case spv::OpLogicalNot:
5046 case spv::OpLogicalNotEqual:
5047 case spv::OpConstantComposite:
5048 case spv::OpSpecConstantComposite:
5049 case spv::OpConstantTrue:
5050 case spv::OpConstantFalse:
5051 case spv::OpConstant:
5052 case spv::OpSpecConstant:
5053 case spv::OpVariable:
5054 case spv::OpFunctionCall:
5055 case spv::OpSampledImage:
alan-baker75090e42020-02-20 11:21:04 -05005056 case spv::OpImageFetch:
David Neto22f144c2017-06-12 14:26:21 -04005057 case spv::OpImageSampleExplicitLod:
David Neto5c22a252018-03-15 16:07:41 -04005058 case spv::OpImageQuerySize:
alan-bakerce179f12019-12-06 19:02:22 -05005059 case spv::OpImageQuerySizeLod:
David Neto22f144c2017-06-12 14:26:21 -04005060 case spv::OpSelect:
5061 case spv::OpPhi:
5062 case spv::OpLoad:
5063 case spv::OpAtomicIAdd:
5064 case spv::OpAtomicISub:
5065 case spv::OpAtomicExchange:
5066 case spv::OpAtomicIIncrement:
5067 case spv::OpAtomicIDecrement:
5068 case spv::OpAtomicCompareExchange:
5069 case spv::OpAtomicUMin:
5070 case spv::OpAtomicSMin:
5071 case spv::OpAtomicUMax:
5072 case spv::OpAtomicSMax:
5073 case spv::OpAtomicAnd:
5074 case spv::OpAtomicOr:
5075 case spv::OpAtomicXor:
SJW806a5d82020-07-15 12:51:38 -05005076 case spv::OpDot:
5077 case spv::OpGroupNonUniformAll:
5078 case spv::OpGroupNonUniformAny:
5079 case spv::OpGroupNonUniformBroadcast:
5080 case spv::OpGroupNonUniformIAdd:
5081 case spv::OpGroupNonUniformFAdd:
5082 case spv::OpGroupNonUniformSMin:
5083 case spv::OpGroupNonUniformUMin:
5084 case spv::OpGroupNonUniformFMin:
5085 case spv::OpGroupNonUniformSMax:
5086 case spv::OpGroupNonUniformUMax:
5087 case spv::OpGroupNonUniformFMax: {
David Neto22f144c2017-06-12 14:26:21 -04005088 WriteWordCountAndOpcode(Inst);
5089 WriteOperand(Ops[0]);
5090 WriteResultID(Inst);
5091 for (uint32_t i = 1; i < Ops.size(); i++) {
5092 WriteOperand(Ops[i]);
5093 }
5094 break;
5095 }
5096 }
5097 }
5098}
Alan Baker9bf93fb2018-08-28 16:59:26 -04005099
alan-bakerb6b09dc2018-11-08 16:59:28 -05005100bool SPIRVProducerPass::IsTypeNullable(const Type *type) const {
Alan Baker9bf93fb2018-08-28 16:59:26 -04005101 switch (type->getTypeID()) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05005102 case Type::HalfTyID:
5103 case Type::FloatTyID:
5104 case Type::DoubleTyID:
5105 case Type::IntegerTyID:
James Price59a1c752020-04-23 23:06:16 -04005106 case Type::FixedVectorTyID:
alan-bakerb6b09dc2018-11-08 16:59:28 -05005107 return true;
5108 case Type::PointerTyID: {
5109 const PointerType *pointer_type = cast<PointerType>(type);
5110 if (pointer_type->getPointerAddressSpace() !=
5111 AddressSpace::UniformConstant) {
5112 auto pointee_type = pointer_type->getPointerElementType();
5113 if (pointee_type->isStructTy() &&
5114 cast<StructType>(pointee_type)->isOpaque()) {
5115 // Images and samplers are not nullable.
5116 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04005117 }
Alan Baker9bf93fb2018-08-28 16:59:26 -04005118 }
alan-bakerb6b09dc2018-11-08 16:59:28 -05005119 return true;
5120 }
5121 case Type::ArrayTyID:
alan-baker8eb435a2020-04-08 00:42:06 -04005122 return IsTypeNullable(type->getArrayElementType());
alan-bakerb6b09dc2018-11-08 16:59:28 -05005123 case Type::StructTyID: {
5124 const StructType *struct_type = cast<StructType>(type);
5125 // Images and samplers are not nullable.
5126 if (struct_type->isOpaque())
Alan Baker9bf93fb2018-08-28 16:59:26 -04005127 return false;
alan-bakerb6b09dc2018-11-08 16:59:28 -05005128 for (const auto element : struct_type->elements()) {
5129 if (!IsTypeNullable(element))
5130 return false;
5131 }
5132 return true;
5133 }
5134 default:
5135 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04005136 }
5137}
Alan Bakerfcda9482018-10-02 17:09:59 -04005138
SJW77b87ad2020-04-21 14:37:52 -05005139void SPIRVProducerPass::PopulateUBOTypeMaps() {
Alan Bakerfcda9482018-10-02 17:09:59 -04005140 if (auto *offsets_md =
SJW77b87ad2020-04-21 14:37:52 -05005141 module->getNamedMetadata(clspv::RemappedTypeOffsetMetadataName())) {
Alan Bakerfcda9482018-10-02 17:09:59 -04005142 // Metdata is stored as key-value pair operands. The first element of each
5143 // operand is the type and the second is a vector of offsets.
5144 for (const auto *operand : offsets_md->operands()) {
5145 const auto *pair = cast<MDTuple>(operand);
5146 auto *type =
5147 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
5148 const auto *offset_vector = cast<MDTuple>(pair->getOperand(1));
5149 std::vector<uint32_t> offsets;
5150 for (const Metadata *offset_md : offset_vector->operands()) {
5151 const auto *constant_md = cast<ConstantAsMetadata>(offset_md);
alan-bakerb6b09dc2018-11-08 16:59:28 -05005152 offsets.push_back(static_cast<uint32_t>(
5153 cast<ConstantInt>(constant_md->getValue())->getZExtValue()));
Alan Bakerfcda9482018-10-02 17:09:59 -04005154 }
5155 RemappedUBOTypeOffsets.insert(std::make_pair(type, offsets));
5156 }
5157 }
5158
5159 if (auto *sizes_md =
SJW77b87ad2020-04-21 14:37:52 -05005160 module->getNamedMetadata(clspv::RemappedTypeSizesMetadataName())) {
Alan Bakerfcda9482018-10-02 17:09:59 -04005161 // Metadata is stored as key-value pair operands. The first element of each
5162 // operand is the type and the second is a triple of sizes: type size in
5163 // bits, store size and alloc size.
5164 for (const auto *operand : sizes_md->operands()) {
5165 const auto *pair = cast<MDTuple>(operand);
5166 auto *type =
5167 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
5168 const auto *size_triple = cast<MDTuple>(pair->getOperand(1));
5169 uint64_t type_size_in_bits =
5170 cast<ConstantInt>(
5171 cast<ConstantAsMetadata>(size_triple->getOperand(0))->getValue())
5172 ->getZExtValue();
5173 uint64_t type_store_size =
5174 cast<ConstantInt>(
5175 cast<ConstantAsMetadata>(size_triple->getOperand(1))->getValue())
5176 ->getZExtValue();
5177 uint64_t type_alloc_size =
5178 cast<ConstantInt>(
5179 cast<ConstantAsMetadata>(size_triple->getOperand(2))->getValue())
5180 ->getZExtValue();
5181 RemappedUBOTypeSizes.insert(std::make_pair(
5182 type, std::make_tuple(type_size_in_bits, type_store_size,
5183 type_alloc_size)));
5184 }
5185 }
5186}
5187
5188uint64_t SPIRVProducerPass::GetTypeSizeInBits(Type *type,
5189 const DataLayout &DL) {
5190 auto iter = RemappedUBOTypeSizes.find(type);
5191 if (iter != RemappedUBOTypeSizes.end()) {
5192 return std::get<0>(iter->second);
5193 }
5194
5195 return DL.getTypeSizeInBits(type);
5196}
5197
5198uint64_t SPIRVProducerPass::GetTypeStoreSize(Type *type, const DataLayout &DL) {
5199 auto iter = RemappedUBOTypeSizes.find(type);
5200 if (iter != RemappedUBOTypeSizes.end()) {
5201 return std::get<1>(iter->second);
5202 }
5203
5204 return DL.getTypeStoreSize(type);
5205}
5206
5207uint64_t SPIRVProducerPass::GetTypeAllocSize(Type *type, const DataLayout &DL) {
5208 auto iter = RemappedUBOTypeSizes.find(type);
5209 if (iter != RemappedUBOTypeSizes.end()) {
5210 return std::get<2>(iter->second);
5211 }
5212
5213 return DL.getTypeAllocSize(type);
5214}
alan-baker5b86ed72019-02-15 08:26:50 -05005215
Kévin Petitbbbda972020-03-03 19:16:31 +00005216uint32_t SPIRVProducerPass::GetExplicitLayoutStructMemberOffset(
5217 StructType *type, unsigned member, const DataLayout &DL) {
5218 const auto StructLayout = DL.getStructLayout(type);
5219 // Search for the correct offsets if this type was remapped.
5220 std::vector<uint32_t> *offsets = nullptr;
5221 auto iter = RemappedUBOTypeOffsets.find(type);
5222 if (iter != RemappedUBOTypeOffsets.end()) {
5223 offsets = &iter->second;
5224 }
5225 auto ByteOffset =
5226 static_cast<uint32_t>(StructLayout->getElementOffset(member));
5227 if (offsets) {
5228 ByteOffset = (*offsets)[member];
5229 }
5230
5231 return ByteOffset;
5232}
5233
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04005234void SPIRVProducerPass::setVariablePointersCapabilities(
5235 unsigned address_space) {
alan-baker5b86ed72019-02-15 08:26:50 -05005236 if (GetStorageClass(address_space) == spv::StorageClassStorageBuffer) {
SJW01901d92020-05-21 08:58:31 -05005237 setVariablePointersStorageBuffer();
alan-baker5b86ed72019-02-15 08:26:50 -05005238 } else {
SJW01901d92020-05-21 08:58:31 -05005239 setVariablePointers();
alan-baker5b86ed72019-02-15 08:26:50 -05005240 }
5241}
5242
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04005243Value *SPIRVProducerPass::GetBasePointer(Value *v) {
alan-baker5b86ed72019-02-15 08:26:50 -05005244 if (auto *gep = dyn_cast<GetElementPtrInst>(v)) {
5245 return GetBasePointer(gep->getPointerOperand());
5246 }
5247
5248 // Conservatively return |v|.
5249 return v;
5250}
5251
5252bool SPIRVProducerPass::sameResource(Value *lhs, Value *rhs) const {
5253 if (auto *lhs_call = dyn_cast<CallInst>(lhs)) {
5254 if (auto *rhs_call = dyn_cast<CallInst>(rhs)) {
alan-baker7506abb2020-09-10 15:02:55 -04005255 const auto &lhs_func_info =
5256 Builtins::Lookup(lhs_call->getCalledFunction());
5257 const auto &rhs_func_info =
5258 Builtins::Lookup(rhs_call->getCalledFunction());
SJW61531372020-06-09 07:31:08 -05005259 if (lhs_func_info.getType() == Builtins::kClspvResource &&
5260 rhs_func_info.getType() == Builtins::kClspvResource) {
alan-baker5b86ed72019-02-15 08:26:50 -05005261 // For resource accessors, match descriptor set and binding.
5262 if (lhs_call->getOperand(0) == rhs_call->getOperand(0) &&
5263 lhs_call->getOperand(1) == rhs_call->getOperand(1))
5264 return true;
SJW61531372020-06-09 07:31:08 -05005265 } else if (lhs_func_info.getType() == Builtins::kClspvLocal &&
5266 rhs_func_info.getType() == Builtins::kClspvLocal) {
alan-baker5b86ed72019-02-15 08:26:50 -05005267 // For workgroup resources, match spec id.
5268 if (lhs_call->getOperand(0) == rhs_call->getOperand(0))
5269 return true;
5270 }
5271 }
5272 }
5273
5274 return false;
5275}
5276
5277bool SPIRVProducerPass::selectFromSameObject(Instruction *inst) {
5278 assert(inst->getType()->isPointerTy());
5279 assert(GetStorageClass(inst->getType()->getPointerAddressSpace()) ==
5280 spv::StorageClassStorageBuffer);
5281 const bool hack_undef = clspv::Option::HackUndef();
5282 if (auto *select = dyn_cast<SelectInst>(inst)) {
5283 auto *true_base = GetBasePointer(select->getTrueValue());
5284 auto *false_base = GetBasePointer(select->getFalseValue());
5285
5286 if (true_base == false_base)
5287 return true;
5288
5289 // If either the true or false operand is a null, then we satisfy the same
5290 // object constraint.
5291 if (auto *true_cst = dyn_cast<Constant>(true_base)) {
5292 if (true_cst->isNullValue() || (hack_undef && isa<UndefValue>(true_base)))
5293 return true;
5294 }
5295
5296 if (auto *false_cst = dyn_cast<Constant>(false_base)) {
5297 if (false_cst->isNullValue() ||
5298 (hack_undef && isa<UndefValue>(false_base)))
5299 return true;
5300 }
5301
5302 if (sameResource(true_base, false_base))
5303 return true;
5304 } else if (auto *phi = dyn_cast<PHINode>(inst)) {
5305 Value *value = nullptr;
5306 bool ok = true;
5307 for (unsigned i = 0; ok && i != phi->getNumIncomingValues(); ++i) {
5308 auto *base = GetBasePointer(phi->getIncomingValue(i));
5309 // Null values satisfy the constraint of selecting of selecting from the
5310 // same object.
5311 if (!value) {
5312 if (auto *cst = dyn_cast<Constant>(base)) {
5313 if (!cst->isNullValue() && !(hack_undef && isa<UndefValue>(base)))
5314 value = base;
5315 } else {
5316 value = base;
5317 }
5318 } else if (base != value) {
5319 if (auto *base_cst = dyn_cast<Constant>(base)) {
5320 if (base_cst->isNullValue() || (hack_undef && isa<UndefValue>(base)))
5321 continue;
5322 }
5323
5324 if (sameResource(value, base))
5325 continue;
5326
5327 // Values don't represent the same base.
5328 ok = false;
5329 }
5330 }
5331
5332 return ok;
5333 }
5334
5335 // Conservatively return false.
5336 return false;
5337}
alan-bakere9308012019-03-15 10:25:13 -04005338
5339bool SPIRVProducerPass::CalledWithCoherentResource(Argument &Arg) {
5340 if (!Arg.getType()->isPointerTy() ||
5341 Arg.getType()->getPointerAddressSpace() != clspv::AddressSpace::Global) {
5342 // Only SSBOs need to be annotated as coherent.
5343 return false;
5344 }
5345
5346 DenseSet<Value *> visited;
5347 std::vector<Value *> stack;
5348 for (auto *U : Arg.getParent()->users()) {
5349 if (auto *call = dyn_cast<CallInst>(U)) {
5350 stack.push_back(call->getOperand(Arg.getArgNo()));
5351 }
5352 }
5353
5354 while (!stack.empty()) {
5355 Value *v = stack.back();
5356 stack.pop_back();
5357
5358 if (!visited.insert(v).second)
5359 continue;
5360
5361 auto *resource_call = dyn_cast<CallInst>(v);
5362 if (resource_call &&
SJW61531372020-06-09 07:31:08 -05005363 Builtins::Lookup(resource_call->getCalledFunction()).getType() ==
5364 Builtins::kClspvResource) {
alan-bakere9308012019-03-15 10:25:13 -04005365 // If this is a resource accessor function, check if the coherent operand
5366 // is set.
5367 const auto coherent =
5368 unsigned(dyn_cast<ConstantInt>(resource_call->getArgOperand(5))
5369 ->getZExtValue());
5370 if (coherent == 1)
5371 return true;
5372 } else if (auto *arg = dyn_cast<Argument>(v)) {
5373 // If this is a function argument, trace through its callers.
alan-bakere98f3f92019-04-08 15:06:36 -04005374 for (auto U : arg->getParent()->users()) {
alan-bakere9308012019-03-15 10:25:13 -04005375 if (auto *call = dyn_cast<CallInst>(U)) {
5376 stack.push_back(call->getOperand(arg->getArgNo()));
5377 }
5378 }
5379 } else if (auto *user = dyn_cast<User>(v)) {
5380 // If this is a user, traverse all operands that could lead to resource
5381 // variables.
5382 for (unsigned i = 0; i != user->getNumOperands(); ++i) {
5383 Value *operand = user->getOperand(i);
5384 if (operand->getType()->isPointerTy() &&
5385 operand->getType()->getPointerAddressSpace() ==
5386 clspv::AddressSpace::Global) {
5387 stack.push_back(operand);
5388 }
5389 }
5390 }
5391 }
5392
5393 // No coherent resource variables encountered.
5394 return false;
5395}
alan-baker06cad652019-12-03 17:56:47 -05005396
SJW77b87ad2020-04-21 14:37:52 -05005397void SPIRVProducerPass::PopulateStructuredCFGMaps() {
alan-baker06cad652019-12-03 17:56:47 -05005398 // First, track loop merges and continues.
5399 DenseSet<BasicBlock *> LoopMergesAndContinues;
SJW77b87ad2020-04-21 14:37:52 -05005400 for (auto &F : *module) {
alan-baker06cad652019-12-03 17:56:47 -05005401 if (F.isDeclaration())
5402 continue;
5403
5404 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
5405 const LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>(F).getLoopInfo();
5406 std::deque<BasicBlock *> order;
5407 DenseSet<BasicBlock *> visited;
5408 clspv::ComputeStructuredOrder(&*F.begin(), &DT, LI, &order, &visited);
5409
5410 for (auto BB : order) {
5411 auto terminator = BB->getTerminator();
5412 auto branch = dyn_cast<BranchInst>(terminator);
5413 if (LI.isLoopHeader(BB)) {
5414 auto L = LI.getLoopFor(BB);
5415 BasicBlock *ContinueBB = nullptr;
5416 BasicBlock *MergeBB = nullptr;
5417
5418 MergeBB = L->getExitBlock();
5419 if (!MergeBB) {
5420 // StructurizeCFG pass converts CFG into triangle shape and the cfg
5421 // has regions with single entry/exit. As a result, loop should not
5422 // have multiple exits.
5423 llvm_unreachable("Loop has multiple exits???");
5424 }
5425
5426 if (L->isLoopLatch(BB)) {
5427 ContinueBB = BB;
5428 } else {
5429 // From SPIR-V spec 2.11, Continue Target must dominate that back-edge
5430 // block.
5431 BasicBlock *Header = L->getHeader();
5432 BasicBlock *Latch = L->getLoopLatch();
5433 for (auto *loop_block : L->blocks()) {
5434 if (loop_block == Header) {
5435 continue;
5436 }
5437
5438 // Check whether block dominates block with back-edge.
5439 // The loop latch is the single block with a back-edge. If it was
5440 // possible, StructurizeCFG made the loop conform to this
5441 // requirement, otherwise |Latch| is a nullptr.
5442 if (DT.dominates(loop_block, Latch)) {
5443 ContinueBB = loop_block;
5444 }
5445 }
5446
5447 if (!ContinueBB) {
5448 llvm_unreachable("Wrong continue block from loop");
5449 }
5450 }
5451
5452 // Record the continue and merge blocks.
5453 MergeBlocks[BB] = MergeBB;
5454 ContinueBlocks[BB] = ContinueBB;
5455 LoopMergesAndContinues.insert(MergeBB);
5456 LoopMergesAndContinues.insert(ContinueBB);
5457 } else if (branch && branch->isConditional()) {
5458 auto L = LI.getLoopFor(BB);
5459 bool HasBackedge = false;
5460 while (L && !HasBackedge) {
5461 if (L->isLoopLatch(BB)) {
5462 HasBackedge = true;
5463 }
5464 L = L->getParentLoop();
5465 }
5466
5467 if (!HasBackedge) {
5468 // Only need a merge if the branch doesn't include a loop break or
5469 // continue.
5470 auto true_bb = branch->getSuccessor(0);
5471 auto false_bb = branch->getSuccessor(1);
5472 if (!LoopMergesAndContinues.count(true_bb) &&
5473 !LoopMergesAndContinues.count(false_bb)) {
5474 // StructurizeCFG pass already manipulated CFG. Just use false block
5475 // of branch instruction as merge block.
5476 MergeBlocks[BB] = false_bb;
5477 }
5478 }
5479 }
5480 }
5481 }
5482}
alan-baker86ce19c2020-08-05 13:09:19 -04005483
5484SPIRVID SPIRVProducerPass::getReflectionImport() {
5485 if (!ReflectionID.isValid()) {
5486 addSPIRVInst<kExtensions>(spv::OpExtension, "SPV_KHR_non_semantic_info");
5487 ReflectionID = addSPIRVInst<kImports>(spv::OpExtInstImport,
5488 "NonSemantic.ClspvReflection.1");
5489 }
5490 return ReflectionID;
5491}
5492
5493void SPIRVProducerPass::GenerateReflection() {
5494 GenerateKernelReflection();
5495 GeneratePushConstantReflection();
5496 GenerateSpecConstantReflection();
5497}
5498
5499void SPIRVProducerPass::GeneratePushConstantReflection() {
5500 if (auto GV = module->getGlobalVariable(clspv::PushConstantsVariableName())) {
5501 auto const &DL = module->getDataLayout();
5502 auto MD = GV->getMetadata(clspv::PushConstantsMetadataName());
5503 auto STy = cast<StructType>(GV->getValueType());
5504
5505 for (unsigned i = 0; i < STy->getNumElements(); i++) {
5506 auto pc = static_cast<clspv::PushConstant>(
5507 mdconst::extract<ConstantInt>(MD->getOperand(i))->getZExtValue());
5508 if (pc == PushConstant::KernelArgument)
5509 continue;
5510
5511 auto memberType = STy->getElementType(i);
5512 auto offset = GetExplicitLayoutStructMemberOffset(STy, i, DL);
5513 unsigned previousOffset = 0;
5514 if (i > 0) {
5515 previousOffset = GetExplicitLayoutStructMemberOffset(STy, i - 1, DL);
5516 }
5517 auto size = static_cast<uint32_t>(GetTypeSizeInBits(memberType, DL)) / 8;
5518 assert(isValidExplicitLayout(*module, STy, i,
5519 spv::StorageClassPushConstant, offset,
5520 previousOffset));
5521
5522 reflection::ExtInst pc_inst = reflection::ExtInstMax;
5523 switch (pc) {
5524 case PushConstant::GlobalOffset:
5525 pc_inst = reflection::ExtInstPushConstantGlobalOffset;
5526 break;
5527 case PushConstant::EnqueuedLocalSize:
5528 pc_inst = reflection::ExtInstPushConstantEnqueuedLocalSize;
5529 break;
5530 case PushConstant::GlobalSize:
5531 pc_inst = reflection::ExtInstPushConstantGlobalSize;
5532 break;
5533 case PushConstant::RegionOffset:
5534 pc_inst = reflection::ExtInstPushConstantRegionOffset;
5535 break;
5536 case PushConstant::NumWorkgroups:
5537 pc_inst = reflection::ExtInstPushConstantNumWorkgroups;
5538 break;
5539 case PushConstant::RegionGroupOffset:
5540 pc_inst = reflection::ExtInstPushConstantRegionGroupOffset;
5541 break;
5542 default:
5543 llvm_unreachable("Unhandled push constant");
5544 break;
5545 }
5546
5547 auto import_id = getReflectionImport();
5548 SPIRVOperandVec Ops;
5549 Ops << getSPIRVType(Type::getVoidTy(module->getContext())) << import_id
5550 << pc_inst << getSPIRVInt32Constant(offset)
5551 << getSPIRVInt32Constant(size);
5552 addSPIRVInst(spv::OpExtInst, Ops);
5553 }
5554 }
5555}
5556
5557void SPIRVProducerPass::GenerateSpecConstantReflection() {
5558 const uint32_t kMax = std::numeric_limits<uint32_t>::max();
5559 uint32_t wgsize_id[3] = {kMax, kMax, kMax};
5560 uint32_t global_offset_id[3] = {kMax, kMax, kMax};
5561 uint32_t work_dim_id = kMax;
5562 for (auto pair : clspv::GetSpecConstants(module)) {
5563 auto kind = pair.first;
5564 auto id = pair.second;
5565
5566 // Local memory size is only used for kernel arguments.
5567 if (kind == SpecConstant::kLocalMemorySize)
5568 continue;
5569
5570 switch (kind) {
5571 case SpecConstant::kWorkgroupSizeX:
5572 wgsize_id[0] = id;
5573 break;
5574 case SpecConstant::kWorkgroupSizeY:
5575 wgsize_id[1] = id;
5576 break;
5577 case SpecConstant::kWorkgroupSizeZ:
5578 wgsize_id[2] = id;
5579 break;
5580 case SpecConstant::kGlobalOffsetX:
5581 global_offset_id[0] = id;
5582 break;
5583 case SpecConstant::kGlobalOffsetY:
5584 global_offset_id[1] = id;
5585 break;
5586 case SpecConstant::kGlobalOffsetZ:
5587 global_offset_id[2] = id;
5588 break;
5589 case SpecConstant::kWorkDim:
5590 work_dim_id = id;
5591 break;
5592 default:
5593 llvm_unreachable("Unhandled spec constant");
5594 }
5595 }
5596
5597 auto import_id = getReflectionImport();
5598 auto void_id = getSPIRVType(Type::getVoidTy(module->getContext()));
5599 SPIRVOperandVec Ops;
5600 if (wgsize_id[0] != kMax) {
5601 assert(wgsize_id[1] != kMax);
5602 assert(wgsize_id[2] != kMax);
5603 Ops.clear();
5604 Ops << void_id << import_id << reflection::ExtInstSpecConstantWorkgroupSize
5605 << getSPIRVInt32Constant(wgsize_id[0])
5606 << getSPIRVInt32Constant(wgsize_id[1])
5607 << getSPIRVInt32Constant(wgsize_id[2]);
5608 addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
5609 }
5610 if (global_offset_id[0] != kMax) {
5611 assert(global_offset_id[1] != kMax);
5612 assert(global_offset_id[2] != kMax);
5613 Ops.clear();
5614 Ops << void_id << import_id << reflection::ExtInstSpecConstantGlobalOffset
5615 << getSPIRVInt32Constant(global_offset_id[0])
5616 << getSPIRVInt32Constant(global_offset_id[1])
5617 << getSPIRVInt32Constant(global_offset_id[2]);
5618 addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
5619 }
5620 if (work_dim_id != kMax) {
5621 Ops.clear();
5622 Ops << void_id << import_id << reflection::ExtInstSpecConstantWorkDim
5623 << getSPIRVInt32Constant(work_dim_id);
5624 addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
5625 }
5626}
5627
5628void SPIRVProducerPass::GenerateKernelReflection() {
5629 const auto &DL = module->getDataLayout();
5630 auto import_id = getReflectionImport();
5631 auto void_id = getSPIRVType(Type::getVoidTy(module->getContext()));
5632
5633 for (auto &F : *module) {
5634 if (F.isDeclaration() || F.getCallingConv() != CallingConv::SPIR_KERNEL) {
5635 continue;
5636 }
5637
5638 // OpString for the kernel name.
5639 auto kernel_name =
5640 addSPIRVInst<kDebug>(spv::OpString, F.getName().str().c_str());
5641
5642 // Kernel declaration
5643 // Ops[0] = void type
5644 // Ops[1] = reflection ext import
5645 // Ops[2] = function id
5646 // Ops[3] = kernel name
5647 SPIRVOperandVec Ops;
5648 Ops << void_id << import_id << reflection::ExtInstKernel << ValueMap[&F]
5649 << kernel_name;
5650 auto kernel_decl = addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
5651
5652 // Generate the required workgroup size property if it was specified.
5653 if (const MDNode *MD = F.getMetadata("reqd_work_group_size")) {
5654 uint32_t CurXDimCst = static_cast<uint32_t>(
5655 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
5656 uint32_t CurYDimCst = static_cast<uint32_t>(
5657 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
5658 uint32_t CurZDimCst = static_cast<uint32_t>(
5659 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
5660
5661 Ops.clear();
5662 Ops << void_id << import_id
5663 << reflection::ExtInstPropertyRequiredWorkgroupSize << kernel_decl
5664 << getSPIRVInt32Constant(CurXDimCst)
5665 << getSPIRVInt32Constant(CurYDimCst)
5666 << getSPIRVInt32Constant(CurZDimCst);
5667 addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
5668 }
5669
5670 auto &resource_var_at_index = FunctionToResourceVarsMap[&F];
5671 auto *func_ty = F.getFunctionType();
5672
5673 // If we've clustered POD arguments, then argument details are in metadata.
5674 // If an argument maps to a resource variable, then get descriptor set and
5675 // binding from the resource variable. Other info comes from the metadata.
5676 const auto *arg_map = F.getMetadata(clspv::KernelArgMapMetadataName());
5677 auto local_spec_id_md =
5678 module->getNamedMetadata(clspv::LocalSpecIdMetadataName());
5679 if (arg_map) {
5680 for (const auto &arg : arg_map->operands()) {
5681 const MDNode *arg_node = dyn_cast<MDNode>(arg.get());
5682 assert(arg_node->getNumOperands() == 6);
5683 const auto name =
5684 dyn_cast<MDString>(arg_node->getOperand(0))->getString();
5685 const auto old_index =
5686 dyn_extract<ConstantInt>(arg_node->getOperand(1))->getZExtValue();
5687 // Remapped argument index
5688 const int new_index = static_cast<int>(
5689 dyn_extract<ConstantInt>(arg_node->getOperand(2))->getSExtValue());
5690 const auto offset =
5691 dyn_extract<ConstantInt>(arg_node->getOperand(3))->getZExtValue();
5692 const auto size =
5693 dyn_extract<ConstantInt>(arg_node->getOperand(4))->getZExtValue();
5694 const auto argKind = clspv::GetArgKindFromName(
5695 dyn_cast<MDString>(arg_node->getOperand(5))->getString().str());
5696
5697 // If this is a local memory argument, find the right spec id for this
5698 // argument.
5699 int64_t spec_id = -1;
5700 if (argKind == clspv::ArgKind::Local) {
5701 for (auto spec_id_arg : local_spec_id_md->operands()) {
5702 if ((&F == dyn_cast<Function>(
5703 dyn_cast<ValueAsMetadata>(spec_id_arg->getOperand(0))
5704 ->getValue())) &&
5705 (static_cast<uint64_t>(new_index) ==
5706 mdconst::extract<ConstantInt>(spec_id_arg->getOperand(1))
5707 ->getZExtValue())) {
5708 spec_id =
5709 mdconst::extract<ConstantInt>(spec_id_arg->getOperand(2))
5710 ->getSExtValue();
5711 break;
5712 }
5713 }
5714 }
5715
5716 // Generate the specific argument instruction.
5717 const uint32_t ordinal = static_cast<uint32_t>(old_index);
5718 const uint32_t arg_offset = static_cast<uint32_t>(offset);
5719 const uint32_t arg_size = static_cast<uint32_t>(size);
5720 uint32_t elem_size = 0;
5721 uint32_t descriptor_set = 0;
5722 uint32_t binding = 0;
5723 if (spec_id > 0) {
5724 elem_size = static_cast<uint32_t>(
5725 GetTypeAllocSize(func_ty->getParamType(unsigned(new_index))
5726 ->getPointerElementType(),
5727 DL));
5728 } else if (new_index >= 0) {
5729 auto *info = resource_var_at_index[new_index];
5730 assert(info);
5731 descriptor_set = info->descriptor_set;
5732 binding = info->binding;
5733 }
5734 AddArgumentReflection(kernel_decl, name.str(), argKind, ordinal,
5735 descriptor_set, binding, arg_offset, arg_size,
5736 static_cast<uint32_t>(spec_id), elem_size);
5737 }
5738 } else {
5739 // There is no argument map.
5740 // Take descriptor info from the resource variable calls.
5741 // Take argument name and size from the arguments list.
5742
5743 SmallVector<Argument *, 4> arguments;
5744 for (auto &arg : F.args()) {
5745 arguments.push_back(&arg);
5746 }
5747
5748 unsigned arg_index = 0;
5749 for (auto *info : resource_var_at_index) {
5750 if (info) {
5751 auto arg = arguments[arg_index];
5752 unsigned arg_size = 0;
5753 if (info->arg_kind == clspv::ArgKind::Pod ||
5754 info->arg_kind == clspv::ArgKind::PodUBO ||
5755 info->arg_kind == clspv::ArgKind::PodPushConstant) {
5756 arg_size =
5757 static_cast<uint32_t>(DL.getTypeStoreSize(arg->getType()));
5758 }
5759
5760 // Local pointer arguments are unused in this case.
5761 // offset, spec_id and elem_size always 0.
5762 AddArgumentReflection(kernel_decl, arg->getName().str(),
5763 info->arg_kind, arg_index, info->descriptor_set,
5764 info->binding, 0, arg_size, 0, 0);
5765 }
5766 arg_index++;
5767 }
5768 // Generate mappings for pointer-to-local arguments.
5769 for (arg_index = 0; arg_index < arguments.size(); ++arg_index) {
5770 Argument *arg = arguments[arg_index];
5771 auto where = LocalArgSpecIds.find(arg);
5772 if (where != LocalArgSpecIds.end()) {
5773 auto &local_arg_info = LocalSpecIdInfoMap[where->second];
5774
5775 // descriptor_set, binding, offset and size are always 0.
5776 AddArgumentReflection(kernel_decl, arg->getName().str(),
5777 ArgKind::Local, arg_index, 0, 0, 0, 0,
5778 static_cast<uint32_t>(local_arg_info.spec_id),
5779 static_cast<uint32_t>(GetTypeAllocSize(
5780 local_arg_info.elem_type, DL)));
5781 }
5782 }
5783 }
5784 }
5785}
5786
5787void SPIRVProducerPass::AddArgumentReflection(
5788 SPIRVID kernel_decl, const std::string &name, clspv::ArgKind arg_kind,
5789 uint32_t ordinal, uint32_t descriptor_set, uint32_t binding,
5790 uint32_t offset, uint32_t size, uint32_t spec_id, uint32_t elem_size) {
5791 // Generate ArgumentInfo for this argument.
5792 // TODO: generate remaining optional operands.
5793 auto import_id = getReflectionImport();
5794 auto arg_name = addSPIRVInst<kDebug>(spv::OpString, name.c_str());
5795 auto void_id = getSPIRVType(Type::getVoidTy(module->getContext()));
5796 SPIRVOperandVec Ops;
5797 Ops << void_id << import_id << reflection::ExtInstArgumentInfo << arg_name;
5798 auto arg_info = addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
5799
5800 Ops.clear();
5801 Ops << void_id << import_id;
5802 reflection::ExtInst ext_inst = reflection::ExtInstMax;
5803 // Determine the extended instruction.
5804 switch (arg_kind) {
5805 case clspv::ArgKind::Buffer:
5806 ext_inst = reflection::ExtInstArgumentStorageBuffer;
5807 break;
5808 case clspv::ArgKind::BufferUBO:
5809 ext_inst = reflection::ExtInstArgumentUniform;
5810 break;
5811 case clspv::ArgKind::Local:
5812 ext_inst = reflection::ExtInstArgumentWorkgroup;
5813 break;
5814 case clspv::ArgKind::Pod:
5815 ext_inst = reflection::ExtInstArgumentPodStorageBuffer;
5816 break;
5817 case clspv::ArgKind::PodUBO:
5818 ext_inst = reflection::ExtInstArgumentPodUniform;
5819 break;
5820 case clspv::ArgKind::PodPushConstant:
5821 ext_inst = reflection::ExtInstArgumentPodPushConstant;
5822 break;
5823 case clspv::ArgKind::ReadOnlyImage:
5824 ext_inst = reflection::ExtInstArgumentSampledImage;
5825 break;
5826 case clspv::ArgKind::WriteOnlyImage:
5827 ext_inst = reflection::ExtInstArgumentStorageImage;
5828 break;
5829 case clspv::ArgKind::Sampler:
5830 ext_inst = reflection::ExtInstArgumentSampler;
5831 break;
5832 default:
5833 llvm_unreachable("Unhandled argument reflection");
5834 break;
5835 }
5836 Ops << ext_inst << kernel_decl << getSPIRVInt32Constant(ordinal);
5837
5838 // Add descriptor set and binding for applicable arguments.
5839 switch (arg_kind) {
5840 case clspv::ArgKind::Buffer:
5841 case clspv::ArgKind::BufferUBO:
5842 case clspv::ArgKind::Pod:
5843 case clspv::ArgKind::PodUBO:
5844 case clspv::ArgKind::ReadOnlyImage:
5845 case clspv::ArgKind::WriteOnlyImage:
5846 case clspv::ArgKind::Sampler:
5847 Ops << getSPIRVInt32Constant(descriptor_set)
5848 << getSPIRVInt32Constant(binding);
5849 break;
5850 default:
5851 break;
5852 }
5853
5854 // Add remaining operands for arguments.
5855 switch (arg_kind) {
5856 case clspv::ArgKind::Local:
5857 Ops << getSPIRVInt32Constant(spec_id) << getSPIRVInt32Constant(elem_size);
5858 break;
5859 case clspv::ArgKind::Pod:
5860 case clspv::ArgKind::PodUBO:
5861 case clspv::ArgKind::PodPushConstant:
5862 Ops << getSPIRVInt32Constant(offset) << getSPIRVInt32Constant(size);
5863 break;
5864 default:
5865 break;
5866 }
5867 Ops << arg_info;
5868 addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
5869}