blob: 864dbc9b853f01757054af344186bf3a1fdd7f86 [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
James Price11010dc2019-12-19 13:53:09 -0500155 SPIRVOperandType getType() const { return Type; };
156 uint32_t getNumID() const { return LiteralNum[0]; };
157 std::string getLiteralStr() const { return LiteralStr; };
SJW88ed5fe2020-05-11 12:40:57 -0500158 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; }
278 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 };
David Neto22f144c2017-06-12 14:26:21 -0400283 EntryPointVecType &getEntryPointVec() { return EntryPointVec; };
284 DeferredInstVecType &getDeferredInstVec() { return DeferredInstVec; };
SJW806a5d82020-07-15 12:51:38 -0500285 SPIRVIDListType &getEntryPointInterfacesList() {
286 return EntryPointInterfacesList;
287 };
SJW01901d92020-05-21 08:58:31 -0500288 SPIRVID getOpExtInstImportID();
289 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 }
Diego Novillo3cc8d7a2019-04-10 13:30:34 -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 }
306 };
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.
898 if (GVList.size() > 0) {
899 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()) {
1022 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
alan-bakere9308012019-03-15 10:25:13 -04001023 binding, &F, arg_kind, coherent);
David Neto862b7d82018-06-14 18:48:37 -04001024 ResourceVarInfoList.emplace_back(rv);
1025 set_and_binding_map[key] = rv;
1026 } else {
1027 rv = where->second;
1028 }
1029 } else {
1030 // The default is to make exactly one resource for each
1031 // clspv.resource.var.* function.
1032 if (first_use) {
1033 first_use = false;
1034 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
alan-bakere9308012019-03-15 10:25:13 -04001035 binding, &F, arg_kind, coherent);
David Neto862b7d82018-06-14 18:48:37 -04001036 ResourceVarInfoList.emplace_back(rv);
1037 } else {
1038 rv = ResourceVarInfoList.back().get();
1039 }
1040 }
1041
1042 // Now populate FunctionToResourceVarsMap.
1043 auto &mapping =
1044 FunctionToResourceVarsMap[call->getParent()->getParent()];
1045 while (mapping.size() <= arg_index) {
1046 mapping.push_back(nullptr);
1047 }
1048 mapping[arg_index] = rv;
1049 }
1050 }
1051 }
1052 }
1053
1054 // Populate ModuleOrderedResourceVars.
SJW77b87ad2020-04-21 14:37:52 -05001055 for (Function &F : *module) {
David Neto862b7d82018-06-14 18:48:37 -04001056 auto where = FunctionToResourceVarsMap.find(&F);
1057 if (where != FunctionToResourceVarsMap.end()) {
1058 for (auto &rv : where->second) {
1059 if (rv != nullptr) {
1060 ModuleOrderedResourceVars.insert(rv);
1061 }
1062 }
1063 }
1064 }
1065 if (ShowResourceVars) {
1066 for (auto *info : ModuleOrderedResourceVars) {
1067 outs() << "MORV index " << info->index << " (" << info->descriptor_set
1068 << "," << info->binding << ") " << *(info->var_fn->getReturnType())
1069 << "\n";
1070 }
1071 }
1072}
1073
David Neto22f144c2017-06-12 14:26:21 -04001074void SPIRVProducerPass::FindTypePerGlobalVar(GlobalVariable &GV) {
1075 // Investigate global variable's type.
1076 FindType(GV.getType());
1077}
1078
1079void SPIRVProducerPass::FindTypePerFunc(Function &F) {
1080 // Investigate function's type.
1081 FunctionType *FTy = F.getFunctionType();
1082
1083 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
1084 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
David Neto9ed8e2f2018-03-24 06:47:24 -07001085 // Handle a regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04001086 if (GlobalConstFuncTyMap.count(FTy)) {
1087 uint32_t GVCstArgIdx = GlobalConstFuncTypeMap[FTy].second;
1088 SmallVector<Type *, 4> NewFuncParamTys;
1089 for (unsigned i = 0; i < FTy->getNumParams(); i++) {
1090 Type *ParamTy = FTy->getParamType(i);
1091 if (i == GVCstArgIdx) {
1092 Type *EleTy = ParamTy->getPointerElementType();
1093 ParamTy = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1094 }
1095
1096 NewFuncParamTys.push_back(ParamTy);
1097 }
1098
1099 FunctionType *NewFTy =
1100 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1101 GlobalConstFuncTyMap[FTy] = std::make_pair(NewFTy, GVCstArgIdx);
1102 FTy = NewFTy;
1103 }
1104
1105 FindType(FTy);
1106 } else {
1107 // As kernel functions do not have parameters, create new function type and
1108 // add it to type map.
1109 SmallVector<Type *, 4> NewFuncParamTys;
1110 FunctionType *NewFTy =
1111 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1112 FindType(NewFTy);
1113 }
1114
1115 // Investigate instructions' type in function body.
1116 for (BasicBlock &BB : F) {
1117 for (Instruction &I : BB) {
1118 if (isa<ShuffleVectorInst>(I)) {
1119 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1120 // Ignore type for mask of shuffle vector instruction.
1121 if (i == 2) {
1122 continue;
1123 }
1124
1125 Value *Op = I.getOperand(i);
1126 if (!isa<MetadataAsValue>(Op)) {
1127 FindType(Op->getType());
1128 }
1129 }
1130
1131 FindType(I.getType());
1132 continue;
1133 }
1134
David Neto862b7d82018-06-14 18:48:37 -04001135 CallInst *Call = dyn_cast<CallInst>(&I);
1136
SJW61531372020-06-09 07:31:08 -05001137 if (Call) {
1138 auto &func_info = Builtins::Lookup(Call->getCalledFunction());
1139 if (func_info.getType() == Builtins::kClspvResource ||
1140 func_info.getType() == Builtins::kClspvLocal) {
1141 // This is a fake call representing access to a resource/workgroup
1142 // variable. We handle that elsewhere.
1143 continue;
1144 }
Alan Baker202c8c72018-08-13 13:47:44 -04001145 }
1146
alan-bakerf083bed2020-01-29 08:15:42 -05001147 // #497: InsertValue and ExtractValue map to OpCompositeInsert and
1148 // OpCompositeExtract which takes literal values for indices. As a result
1149 // don't map the type of indices.
1150 if (I.getOpcode() == Instruction::ExtractValue) {
1151 FindType(I.getOperand(0)->getType());
1152 continue;
1153 }
1154 if (I.getOpcode() == Instruction::InsertValue) {
1155 FindType(I.getOperand(0)->getType());
1156 FindType(I.getOperand(1)->getType());
1157 continue;
1158 }
1159
1160 // #497: InsertElement and ExtractElement map to OpCompositeExtract if
1161 // the index is a constant. In such a case don't map the index type.
1162 if (I.getOpcode() == Instruction::ExtractElement) {
1163 FindType(I.getOperand(0)->getType());
1164 Value *op1 = I.getOperand(1);
1165 if (!isa<Constant>(op1) || isa<GlobalValue>(op1)) {
1166 FindType(op1->getType());
1167 }
1168 continue;
1169 }
1170 if (I.getOpcode() == Instruction::InsertElement) {
1171 FindType(I.getOperand(0)->getType());
1172 FindType(I.getOperand(1)->getType());
1173 Value *op2 = I.getOperand(2);
1174 if (!isa<Constant>(op2) || isa<GlobalValue>(op2)) {
1175 FindType(op2->getType());
1176 }
1177 continue;
1178 }
1179
David Neto22f144c2017-06-12 14:26:21 -04001180 // Work through the operands of the instruction.
1181 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1182 Value *const Op = I.getOperand(i);
1183 // If any of the operands is a constant, find the type!
1184 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1185 FindType(Op->getType());
1186 }
1187 }
1188
1189 for (Use &Op : I.operands()) {
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001190 if (isa<CallInst>(&I)) {
David Neto22f144c2017-06-12 14:26:21 -04001191 // Avoid to check call instruction's type.
1192 break;
1193 }
Alan Baker202c8c72018-08-13 13:47:44 -04001194 if (CallInst *OpCall = dyn_cast<CallInst>(Op)) {
SJW61531372020-06-09 07:31:08 -05001195 if (Builtins::Lookup(OpCall->getCalledFunction()) ==
1196 Builtins::kClspvLocal) {
Alan Baker202c8c72018-08-13 13:47:44 -04001197 // This is a fake call representing access to a workgroup variable.
1198 // We handle that elsewhere.
1199 continue;
1200 }
1201 }
David Neto22f144c2017-06-12 14:26:21 -04001202 if (!isa<MetadataAsValue>(&Op)) {
1203 FindType(Op->getType());
1204 continue;
1205 }
1206 }
1207
David Neto22f144c2017-06-12 14:26:21 -04001208 // We don't want to track the type of this call as we are going to replace
1209 // it.
SJW61531372020-06-09 07:31:08 -05001210 if (Call && Builtins::Lookup(Call->getCalledFunction()) ==
1211 Builtins::kClspvSamplerVarLiteral) {
David Neto22f144c2017-06-12 14:26:21 -04001212 continue;
1213 }
1214
1215 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
1216 // If gep's base operand has ModuleScopePrivate address space, make gep
1217 // return ModuleScopePrivate address space.
1218 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate) {
1219 // Add pointer type with private address space for global constant to
1220 // type list.
1221 Type *EleTy = I.getType()->getPointerElementType();
1222 Type *NewPTy =
1223 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1224
1225 FindType(NewPTy);
1226 continue;
1227 }
1228 }
1229
1230 FindType(I.getType());
1231 }
1232 }
1233}
1234
SJW77b87ad2020-04-21 14:37:52 -05001235void SPIRVProducerPass::FindTypesForSamplerMap() {
David Neto862b7d82018-06-14 18:48:37 -04001236 // If we are using a sampler map, find the type of the sampler.
SJW77b87ad2020-04-21 14:37:52 -05001237 if (module->getFunction(clspv::LiteralSamplerFunction()) ||
David Neto862b7d82018-06-14 18:48:37 -04001238 0 < getSamplerMap().size()) {
SJW77b87ad2020-04-21 14:37:52 -05001239 auto SamplerStructTy = module->getTypeByName("opencl.sampler_t");
David Neto862b7d82018-06-14 18:48:37 -04001240 if (!SamplerStructTy) {
SJW77b87ad2020-04-21 14:37:52 -05001241 SamplerStructTy =
1242 StructType::create(module->getContext(), "opencl.sampler_t");
David Neto862b7d82018-06-14 18:48:37 -04001243 }
1244
1245 SamplerTy = SamplerStructTy->getPointerTo(AddressSpace::UniformConstant);
1246
1247 FindType(SamplerTy);
1248 }
1249}
1250
SJW77b87ad2020-04-21 14:37:52 -05001251void SPIRVProducerPass::FindTypesForResourceVars() {
David Neto862b7d82018-06-14 18:48:37 -04001252 // Record types so they are generated.
1253 TypesNeedingLayout.reset();
1254 StructTypesNeedingBlock.reset();
1255
1256 // To match older clspv codegen, generate the float type first if required
1257 // for images.
1258 for (const auto *info : ModuleOrderedResourceVars) {
1259 if (info->arg_kind == clspv::ArgKind::ReadOnlyImage ||
1260 info->arg_kind == clspv::ArgKind::WriteOnlyImage) {
alan-bakerf67468c2019-11-25 15:51:49 -05001261 if (IsIntImageType(info->var_fn->getReturnType())) {
1262 // Nothing for now...
1263 } else if (IsUintImageType(info->var_fn->getReturnType())) {
SJW77b87ad2020-04-21 14:37:52 -05001264 FindType(Type::getInt32Ty(module->getContext()));
alan-bakerf67468c2019-11-25 15:51:49 -05001265 }
1266
1267 // We need "float" either for the sampled type or for the Lod operand.
SJW77b87ad2020-04-21 14:37:52 -05001268 FindType(Type::getFloatTy(module->getContext()));
David Neto862b7d82018-06-14 18:48:37 -04001269 }
1270 }
1271
1272 for (const auto *info : ModuleOrderedResourceVars) {
1273 Type *type = info->var_fn->getReturnType();
1274
1275 switch (info->arg_kind) {
1276 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04001277 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04001278 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1279 StructTypesNeedingBlock.insert(sty);
1280 } else {
1281 errs() << *type << "\n";
1282 llvm_unreachable("Buffer arguments must map to structures!");
1283 }
1284 break;
1285 case clspv::ArgKind::Pod:
alan-baker9b0ec3c2020-04-06 14:45:34 -04001286 case clspv::ArgKind::PodUBO:
1287 case clspv::ArgKind::PodPushConstant:
David Neto862b7d82018-06-14 18:48:37 -04001288 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1289 StructTypesNeedingBlock.insert(sty);
1290 } else {
1291 errs() << *type << "\n";
1292 llvm_unreachable("POD arguments must map to structures!");
1293 }
1294 break;
1295 case clspv::ArgKind::ReadOnlyImage:
1296 case clspv::ArgKind::WriteOnlyImage:
1297 case clspv::ArgKind::Sampler:
1298 // Sampler and image types map to the pointee type but
1299 // in the uniform constant address space.
1300 type = PointerType::get(type->getPointerElementType(),
1301 clspv::AddressSpace::UniformConstant);
1302 break;
1303 default:
1304 break;
1305 }
1306
1307 // The converted type is the type of the OpVariable we will generate.
1308 // If the pointee type is an array of size zero, FindType will convert it
1309 // to a runtime array.
1310 FindType(type);
1311 }
1312
alan-bakerdcd97412019-09-16 15:32:30 -04001313 // If module constants are clustered in a storage buffer then that struct
1314 // needs layout decorations.
1315 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
SJW77b87ad2020-04-21 14:37:52 -05001316 for (GlobalVariable &GV : module->globals()) {
alan-bakerdcd97412019-09-16 15:32:30 -04001317 PointerType *PTy = cast<PointerType>(GV.getType());
1318 const auto AS = PTy->getAddressSpace();
1319 const bool module_scope_constant_external_init =
1320 (AS == AddressSpace::Constant) && GV.hasInitializer();
1321 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
1322 if (module_scope_constant_external_init &&
1323 spv::BuiltInMax == BuiltinType) {
1324 StructTypesNeedingBlock.insert(
1325 cast<StructType>(PTy->getPointerElementType()));
1326 }
1327 }
1328 }
1329
SJW77b87ad2020-04-21 14:37:52 -05001330 for (const GlobalVariable &GV : module->globals()) {
Kévin Petitbbbda972020-03-03 19:16:31 +00001331 if (GV.getAddressSpace() == clspv::AddressSpace::PushConstant) {
1332 auto Ty = cast<PointerType>(GV.getType())->getPointerElementType();
1333 assert(Ty->isStructTy() && "Push constants have to be structures.");
1334 auto STy = cast<StructType>(Ty);
1335 StructTypesNeedingBlock.insert(STy);
1336 }
1337 }
1338
David Neto862b7d82018-06-14 18:48:37 -04001339 // Traverse the arrays and structures underneath each Block, and
1340 // mark them as needing layout.
1341 std::vector<Type *> work_list(StructTypesNeedingBlock.begin(),
1342 StructTypesNeedingBlock.end());
1343 while (!work_list.empty()) {
1344 Type *type = work_list.back();
1345 work_list.pop_back();
1346 TypesNeedingLayout.insert(type);
1347 switch (type->getTypeID()) {
1348 case Type::ArrayTyID:
1349 work_list.push_back(type->getArrayElementType());
1350 if (!Hack_generate_runtime_array_stride_early) {
1351 // Remember this array type for deferred decoration.
1352 TypesNeedingArrayStride.insert(type);
1353 }
1354 break;
1355 case Type::StructTyID:
1356 for (auto *elem_ty : cast<StructType>(type)->elements()) {
1357 work_list.push_back(elem_ty);
1358 }
1359 default:
1360 // This type and its contained types don't get layout.
1361 break;
1362 }
1363 }
1364}
1365
SJWf93f5f32020-05-05 07:27:56 -05001366void SPIRVProducerPass::GenerateWorkgroupVars() {
Alan Baker202c8c72018-08-13 13:47:44 -04001367 // The SpecId assignment for pointer-to-local arguments is recorded in
1368 // module-level metadata. Translate that information into local argument
1369 // information.
SJWf93f5f32020-05-05 07:27:56 -05001370 LLVMContext &Context = module->getContext();
SJW77b87ad2020-04-21 14:37:52 -05001371 NamedMDNode *nmd = module->getNamedMetadata(clspv::LocalSpecIdMetadataName());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001372 if (!nmd)
1373 return;
Alan Baker202c8c72018-08-13 13:47:44 -04001374 for (auto operand : nmd->operands()) {
1375 MDTuple *tuple = cast<MDTuple>(operand);
1376 ValueAsMetadata *fn_md = cast<ValueAsMetadata>(tuple->getOperand(0));
1377 Function *func = cast<Function>(fn_md->getValue());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001378 ConstantAsMetadata *arg_index_md =
1379 cast<ConstantAsMetadata>(tuple->getOperand(1));
1380 int arg_index = static_cast<int>(
1381 cast<ConstantInt>(arg_index_md->getValue())->getSExtValue());
1382 Argument *arg = &*(func->arg_begin() + arg_index);
Alan Baker202c8c72018-08-13 13:47:44 -04001383
1384 ConstantAsMetadata *spec_id_md =
1385 cast<ConstantAsMetadata>(tuple->getOperand(2));
alan-bakerb6b09dc2018-11-08 16:59:28 -05001386 int spec_id = static_cast<int>(
1387 cast<ConstantInt>(spec_id_md->getValue())->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04001388
Alan Baker202c8c72018-08-13 13:47:44 -04001389 LocalArgSpecIds[arg] = spec_id;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001390 if (LocalSpecIdInfoMap.count(spec_id))
1391 continue;
Alan Baker202c8c72018-08-13 13:47:44 -04001392
SJWf93f5f32020-05-05 07:27:56 -05001393 // Generate the spec constant.
1394 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05001395 Ops << Type::getInt32Ty(Context) << 1;
SJWf93f5f32020-05-05 07:27:56 -05001396 SPIRVID ArraySizeID = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
Alan Baker202c8c72018-08-13 13:47:44 -04001397
SJWf93f5f32020-05-05 07:27:56 -05001398 // Generate the array type.
1399 Type *ElemTy = arg->getType()->getPointerElementType();
1400 Ops.clear();
1401 // The element type must have been created.
SJW01901d92020-05-21 08:58:31 -05001402 Ops << ElemTy << ArraySizeID;
SJWf93f5f32020-05-05 07:27:56 -05001403
1404 SPIRVID ArrayTypeID = addSPIRVInst<kTypes>(spv::OpTypeArray, Ops);
1405
1406 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05001407 Ops << spv::StorageClassWorkgroup << ArrayTypeID;
SJWf93f5f32020-05-05 07:27:56 -05001408 SPIRVID PtrArrayTypeID = addSPIRVInst<kTypes>(spv::OpTypePointer, Ops);
1409
1410 // Generate OpVariable.
1411 //
1412 // Ops[0] : Result Type ID
1413 // Ops[1] : Storage Class
SJW806a5d82020-07-15 12:51:38 -05001414 SPIRVID VariableID =
1415 addSPIRVGlobalVariable(PtrArrayTypeID, spv::StorageClassWorkgroup);
SJWf93f5f32020-05-05 07:27:56 -05001416
1417 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05001418 Ops << ArraySizeID << spv::DecorationSpecId << spec_id;
SJWf93f5f32020-05-05 07:27:56 -05001419 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
1420
1421 LocalArgInfo info{VariableID, ElemTy, ArraySizeID,
1422 ArrayTypeID, PtrArrayTypeID, spec_id};
1423 LocalSpecIdInfoMap[spec_id] = info;
Alan Baker202c8c72018-08-13 13:47:44 -04001424 }
1425}
1426
David Neto22f144c2017-06-12 14:26:21 -04001427void SPIRVProducerPass::FindType(Type *Ty) {
1428 TypeList &TyList = getTypeList();
1429
1430 if (0 != TyList.idFor(Ty)) {
1431 return;
1432 }
1433
1434 if (Ty->isPointerTy()) {
1435 auto AddrSpace = Ty->getPointerAddressSpace();
1436 if ((AddressSpace::Constant == AddrSpace) ||
1437 (AddressSpace::Global == AddrSpace)) {
1438 auto PointeeTy = Ty->getPointerElementType();
1439
1440 if (PointeeTy->isStructTy() &&
1441 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1442 FindType(PointeeTy);
1443 auto ActualPointerTy =
1444 PointeeTy->getPointerTo(AddressSpace::UniformConstant);
1445 FindType(ActualPointerTy);
1446 return;
1447 }
1448 }
1449 }
1450
David Neto862b7d82018-06-14 18:48:37 -04001451 // By convention, LLVM array type with 0 elements will map to
1452 // OpTypeRuntimeArray. Otherwise, it will map to OpTypeArray, which
1453 // has a constant number of elements. We need to support type of the
1454 // constant.
1455 if (auto *arrayTy = dyn_cast<ArrayType>(Ty)) {
1456 if (arrayTy->getNumElements() > 0) {
1457 LLVMContext &Context = Ty->getContext();
1458 FindType(Type::getInt32Ty(Context));
1459 }
David Neto22f144c2017-06-12 14:26:21 -04001460 }
1461
1462 for (Type *SubTy : Ty->subtypes()) {
1463 FindType(SubTy);
1464 }
1465
1466 TyList.insert(Ty);
1467}
1468
David Neto22f144c2017-06-12 14:26:21 -04001469spv::StorageClass SPIRVProducerPass::GetStorageClass(unsigned AddrSpace) const {
1470 switch (AddrSpace) {
1471 default:
1472 llvm_unreachable("Unsupported OpenCL address space");
1473 case AddressSpace::Private:
1474 return spv::StorageClassFunction;
1475 case AddressSpace::Global:
David Neto22f144c2017-06-12 14:26:21 -04001476 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001477 case AddressSpace::Constant:
1478 return clspv::Option::ConstantArgsInUniformBuffer()
1479 ? spv::StorageClassUniform
1480 : spv::StorageClassStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -04001481 case AddressSpace::Input:
1482 return spv::StorageClassInput;
1483 case AddressSpace::Local:
1484 return spv::StorageClassWorkgroup;
1485 case AddressSpace::UniformConstant:
1486 return spv::StorageClassUniformConstant;
David Neto9ed8e2f2018-03-24 06:47:24 -07001487 case AddressSpace::Uniform:
David Netoe439d702018-03-23 13:14:08 -07001488 return spv::StorageClassUniform;
David Neto22f144c2017-06-12 14:26:21 -04001489 case AddressSpace::ModuleScopePrivate:
1490 return spv::StorageClassPrivate;
Kévin Petitbbbda972020-03-03 19:16:31 +00001491 case AddressSpace::PushConstant:
1492 return spv::StorageClassPushConstant;
David Neto22f144c2017-06-12 14:26:21 -04001493 }
1494}
1495
David Neto862b7d82018-06-14 18:48:37 -04001496spv::StorageClass
1497SPIRVProducerPass::GetStorageClassForArgKind(clspv::ArgKind arg_kind) const {
1498 switch (arg_kind) {
1499 case clspv::ArgKind::Buffer:
1500 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001501 case clspv::ArgKind::BufferUBO:
1502 return spv::StorageClassUniform;
David Neto862b7d82018-06-14 18:48:37 -04001503 case clspv::ArgKind::Pod:
alan-baker9b0ec3c2020-04-06 14:45:34 -04001504 return spv::StorageClassStorageBuffer;
1505 case clspv::ArgKind::PodUBO:
1506 return spv::StorageClassUniform;
1507 case clspv::ArgKind::PodPushConstant:
1508 return spv::StorageClassPushConstant;
David Neto862b7d82018-06-14 18:48:37 -04001509 case clspv::ArgKind::Local:
1510 return spv::StorageClassWorkgroup;
1511 case clspv::ArgKind::ReadOnlyImage:
1512 case clspv::ArgKind::WriteOnlyImage:
1513 case clspv::ArgKind::Sampler:
1514 return spv::StorageClassUniformConstant;
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001515 default:
1516 llvm_unreachable("Unsupported storage class for argument kind");
David Neto862b7d82018-06-14 18:48:37 -04001517 }
1518}
1519
David Neto22f144c2017-06-12 14:26:21 -04001520spv::BuiltIn SPIRVProducerPass::GetBuiltin(StringRef Name) const {
1521 return StringSwitch<spv::BuiltIn>(Name)
1522 .Case("__spirv_GlobalInvocationId", spv::BuiltInGlobalInvocationId)
1523 .Case("__spirv_LocalInvocationId", spv::BuiltInLocalInvocationId)
1524 .Case("__spirv_WorkgroupSize", spv::BuiltInWorkgroupSize)
1525 .Case("__spirv_NumWorkgroups", spv::BuiltInNumWorkgroups)
1526 .Case("__spirv_WorkgroupId", spv::BuiltInWorkgroupId)
alan-bakerbed3a882020-04-21 14:42:41 -04001527 .Case("__spirv_WorkDim", spv::BuiltInWorkDim)
alan-bakere1996972020-05-04 08:38:12 -04001528 .Case("__spirv_GlobalOffset", spv::BuiltInGlobalOffset)
David Neto22f144c2017-06-12 14:26:21 -04001529 .Default(spv::BuiltInMax);
1530}
1531
SJW01901d92020-05-21 08:58:31 -05001532SPIRVID SPIRVProducerPass::getOpExtInstImportID() {
1533 if (OpExtInstImportID == 0) {
1534 //
1535 // Generate OpExtInstImport.
1536 //
1537 // Ops[0] ... Ops[n] = Name (Literal String)
David Neto22f144c2017-06-12 14:26:21 -04001538
SJW01901d92020-05-21 08:58:31 -05001539 OpExtInstImportID =
1540 addSPIRVInst<kImports>(spv::OpExtInstImport, "GLSL.std.450");
1541 }
1542 return OpExtInstImportID;
SJWf93f5f32020-05-05 07:27:56 -05001543}
1544
SJW806a5d82020-07-15 12:51:38 -05001545SPIRVID SPIRVProducerPass::addSPIRVGlobalVariable(const SPIRVID &TypeID,
1546 spv::StorageClass SC,
1547 const SPIRVID &InitID) {
1548 // Generate OpVariable.
1549 //
1550 // Ops[0] : Result Type ID
1551 // Ops[1] : Storage Class
1552 // Ops[2] : Initialization Value ID (optional)
1553
1554 SPIRVOperandVec Ops;
1555 Ops << TypeID << SC;
1556 if (InitID.isValid()) {
1557 Ops << InitID;
1558 }
1559
1560 SPIRVID VID = addSPIRVInst<kGlobalVariables>(spv::OpVariable, Ops);
1561
1562 if (SC == spv::StorageClassInput) {
1563 getEntryPointInterfacesList().push_back(VID);
1564 }
1565
1566 return VID;
1567}
1568
SJW01901d92020-05-21 08:58:31 -05001569SPIRVID SPIRVProducerPass::getSPIRVType(Type *Ty) {
SJWf93f5f32020-05-05 07:27:56 -05001570 auto TI = TypeMap.find(Ty);
1571 if (TI != TypeMap.end()) {
SJW01901d92020-05-21 08:58:31 -05001572 assert(TI->second.isValid());
SJWf93f5f32020-05-05 07:27:56 -05001573 return TI->second;
1574 }
1575
1576 const auto &DL = module->getDataLayout();
1577
SJW01901d92020-05-21 08:58:31 -05001578 SPIRVID RID;
SJWf93f5f32020-05-05 07:27:56 -05001579
1580 switch (Ty->getTypeID()) {
1581 default: {
1582 Ty->print(errs());
1583 llvm_unreachable("Unsupported type???");
1584 break;
1585 }
1586 case Type::MetadataTyID:
1587 case Type::LabelTyID: {
1588 // Ignore these types.
1589 break;
1590 }
1591 case Type::PointerTyID: {
1592 PointerType *PTy = cast<PointerType>(Ty);
1593 unsigned AddrSpace = PTy->getAddressSpace();
1594
1595 if (AddrSpace != AddressSpace::UniformConstant) {
1596 auto PointeeTy = PTy->getElementType();
1597 if (PointeeTy->isStructTy() &&
1598 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1599 // TODO(sjw): assert always an image?
1600 RID = getSPIRVType(PointeeTy);
1601 break;
1602 }
1603 }
1604
1605 // For the purposes of our Vulkan SPIR-V type system, constant and global
1606 // are conflated.
1607 if (AddressSpace::Constant == AddrSpace) {
1608 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1609 AddrSpace = AddressSpace::Global;
1610 // Check to see if we already created this type (for instance, if we
1611 // had a constant <type>* and a global <type>*, the type would be
1612 // created by one of these types, and shared by both).
1613 auto GlobalTy = PTy->getPointerElementType()->getPointerTo(AddrSpace);
1614 if (0 < TypeMap.count(GlobalTy)) {
1615 RID = TypeMap[GlobalTy];
1616 break;
1617 }
1618 }
1619 } else if (AddressSpace::Global == AddrSpace) {
1620 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1621 AddrSpace = AddressSpace::Constant;
1622
1623 // Check to see if we already created this type (for instance, if we
1624 // had a constant <type>* and a global <type>*, the type would be
1625 // created by one of these types, and shared by both).
1626 auto ConstantTy = PTy->getPointerElementType()->getPointerTo(AddrSpace);
1627 if (0 < TypeMap.count(ConstantTy)) {
1628 RID = TypeMap[ConstantTy];
1629 break;
1630 }
1631 }
1632 }
1633
1634 //
1635 // Generate OpTypePointer.
1636 //
1637
1638 // OpTypePointer
1639 // Ops[0] = Storage Class
1640 // Ops[1] = Element Type ID
1641 SPIRVOperandVec Ops;
1642
SJW01901d92020-05-21 08:58:31 -05001643 Ops << GetStorageClass(AddrSpace) << PTy->getElementType();
SJWf93f5f32020-05-05 07:27:56 -05001644
1645 RID = addSPIRVInst<kTypes>(spv::OpTypePointer, Ops);
1646 break;
1647 }
1648 case Type::StructTyID: {
1649 StructType *STy = cast<StructType>(Ty);
1650
1651 // Handle sampler type.
1652 if (STy->isOpaque()) {
1653 if (STy->getName().equals("opencl.sampler_t")) {
1654 //
1655 // Generate OpTypeSampler
1656 //
1657 // Empty Ops.
1658
1659 RID = addSPIRVInst<kTypes>(spv::OpTypeSampler);
1660 break;
1661 } else if (STy->getName().startswith("opencl.image1d_ro_t") ||
1662 STy->getName().startswith("opencl.image1d_wo_t") ||
1663 STy->getName().startswith("opencl.image1d_array_ro_t") ||
1664 STy->getName().startswith("opencl.image1d_array_wo_t") ||
1665 STy->getName().startswith("opencl.image2d_ro_t") ||
1666 STy->getName().startswith("opencl.image2d_wo_t") ||
1667 STy->getName().startswith("opencl.image2d_array_ro_t") ||
1668 STy->getName().startswith("opencl.image2d_array_wo_t") ||
1669 STy->getName().startswith("opencl.image3d_ro_t") ||
1670 STy->getName().startswith("opencl.image3d_wo_t")) {
SJW01901d92020-05-21 08:58:31 -05001671
1672 if (STy->getName().contains("_wo_t")) {
1673 addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
1674 }
1675 if (STy->getName().startswith("opencl.image1d_")) {
1676 if (STy->getName().contains(".sampled"))
1677 addCapability(spv::CapabilitySampled1D);
1678 else
1679 addCapability(spv::CapabilityImage1D);
1680 }
1681
SJWf93f5f32020-05-05 07:27:56 -05001682 //
1683 // Generate OpTypeImage
1684 //
1685 // Ops[0] = Sampled Type ID
1686 // Ops[1] = Dim ID
1687 // Ops[2] = Depth (Literal Number)
1688 // Ops[3] = Arrayed (Literal Number)
1689 // Ops[4] = MS (Literal Number)
1690 // Ops[5] = Sampled (Literal Number)
1691 // Ops[6] = Image Format ID
1692 //
1693 SPIRVOperandVec Ops;
1694
SJW01901d92020-05-21 08:58:31 -05001695 SPIRVID SampledTyID;
SJWf93f5f32020-05-05 07:27:56 -05001696 if (STy->getName().contains(".float")) {
1697 SampledTyID = getSPIRVType(Type::getFloatTy(Ty->getContext()));
1698 } else if (STy->getName().contains(".uint")) {
1699 SampledTyID = getSPIRVType(Type::getInt32Ty(Ty->getContext()));
1700 } else if (STy->getName().contains(".int")) {
1701 // Generate a signed 32-bit integer if necessary.
1702 if (int32ID == 0) {
1703 SPIRVOperandVec intOps;
SJW01901d92020-05-21 08:58:31 -05001704 intOps << 32 << 1;
SJWf93f5f32020-05-05 07:27:56 -05001705 int32ID = addSPIRVInst<kTypes>(spv::OpTypeInt, intOps);
1706 }
1707 SampledTyID = int32ID;
1708
1709 // Generate a vec4 of the signed int if necessary.
1710 if (v4int32ID == 0) {
1711 SPIRVOperandVec vecOps;
SJW01901d92020-05-21 08:58:31 -05001712 vecOps << int32ID << 4;
SJWf93f5f32020-05-05 07:27:56 -05001713 v4int32ID = addSPIRVInst<kTypes>(spv::OpTypeVector, vecOps);
1714 }
1715 } else {
1716 // This was likely an UndefValue.
1717 SampledTyID = getSPIRVType(Type::getFloatTy(Ty->getContext()));
1718 }
SJW01901d92020-05-21 08:58:31 -05001719 Ops << SampledTyID;
SJWf93f5f32020-05-05 07:27:56 -05001720
1721 spv::Dim DimID = spv::Dim2D;
1722 if (STy->getName().startswith("opencl.image1d_ro_t") ||
1723 STy->getName().startswith("opencl.image1d_wo_t") ||
1724 STy->getName().startswith("opencl.image1d_array_ro_t") ||
1725 STy->getName().startswith("opencl.image1d_array_wo_t")) {
1726 DimID = spv::Dim1D;
1727 } else if (STy->getName().startswith("opencl.image3d_ro_t") ||
1728 STy->getName().startswith("opencl.image3d_wo_t")) {
1729 DimID = spv::Dim3D;
1730 }
SJW01901d92020-05-21 08:58:31 -05001731 Ops << DimID;
SJWf93f5f32020-05-05 07:27:56 -05001732
1733 // TODO: Set up Depth.
SJW01901d92020-05-21 08:58:31 -05001734 Ops << 0;
SJWf93f5f32020-05-05 07:27:56 -05001735
1736 uint32_t arrayed = STy->getName().contains("_array_") ? 1 : 0;
SJW01901d92020-05-21 08:58:31 -05001737 Ops << arrayed;
SJWf93f5f32020-05-05 07:27:56 -05001738
1739 // TODO: Set up MS.
SJW01901d92020-05-21 08:58:31 -05001740 Ops << 0;
SJWf93f5f32020-05-05 07:27:56 -05001741
1742 // Set up Sampled.
1743 //
1744 // From Spec
1745 //
1746 // 0 indicates this is only known at run time, not at compile time
1747 // 1 indicates will be used with sampler
1748 // 2 indicates will be used without a sampler (a storage image)
1749 uint32_t Sampled = 1;
1750 if (!STy->getName().contains(".sampled")) {
1751 Sampled = 2;
1752 }
SJW01901d92020-05-21 08:58:31 -05001753 Ops << Sampled;
SJWf93f5f32020-05-05 07:27:56 -05001754
1755 // TODO: Set up Image Format.
SJW01901d92020-05-21 08:58:31 -05001756 Ops << spv::ImageFormatUnknown;
SJWf93f5f32020-05-05 07:27:56 -05001757
1758 RID = addSPIRVInst<kTypes>(spv::OpTypeImage, Ops);
1759
1760 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05001761 Ops << RID;
SJWf93f5f32020-05-05 07:27:56 -05001762
1763 getImageTypeMap()[Ty] =
1764 addSPIRVInst<kTypes>(spv::OpTypeSampledImage, Ops);
1765 break;
1766 }
1767 }
1768
1769 //
1770 // Generate OpTypeStruct
1771 //
1772 // Ops[0] ... Ops[n] = Member IDs
1773 SPIRVOperandVec Ops;
1774
1775 for (auto *EleTy : STy->elements()) {
SJW01901d92020-05-21 08:58:31 -05001776 Ops << EleTy;
SJWf93f5f32020-05-05 07:27:56 -05001777 }
1778
1779 RID = addSPIRVInst<kTypes>(spv::OpTypeStruct, Ops);
1780
1781 // Generate OpMemberDecorate.
1782 if (TypesNeedingLayout.idFor(STy)) {
1783 for (unsigned MemberIdx = 0; MemberIdx < STy->getNumElements();
1784 MemberIdx++) {
1785 // Ops[0] = Structure Type ID
1786 // Ops[1] = Member Index(Literal Number)
1787 // Ops[2] = Decoration (Offset)
1788 // Ops[3] = Byte Offset (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05001789 const auto ByteOffset =
1790 GetExplicitLayoutStructMemberOffset(STy, MemberIdx, DL);
1791
SJW01901d92020-05-21 08:58:31 -05001792 Ops.clear();
1793 Ops << RID << MemberIdx << spv::DecorationOffset << ByteOffset;
SJWf93f5f32020-05-05 07:27:56 -05001794
1795 addSPIRVInst<kAnnotations>(spv::OpMemberDecorate, Ops);
1796 }
1797 }
1798
1799 // Generate OpDecorate.
1800 if (StructTypesNeedingBlock.idFor(STy)) {
1801 Ops.clear();
1802 // Use Block decorations with StorageBuffer storage class.
SJW01901d92020-05-21 08:58:31 -05001803 Ops << RID << spv::DecorationBlock;
SJWf93f5f32020-05-05 07:27:56 -05001804
1805 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
1806 }
1807 break;
1808 }
1809 case Type::IntegerTyID: {
alan-bakere2a62752020-07-09 22:53:23 -04001810 uint32_t bit_width = static_cast<uint32_t>(Ty->getPrimitiveSizeInBits());
SJWf93f5f32020-05-05 07:27:56 -05001811
alan-bakere2a62752020-07-09 22:53:23 -04001812 if (clspv::Option::Int8Support() && bit_width == 8) {
SJW01901d92020-05-21 08:58:31 -05001813 addCapability(spv::CapabilityInt8);
alan-bakere2a62752020-07-09 22:53:23 -04001814 } else if (bit_width == 16) {
SJW01901d92020-05-21 08:58:31 -05001815 addCapability(spv::CapabilityInt16);
alan-bakere2a62752020-07-09 22:53:23 -04001816 } else if (bit_width == 64) {
SJW01901d92020-05-21 08:58:31 -05001817 addCapability(spv::CapabilityInt64);
1818 }
1819
alan-bakere2a62752020-07-09 22:53:23 -04001820 if (bit_width == 1) {
SJWf93f5f32020-05-05 07:27:56 -05001821 RID = addSPIRVInst<kTypes>(spv::OpTypeBool);
1822 } else {
alan-bakere2a62752020-07-09 22:53:23 -04001823 if (!clspv::Option::Int8Support() && bit_width == 8) {
SJWf93f5f32020-05-05 07:27:56 -05001824 // i8 is added to TypeMap as i32.
1825 RID = getSPIRVType(Type::getIntNTy(Ty->getContext(), 32));
1826 } else {
1827 SPIRVOperandVec Ops;
alan-bakere2a62752020-07-09 22:53:23 -04001828 Ops << bit_width << 0 /* not signed */;
SJWf93f5f32020-05-05 07:27:56 -05001829 RID = addSPIRVInst<kTypes>(spv::OpTypeInt, Ops);
1830 }
1831 }
1832 break;
1833 }
1834 case Type::HalfTyID:
1835 case Type::FloatTyID:
1836 case Type::DoubleTyID: {
alan-bakere2a62752020-07-09 22:53:23 -04001837 uint32_t bit_width = static_cast<uint32_t>(Ty->getPrimitiveSizeInBits());
1838 if (bit_width == 16) {
SJW01901d92020-05-21 08:58:31 -05001839 addCapability(spv::CapabilityFloat16);
alan-bakere2a62752020-07-09 22:53:23 -04001840 } else if (bit_width == 64) {
SJW01901d92020-05-21 08:58:31 -05001841 addCapability(spv::CapabilityFloat64);
1842 }
1843
SJWf93f5f32020-05-05 07:27:56 -05001844 SPIRVOperandVec Ops;
alan-bakere2a62752020-07-09 22:53:23 -04001845 Ops << bit_width;
SJWf93f5f32020-05-05 07:27:56 -05001846
1847 RID = addSPIRVInst<kTypes>(spv::OpTypeFloat, Ops);
1848 break;
1849 }
1850 case Type::ArrayTyID: {
1851 ArrayType *ArrTy = cast<ArrayType>(Ty);
1852 const uint64_t Length = ArrTy->getArrayNumElements();
1853 if (Length == 0) {
1854 // By convention, map it to a RuntimeArray.
1855
1856 Type *EleTy = ArrTy->getArrayElementType();
1857
1858 //
1859 // Generate OpTypeRuntimeArray.
1860 //
1861 // OpTypeRuntimeArray
1862 // Ops[0] = Element Type ID
1863 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05001864 Ops << EleTy;
SJWf93f5f32020-05-05 07:27:56 -05001865
1866 RID = addSPIRVInst<kTypes>(spv::OpTypeRuntimeArray, Ops);
1867
1868 if (Hack_generate_runtime_array_stride_early) {
1869 // Generate OpDecorate.
1870
1871 // Ops[0] = Target ID
1872 // Ops[1] = Decoration (ArrayStride)
1873 // Ops[2] = Stride Number(Literal Number)
1874 Ops.clear();
1875
SJW01901d92020-05-21 08:58:31 -05001876 Ops << RID << spv::DecorationArrayStride
1877 << static_cast<uint32_t>(GetTypeAllocSize(EleTy, DL));
SJWf93f5f32020-05-05 07:27:56 -05001878
1879 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
1880 }
1881
1882 } else {
1883
1884 //
1885 // Generate OpConstant and OpTypeArray.
1886 //
1887
1888 //
1889 // Generate OpConstant for array length.
1890 //
1891 // Add constant for length to constant list.
1892 Constant *CstLength =
1893 ConstantInt::get(Type::getInt32Ty(module->getContext()), Length);
SJWf93f5f32020-05-05 07:27:56 -05001894
1895 // Remember to generate ArrayStride later
1896 getTypesNeedingArrayStride().insert(Ty);
1897
1898 //
1899 // Generate OpTypeArray.
1900 //
1901 // Ops[0] = Element Type ID
1902 // Ops[1] = Array Length Constant ID
1903 SPIRVOperandVec Ops;
1904
SJW01901d92020-05-21 08:58:31 -05001905 Ops << ArrTy->getElementType() << CstLength;
SJWf93f5f32020-05-05 07:27:56 -05001906
1907 RID = addSPIRVInst<kTypes>(spv::OpTypeArray, Ops);
1908 }
1909 break;
1910 }
1911 case Type::FixedVectorTyID: {
1912 auto VecTy = cast<VectorType>(Ty);
1913 // <4 x i8> is changed to i32 if i8 is not generally supported.
1914 if (!clspv::Option::Int8Support() &&
1915 VecTy->getElementType() == Type::getInt8Ty(module->getContext())) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001916 if (VecTy->getElementCount().getKnownMinValue() == 4) {
SJWf93f5f32020-05-05 07:27:56 -05001917 RID = getSPIRVType(VecTy->getElementType());
1918 break;
1919 } else {
1920 Ty->print(errs());
1921 llvm_unreachable("Support above i8 vector type");
1922 }
1923 }
1924
1925 // Ops[0] = Component Type ID
1926 // Ops[1] = Component Count (Literal Number)
1927 SPIRVOperandVec Ops;
alan-baker5a8c3be2020-09-09 13:44:26 -04001928 Ops << VecTy->getElementType()
1929 << VecTy->getElementCount().getKnownMinValue();
SJWf93f5f32020-05-05 07:27:56 -05001930
1931 RID = addSPIRVInst<kTypes>(spv::OpTypeVector, Ops);
1932 break;
1933 }
1934 case Type::VoidTyID: {
1935 RID = addSPIRVInst<kTypes>(spv::OpTypeVoid);
1936 break;
1937 }
1938 case Type::FunctionTyID: {
1939 // Generate SPIRV instruction for function type.
1940 FunctionType *FTy = cast<FunctionType>(Ty);
1941
1942 // Ops[0] = Return Type ID
1943 // Ops[1] ... Ops[n] = Parameter Type IDs
1944 SPIRVOperandVec Ops;
1945
1946 // Find SPIRV instruction for return type
SJW01901d92020-05-21 08:58:31 -05001947 Ops << FTy->getReturnType();
SJWf93f5f32020-05-05 07:27:56 -05001948
1949 // Find SPIRV instructions for parameter types
1950 for (unsigned k = 0; k < FTy->getNumParams(); k++) {
1951 // Find SPIRV instruction for parameter type.
1952 auto ParamTy = FTy->getParamType(k);
1953 if (ParamTy->isPointerTy()) {
1954 auto PointeeTy = ParamTy->getPointerElementType();
1955 if (PointeeTy->isStructTy() &&
1956 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1957 ParamTy = PointeeTy;
1958 }
1959 }
1960
SJW01901d92020-05-21 08:58:31 -05001961 Ops << ParamTy;
SJWf93f5f32020-05-05 07:27:56 -05001962 }
1963
1964 RID = addSPIRVInst<kTypes>(spv::OpTypeFunction, Ops);
1965 break;
1966 }
1967 }
1968
SJW01901d92020-05-21 08:58:31 -05001969 if (RID.isValid()) {
SJWf93f5f32020-05-05 07:27:56 -05001970 TypeMap[Ty] = RID;
1971 }
1972 return RID;
David Neto22f144c2017-06-12 14:26:21 -04001973}
1974
SJW77b87ad2020-04-21 14:37:52 -05001975void SPIRVProducerPass::GenerateSPIRVTypes() {
David Neto22f144c2017-06-12 14:26:21 -04001976 for (Type *Ty : getTypeList()) {
SJWf93f5f32020-05-05 07:27:56 -05001977 getSPIRVType(Ty);
David Netoc6f3ab22018-04-06 18:02:31 -04001978 }
David Neto22f144c2017-06-12 14:26:21 -04001979}
1980
SJW806a5d82020-07-15 12:51:38 -05001981SPIRVID SPIRVProducerPass::getSPIRVInt32Constant(uint32_t CstVal) {
1982 Type *i32 = Type::getInt32Ty(module->getContext());
1983 Constant *Cst = ConstantInt::get(i32, CstVal);
1984 return getSPIRVValue(Cst);
1985}
1986
SJWf93f5f32020-05-05 07:27:56 -05001987SPIRVID SPIRVProducerPass::getSPIRVConstant(Constant *Cst) {
David Neto22f144c2017-06-12 14:26:21 -04001988 ValueMapType &VMap = getValueMap();
David Neto482550a2018-03-24 05:21:07 -07001989 const bool hack_undef = clspv::Option::HackUndef();
David Neto22f144c2017-06-12 14:26:21 -04001990
SJW01901d92020-05-21 08:58:31 -05001991 SPIRVID RID;
David Neto22f144c2017-06-12 14:26:21 -04001992
SJWf93f5f32020-05-05 07:27:56 -05001993 //
1994 // Generate OpConstant.
1995 //
1996 // Ops[0] = Result Type ID
1997 // Ops[1] .. Ops[n] = Values LiteralNumber
1998 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04001999
SJW01901d92020-05-21 08:58:31 -05002000 Ops << Cst->getType();
David Neto22f144c2017-06-12 14:26:21 -04002001
SJWf93f5f32020-05-05 07:27:56 -05002002 std::vector<uint32_t> LiteralNum;
2003 spv::Op Opcode = spv::OpNop;
David Neto22f144c2017-06-12 14:26:21 -04002004
SJWf93f5f32020-05-05 07:27:56 -05002005 if (isa<UndefValue>(Cst)) {
David Neto22f144c2017-06-12 14:26:21 -04002006 // Ops[0] = Result Type ID
SJWf93f5f32020-05-05 07:27:56 -05002007 Opcode = spv::OpUndef;
2008 if (hack_undef && IsTypeNullable(Cst->getType())) {
2009 Opcode = spv::OpConstantNull;
2010 }
2011 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(Cst)) {
alan-bakere2a62752020-07-09 22:53:23 -04002012 unsigned bit_width = CI->getBitWidth();
2013 if (bit_width == 1) {
SJWf93f5f32020-05-05 07:27:56 -05002014 // If the bitwidth of constant is 1, generate OpConstantTrue or
2015 // OpConstantFalse.
2016 if (CI->getZExtValue()) {
2017 // Ops[0] = Result Type ID
2018 Opcode = spv::OpConstantTrue;
David Neto22f144c2017-06-12 14:26:21 -04002019 } else {
SJWf93f5f32020-05-05 07:27:56 -05002020 // Ops[0] = Result Type ID
2021 Opcode = spv::OpConstantFalse;
David Neto22f144c2017-06-12 14:26:21 -04002022 }
SJWf93f5f32020-05-05 07:27:56 -05002023 } else {
2024 auto V = CI->getZExtValue();
2025 LiteralNum.push_back(V & 0xFFFFFFFF);
2026
alan-bakere2a62752020-07-09 22:53:23 -04002027 if (bit_width > 32) {
SJWf93f5f32020-05-05 07:27:56 -05002028 LiteralNum.push_back(V >> 32);
David Neto22f144c2017-06-12 14:26:21 -04002029 }
2030
2031 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002032
SJW01901d92020-05-21 08:58:31 -05002033 Ops << LiteralNum;
SJWf93f5f32020-05-05 07:27:56 -05002034 }
2035 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Cst)) {
2036 uint64_t FPVal = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
2037 Type *CFPTy = CFP->getType();
2038 if (CFPTy->isFloatTy()) {
2039 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
2040 } else if (CFPTy->isDoubleTy()) {
2041 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
2042 LiteralNum.push_back(FPVal >> 32);
2043 } else if (CFPTy->isHalfTy()) {
2044 LiteralNum.push_back(FPVal & 0xFFFF);
2045 } else {
2046 CFPTy->print(errs());
2047 llvm_unreachable("Implement this ConstantFP Type");
2048 }
David Neto22f144c2017-06-12 14:26:21 -04002049
SJWf93f5f32020-05-05 07:27:56 -05002050 Opcode = spv::OpConstant;
David Neto49351ac2017-08-26 17:32:20 -04002051
SJW01901d92020-05-21 08:58:31 -05002052 Ops << LiteralNum;
SJWf93f5f32020-05-05 07:27:56 -05002053 } else if (isa<ConstantDataSequential>(Cst) &&
2054 cast<ConstantDataSequential>(Cst)->isString()) {
2055 Cst->print(errs());
2056 llvm_unreachable("Implement this Constant");
David Neto49351ac2017-08-26 17:32:20 -04002057
SJWf93f5f32020-05-05 07:27:56 -05002058 } else if (const ConstantDataSequential *CDS =
2059 dyn_cast<ConstantDataSequential>(Cst)) {
2060 // Let's convert <4 x i8> constant to int constant specially.
2061 // This case occurs when all the values are specified as constant
2062 // ints.
2063 Type *CstTy = Cst->getType();
2064 if (is4xi8vec(CstTy)) {
SJWf93f5f32020-05-05 07:27:56 -05002065 //
2066 // Generate OpConstant with OpTypeInt 32 0.
2067 //
2068 uint32_t IntValue = 0;
2069 for (unsigned k = 0; k < 4; k++) {
2070 const uint64_t Val = CDS->getElementAsInteger(k);
2071 IntValue = (IntValue << 8) | (Val & 0xffu);
David Neto49351ac2017-08-26 17:32:20 -04002072 }
2073
SJW806a5d82020-07-15 12:51:38 -05002074 RID = getSPIRVInt32Constant(IntValue);
SJWf93f5f32020-05-05 07:27:56 -05002075 } else {
2076
David Neto49351ac2017-08-26 17:32:20 -04002077 // A normal constant-data-sequential case.
David Neto22f144c2017-06-12 14:26:21 -04002078 for (unsigned k = 0; k < CDS->getNumElements(); k++) {
SJW01901d92020-05-21 08:58:31 -05002079 Ops << CDS->getElementAsConstant(k);
David Neto22f144c2017-06-12 14:26:21 -04002080 }
2081
2082 Opcode = spv::OpConstantComposite;
SJWf93f5f32020-05-05 07:27:56 -05002083 }
2084 } else if (const ConstantAggregate *CA = dyn_cast<ConstantAggregate>(Cst)) {
2085 // Let's convert <4 x i8> constant to int constant specially.
2086 // This case occurs when at least one of the values is an undef.
2087 Type *CstTy = Cst->getType();
2088 if (is4xi8vec(CstTy)) {
SJWf93f5f32020-05-05 07:27:56 -05002089 //
2090 // Generate OpConstant with OpTypeInt 32 0.
2091 //
2092 uint32_t IntValue = 0;
2093 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end();
2094 I != E; ++I) {
2095 uint64_t Val = 0;
2096 const Value *CV = *I;
2097 if (auto *CI2 = dyn_cast<ConstantInt>(CV)) {
2098 Val = CI2->getZExtValue();
David Neto22f144c2017-06-12 14:26:21 -04002099 }
SJWf93f5f32020-05-05 07:27:56 -05002100 IntValue = (IntValue << 8) | (Val & 0xffu);
David Neto22f144c2017-06-12 14:26:21 -04002101 }
2102
SJW806a5d82020-07-15 12:51:38 -05002103 RID = getSPIRVInt32Constant(IntValue);
SJWf93f5f32020-05-05 07:27:56 -05002104 } else {
2105
David Neto22f144c2017-06-12 14:26:21 -04002106 // We use a constant composite in SPIR-V for our constant aggregate in
2107 // LLVM.
2108 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002109
2110 for (unsigned k = 0; k < CA->getNumOperands(); k++) {
David Neto22f144c2017-06-12 14:26:21 -04002111 // And add an operand to the composite we are constructing
SJW01901d92020-05-21 08:58:31 -05002112 Ops << CA->getAggregateElement(k);
David Neto22f144c2017-06-12 14:26:21 -04002113 }
David Neto22f144c2017-06-12 14:26:21 -04002114 }
SJWf93f5f32020-05-05 07:27:56 -05002115 } else if (Cst->isNullValue()) {
2116 Opcode = spv::OpConstantNull;
2117 } else {
2118 Cst->print(errs());
2119 llvm_unreachable("Unsupported Constant???");
2120 }
David Neto22f144c2017-06-12 14:26:21 -04002121
SJWf93f5f32020-05-05 07:27:56 -05002122 if (Opcode == spv::OpConstantNull && Cst->getType()->isPointerTy()) {
2123 // Null pointer requires variable pointers.
2124 setVariablePointersCapabilities(Cst->getType()->getPointerAddressSpace());
2125 }
alan-baker5b86ed72019-02-15 08:26:50 -05002126
SJWf93f5f32020-05-05 07:27:56 -05002127 if (RID == 0) {
2128 RID = addSPIRVInst<kConstants>(Opcode, Ops);
2129 }
2130
2131 VMap[Cst] = RID;
2132
2133 return RID;
2134}
2135
2136SPIRVID SPIRVProducerPass::getSPIRVValue(Value *V) {
2137 auto II = ValueMap.find(V);
2138 if (II != ValueMap.end()) {
SJW01901d92020-05-21 08:58:31 -05002139 assert(II->second.isValid());
SJWf93f5f32020-05-05 07:27:56 -05002140 return II->second;
2141 }
2142 if (Constant *Cst = dyn_cast<Constant>(V)) {
2143 return getSPIRVConstant(Cst);
2144 } else {
2145 llvm_unreachable("Variable not found");
2146 }
2147}
2148
SJW77b87ad2020-04-21 14:37:52 -05002149void SPIRVProducerPass::GenerateSamplers() {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002150 auto &sampler_map = getSamplerMap();
alan-baker09cb9802019-12-10 13:16:27 -05002151 SamplerLiteralToIDMap.clear();
David Neto862b7d82018-06-14 18:48:37 -04002152 DenseMap<unsigned, unsigned> SamplerLiteralToDescriptorSetMap;
2153 DenseMap<unsigned, unsigned> SamplerLiteralToBindingMap;
David Neto22f144c2017-06-12 14:26:21 -04002154
David Neto862b7d82018-06-14 18:48:37 -04002155 // We might have samplers in the sampler map that are not used
2156 // in the translation unit. We need to allocate variables
2157 // for them and bindings too.
2158 DenseSet<unsigned> used_bindings;
David Neto22f144c2017-06-12 14:26:21 -04002159
SJW77b87ad2020-04-21 14:37:52 -05002160 auto *var_fn = module->getFunction(clspv::LiteralSamplerFunction());
alan-baker09cb9802019-12-10 13:16:27 -05002161 // Return if there are no literal samplers.
alan-bakerb6b09dc2018-11-08 16:59:28 -05002162 if (!var_fn)
2163 return;
alan-baker09cb9802019-12-10 13:16:27 -05002164
David Neto862b7d82018-06-14 18:48:37 -04002165 for (auto user : var_fn->users()) {
2166 // Populate SamplerLiteralToDescriptorSetMap and
2167 // SamplerLiteralToBindingMap.
2168 //
2169 // Look for calls like
2170 // call %opencl.sampler_t addrspace(2)*
2171 // @clspv.sampler.var.literal(
2172 // i32 descriptor,
2173 // i32 binding,
alan-baker09cb9802019-12-10 13:16:27 -05002174 // i32 (index-into-sampler-map|sampler_mask))
alan-bakerb6b09dc2018-11-08 16:59:28 -05002175 if (auto *call = dyn_cast<CallInst>(user)) {
alan-baker09cb9802019-12-10 13:16:27 -05002176 const auto third_param = static_cast<unsigned>(
alan-bakerb6b09dc2018-11-08 16:59:28 -05002177 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
alan-baker09cb9802019-12-10 13:16:27 -05002178 auto sampler_value = third_param;
2179 if (clspv::Option::UseSamplerMap()) {
2180 if (third_param >= sampler_map.size()) {
2181 errs() << "Out of bounds index to sampler map: " << third_param;
2182 llvm_unreachable("bad sampler init: out of bounds");
2183 }
2184 sampler_value = sampler_map[third_param].first;
David Neto862b7d82018-06-14 18:48:37 -04002185 }
2186
David Neto862b7d82018-06-14 18:48:37 -04002187 const auto descriptor_set = static_cast<unsigned>(
2188 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
2189 const auto binding = static_cast<unsigned>(
2190 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
2191
2192 SamplerLiteralToDescriptorSetMap[sampler_value] = descriptor_set;
2193 SamplerLiteralToBindingMap[sampler_value] = binding;
2194 used_bindings.insert(binding);
2195 }
2196 }
2197
alan-baker09cb9802019-12-10 13:16:27 -05002198 DenseSet<size_t> seen;
2199 for (auto user : var_fn->users()) {
2200 if (!isa<CallInst>(user))
2201 continue;
2202
2203 auto call = cast<CallInst>(user);
2204 const unsigned third_param = static_cast<unsigned>(
2205 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
2206
2207 // Already allocated a variable for this value.
2208 if (!seen.insert(third_param).second)
2209 continue;
2210
2211 auto sampler_value = third_param;
2212 if (clspv::Option::UseSamplerMap()) {
2213 sampler_value = sampler_map[third_param].first;
2214 }
2215
SJW806a5d82020-07-15 12:51:38 -05002216 auto sampler_var_id = addSPIRVGlobalVariable(
2217 getSPIRVType(SamplerTy), spv::StorageClassUniformConstant);
David Neto22f144c2017-06-12 14:26:21 -04002218
alan-baker09cb9802019-12-10 13:16:27 -05002219 SamplerLiteralToIDMap[sampler_value] = sampler_var_id;
David Neto22f144c2017-06-12 14:26:21 -04002220
David Neto862b7d82018-06-14 18:48:37 -04002221 unsigned descriptor_set;
2222 unsigned binding;
alan-baker09cb9802019-12-10 13:16:27 -05002223 if (SamplerLiteralToBindingMap.find(sampler_value) ==
alan-bakerb6b09dc2018-11-08 16:59:28 -05002224 SamplerLiteralToBindingMap.end()) {
David Neto862b7d82018-06-14 18:48:37 -04002225 // This sampler is not actually used. Find the next one.
2226 for (binding = 0; used_bindings.count(binding); binding++)
2227 ;
2228 descriptor_set = 0; // Literal samplers always use descriptor set 0.
2229 used_bindings.insert(binding);
2230 } else {
alan-baker09cb9802019-12-10 13:16:27 -05002231 descriptor_set = SamplerLiteralToDescriptorSetMap[sampler_value];
2232 binding = SamplerLiteralToBindingMap[sampler_value];
alan-bakercff80152019-06-15 00:38:00 -04002233
alan-baker86ce19c2020-08-05 13:09:19 -04002234 auto import_id = getReflectionImport();
2235 SPIRVOperandVec Ops;
2236 Ops << getSPIRVType(Type::getVoidTy(module->getContext())) << import_id
2237 << reflection::ExtInstLiteralSampler
2238 << getSPIRVInt32Constant(descriptor_set)
2239 << getSPIRVInt32Constant(binding)
2240 << getSPIRVInt32Constant(sampler_value);
2241 addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
David Neto862b7d82018-06-14 18:48:37 -04002242 }
2243
SJW69939d52020-04-16 07:29:07 -05002244 // Ops[0] = Target ID
2245 // Ops[1] = Decoration (DescriptorSet)
2246 // Ops[2] = LiteralNumber according to Decoration
SJW806a5d82020-07-15 12:51:38 -05002247 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05002248 Ops << sampler_var_id << spv::DecorationDescriptorSet << descriptor_set;
David Neto22f144c2017-06-12 14:26:21 -04002249
SJWf93f5f32020-05-05 07:27:56 -05002250 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002251
2252 // Ops[0] = Target ID
2253 // Ops[1] = Decoration (Binding)
2254 // Ops[2] = LiteralNumber according to Decoration
2255 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002256 Ops << sampler_var_id << spv::DecorationBinding << binding;
David Neto22f144c2017-06-12 14:26:21 -04002257
SJWf93f5f32020-05-05 07:27:56 -05002258 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002259 }
David Neto862b7d82018-06-14 18:48:37 -04002260}
David Neto22f144c2017-06-12 14:26:21 -04002261
SJW77b87ad2020-04-21 14:37:52 -05002262void SPIRVProducerPass::GenerateResourceVars() {
David Neto862b7d82018-06-14 18:48:37 -04002263 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04002264
David Neto862b7d82018-06-14 18:48:37 -04002265 // Generate variables. Make one for each of resource var info object.
2266 for (auto *info : ModuleOrderedResourceVars) {
2267 Type *type = info->var_fn->getReturnType();
2268 // Remap the address space for opaque types.
2269 switch (info->arg_kind) {
2270 case clspv::ArgKind::Sampler:
2271 case clspv::ArgKind::ReadOnlyImage:
2272 case clspv::ArgKind::WriteOnlyImage:
2273 type = PointerType::get(type->getPointerElementType(),
2274 clspv::AddressSpace::UniformConstant);
2275 break;
2276 default:
2277 break;
2278 }
David Neto22f144c2017-06-12 14:26:21 -04002279
David Neto862b7d82018-06-14 18:48:37 -04002280 const auto sc = GetStorageClassForArgKind(info->arg_kind);
David Neto22f144c2017-06-12 14:26:21 -04002281
SJW806a5d82020-07-15 12:51:38 -05002282 info->var_id = addSPIRVGlobalVariable(getSPIRVType(type), sc);
David Neto862b7d82018-06-14 18:48:37 -04002283
2284 // Map calls to the variable-builtin-function.
2285 for (auto &U : info->var_fn->uses()) {
2286 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
2287 const auto set = unsigned(
2288 dyn_cast<ConstantInt>(call->getOperand(0))->getZExtValue());
2289 const auto binding = unsigned(
2290 dyn_cast<ConstantInt>(call->getOperand(1))->getZExtValue());
2291 if (set == info->descriptor_set && binding == info->binding) {
2292 switch (info->arg_kind) {
2293 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002294 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002295 case clspv::ArgKind::Pod:
alan-baker9b0ec3c2020-04-06 14:45:34 -04002296 case clspv::ArgKind::PodUBO:
2297 case clspv::ArgKind::PodPushConstant:
David Neto862b7d82018-06-14 18:48:37 -04002298 // The call maps to the variable directly.
2299 VMap[call] = info->var_id;
2300 break;
2301 case clspv::ArgKind::Sampler:
2302 case clspv::ArgKind::ReadOnlyImage:
2303 case clspv::ArgKind::WriteOnlyImage:
2304 // The call maps to a load we generate later.
2305 ResourceVarDeferredLoadCalls[call] = info->var_id;
2306 break;
2307 default:
2308 llvm_unreachable("Unhandled arg kind");
2309 }
2310 }
David Neto22f144c2017-06-12 14:26:21 -04002311 }
David Neto862b7d82018-06-14 18:48:37 -04002312 }
2313 }
David Neto22f144c2017-06-12 14:26:21 -04002314
David Neto862b7d82018-06-14 18:48:37 -04002315 // Generate associated decorations.
SJWf93f5f32020-05-05 07:27:56 -05002316 SPIRVOperandVec Ops;
David Neto862b7d82018-06-14 18:48:37 -04002317 for (auto *info : ModuleOrderedResourceVars) {
alan-baker9b0ec3c2020-04-06 14:45:34 -04002318 // Push constants don't need descriptor set or binding decorations.
2319 if (info->arg_kind == clspv::ArgKind::PodPushConstant)
2320 continue;
2321
David Neto862b7d82018-06-14 18:48:37 -04002322 // Decorate with DescriptorSet and Binding.
2323 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002324 Ops << info->var_id << spv::DecorationDescriptorSet << info->descriptor_set;
SJWf93f5f32020-05-05 07:27:56 -05002325 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto862b7d82018-06-14 18:48:37 -04002326
2327 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002328 Ops << info->var_id << spv::DecorationBinding << info->binding;
SJWf93f5f32020-05-05 07:27:56 -05002329 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto862b7d82018-06-14 18:48:37 -04002330
alan-bakere9308012019-03-15 10:25:13 -04002331 if (info->coherent) {
2332 // Decorate with Coherent if required for the variable.
2333 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002334 Ops << info->var_id << spv::DecorationCoherent;
SJWf93f5f32020-05-05 07:27:56 -05002335 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
alan-bakere9308012019-03-15 10:25:13 -04002336 }
2337
David Neto862b7d82018-06-14 18:48:37 -04002338 // Generate NonWritable and NonReadable
2339 switch (info->arg_kind) {
2340 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002341 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002342 if (info->var_fn->getReturnType()->getPointerAddressSpace() ==
2343 clspv::AddressSpace::Constant) {
2344 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002345 Ops << info->var_id << spv::DecorationNonWritable;
SJWf93f5f32020-05-05 07:27:56 -05002346 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002347 }
David Neto862b7d82018-06-14 18:48:37 -04002348 break;
David Neto862b7d82018-06-14 18:48:37 -04002349 case clspv::ArgKind::WriteOnlyImage:
2350 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002351 Ops << info->var_id << spv::DecorationNonReadable;
SJWf93f5f32020-05-05 07:27:56 -05002352 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto862b7d82018-06-14 18:48:37 -04002353 break;
2354 default:
2355 break;
David Neto22f144c2017-06-12 14:26:21 -04002356 }
2357 }
2358}
2359
2360void SPIRVProducerPass::GenerateGlobalVar(GlobalVariable &GV) {
David Neto22f144c2017-06-12 14:26:21 -04002361 ValueMapType &VMap = getValueMap();
SJW01901d92020-05-21 08:58:31 -05002362 std::vector<SPIRVID> &BuiltinDimVec = getBuiltinDimVec();
David Neto85082642018-03-24 06:55:20 -07002363 const DataLayout &DL = GV.getParent()->getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04002364
2365 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
2366 Type *Ty = GV.getType();
2367 PointerType *PTy = cast<PointerType>(Ty);
2368
SJW01901d92020-05-21 08:58:31 -05002369 SPIRVID InitializerID;
David Neto22f144c2017-06-12 14:26:21 -04002370
2371 // Workgroup size is handled differently (it goes into a constant)
2372 if (spv::BuiltInWorkgroupSize == BuiltinType) {
David Neto22f144c2017-06-12 14:26:21 -04002373 uint32_t PrevXDimCst = 0xFFFFFFFF;
2374 uint32_t PrevYDimCst = 0xFFFFFFFF;
2375 uint32_t PrevZDimCst = 0xFFFFFFFF;
alan-baker3b609772020-09-03 19:10:17 -04002376 bool HasMD = true;
David Neto22f144c2017-06-12 14:26:21 -04002377 for (Function &Func : *GV.getParent()) {
2378 if (Func.isDeclaration()) {
2379 continue;
2380 }
2381
2382 // We only need to check kernels.
2383 if (Func.getCallingConv() != CallingConv::SPIR_KERNEL) {
2384 continue;
2385 }
2386
2387 if (const MDNode *MD =
2388 dyn_cast<Function>(&Func)->getMetadata("reqd_work_group_size")) {
2389 uint32_t CurXDimCst = static_cast<uint32_t>(
2390 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
2391 uint32_t CurYDimCst = static_cast<uint32_t>(
2392 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
2393 uint32_t CurZDimCst = static_cast<uint32_t>(
2394 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
2395
2396 if (PrevXDimCst == 0xFFFFFFFF && PrevYDimCst == 0xFFFFFFFF &&
2397 PrevZDimCst == 0xFFFFFFFF) {
2398 PrevXDimCst = CurXDimCst;
2399 PrevYDimCst = CurYDimCst;
2400 PrevZDimCst = CurZDimCst;
2401 } else if (CurXDimCst != PrevXDimCst || CurYDimCst != PrevYDimCst ||
2402 CurZDimCst != PrevZDimCst) {
alan-baker3b609772020-09-03 19:10:17 -04002403 HasMD = false;
2404 continue;
David Neto22f144c2017-06-12 14:26:21 -04002405 } else {
2406 continue;
2407 }
2408
2409 //
2410 // Generate OpConstantComposite.
2411 //
2412 // Ops[0] : Result Type ID
2413 // Ops[1] : Constant size for x dimension.
2414 // Ops[2] : Constant size for y dimension.
2415 // Ops[3] : Constant size for z dimension.
SJWf93f5f32020-05-05 07:27:56 -05002416 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04002417
SJW01901d92020-05-21 08:58:31 -05002418 SPIRVID XDimCstID =
SJWf93f5f32020-05-05 07:27:56 -05002419 getSPIRVValue(mdconst::extract<ConstantInt>(MD->getOperand(0)));
SJW01901d92020-05-21 08:58:31 -05002420 SPIRVID YDimCstID =
SJWf93f5f32020-05-05 07:27:56 -05002421 getSPIRVValue(mdconst::extract<ConstantInt>(MD->getOperand(1)));
SJW01901d92020-05-21 08:58:31 -05002422 SPIRVID ZDimCstID =
SJWf93f5f32020-05-05 07:27:56 -05002423 getSPIRVValue(mdconst::extract<ConstantInt>(MD->getOperand(2)));
David Neto22f144c2017-06-12 14:26:21 -04002424
SJW01901d92020-05-21 08:58:31 -05002425 Ops << Ty->getPointerElementType() << XDimCstID << YDimCstID
2426 << ZDimCstID;
David Neto22f144c2017-06-12 14:26:21 -04002427
SJWf93f5f32020-05-05 07:27:56 -05002428 InitializerID =
2429 addSPIRVInst<kGlobalVariables>(spv::OpConstantComposite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002430 } else {
alan-baker3b609772020-09-03 19:10:17 -04002431 HasMD = false;
David Neto22f144c2017-06-12 14:26:21 -04002432 }
2433 }
2434
2435 // If all kernels do not have metadata for reqd_work_group_size, generate
2436 // OpSpecConstants for x/y/z dimension.
Kévin Petit21c23c62020-04-29 01:38:28 +01002437 if (!HasMD || clspv::Option::NonUniformNDRangeSupported()) {
David Neto22f144c2017-06-12 14:26:21 -04002438 //
2439 // Generate OpSpecConstants for x/y/z dimension.
2440 //
2441 // Ops[0] : Result Type ID
2442 // Ops[1] : Constant size for x/y/z dimension (Literal Number).
David Neto22f144c2017-06-12 14:26:21 -04002443
alan-bakera1be3322020-04-20 12:48:18 -04002444 // Allocate spec constants for workgroup size.
SJW77b87ad2020-04-21 14:37:52 -05002445 clspv::AddWorkgroupSpecConstants(module);
alan-bakera1be3322020-04-20 12:48:18 -04002446
SJWf93f5f32020-05-05 07:27:56 -05002447 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05002448 SPIRVID result_type_id = getSPIRVType(
SJWf93f5f32020-05-05 07:27:56 -05002449 dyn_cast<VectorType>(Ty->getPointerElementType())->getElementType());
David Neto22f144c2017-06-12 14:26:21 -04002450
David Neto257c3892018-04-11 13:19:45 -04002451 // X Dimension
SJW01901d92020-05-21 08:58:31 -05002452 Ops << result_type_id << 1;
2453 SPIRVID XDimCstID = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002454
2455 // Y Dimension
2456 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002457 Ops << result_type_id << 1;
2458 SPIRVID YDimCstID = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002459
2460 // Z Dimension
2461 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002462 Ops << result_type_id << 1;
2463 SPIRVID ZDimCstID = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002464
David Neto257c3892018-04-11 13:19:45 -04002465 BuiltinDimVec.push_back(XDimCstID);
2466 BuiltinDimVec.push_back(YDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002467 BuiltinDimVec.push_back(ZDimCstID);
2468
David Neto22f144c2017-06-12 14:26:21 -04002469 //
2470 // Generate OpSpecConstantComposite.
2471 //
2472 // Ops[0] : Result Type ID
2473 // Ops[1] : Constant size for x dimension.
2474 // Ops[2] : Constant size for y dimension.
2475 // Ops[3] : Constant size for z dimension.
David Neto22f144c2017-06-12 14:26:21 -04002476 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002477 Ops << Ty->getPointerElementType() << XDimCstID << YDimCstID << ZDimCstID;
David Neto22f144c2017-06-12 14:26:21 -04002478
SJWf93f5f32020-05-05 07:27:56 -05002479 InitializerID =
2480 addSPIRVInst<kConstants>(spv::OpSpecConstantComposite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002481 }
alan-bakerbed3a882020-04-21 14:42:41 -04002482 } else if (BuiltinType == spv::BuiltInWorkDim) {
2483 // 1. Generate a specialization constant with a default of 3.
2484 // 2. Allocate and annotate a SpecId for the constant.
2485 // 3. Use the spec constant as the initializer for the variable.
SJWf93f5f32020-05-05 07:27:56 -05002486 SPIRVOperandVec Ops;
alan-bakerbed3a882020-04-21 14:42:41 -04002487
2488 //
2489 // Generate OpSpecConstant.
2490 //
2491 // Ops[0] : Result Type ID
2492 // Ops[1] : Default literal value
alan-bakerbed3a882020-04-21 14:42:41 -04002493
SJW01901d92020-05-21 08:58:31 -05002494 Ops << IntegerType::get(GV.getContext(), 32) << 3;
alan-bakerbed3a882020-04-21 14:42:41 -04002495
SJWf93f5f32020-05-05 07:27:56 -05002496 InitializerID = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
alan-bakerbed3a882020-04-21 14:42:41 -04002497
2498 //
2499 // Generate SpecId decoration.
2500 //
2501 // Ops[0] : target
2502 // Ops[1] : decoration
2503 // Ops[2] : SpecId
Alan Baker75ccc252020-04-21 17:11:52 -04002504 auto spec_id = AllocateSpecConstant(module, SpecConstant::kWorkDim);
alan-bakerbed3a882020-04-21 14:42:41 -04002505 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002506 Ops << InitializerID << spv::DecorationSpecId << spec_id;
alan-bakerbed3a882020-04-21 14:42:41 -04002507
SJWf93f5f32020-05-05 07:27:56 -05002508 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002509 } else if (BuiltinType == spv::BuiltInGlobalOffset) {
2510 // 1. Generate a spec constant with a default of {0, 0, 0}.
2511 // 2. Allocate and annotate SpecIds for the constants.
2512 // 3. Use the spec constant as the initializer for the variable.
SJWf93f5f32020-05-05 07:27:56 -05002513 SPIRVOperandVec Ops;
alan-bakere1996972020-05-04 08:38:12 -04002514
2515 //
2516 // Generate OpSpecConstant for each dimension.
2517 //
2518 // Ops[0] : Result Type ID
2519 // Ops[1] : Default literal value
2520 //
SJW01901d92020-05-21 08:58:31 -05002521 Ops << IntegerType::get(GV.getContext(), 32) << 0;
2522 SPIRVID x_id = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002523
alan-bakere1996972020-05-04 08:38:12 -04002524 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002525 Ops << IntegerType::get(GV.getContext(), 32) << 0;
2526 SPIRVID y_id = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002527
alan-bakere1996972020-05-04 08:38:12 -04002528 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002529 Ops << IntegerType::get(GV.getContext(), 32) << 0;
2530 SPIRVID z_id = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002531
2532 //
2533 // Generate SpecId decoration for each dimension.
2534 //
2535 // Ops[0] : target
2536 // Ops[1] : decoration
2537 // Ops[2] : SpecId
2538 //
2539 auto spec_id = AllocateSpecConstant(module, SpecConstant::kGlobalOffsetX);
2540 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002541 Ops << x_id << spv::DecorationSpecId << spec_id;
SJWf93f5f32020-05-05 07:27:56 -05002542 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002543
2544 spec_id = AllocateSpecConstant(module, SpecConstant::kGlobalOffsetY);
2545 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002546 Ops << y_id << spv::DecorationSpecId << spec_id;
SJWf93f5f32020-05-05 07:27:56 -05002547 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002548
2549 spec_id = AllocateSpecConstant(module, SpecConstant::kGlobalOffsetZ);
2550 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002551 Ops << z_id << spv::DecorationSpecId << spec_id;
SJWf93f5f32020-05-05 07:27:56 -05002552 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002553
2554 //
2555 // Generate OpSpecConstantComposite.
2556 //
2557 // Ops[0] : type id
2558 // Ops[1..n-1] : elements
2559 //
alan-bakere1996972020-05-04 08:38:12 -04002560 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002561 Ops << GV.getType()->getPointerElementType() << x_id << y_id << z_id;
SJWf93f5f32020-05-05 07:27:56 -05002562 InitializerID = addSPIRVInst<kConstants>(spv::OpSpecConstantComposite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002563 }
2564
David Neto85082642018-03-24 06:55:20 -07002565 const auto AS = PTy->getAddressSpace();
SJW806a5d82020-07-15 12:51:38 -05002566 const auto spvSC = GetStorageClass(AS);
David Neto22f144c2017-06-12 14:26:21 -04002567
David Neto85082642018-03-24 06:55:20 -07002568 const bool module_scope_constant_external_init =
David Neto862b7d82018-06-14 18:48:37 -04002569 (AS == AddressSpace::Constant) && GV.hasInitializer() &&
David Neto85082642018-03-24 06:55:20 -07002570 clspv::Option::ModuleConstantsInStorageBuffer();
2571
Kévin Petit23d5f182019-08-13 16:21:29 +01002572 if (GV.hasInitializer()) {
2573 auto GVInit = GV.getInitializer();
2574 if (!isa<UndefValue>(GVInit) && !module_scope_constant_external_init) {
SJWf93f5f32020-05-05 07:27:56 -05002575 InitializerID = getSPIRVValue(GVInit);
David Neto85082642018-03-24 06:55:20 -07002576 }
2577 }
Kévin Petit23d5f182019-08-13 16:21:29 +01002578
SJW806a5d82020-07-15 12:51:38 -05002579 SPIRVID var_id =
2580 addSPIRVGlobalVariable(getSPIRVType(Ty), spvSC, InitializerID);
David Neto85082642018-03-24 06:55:20 -07002581
SJWf93f5f32020-05-05 07:27:56 -05002582 VMap[&GV] = var_id;
David Neto22f144c2017-06-12 14:26:21 -04002583
alan-bakere1996972020-05-04 08:38:12 -04002584 auto IsOpenCLBuiltin = [](spv::BuiltIn builtin) {
2585 return builtin == spv::BuiltInWorkDim ||
2586 builtin == spv::BuiltInGlobalOffset;
2587 };
2588
alan-bakere1996972020-05-04 08:38:12 -04002589 // If we have a builtin (not an OpenCL builtin).
2590 if (spv::BuiltInMax != BuiltinType && !IsOpenCLBuiltin(BuiltinType)) {
David Neto22f144c2017-06-12 14:26:21 -04002591 //
2592 // Generate OpDecorate.
2593 //
2594 // DOps[0] = Target ID
2595 // DOps[1] = Decoration (Builtin)
2596 // DOps[2] = BuiltIn ID
SJW01901d92020-05-21 08:58:31 -05002597 SPIRVID ResultID;
David Neto22f144c2017-06-12 14:26:21 -04002598
2599 // WorkgroupSize is different, we decorate the constant composite that has
2600 // its value, rather than the variable that we use to access the value.
2601 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2602 ResultID = InitializerID;
David Netoa60b00b2017-09-15 16:34:09 -04002603 // Save both the value and variable IDs for later.
2604 WorkgroupSizeValueID = InitializerID;
SJWf93f5f32020-05-05 07:27:56 -05002605 WorkgroupSizeVarID = getSPIRVValue(&GV);
David Neto22f144c2017-06-12 14:26:21 -04002606 } else {
SJWf93f5f32020-05-05 07:27:56 -05002607 ResultID = getSPIRVValue(&GV);
David Neto22f144c2017-06-12 14:26:21 -04002608 }
2609
SJW806a5d82020-07-15 12:51:38 -05002610 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05002611 Ops << ResultID << spv::DecorationBuiltIn << BuiltinType;
David Neto22f144c2017-06-12 14:26:21 -04002612
SJW01901d92020-05-21 08:58:31 -05002613 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto85082642018-03-24 06:55:20 -07002614 } else if (module_scope_constant_external_init) {
2615 // This module scope constant is initialized from a storage buffer with data
2616 // provided by the host at binding 0 of the next descriptor set.
SJW77b87ad2020-04-21 14:37:52 -05002617 const uint32_t descriptor_set = TakeDescriptorIndex(module);
David Neto85082642018-03-24 06:55:20 -07002618
alan-baker86ce19c2020-08-05 13:09:19 -04002619 // Emit the intializer as a reflection instruction.
David Neto85082642018-03-24 06:55:20 -07002620 // Use "kind,buffer" to indicate storage buffer. We might want to expand
2621 // that later to other types, like uniform buffer.
alan-bakerf5e5f692018-11-27 08:33:24 -05002622 std::string hexbytes;
2623 llvm::raw_string_ostream str(hexbytes);
2624 clspv::ConstantEmitter(DL, str).Emit(GV.getInitializer());
alan-baker86ce19c2020-08-05 13:09:19 -04002625
2626 // Reflection instruction for constant data.
2627 SPIRVOperandVec Ops;
2628 auto data_id = addSPIRVInst<kDebug>(spv::OpString, str.str().c_str());
2629 Ops << getSPIRVType(Type::getVoidTy(module->getContext()))
2630 << getReflectionImport() << reflection::ExtInstConstantDataStorageBuffer
2631 << getSPIRVInt32Constant(descriptor_set) << getSPIRVInt32Constant(0)
2632 << data_id;
2633 addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
David Neto85082642018-03-24 06:55:20 -07002634
David Neto85082642018-03-24 06:55:20 -07002635 // OpDecorate %var DescriptorSet <descriptor_set>
alan-baker86ce19c2020-08-05 13:09:19 -04002636 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002637 Ops << var_id << spv::DecorationDescriptorSet << descriptor_set;
2638 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
SJW69939d52020-04-16 07:29:07 -05002639
2640 // OpDecorate %var Binding <binding>
SJW01901d92020-05-21 08:58:31 -05002641 Ops.clear();
2642 Ops << var_id << spv::DecorationBinding << 0;
2643 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Netoc6f3ab22018-04-06 18:02:31 -04002644 }
2645}
2646
David Neto22f144c2017-06-12 14:26:21 -04002647void SPIRVProducerPass::GenerateFuncPrologue(Function &F) {
David Neto22f144c2017-06-12 14:26:21 -04002648 ValueMapType &VMap = getValueMap();
2649 EntryPointVecType &EntryPoints = getEntryPointVec();
David Neto22f144c2017-06-12 14:26:21 -04002650 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
2651 auto &GlobalConstArgSet = getGlobalConstArgSet();
2652
2653 FunctionType *FTy = F.getFunctionType();
2654
2655 //
David Neto22f144c2017-06-12 14:26:21 -04002656 // Generate OPFunction.
2657 //
2658
2659 // FOps[0] : Result Type ID
2660 // FOps[1] : Function Control
2661 // FOps[2] : Function Type ID
SJWf93f5f32020-05-05 07:27:56 -05002662 SPIRVOperandVec FOps;
David Neto22f144c2017-06-12 14:26:21 -04002663
2664 // Find SPIRV instruction for return type.
SJW01901d92020-05-21 08:58:31 -05002665 FOps << FTy->getReturnType();
David Neto22f144c2017-06-12 14:26:21 -04002666
2667 // Check function attributes for SPIRV Function Control.
2668 uint32_t FuncControl = spv::FunctionControlMaskNone;
2669 if (F.hasFnAttribute(Attribute::AlwaysInline)) {
2670 FuncControl |= spv::FunctionControlInlineMask;
2671 }
2672 if (F.hasFnAttribute(Attribute::NoInline)) {
2673 FuncControl |= spv::FunctionControlDontInlineMask;
2674 }
2675 // TODO: Check llvm attribute for Function Control Pure.
2676 if (F.hasFnAttribute(Attribute::ReadOnly)) {
2677 FuncControl |= spv::FunctionControlPureMask;
2678 }
2679 // TODO: Check llvm attribute for Function Control Const.
2680 if (F.hasFnAttribute(Attribute::ReadNone)) {
2681 FuncControl |= spv::FunctionControlConstMask;
2682 }
2683
SJW01901d92020-05-21 08:58:31 -05002684 FOps << FuncControl;
David Neto22f144c2017-06-12 14:26:21 -04002685
SJW01901d92020-05-21 08:58:31 -05002686 SPIRVID FTyID;
David Neto22f144c2017-06-12 14:26:21 -04002687 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
2688 SmallVector<Type *, 4> NewFuncParamTys;
2689 FunctionType *NewFTy =
2690 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
SJWf93f5f32020-05-05 07:27:56 -05002691 FTyID = getSPIRVType(NewFTy);
David Neto22f144c2017-06-12 14:26:21 -04002692 } else {
David Neto9ed8e2f2018-03-24 06:47:24 -07002693 // Handle regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04002694 if (GlobalConstFuncTyMap.count(FTy)) {
SJWf93f5f32020-05-05 07:27:56 -05002695 FTyID = getSPIRVType(GlobalConstFuncTyMap[FTy].first);
David Neto22f144c2017-06-12 14:26:21 -04002696 } else {
SJWf93f5f32020-05-05 07:27:56 -05002697 FTyID = getSPIRVType(FTy);
David Neto22f144c2017-06-12 14:26:21 -04002698 }
2699 }
2700
SJW01901d92020-05-21 08:58:31 -05002701 FOps << FTyID;
David Neto22f144c2017-06-12 14:26:21 -04002702
SJWf93f5f32020-05-05 07:27:56 -05002703 // Generate SPIRV instruction for function.
2704 SPIRVID FID = addSPIRVInst(spv::OpFunction, FOps);
2705 VMap[&F] = FID;
David Neto22f144c2017-06-12 14:26:21 -04002706
SJWf93f5f32020-05-05 07:27:56 -05002707 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
2708 EntryPoints.push_back(std::make_pair(&F, FID));
2709 }
David Neto22f144c2017-06-12 14:26:21 -04002710
David Neto482550a2018-03-24 05:21:07 -07002711 if (clspv::Option::ShowIDs()) {
SJW01901d92020-05-21 08:58:31 -05002712 errs() << "Function " << F.getName() << " is " << FID.get() << "\n";
David Netob05675d2018-02-16 12:37:49 -05002713 }
David Neto22f144c2017-06-12 14:26:21 -04002714
2715 //
2716 // Generate OpFunctionParameter for Normal function.
2717 //
2718
2719 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
alan-bakere9308012019-03-15 10:25:13 -04002720
David Neto22f144c2017-06-12 14:26:21 -04002721 // Iterate Argument for name instead of param type from function type.
2722 unsigned ArgIdx = 0;
2723 for (Argument &Arg : F.args()) {
David Neto22f144c2017-06-12 14:26:21 -04002724 // ParamOps[0] : Result Type ID
SJW01901d92020-05-21 08:58:31 -05002725 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04002726
2727 // Find SPIRV instruction for parameter type.
SJW01901d92020-05-21 08:58:31 -05002728 SPIRVID ParamTyID = getSPIRVType(Arg.getType());
David Neto22f144c2017-06-12 14:26:21 -04002729 if (PointerType *PTy = dyn_cast<PointerType>(Arg.getType())) {
2730 if (GlobalConstFuncTyMap.count(FTy)) {
2731 if (ArgIdx == GlobalConstFuncTyMap[FTy].second) {
2732 Type *EleTy = PTy->getPointerElementType();
2733 Type *ArgTy =
2734 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
SJWf93f5f32020-05-05 07:27:56 -05002735 ParamTyID = getSPIRVType(ArgTy);
David Neto22f144c2017-06-12 14:26:21 -04002736 GlobalConstArgSet.insert(&Arg);
2737 }
2738 }
2739 }
SJW01901d92020-05-21 08:58:31 -05002740 Ops << ParamTyID;
David Neto22f144c2017-06-12 14:26:21 -04002741
2742 // Generate SPIRV instruction for parameter.
SJW01901d92020-05-21 08:58:31 -05002743 SPIRVID param_id = addSPIRVInst(spv::OpFunctionParameter, Ops);
SJWf93f5f32020-05-05 07:27:56 -05002744 VMap[&Arg] = param_id;
2745
2746 if (CalledWithCoherentResource(Arg)) {
2747 // If the arg is passed a coherent resource ever, then decorate this
2748 // parameter with Coherent too.
SJW01901d92020-05-21 08:58:31 -05002749 Ops.clear();
2750 Ops << param_id << spv::DecorationCoherent;
2751 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
SJWf93f5f32020-05-05 07:27:56 -05002752 }
David Neto22f144c2017-06-12 14:26:21 -04002753
2754 ArgIdx++;
2755 }
2756 }
2757}
2758
SJW77b87ad2020-04-21 14:37:52 -05002759void SPIRVProducerPass::GenerateModuleInfo() {
David Neto22f144c2017-06-12 14:26:21 -04002760 EntryPointVecType &EntryPoints = getEntryPointVec();
SJW806a5d82020-07-15 12:51:38 -05002761 auto &EntryPointInterfaces = getEntryPointInterfacesList();
SJW01901d92020-05-21 08:58:31 -05002762 std::vector<SPIRVID> &BuiltinDimVec = getBuiltinDimVec();
David Neto22f144c2017-06-12 14:26:21 -04002763
SJWf93f5f32020-05-05 07:27:56 -05002764 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04002765
SJW01901d92020-05-21 08:58:31 -05002766 for (auto Capability : CapabilitySet) {
David Neto22f144c2017-06-12 14:26:21 -04002767 //
SJW01901d92020-05-21 08:58:31 -05002768 // Generate OpCapability
David Neto22f144c2017-06-12 14:26:21 -04002769 //
2770 // Ops[0] = Capability
SJW01901d92020-05-21 08:58:31 -05002771 addSPIRVInst<kCapabilities>(spv::OpCapability, Capability);
alan-baker5b86ed72019-02-15 08:26:50 -05002772 }
2773
2774 // Always add the storage buffer extension
2775 {
David Neto22f144c2017-06-12 14:26:21 -04002776 //
2777 // Generate OpExtension.
2778 //
2779 // Ops[0] = Name (Literal String)
2780 //
SJWf93f5f32020-05-05 07:27:56 -05002781 addSPIRVInst<kExtensions>(spv::OpExtension,
2782 "SPV_KHR_storage_buffer_storage_class");
alan-baker5b86ed72019-02-15 08:26:50 -05002783 }
David Neto22f144c2017-06-12 14:26:21 -04002784
alan-baker5b86ed72019-02-15 08:26:50 -05002785 if (hasVariablePointers() || hasVariablePointersStorageBuffer()) {
2786 //
2787 // Generate OpExtension.
2788 //
2789 // Ops[0] = Name (Literal String)
2790 //
SJWf93f5f32020-05-05 07:27:56 -05002791 addSPIRVInst<kExtensions>(spv::OpExtension, "SPV_KHR_variable_pointers");
David Neto22f144c2017-06-12 14:26:21 -04002792 }
2793
2794 //
2795 // Generate OpMemoryModel
2796 //
2797 // Memory model for Vulkan will always be GLSL450.
2798
2799 // Ops[0] = Addressing Model
2800 // Ops[1] = Memory Model
2801 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002802 Ops << spv::AddressingModelLogical << spv::MemoryModelGLSL450;
David Neto22f144c2017-06-12 14:26:21 -04002803
SJWf93f5f32020-05-05 07:27:56 -05002804 addSPIRVInst<kMemoryModel>(spv::OpMemoryModel, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002805
2806 //
2807 // Generate OpEntryPoint
2808 //
2809 for (auto EntryPoint : EntryPoints) {
2810 // Ops[0] = Execution Model
2811 // Ops[1] = EntryPoint ID
2812 // Ops[2] = Name (Literal String)
2813 // ...
2814 //
2815 // TODO: Do we need to consider Interface ID for forward references???
2816 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05002817 const StringRef &name = EntryPoint.first->getName();
SJW01901d92020-05-21 08:58:31 -05002818 Ops << spv::ExecutionModelGLCompute << EntryPoint.second << name;
David Neto22f144c2017-06-12 14:26:21 -04002819
SJW806a5d82020-07-15 12:51:38 -05002820 for (auto &Interface : EntryPointInterfaces) {
SJW01901d92020-05-21 08:58:31 -05002821 Ops << Interface;
David Neto22f144c2017-06-12 14:26:21 -04002822 }
2823
SJWf93f5f32020-05-05 07:27:56 -05002824 addSPIRVInst<kEntryPoints>(spv::OpEntryPoint, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002825 }
2826
alan-baker3b609772020-09-03 19:10:17 -04002827 if (BuiltinDimVec.empty()) {
2828 for (auto EntryPoint : EntryPoints) {
2829 const MDNode *MD = dyn_cast<Function>(EntryPoint.first)
2830 ->getMetadata("reqd_work_group_size");
2831 if ((MD != nullptr) && !clspv::Option::NonUniformNDRangeSupported()) {
2832 //
2833 // Generate OpExecutionMode
2834 //
David Neto22f144c2017-06-12 14:26:21 -04002835
alan-baker3b609772020-09-03 19:10:17 -04002836 // Ops[0] = Entry Point ID
2837 // Ops[1] = Execution Mode
2838 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
2839 Ops.clear();
2840 Ops << EntryPoint.second << spv::ExecutionModeLocalSize;
2841
2842 uint32_t XDim = static_cast<uint32_t>(
2843 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
2844 uint32_t YDim = static_cast<uint32_t>(
2845 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
2846 uint32_t ZDim = static_cast<uint32_t>(
2847 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
2848
2849 Ops << XDim << YDim << ZDim;
2850
2851 addSPIRVInst<kExecutionModes>(spv::OpExecutionMode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002852 }
David Neto22f144c2017-06-12 14:26:21 -04002853 }
2854 }
2855
2856 //
2857 // Generate OpSource.
2858 //
2859 // Ops[0] = SourceLanguage ID
2860 // Ops[1] = Version (LiteralNum)
2861 //
SJW01901d92020-05-21 08:58:31 -05002862 uint32_t LangID = spv::SourceLanguageUnknown;
2863 uint32_t LangVer = 0;
Kévin Petitf0515712020-01-07 18:29:20 +00002864 switch (clspv::Option::Language()) {
2865 case clspv::Option::SourceLanguage::OpenCL_C_10:
SJW01901d92020-05-21 08:58:31 -05002866 LangID = spv::SourceLanguageOpenCL_C;
2867 LangVer = 100;
Kévin Petitf0515712020-01-07 18:29:20 +00002868 break;
2869 case clspv::Option::SourceLanguage::OpenCL_C_11:
SJW01901d92020-05-21 08:58:31 -05002870 LangID = spv::SourceLanguageOpenCL_C;
2871 LangVer = 110;
Kévin Petitf0515712020-01-07 18:29:20 +00002872 break;
2873 case clspv::Option::SourceLanguage::OpenCL_C_12:
SJW01901d92020-05-21 08:58:31 -05002874 LangID = spv::SourceLanguageOpenCL_C;
2875 LangVer = 120;
Kévin Petitf0515712020-01-07 18:29:20 +00002876 break;
2877 case clspv::Option::SourceLanguage::OpenCL_C_20:
SJW01901d92020-05-21 08:58:31 -05002878 LangID = spv::SourceLanguageOpenCL_C;
2879 LangVer = 200;
Kévin Petitf0515712020-01-07 18:29:20 +00002880 break;
2881 case clspv::Option::SourceLanguage::OpenCL_CPP:
SJW01901d92020-05-21 08:58:31 -05002882 LangID = spv::SourceLanguageOpenCL_CPP;
2883 LangVer = 100;
Kévin Petitf0515712020-01-07 18:29:20 +00002884 break;
2885 default:
Kévin Petitf0515712020-01-07 18:29:20 +00002886 break;
Kévin Petit0fc88042019-04-09 23:25:02 +01002887 }
David Neto22f144c2017-06-12 14:26:21 -04002888
SJW01901d92020-05-21 08:58:31 -05002889 Ops.clear();
2890 Ops << LangID << LangVer;
SJWf93f5f32020-05-05 07:27:56 -05002891 addSPIRVInst<kDebug>(spv::OpSource, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002892
2893 if (!BuiltinDimVec.empty()) {
2894 //
2895 // Generate OpDecorates for x/y/z dimension.
2896 //
2897 // Ops[0] = Target ID
2898 // Ops[1] = Decoration (SpecId)
David Neto257c3892018-04-11 13:19:45 -04002899 // Ops[2] = Specialization Constant ID (Literal Number)
David Neto22f144c2017-06-12 14:26:21 -04002900
2901 // X Dimension
2902 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002903 Ops << BuiltinDimVec[0] << spv::DecorationSpecId << 0;
SJWf93f5f32020-05-05 07:27:56 -05002904 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002905
2906 // Y Dimension
2907 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002908 Ops << BuiltinDimVec[1] << spv::DecorationSpecId << 1;
SJWf93f5f32020-05-05 07:27:56 -05002909 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002910
2911 // Z Dimension
2912 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002913 Ops << BuiltinDimVec[2] << spv::DecorationSpecId << 2;
SJWf93f5f32020-05-05 07:27:56 -05002914 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002915 }
2916}
2917
David Netob6e2e062018-04-25 10:32:06 -04002918void SPIRVProducerPass::GenerateEntryPointInitialStores() {
2919 // Work around a driver bug. Initializers on Private variables might not
2920 // work. So the start of the kernel should store the initializer value to the
2921 // variables. Yes, *every* entry point pays this cost if *any* entry point
2922 // uses this builtin. At this point I judge this to be an acceptable tradeoff
2923 // of complexity vs. runtime, for a broken driver.
alan-bakerb6b09dc2018-11-08 16:59:28 -05002924 // TODO(dneto): Remove this at some point once fixed drivers are widely
2925 // available.
SJW01901d92020-05-21 08:58:31 -05002926 if (WorkgroupSizeVarID.isValid()) {
2927 assert(WorkgroupSizeValueID.isValid());
David Netob6e2e062018-04-25 10:32:06 -04002928
SJWf93f5f32020-05-05 07:27:56 -05002929 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05002930 Ops << WorkgroupSizeVarID << WorkgroupSizeValueID;
David Netob6e2e062018-04-25 10:32:06 -04002931
SJWf93f5f32020-05-05 07:27:56 -05002932 addSPIRVInst(spv::OpStore, Ops);
David Netob6e2e062018-04-25 10:32:06 -04002933 }
2934}
2935
David Neto22f144c2017-06-12 14:26:21 -04002936void SPIRVProducerPass::GenerateFuncBody(Function &F) {
David Neto22f144c2017-06-12 14:26:21 -04002937 ValueMapType &VMap = getValueMap();
2938
David Netob6e2e062018-04-25 10:32:06 -04002939 const bool IsKernel = F.getCallingConv() == CallingConv::SPIR_KERNEL;
David Neto22f144c2017-06-12 14:26:21 -04002940
2941 for (BasicBlock &BB : F) {
2942 // Register BasicBlock to ValueMap.
David Neto22f144c2017-06-12 14:26:21 -04002943
2944 //
2945 // Generate OpLabel for Basic Block.
2946 //
SJWf93f5f32020-05-05 07:27:56 -05002947 VMap[&BB] = addSPIRVInst(spv::OpLabel);
David Neto22f144c2017-06-12 14:26:21 -04002948
David Neto6dcd4712017-06-23 11:06:47 -04002949 // OpVariable instructions must come first.
2950 for (Instruction &I : BB) {
alan-baker5b86ed72019-02-15 08:26:50 -05002951 if (auto *alloca = dyn_cast<AllocaInst>(&I)) {
2952 // Allocating a pointer requires variable pointers.
2953 if (alloca->getAllocatedType()->isPointerTy()) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002954 setVariablePointersCapabilities(
2955 alloca->getAllocatedType()->getPointerAddressSpace());
alan-baker5b86ed72019-02-15 08:26:50 -05002956 }
David Neto6dcd4712017-06-23 11:06:47 -04002957 GenerateInstruction(I);
2958 }
2959 }
2960
David Neto22f144c2017-06-12 14:26:21 -04002961 if (&BB == &F.getEntryBlock() && IsKernel) {
David Netob6e2e062018-04-25 10:32:06 -04002962 if (clspv::Option::HackInitializers()) {
2963 GenerateEntryPointInitialStores();
2964 }
David Neto22f144c2017-06-12 14:26:21 -04002965 }
2966
2967 for (Instruction &I : BB) {
David Neto6dcd4712017-06-23 11:06:47 -04002968 if (!isa<AllocaInst>(I)) {
2969 GenerateInstruction(I);
2970 }
David Neto22f144c2017-06-12 14:26:21 -04002971 }
2972 }
2973}
2974
2975spv::Op SPIRVProducerPass::GetSPIRVCmpOpcode(CmpInst *I) {
2976 const std::map<CmpInst::Predicate, spv::Op> Map = {
2977 {CmpInst::ICMP_EQ, spv::OpIEqual},
2978 {CmpInst::ICMP_NE, spv::OpINotEqual},
2979 {CmpInst::ICMP_UGT, spv::OpUGreaterThan},
2980 {CmpInst::ICMP_UGE, spv::OpUGreaterThanEqual},
2981 {CmpInst::ICMP_ULT, spv::OpULessThan},
2982 {CmpInst::ICMP_ULE, spv::OpULessThanEqual},
2983 {CmpInst::ICMP_SGT, spv::OpSGreaterThan},
2984 {CmpInst::ICMP_SGE, spv::OpSGreaterThanEqual},
2985 {CmpInst::ICMP_SLT, spv::OpSLessThan},
2986 {CmpInst::ICMP_SLE, spv::OpSLessThanEqual},
2987 {CmpInst::FCMP_OEQ, spv::OpFOrdEqual},
2988 {CmpInst::FCMP_OGT, spv::OpFOrdGreaterThan},
2989 {CmpInst::FCMP_OGE, spv::OpFOrdGreaterThanEqual},
2990 {CmpInst::FCMP_OLT, spv::OpFOrdLessThan},
2991 {CmpInst::FCMP_OLE, spv::OpFOrdLessThanEqual},
2992 {CmpInst::FCMP_ONE, spv::OpFOrdNotEqual},
2993 {CmpInst::FCMP_UEQ, spv::OpFUnordEqual},
2994 {CmpInst::FCMP_UGT, spv::OpFUnordGreaterThan},
2995 {CmpInst::FCMP_UGE, spv::OpFUnordGreaterThanEqual},
2996 {CmpInst::FCMP_ULT, spv::OpFUnordLessThan},
2997 {CmpInst::FCMP_ULE, spv::OpFUnordLessThanEqual},
2998 {CmpInst::FCMP_UNE, spv::OpFUnordNotEqual}};
2999
3000 assert(0 != Map.count(I->getPredicate()));
3001
3002 return Map.at(I->getPredicate());
3003}
3004
3005spv::Op SPIRVProducerPass::GetSPIRVCastOpcode(Instruction &I) {
3006 const std::map<unsigned, spv::Op> Map{
3007 {Instruction::Trunc, spv::OpUConvert},
3008 {Instruction::ZExt, spv::OpUConvert},
3009 {Instruction::SExt, spv::OpSConvert},
3010 {Instruction::FPToUI, spv::OpConvertFToU},
3011 {Instruction::FPToSI, spv::OpConvertFToS},
3012 {Instruction::UIToFP, spv::OpConvertUToF},
3013 {Instruction::SIToFP, spv::OpConvertSToF},
3014 {Instruction::FPTrunc, spv::OpFConvert},
3015 {Instruction::FPExt, spv::OpFConvert},
3016 {Instruction::BitCast, spv::OpBitcast}};
3017
3018 assert(0 != Map.count(I.getOpcode()));
3019
3020 return Map.at(I.getOpcode());
3021}
3022
3023spv::Op SPIRVProducerPass::GetSPIRVBinaryOpcode(Instruction &I) {
Kévin Petit24272b62018-10-18 19:16:12 +00003024 if (I.getType()->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003025 switch (I.getOpcode()) {
3026 default:
3027 break;
3028 case Instruction::Or:
3029 return spv::OpLogicalOr;
3030 case Instruction::And:
3031 return spv::OpLogicalAnd;
3032 case Instruction::Xor:
3033 return spv::OpLogicalNotEqual;
3034 }
3035 }
3036
alan-bakerb6b09dc2018-11-08 16:59:28 -05003037 const std::map<unsigned, spv::Op> Map{
David Neto22f144c2017-06-12 14:26:21 -04003038 {Instruction::Add, spv::OpIAdd},
3039 {Instruction::FAdd, spv::OpFAdd},
3040 {Instruction::Sub, spv::OpISub},
3041 {Instruction::FSub, spv::OpFSub},
3042 {Instruction::Mul, spv::OpIMul},
3043 {Instruction::FMul, spv::OpFMul},
3044 {Instruction::UDiv, spv::OpUDiv},
3045 {Instruction::SDiv, spv::OpSDiv},
3046 {Instruction::FDiv, spv::OpFDiv},
3047 {Instruction::URem, spv::OpUMod},
3048 {Instruction::SRem, spv::OpSRem},
3049 {Instruction::FRem, spv::OpFRem},
3050 {Instruction::Or, spv::OpBitwiseOr},
3051 {Instruction::Xor, spv::OpBitwiseXor},
3052 {Instruction::And, spv::OpBitwiseAnd},
3053 {Instruction::Shl, spv::OpShiftLeftLogical},
3054 {Instruction::LShr, spv::OpShiftRightLogical},
3055 {Instruction::AShr, spv::OpShiftRightArithmetic}};
3056
3057 assert(0 != Map.count(I.getOpcode()));
3058
3059 return Map.at(I.getOpcode());
3060}
3061
SJW806a5d82020-07-15 12:51:38 -05003062SPIRVID SPIRVProducerPass::getSPIRVBuiltin(spv::BuiltIn BID,
3063 spv::Capability Cap) {
3064 SPIRVID RID;
3065
3066 auto ii = BuiltinConstantMap.find(BID);
3067
3068 if (ii != BuiltinConstantMap.end()) {
3069 return ii->second;
3070 } else {
3071
3072 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 {
3286
3287 // read_image (without a sampler) is mapped to OpImageFetch.
3288 Value *Image = Call->getArgOperand(0);
3289 Value *Coordinate = Call->getArgOperand(1);
3290
3291 //
3292 // Generate OpImageFetch
3293 //
3294 // Ops[0] = Result Type ID
3295 // Ops[1] = Image ID
3296 // Ops[2] = Coordinate ID
3297 // Ops[3] = Lod
3298 // Ops[4] = 0
3299 //
3300 SPIRVOperandVec Ops;
3301
3302 const bool is_int_image = IsIntImageType(Image->getType());
3303 SPIRVID result_type;
3304 if (is_int_image) {
3305 result_type = v4int32ID;
3306 } else {
3307 result_type = getSPIRVType(Call->getType());
3308 }
3309
3310 Ops << result_type << Image << Coordinate << spv::ImageOperandsLodMask
3311 << getSPIRVInt32Constant(0);
3312
3313 RID = addSPIRVInst(spv::OpImageFetch, Ops);
3314
3315 if (is_int_image) {
3316 // Generate the bitcast.
3317 Ops.clear();
3318 Ops << Call->getType() << RID;
3319 RID = addSPIRVInst(spv::OpBitcast, Ops);
3320 }
3321 }
3322 break;
3323 }
3324
3325 case Builtins::kWriteImagef:
3326 case Builtins::kWriteImageh:
3327 case Builtins::kWriteImagei:
3328 case Builtins::kWriteImageui: {
3329 // write_image is mapped to OpImageWrite.
3330 //
3331 // Generate OpImageWrite.
3332 //
3333 // Ops[0] = Image ID
3334 // Ops[1] = Coordinate ID
3335 // Ops[2] = Texel ID
3336 // Ops[3] = (Optional) Image Operands Type (Literal Number)
3337 // Ops[4] ... Ops[n] = (Optional) Operands ID
3338 //
3339 SPIRVOperandVec Ops;
3340
3341 Value *Image = Call->getArgOperand(0);
3342 Value *Coordinate = Call->getArgOperand(1);
3343 Value *Texel = Call->getArgOperand(2);
3344
3345 SPIRVID TexelID = getSPIRVValue(Texel);
3346
3347 const bool is_int_image = IsIntImageType(Image->getType());
3348 if (is_int_image) {
3349 // Generate a bitcast to v4int and use it as the texel value.
3350 Ops << v4int32ID << TexelID;
3351 TexelID = addSPIRVInst(spv::OpBitcast, Ops);
3352 Ops.clear();
3353 }
3354 Ops << Image << Coordinate << TexelID;
3355
3356 RID = addSPIRVInst(spv::OpImageWrite, Ops);
3357 break;
3358 }
3359
3360 case Builtins::kGetImageHeight:
3361 case Builtins::kGetImageWidth:
3362 case Builtins::kGetImageDepth:
3363 case Builtins::kGetImageDim: {
3364 // get_image_* is mapped to OpImageQuerySize or OpImageQuerySizeLod
3365 addCapability(spv::CapabilityImageQuery);
3366
3367 //
3368 // Generate OpImageQuerySize[Lod]
3369 //
3370 // Ops[0] = Image ID
3371 //
3372 // Result type has components equal to the dimensionality of the image,
3373 // plus 1 if the image is arrayed.
3374 //
3375 // %sizes = OpImageQuerySize[Lod] %uint[2|3|4] %im [%uint_0]
3376 SPIRVOperandVec Ops;
3377
3378 // Implement:
3379 // %sizes = OpImageQuerySize[Lod] %uint[2|3|4] %im [%uint_0]
3380 SPIRVID SizesTypeID;
3381
3382 Value *Image = Call->getArgOperand(0);
3383 const uint32_t dim = ImageDimensionality(Image->getType());
3384 const uint32_t components =
3385 dim + (IsArrayImageType(Image->getType()) ? 1 : 0);
3386 if (components == 1) {
3387 SizesTypeID = getSPIRVType(Type::getInt32Ty(Context));
3388 } else {
3389 SizesTypeID = getSPIRVType(
3390 FixedVectorType::get(Type::getInt32Ty(Context), components));
3391 }
3392 Ops << SizesTypeID << Image;
3393 spv::Op query_opcode = spv::OpImageQuerySize;
3394 if (IsSampledImageType(Image->getType())) {
3395 query_opcode = spv::OpImageQuerySizeLod;
3396 // Need explicit 0 for Lod operand.
3397 Ops << getSPIRVInt32Constant(0);
3398 }
3399
3400 RID = addSPIRVInst(query_opcode, Ops);
3401
3402 // May require an extra instruction to create the appropriate result of
3403 // the builtin function.
3404 if (FuncInfo.getType() == Builtins::kGetImageDim) {
3405 if (dim == 3) {
3406 // get_image_dim returns an int4 for 3D images.
3407 //
3408
3409 // Implement:
3410 // %result = OpCompositeConstruct %uint4 %sizes %uint_0
3411 Ops.clear();
3412 Ops << FixedVectorType::get(Type::getInt32Ty(Context), 4) << RID
3413 << getSPIRVInt32Constant(0);
3414
3415 RID = addSPIRVInst(spv::OpCompositeConstruct, Ops);
3416 } else if (dim != components) {
3417 // get_image_dim return an int2 regardless of the arrayedness of the
3418 // image. If the image is arrayed an element must be dropped from the
3419 // query result.
3420 //
3421
3422 // Implement:
3423 // %result = OpVectorShuffle %uint2 %sizes %sizes 0 1
3424 Ops.clear();
3425 Ops << FixedVectorType::get(Type::getInt32Ty(Context), 2) << RID << RID
3426 << 0 << 1;
3427
3428 RID = addSPIRVInst(spv::OpVectorShuffle, Ops);
3429 }
3430 } else if (components > 1) {
3431 // Implement:
3432 // %result = OpCompositeExtract %uint %sizes <component number>
3433 Ops.clear();
3434 Ops << Call->getType() << RID;
3435
3436 uint32_t component = 0;
3437 if (FuncInfo.getType() == Builtins::kGetImageHeight)
3438 component = 1;
3439 else if (FuncInfo.getType() == Builtins::kGetImageDepth)
3440 component = 2;
3441 Ops << component;
3442
3443 RID = addSPIRVInst(spv::OpCompositeExtract, Ops);
3444 }
3445 break;
3446 }
3447 default:
3448 llvm_unreachable("Unsupported Image builtin");
3449 }
3450
3451 return RID;
3452}
3453
3454SPIRVID
3455SPIRVProducerPass::GenerateSubgroupInstruction(CallInst *Call,
3456 const FunctionInfo &FuncInfo) {
3457 SPIRVID RID;
3458
3459 // requires SPIRV version 1.3 or greater
3460 if (SpvVersion() != SPIRVVersion::SPIRV_1_3) {
3461 // llvm_unreachable("SubGroups extension requires SPIRV 1.3 or greater");
3462 // TODO(sjw): error out gracefully
3463 }
3464
3465 auto loadBuiltin = [this, Call](spv::BuiltIn spvBI,
3466 spv::Capability spvCap =
3467 spv::CapabilityGroupNonUniform) {
3468 SPIRVOperandVec Ops;
3469 Ops << Call->getType() << this->getSPIRVBuiltin(spvBI, spvCap);
3470
3471 return addSPIRVInst(spv::OpLoad, Ops);
3472 };
3473
3474 spv::Op op = spv::OpNop;
3475 switch (FuncInfo.getType()) {
3476 case Builtins::kGetSubGroupSize:
3477 return loadBuiltin(spv::BuiltInSubgroupSize);
3478 case Builtins::kGetNumSubGroups:
3479 return loadBuiltin(spv::BuiltInNumSubgroups);
3480 case Builtins::kGetSubGroupId:
3481 return loadBuiltin(spv::BuiltInSubgroupId);
3482 case Builtins::kGetSubGroupLocalId:
3483 return loadBuiltin(spv::BuiltInSubgroupLocalInvocationId);
3484
3485 case Builtins::kSubGroupBroadcast:
3486 if (SpvVersion() < SPIRVVersion::SPIRV_1_5 &&
3487 !dyn_cast<ConstantInt>(Call->getOperand(1))) {
3488 llvm_unreachable("sub_group_broadcast requires constant lane Id for "
3489 "SPIRV version < 1.5");
3490 }
3491 addCapability(spv::CapabilityGroupNonUniformBallot);
3492 op = spv::OpGroupNonUniformBroadcast;
3493 break;
3494
3495 case Builtins::kSubGroupAll:
3496 addCapability(spv::CapabilityGroupNonUniformVote);
3497 op = spv::OpGroupNonUniformAll;
3498 break;
3499 case Builtins::kSubGroupAny:
3500 addCapability(spv::CapabilityGroupNonUniformVote);
3501 op = spv::OpGroupNonUniformAny;
3502 break;
3503 case Builtins::kSubGroupReduceAdd:
3504 case Builtins::kSubGroupScanExclusiveAdd:
3505 case Builtins::kSubGroupScanInclusiveAdd: {
3506 addCapability(spv::CapabilityGroupNonUniformArithmetic);
3507 if (FuncInfo.getParameter(0).type_id == Type::IntegerTyID) {
3508 op = spv::OpGroupNonUniformIAdd;
3509 } else {
3510 op = spv::OpGroupNonUniformFAdd;
3511 }
3512 break;
3513 }
3514 case Builtins::kSubGroupReduceMin:
3515 case Builtins::kSubGroupScanExclusiveMin:
3516 case Builtins::kSubGroupScanInclusiveMin: {
3517 addCapability(spv::CapabilityGroupNonUniformArithmetic);
3518 auto &param = FuncInfo.getParameter(0);
3519 if (param.type_id == Type::IntegerTyID) {
3520 op = param.is_signed ? spv::OpGroupNonUniformSMin
3521 : spv::OpGroupNonUniformUMin;
3522 } else {
3523 op = spv::OpGroupNonUniformFMin;
3524 }
3525 break;
3526 }
3527 case Builtins::kSubGroupReduceMax:
3528 case Builtins::kSubGroupScanExclusiveMax:
3529 case Builtins::kSubGroupScanInclusiveMax: {
3530 addCapability(spv::CapabilityGroupNonUniformArithmetic);
3531 auto &param = FuncInfo.getParameter(0);
3532 if (param.type_id == Type::IntegerTyID) {
3533 op = param.is_signed ? spv::OpGroupNonUniformSMax
3534 : spv::OpGroupNonUniformUMax;
3535 } else {
3536 op = spv::OpGroupNonUniformFMax;
3537 }
3538 break;
3539 }
3540
3541 case Builtins::kGetEnqueuedNumSubGroups:
3542 // TODO(sjw): requires CapabilityKernel (incompatible with Shader)
3543 case Builtins::kGetMaxSubGroupSize:
3544 // TODO(sjw): use SpecConstant, capability Kernel (incompatible with Shader)
3545 case Builtins::kSubGroupBarrier:
3546 case Builtins::kSubGroupReserveReadPipe:
3547 case Builtins::kSubGroupReserveWritePipe:
3548 case Builtins::kSubGroupCommitReadPipe:
3549 case Builtins::kSubGroupCommitWritePipe:
3550 case Builtins::kGetKernelSubGroupCountForNdrange:
3551 case Builtins::kGetKernelMaxSubGroupSizeForNdrange:
3552 default:
3553 Call->print(errs());
3554 llvm_unreachable("Unsupported sub_group operation");
3555 break;
3556 }
3557
3558 assert(op != spv::OpNop);
3559
3560 SPIRVOperandVec Operands;
3561
3562 //
3563 // Generate OpGroupNonUniform*
3564 //
3565 // Ops[0] = Result Type ID
3566 // Ops[1] = ScopeSubgroup
3567 // Ops[2] = Value ID
3568 // Ops[3] = Local ID
3569
3570 // The result type.
3571 Operands << Call->getType();
3572
3573 // Subgroup Scope
3574 Operands << getSPIRVInt32Constant(spv::ScopeSubgroup);
3575
3576 switch (FuncInfo.getType()) {
3577 case Builtins::kSubGroupReduceAdd:
3578 case Builtins::kSubGroupReduceMin:
3579 case Builtins::kSubGroupReduceMax:
3580 Operands << spv::GroupOperationReduce;
3581 break;
3582 case Builtins::kSubGroupScanExclusiveAdd:
3583 case Builtins::kSubGroupScanExclusiveMin:
3584 case Builtins::kSubGroupScanExclusiveMax:
3585 Operands << spv::GroupOperationExclusiveScan;
3586 break;
3587 case Builtins::kSubGroupScanInclusiveAdd:
3588 case Builtins::kSubGroupScanInclusiveMin:
3589 case Builtins::kSubGroupScanInclusiveMax:
3590 Operands << spv::GroupOperationInclusiveScan;
3591 break;
3592 default:
3593 break;
3594 }
3595
3596 for (Use &use : Call->arg_operands()) {
3597 Operands << use.get();
3598 }
3599
3600 return addSPIRVInst(op, Operands);
3601}
3602
3603SPIRVID SPIRVProducerPass::GenerateInstructionFromCall(CallInst *Call) {
3604 LLVMContext &Context = module->getContext();
3605
3606 auto &func_info = Builtins::Lookup(Call->getCalledFunction());
3607 auto func_type = func_info.getType();
3608
3609 if (BUILTIN_IN_GROUP(func_type, Clspv)) {
3610 return GenerateClspvInstruction(Call, func_info);
3611 } else if (BUILTIN_IN_GROUP(func_type, Image)) {
3612 return GenerateImageInstruction(Call, func_info);
3613 } else if (BUILTIN_IN_GROUP(func_type, SubgroupsKHR)) {
3614 return GenerateSubgroupInstruction(Call, func_info);
3615 }
3616
3617 SPIRVID RID;
3618
3619 switch (func_type) {
3620 case Builtins::kPopcount: {
3621 //
3622 // Generate OpBitCount
3623 //
3624 // Ops[0] = Result Type ID
3625 // Ops[1] = Base ID
3626 SPIRVOperandVec Ops;
3627 Ops << Call->getType() << Call->getOperand(0);
3628
3629 RID = addSPIRVInst(spv::OpBitCount, Ops);
3630 break;
3631 }
3632 default: {
3633 glsl::ExtInst EInst = getDirectOrIndirectExtInstEnum(func_info);
3634
3635 if (EInst) {
3636 SPIRVID ExtInstImportID = getOpExtInstImportID();
3637
3638 //
3639 // Generate OpExtInst.
3640 //
3641
3642 // Ops[0] = Result Type ID
3643 // Ops[1] = Set ID (OpExtInstImport ID)
3644 // Ops[2] = Instruction Number (Literal Number)
3645 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
3646 SPIRVOperandVec Ops;
3647
3648 Ops << Call->getType() << ExtInstImportID << EInst;
3649
3650 for (auto &use : Call->arg_operands()) {
3651 Ops << use.get();
3652 }
3653
3654 RID = addSPIRVInst(spv::OpExtInst, Ops);
3655
3656 const auto IndirectExtInst = getIndirectExtInstEnum(func_info);
3657 if (IndirectExtInst != kGlslExtInstBad) {
3658
3659 // Generate one more instruction that uses the result of the extended
3660 // instruction. Its result id is one more than the id of the
3661 // extended instruction.
3662 auto generate_extra_inst = [this, &Context, &Call,
3663 &RID](spv::Op opcode, Constant *constant) {
3664 //
3665 // Generate instruction like:
3666 // result = opcode constant <extinst-result>
3667 //
3668 // Ops[0] = Result Type ID
3669 // Ops[1] = Operand 0 ;; the constant, suitably splatted
3670 // Ops[2] = Operand 1 ;; the result of the extended instruction
3671 SPIRVOperandVec Ops;
3672
3673 Type *resultTy = Call->getType();
3674
3675 if (auto *vectorTy = dyn_cast<VectorType>(resultTy)) {
alan-baker931253b2020-08-20 17:15:38 -04003676 constant =
3677 ConstantVector::getSplat(vectorTy->getElementCount(), constant);
SJW806a5d82020-07-15 12:51:38 -05003678 }
3679 Ops << resultTy << constant << RID;
3680
3681 RID = addSPIRVInst(opcode, Ops);
3682 };
3683
3684 auto IntTy = Type::getInt32Ty(Context);
3685 switch (IndirectExtInst) {
3686 case glsl::ExtInstFindUMsb: // Implementing clz
3687 generate_extra_inst(spv::OpISub, ConstantInt::get(IntTy, 31));
3688 break;
3689 case glsl::ExtInstAcos: // Implementing acospi
3690 case glsl::ExtInstAsin: // Implementing asinpi
3691 case glsl::ExtInstAtan: // Implementing atanpi
3692 case glsl::ExtInstAtan2: // Implementing atan2pi
3693 generate_extra_inst(
3694 spv::OpFMul,
3695 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
3696 break;
3697
3698 default:
3699 assert(false && "internally inconsistent");
3700 }
3701 }
3702 } else {
3703
3704 // A real function call (not builtin)
3705 // Call instruction is deferred because it needs function's ID.
3706 RID = addSPIRVPlaceholder(Call);
3707 }
3708
3709 break;
3710 }
3711 }
3712
3713 return RID;
3714}
3715
David Neto22f144c2017-06-12 14:26:21 -04003716void SPIRVProducerPass::GenerateInstruction(Instruction &I) {
David Neto22f144c2017-06-12 14:26:21 -04003717 ValueMapType &VMap = getValueMap();
SJW806a5d82020-07-15 12:51:38 -05003718 LLVMContext &Context = module->getContext();
David Neto22f144c2017-06-12 14:26:21 -04003719
SJW806a5d82020-07-15 12:51:38 -05003720 SPIRVID RID;
David Neto22f144c2017-06-12 14:26:21 -04003721
3722 switch (I.getOpcode()) {
3723 default: {
3724 if (Instruction::isCast(I.getOpcode())) {
3725 //
3726 // Generate SPIRV instructions for cast operators.
3727 //
3728
David Netod2de94a2017-08-28 17:27:47 -04003729 auto Ty = I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003730 auto OpTy = I.getOperand(0)->getType();
David Netod2de94a2017-08-28 17:27:47 -04003731 auto toI8 = Ty == Type::getInt8Ty(Context);
3732 auto fromI32 = OpTy == Type::getInt32Ty(Context);
David Neto22f144c2017-06-12 14:26:21 -04003733 // Handle zext, sext and uitofp with i1 type specially.
3734 if ((I.getOpcode() == Instruction::ZExt ||
3735 I.getOpcode() == Instruction::SExt ||
3736 I.getOpcode() == Instruction::UIToFP) &&
alan-bakerb6b09dc2018-11-08 16:59:28 -05003737 OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003738 //
3739 // Generate OpSelect.
3740 //
3741
3742 // Ops[0] = Result Type ID
3743 // Ops[1] = Condition ID
3744 // Ops[2] = True Constant ID
3745 // Ops[3] = False Constant ID
SJWf93f5f32020-05-05 07:27:56 -05003746 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04003747
SJW01901d92020-05-21 08:58:31 -05003748 Ops << I.getType() << I.getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04003749
David Neto22f144c2017-06-12 14:26:21 -04003750 if (I.getOpcode() == Instruction::ZExt) {
SJW01901d92020-05-21 08:58:31 -05003751 Ops << ConstantInt::get(I.getType(), 1);
David Neto22f144c2017-06-12 14:26:21 -04003752 } else if (I.getOpcode() == Instruction::SExt) {
SJW01901d92020-05-21 08:58:31 -05003753 Ops << ConstantInt::getSigned(I.getType(), -1);
David Neto22f144c2017-06-12 14:26:21 -04003754 } else {
SJW01901d92020-05-21 08:58:31 -05003755 Ops << ConstantFP::get(Context, APFloat(1.0f));
David Neto22f144c2017-06-12 14:26:21 -04003756 }
David Neto22f144c2017-06-12 14:26:21 -04003757
David Neto22f144c2017-06-12 14:26:21 -04003758 if (I.getOpcode() == Instruction::ZExt) {
SJW01901d92020-05-21 08:58:31 -05003759 Ops << Constant::getNullValue(I.getType());
David Neto22f144c2017-06-12 14:26:21 -04003760 } else if (I.getOpcode() == Instruction::SExt) {
SJW01901d92020-05-21 08:58:31 -05003761 Ops << Constant::getNullValue(I.getType());
David Neto22f144c2017-06-12 14:26:21 -04003762 } else {
SJW01901d92020-05-21 08:58:31 -05003763 Ops << ConstantFP::get(Context, APFloat(0.0f));
David Neto22f144c2017-06-12 14:26:21 -04003764 }
David Neto22f144c2017-06-12 14:26:21 -04003765
SJWf93f5f32020-05-05 07:27:56 -05003766 RID = addSPIRVInst(spv::OpSelect, Ops);
alan-bakerb39c8262019-03-08 14:03:37 -05003767 } else if (!clspv::Option::Int8Support() &&
3768 I.getOpcode() == Instruction::Trunc && fromI32 && toI8) {
David Netod2de94a2017-08-28 17:27:47 -04003769 // The SPIR-V target type is a 32-bit int. Keep only the bottom
3770 // 8 bits.
3771 // Before:
3772 // %result = trunc i32 %a to i8
3773 // After
3774 // %result = OpBitwiseAnd %uint %a %uint_255
3775
SJWf93f5f32020-05-05 07:27:56 -05003776 SPIRVOperandVec Ops;
David Netod2de94a2017-08-28 17:27:47 -04003777
SJW806a5d82020-07-15 12:51:38 -05003778 Ops << OpTy << I.getOperand(0) << getSPIRVInt32Constant(255);
David Netod2de94a2017-08-28 17:27:47 -04003779
SJWf93f5f32020-05-05 07:27:56 -05003780 RID = addSPIRVInst(spv::OpBitwiseAnd, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003781 } else {
3782 // Ops[0] = Result Type ID
3783 // Ops[1] = Source Value ID
SJWf93f5f32020-05-05 07:27:56 -05003784 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04003785
SJW01901d92020-05-21 08:58:31 -05003786 Ops << I.getType() << I.getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04003787
SJWf93f5f32020-05-05 07:27:56 -05003788 RID = addSPIRVInst(GetSPIRVCastOpcode(I), Ops);
David Neto22f144c2017-06-12 14:26:21 -04003789 }
3790 } else if (isa<BinaryOperator>(I)) {
3791 //
3792 // Generate SPIRV instructions for binary operators.
3793 //
3794
3795 // Handle xor with i1 type specially.
3796 if (I.getOpcode() == Instruction::Xor &&
3797 I.getType() == Type::getInt1Ty(Context) &&
Kévin Petit24272b62018-10-18 19:16:12 +00003798 ((isa<ConstantInt>(I.getOperand(0)) &&
3799 !cast<ConstantInt>(I.getOperand(0))->isZero()) ||
3800 (isa<ConstantInt>(I.getOperand(1)) &&
3801 !cast<ConstantInt>(I.getOperand(1))->isZero()))) {
David Neto22f144c2017-06-12 14:26:21 -04003802 //
3803 // Generate OpLogicalNot.
3804 //
3805 // Ops[0] = Result Type ID
3806 // Ops[1] = Operand
SJWf93f5f32020-05-05 07:27:56 -05003807 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04003808
SJW01901d92020-05-21 08:58:31 -05003809 Ops << I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003810
3811 Value *CondV = I.getOperand(0);
3812 if (isa<Constant>(I.getOperand(0))) {
3813 CondV = I.getOperand(1);
3814 }
SJW01901d92020-05-21 08:58:31 -05003815 Ops << CondV;
David Neto22f144c2017-06-12 14:26:21 -04003816
SJWf93f5f32020-05-05 07:27:56 -05003817 RID = addSPIRVInst(spv::OpLogicalNot, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003818 } else {
3819 // Ops[0] = Result Type ID
3820 // Ops[1] = Operand 0
3821 // Ops[2] = Operand 1
SJWf93f5f32020-05-05 07:27:56 -05003822 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04003823
SJW01901d92020-05-21 08:58:31 -05003824 Ops << I.getType() << I.getOperand(0) << I.getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04003825
SJWf93f5f32020-05-05 07:27:56 -05003826 RID = addSPIRVInst(GetSPIRVBinaryOpcode(I), Ops);
David Neto22f144c2017-06-12 14:26:21 -04003827 }
alan-bakerc9c55ae2019-12-02 16:01:27 -05003828 } else if (I.getOpcode() == Instruction::FNeg) {
3829 // The only unary operator.
3830 //
3831 // Ops[0] = Result Type ID
3832 // Ops[1] = Operand 0
SJW01901d92020-05-21 08:58:31 -05003833 SPIRVOperandVec Ops;
alan-bakerc9c55ae2019-12-02 16:01:27 -05003834
SJW01901d92020-05-21 08:58:31 -05003835 Ops << I.getType() << I.getOperand(0);
3836 RID = addSPIRVInst(spv::OpFNegate, Ops);
Marco Antognini68e5c512020-09-09 16:08:57 +01003837 } else if (I.getOpcode() == Instruction::Unreachable) {
3838 RID = addSPIRVInst(spv::OpUnreachable);
David Neto22f144c2017-06-12 14:26:21 -04003839 } else {
3840 I.print(errs());
3841 llvm_unreachable("Unsupported instruction???");
3842 }
3843 break;
3844 }
3845 case Instruction::GetElementPtr: {
3846 auto &GlobalConstArgSet = getGlobalConstArgSet();
3847
3848 //
3849 // Generate OpAccessChain.
3850 //
3851 GetElementPtrInst *GEP = cast<GetElementPtrInst>(&I);
3852
3853 //
3854 // Generate OpAccessChain.
3855 //
3856
3857 // Ops[0] = Result Type ID
3858 // Ops[1] = Base ID
3859 // Ops[2] ... Ops[n] = Indexes ID
SJWf93f5f32020-05-05 07:27:56 -05003860 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04003861
alan-bakerb6b09dc2018-11-08 16:59:28 -05003862 PointerType *ResultType = cast<PointerType>(GEP->getType());
David Neto22f144c2017-06-12 14:26:21 -04003863 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate ||
3864 GlobalConstArgSet.count(GEP->getPointerOperand())) {
3865 // Use pointer type with private address space for global constant.
3866 Type *EleTy = I.getType()->getPointerElementType();
David Neto1a1a0582017-07-07 12:01:44 -04003867 ResultType = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
David Neto22f144c2017-06-12 14:26:21 -04003868 }
David Neto257c3892018-04-11 13:19:45 -04003869
SJW01901d92020-05-21 08:58:31 -05003870 Ops << ResultType;
David Neto22f144c2017-06-12 14:26:21 -04003871
David Neto862b7d82018-06-14 18:48:37 -04003872 // Generate the base pointer.
SJW01901d92020-05-21 08:58:31 -05003873 Ops << GEP->getPointerOperand();
David Neto22f144c2017-06-12 14:26:21 -04003874
David Neto862b7d82018-06-14 18:48:37 -04003875 // TODO(dneto): Simplify the following?
David Neto22f144c2017-06-12 14:26:21 -04003876
3877 //
3878 // Follows below rules for gep.
3879 //
David Neto862b7d82018-06-14 18:48:37 -04003880 // 1. If gep's first index is 0 generate OpAccessChain and ignore gep's
3881 // first index.
David Neto22f144c2017-06-12 14:26:21 -04003882 // 2. If gep's first index is not 0, generate OpPtrAccessChain and use gep's
3883 // first index.
3884 // 3. If gep's first index is not constant, generate OpPtrAccessChain and
3885 // use gep's first index.
3886 // 4. If it is not above case 1, 2 and 3, generate OpAccessChain and use
3887 // gep's first index.
3888 //
3889 spv::Op Opcode = spv::OpAccessChain;
3890 unsigned offset = 0;
3891 if (ConstantInt *CstInt = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
David Neto862b7d82018-06-14 18:48:37 -04003892 if (CstInt->getZExtValue() == 0) {
David Neto22f144c2017-06-12 14:26:21 -04003893 offset = 1;
David Neto862b7d82018-06-14 18:48:37 -04003894 } else if (CstInt->getZExtValue() != 0) {
David Neto22f144c2017-06-12 14:26:21 -04003895 Opcode = spv::OpPtrAccessChain;
David Neto22f144c2017-06-12 14:26:21 -04003896 }
David Neto862b7d82018-06-14 18:48:37 -04003897 } else {
David Neto22f144c2017-06-12 14:26:21 -04003898 Opcode = spv::OpPtrAccessChain;
David Neto1a1a0582017-07-07 12:01:44 -04003899 }
3900
3901 if (Opcode == spv::OpPtrAccessChain) {
David Neto1a1a0582017-07-07 12:01:44 -04003902 // Do we need to generate ArrayStride? Check against the GEP result type
3903 // rather than the pointer type of the base because when indexing into
3904 // an OpenCL program-scope constant, we'll swap out the LLVM base pointer
3905 // for something else in the SPIR-V.
3906 // E.g. see test/PointerAccessChain/pointer_index_is_constant_1.cl
alan-baker5b86ed72019-02-15 08:26:50 -05003907 auto address_space = ResultType->getAddressSpace();
3908 setVariablePointersCapabilities(address_space);
3909 switch (GetStorageClass(address_space)) {
Alan Bakerfcda9482018-10-02 17:09:59 -04003910 case spv::StorageClassStorageBuffer:
3911 case spv::StorageClassUniform:
David Neto1a1a0582017-07-07 12:01:44 -04003912 // Save the need to generate an ArrayStride decoration. But defer
3913 // generation until later, so we only make one decoration.
David Neto85082642018-03-24 06:55:20 -07003914 getTypesNeedingArrayStride().insert(ResultType);
Alan Bakerfcda9482018-10-02 17:09:59 -04003915 break;
3916 default:
3917 break;
David Neto1a1a0582017-07-07 12:01:44 -04003918 }
David Neto22f144c2017-06-12 14:26:21 -04003919 }
3920
3921 for (auto II = GEP->idx_begin() + offset; II != GEP->idx_end(); II++) {
SJW01901d92020-05-21 08:58:31 -05003922 Ops << *II;
David Neto22f144c2017-06-12 14:26:21 -04003923 }
3924
SJWf93f5f32020-05-05 07:27:56 -05003925 RID = addSPIRVInst(Opcode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003926 break;
3927 }
3928 case Instruction::ExtractValue: {
3929 ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
3930 // Ops[0] = Result Type ID
3931 // Ops[1] = Composite ID
3932 // Ops[2] ... Ops[n] = Indexes (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05003933 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04003934
SJW01901d92020-05-21 08:58:31 -05003935 Ops << I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003936
SJW01901d92020-05-21 08:58:31 -05003937 Ops << EVI->getAggregateOperand();
David Neto22f144c2017-06-12 14:26:21 -04003938
3939 for (auto &Index : EVI->indices()) {
SJW01901d92020-05-21 08:58:31 -05003940 Ops << Index;
David Neto22f144c2017-06-12 14:26:21 -04003941 }
3942
SJWf93f5f32020-05-05 07:27:56 -05003943 RID = addSPIRVInst(spv::OpCompositeExtract, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003944 break;
3945 }
3946 case Instruction::InsertValue: {
3947 InsertValueInst *IVI = cast<InsertValueInst>(&I);
3948 // Ops[0] = Result Type ID
3949 // Ops[1] = Object ID
3950 // Ops[2] = Composite ID
3951 // Ops[3] ... Ops[n] = Indexes (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05003952 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04003953
SJW01901d92020-05-21 08:58:31 -05003954 Ops << I.getType() << IVI->getInsertedValueOperand()
3955 << IVI->getAggregateOperand();
David Neto22f144c2017-06-12 14:26:21 -04003956
3957 for (auto &Index : IVI->indices()) {
SJW01901d92020-05-21 08:58:31 -05003958 Ops << Index;
David Neto22f144c2017-06-12 14:26:21 -04003959 }
3960
SJWf93f5f32020-05-05 07:27:56 -05003961 RID = addSPIRVInst(spv::OpCompositeInsert, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003962 break;
3963 }
3964 case Instruction::Select: {
3965 //
3966 // Generate OpSelect.
3967 //
3968
3969 // Ops[0] = Result Type ID
3970 // Ops[1] = Condition ID
3971 // Ops[2] = True Constant ID
3972 // Ops[3] = False Constant ID
SJWf93f5f32020-05-05 07:27:56 -05003973 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04003974
3975 // Find SPIRV instruction for parameter type.
3976 auto Ty = I.getType();
3977 if (Ty->isPointerTy()) {
3978 auto PointeeTy = Ty->getPointerElementType();
3979 if (PointeeTy->isStructTy() &&
3980 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
3981 Ty = PointeeTy;
alan-baker5b86ed72019-02-15 08:26:50 -05003982 } else {
3983 // Selecting between pointers requires variable pointers.
3984 setVariablePointersCapabilities(Ty->getPointerAddressSpace());
3985 if (!hasVariablePointers() && !selectFromSameObject(&I)) {
SJW01901d92020-05-21 08:58:31 -05003986 setVariablePointers();
alan-baker5b86ed72019-02-15 08:26:50 -05003987 }
David Neto22f144c2017-06-12 14:26:21 -04003988 }
3989 }
3990
SJW01901d92020-05-21 08:58:31 -05003991 Ops << Ty << I.getOperand(0) << I.getOperand(1) << I.getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04003992
SJWf93f5f32020-05-05 07:27:56 -05003993 RID = addSPIRVInst(spv::OpSelect, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003994 break;
3995 }
3996 case Instruction::ExtractElement: {
3997 // Handle <4 x i8> type manually.
3998 Type *CompositeTy = I.getOperand(0)->getType();
3999 if (is4xi8vec(CompositeTy)) {
4000 //
4001 // Generate OpShiftRightLogical and OpBitwiseAnd for extractelement with
4002 // <4 x i8>.
4003 //
4004
4005 //
4006 // Generate OpShiftRightLogical
4007 //
4008 // Ops[0] = Result Type ID
4009 // Ops[1] = Operand 0
4010 // Ops[2] = Operand 1
4011 //
SJWf93f5f32020-05-05 07:27:56 -05004012 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004013
SJW01901d92020-05-21 08:58:31 -05004014 Ops << CompositeTy << I.getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04004015
SJW01901d92020-05-21 08:58:31 -05004016 SPIRVID Op1ID = 0;
David Neto22f144c2017-06-12 14:26:21 -04004017 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
4018 // Handle constant index.
SJW806a5d82020-07-15 12:51:38 -05004019 uint32_t Idx = static_cast<uint32_t>(CI->getZExtValue());
4020 Op1ID = getSPIRVInt32Constant(Idx * 8);
David Neto22f144c2017-06-12 14:26:21 -04004021 } else {
4022 // Handle variable index.
SJWf93f5f32020-05-05 07:27:56 -05004023 SPIRVOperandVec TmpOps;
David Neto22f144c2017-06-12 14:26:21 -04004024
SJW806a5d82020-07-15 12:51:38 -05004025 TmpOps << Type::getInt32Ty(Context) << I.getOperand(1)
4026 << getSPIRVInt32Constant(8);
David Neto22f144c2017-06-12 14:26:21 -04004027
SJWf93f5f32020-05-05 07:27:56 -05004028 Op1ID = addSPIRVInst(spv::OpIMul, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04004029 }
SJW01901d92020-05-21 08:58:31 -05004030 Ops << Op1ID;
David Neto22f144c2017-06-12 14:26:21 -04004031
SJW01901d92020-05-21 08:58:31 -05004032 SPIRVID ShiftID = addSPIRVInst(spv::OpShiftRightLogical, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004033
4034 //
4035 // Generate OpBitwiseAnd
4036 //
4037 // Ops[0] = Result Type ID
4038 // Ops[1] = Operand 0
4039 // Ops[2] = Operand 1
4040 //
4041 Ops.clear();
4042
SJW806a5d82020-07-15 12:51:38 -05004043 Ops << CompositeTy << ShiftID << getSPIRVInt32Constant(0xFF);
David Neto22f144c2017-06-12 14:26:21 -04004044
SJWf93f5f32020-05-05 07:27:56 -05004045 RID = addSPIRVInst(spv::OpBitwiseAnd, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004046 break;
4047 }
4048
4049 // Ops[0] = Result Type ID
4050 // Ops[1] = Composite ID
4051 // Ops[2] ... Ops[n] = Indexes (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05004052 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004053
SJW01901d92020-05-21 08:58:31 -05004054 Ops << I.getType() << I.getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04004055
4056 spv::Op Opcode = spv::OpCompositeExtract;
4057 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
SJW01901d92020-05-21 08:58:31 -05004058 Ops << static_cast<uint32_t>(CI->getZExtValue());
David Neto22f144c2017-06-12 14:26:21 -04004059 } else {
SJW01901d92020-05-21 08:58:31 -05004060 Ops << I.getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04004061 Opcode = spv::OpVectorExtractDynamic;
4062 }
4063
SJWf93f5f32020-05-05 07:27:56 -05004064 RID = addSPIRVInst(Opcode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004065 break;
4066 }
4067 case Instruction::InsertElement: {
4068 // Handle <4 x i8> type manually.
4069 Type *CompositeTy = I.getOperand(0)->getType();
4070 if (is4xi8vec(CompositeTy)) {
SJW806a5d82020-07-15 12:51:38 -05004071 SPIRVID CstFFID = getSPIRVInt32Constant(0xFF);
David Neto22f144c2017-06-12 14:26:21 -04004072
SJW01901d92020-05-21 08:58:31 -05004073 SPIRVID ShiftAmountID = 0;
David Neto22f144c2017-06-12 14:26:21 -04004074 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
4075 // Handle constant index.
SJW806a5d82020-07-15 12:51:38 -05004076 uint32_t Idx = static_cast<uint32_t>(CI->getZExtValue());
4077 ShiftAmountID = getSPIRVInt32Constant(Idx * 8);
David Neto22f144c2017-06-12 14:26:21 -04004078 } else {
4079 // Handle variable index.
SJWf93f5f32020-05-05 07:27:56 -05004080 SPIRVOperandVec TmpOps;
David Neto22f144c2017-06-12 14:26:21 -04004081
SJW806a5d82020-07-15 12:51:38 -05004082 TmpOps << Type::getInt32Ty(Context) << I.getOperand(2)
4083 << getSPIRVInt32Constant(8);
David Neto22f144c2017-06-12 14:26:21 -04004084
SJWf93f5f32020-05-05 07:27:56 -05004085 ShiftAmountID = addSPIRVInst(spv::OpIMul, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04004086 }
4087
4088 //
4089 // Generate mask operations.
4090 //
4091
4092 // ShiftLeft mask according to index of insertelement.
SJWf93f5f32020-05-05 07:27:56 -05004093 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004094
SJW01901d92020-05-21 08:58:31 -05004095 Ops << CompositeTy << CstFFID << ShiftAmountID;
David Neto22f144c2017-06-12 14:26:21 -04004096
SJW01901d92020-05-21 08:58:31 -05004097 SPIRVID MaskID = addSPIRVInst(spv::OpShiftLeftLogical, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004098
4099 // Inverse mask.
4100 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05004101 Ops << CompositeTy << MaskID;
David Neto22f144c2017-06-12 14:26:21 -04004102
SJW01901d92020-05-21 08:58:31 -05004103 SPIRVID InvMaskID = addSPIRVInst(spv::OpNot, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004104
4105 // Apply mask.
4106 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05004107 Ops << CompositeTy << I.getOperand(0) << InvMaskID;
David Neto22f144c2017-06-12 14:26:21 -04004108
SJW01901d92020-05-21 08:58:31 -05004109 SPIRVID OrgValID = addSPIRVInst(spv::OpBitwiseAnd, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004110
4111 // Create correct value according to index of insertelement.
4112 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05004113 Ops << CompositeTy << I.getOperand(1) << ShiftAmountID;
David Neto22f144c2017-06-12 14:26:21 -04004114
SJW01901d92020-05-21 08:58:31 -05004115 SPIRVID InsertValID = addSPIRVInst(spv::OpShiftLeftLogical, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004116
4117 // Insert value to original value.
4118 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05004119 Ops << CompositeTy << OrgValID << InsertValID;
David Neto22f144c2017-06-12 14:26:21 -04004120
SJWf93f5f32020-05-05 07:27:56 -05004121 RID = addSPIRVInst(spv::OpBitwiseOr, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004122 break;
4123 }
4124
SJWf93f5f32020-05-05 07:27:56 -05004125 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004126
James Priced26efea2018-06-09 23:28:32 +01004127 // Ops[0] = Result Type ID
SJW01901d92020-05-21 08:58:31 -05004128 Ops << I.getType();
David Neto22f144c2017-06-12 14:26:21 -04004129
4130 spv::Op Opcode = spv::OpCompositeInsert;
4131 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
David Neto257c3892018-04-11 13:19:45 -04004132 const auto value = CI->getZExtValue();
4133 assert(value <= UINT32_MAX);
James Priced26efea2018-06-09 23:28:32 +01004134 // Ops[1] = Object ID
4135 // Ops[2] = Composite ID
4136 // Ops[3] ... Ops[n] = Indexes (Literal Number)
SJW01901d92020-05-21 08:58:31 -05004137 Ops << I.getOperand(1) << I.getOperand(0) << static_cast<uint32_t>(value);
David Neto22f144c2017-06-12 14:26:21 -04004138 } else {
James Priced26efea2018-06-09 23:28:32 +01004139 // Ops[1] = Composite ID
4140 // Ops[2] = Object ID
4141 // Ops[3] ... Ops[n] = Indexes (Literal Number)
SJW01901d92020-05-21 08:58:31 -05004142 Ops << I.getOperand(0) << I.getOperand(1) << I.getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04004143 Opcode = spv::OpVectorInsertDynamic;
4144 }
4145
SJWf93f5f32020-05-05 07:27:56 -05004146 RID = addSPIRVInst(Opcode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004147 break;
4148 }
4149 case Instruction::ShuffleVector: {
4150 // Ops[0] = Result Type ID
4151 // Ops[1] = Vector 1 ID
4152 // Ops[2] = Vector 2 ID
4153 // Ops[3] ... Ops[n] = Components (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05004154 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004155
SJW01901d92020-05-21 08:58:31 -05004156 Ops << I.getType() << I.getOperand(0) << I.getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04004157
alan-bakerc9666712020-04-01 16:31:21 -04004158 auto shuffle = cast<ShuffleVectorInst>(&I);
4159 SmallVector<int, 4> mask;
4160 shuffle->getShuffleMask(mask);
4161 for (auto i : mask) {
4162 if (i == UndefMaskElem) {
4163 if (clspv::Option::HackUndef())
4164 // Use 0 instead of undef.
SJW01901d92020-05-21 08:58:31 -05004165 Ops << 0;
alan-bakerc9666712020-04-01 16:31:21 -04004166 else
4167 // Undef for shuffle in SPIR-V.
SJW01901d92020-05-21 08:58:31 -05004168 Ops << 0xffffffff;
David Neto22f144c2017-06-12 14:26:21 -04004169 } else {
SJW01901d92020-05-21 08:58:31 -05004170 Ops << i;
David Neto22f144c2017-06-12 14:26:21 -04004171 }
4172 }
4173
SJWf93f5f32020-05-05 07:27:56 -05004174 RID = addSPIRVInst(spv::OpVectorShuffle, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004175 break;
4176 }
4177 case Instruction::ICmp:
4178 case Instruction::FCmp: {
4179 CmpInst *CmpI = cast<CmpInst>(&I);
4180
David Netod4ca2e62017-07-06 18:47:35 -04004181 // Pointer equality is invalid.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004182 Type *ArgTy = CmpI->getOperand(0)->getType();
David Netod4ca2e62017-07-06 18:47:35 -04004183 if (isa<PointerType>(ArgTy)) {
4184 CmpI->print(errs());
alan-baker21574d32020-01-29 16:00:31 -05004185 std::string name = I.getParent()->getParent()->getName().str();
David Netod4ca2e62017-07-06 18:47:35 -04004186 errs()
4187 << "\nPointer equality test is not supported by SPIR-V for Vulkan, "
4188 << "in function " << name << "\n";
4189 llvm_unreachable("Pointer equality check is invalid");
4190 break;
4191 }
4192
David Neto257c3892018-04-11 13:19:45 -04004193 // Ops[0] = Result Type ID
4194 // Ops[1] = Operand 1 ID
4195 // Ops[2] = Operand 2 ID
SJWf93f5f32020-05-05 07:27:56 -05004196 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004197
SJW01901d92020-05-21 08:58:31 -05004198 Ops << CmpI->getType() << CmpI->getOperand(0) << CmpI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04004199
4200 spv::Op Opcode = GetSPIRVCmpOpcode(CmpI);
SJWf93f5f32020-05-05 07:27:56 -05004201 RID = addSPIRVInst(Opcode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004202 break;
4203 }
4204 case Instruction::Br: {
SJW88ed5fe2020-05-11 12:40:57 -05004205 // Branch instruction is deferred because it needs label's ID.
4206 BasicBlock *BrBB = I.getParent();
4207 if (ContinueBlocks.count(BrBB) || MergeBlocks.count(BrBB)) {
4208 // Placeholder for Merge operation
4209 RID = addSPIRVPlaceholder(&I);
4210 }
4211 RID = addSPIRVPlaceholder(&I);
David Neto22f144c2017-06-12 14:26:21 -04004212 break;
4213 }
4214 case Instruction::Switch: {
4215 I.print(errs());
4216 llvm_unreachable("Unsupported instruction???");
4217 break;
4218 }
4219 case Instruction::IndirectBr: {
4220 I.print(errs());
4221 llvm_unreachable("Unsupported instruction???");
4222 break;
4223 }
4224 case Instruction::PHI: {
SJW88ed5fe2020-05-11 12:40:57 -05004225 // PHI instruction is deferred because it needs label's ID.
4226 RID = addSPIRVPlaceholder(&I);
David Neto22f144c2017-06-12 14:26:21 -04004227 break;
4228 }
4229 case Instruction::Alloca: {
4230 //
4231 // Generate OpVariable.
4232 //
4233 // Ops[0] : Result Type ID
4234 // Ops[1] : Storage Class
SJWf93f5f32020-05-05 07:27:56 -05004235 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004236
SJW01901d92020-05-21 08:58:31 -05004237 Ops << I.getType() << spv::StorageClassFunction;
David Neto22f144c2017-06-12 14:26:21 -04004238
SJWf93f5f32020-05-05 07:27:56 -05004239 RID = addSPIRVInst(spv::OpVariable, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004240 break;
4241 }
4242 case Instruction::Load: {
4243 LoadInst *LD = cast<LoadInst>(&I);
4244 //
4245 // Generate OpLoad.
4246 //
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04004247
alan-baker5b86ed72019-02-15 08:26:50 -05004248 if (LD->getType()->isPointerTy()) {
4249 // Loading a pointer requires variable pointers.
4250 setVariablePointersCapabilities(LD->getType()->getPointerAddressSpace());
4251 }
David Neto22f144c2017-06-12 14:26:21 -04004252
SJW01901d92020-05-21 08:58:31 -05004253 SPIRVID PointerID = getSPIRVValue(LD->getPointerOperand());
David Netoa60b00b2017-09-15 16:34:09 -04004254 // This is a hack to work around what looks like a driver bug.
4255 // When we're loading from the special variable holding the WorkgroupSize
David Neto0a2f98d2017-09-15 19:38:40 -04004256 // builtin value, use an OpBitWiseAnd of the value's ID rather than
4257 // generating a load.
David Neto66cfe642018-03-24 06:13:56 -07004258 // TODO(dneto): Remove this awful hack once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -04004259 if (PointerID == WorkgroupSizeVarID) {
David Neto0a2f98d2017-09-15 19:38:40 -04004260 // Generate a bitwise-and of the original value with itself.
4261 // We should have been able to get away with just an OpCopyObject,
4262 // but we need something more complex to get past certain driver bugs.
4263 // This is ridiculous, but necessary.
4264 // TODO(dneto): Revisit this once drivers fix their bugs.
4265
SJWf93f5f32020-05-05 07:27:56 -05004266 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05004267 Ops << LD->getType() << WorkgroupSizeValueID << WorkgroupSizeValueID;
David Neto0a2f98d2017-09-15 19:38:40 -04004268
SJWf93f5f32020-05-05 07:27:56 -05004269 RID = addSPIRVInst(spv::OpBitwiseAnd, Ops);
David Netoa60b00b2017-09-15 16:34:09 -04004270 break;
4271 }
4272
4273 // This is the normal path. Generate a load.
4274
David Neto22f144c2017-06-12 14:26:21 -04004275 // Ops[0] = Result Type ID
4276 // Ops[1] = Pointer ID
4277 // Ops[2] ... Ops[n] = Optional Memory Access
4278 //
4279 // TODO: Do we need to implement Optional Memory Access???
David Neto0a2f98d2017-09-15 19:38:40 -04004280
SJWf93f5f32020-05-05 07:27:56 -05004281 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05004282 Ops << LD->getType() << LD->getPointerOperand();
David Neto22f144c2017-06-12 14:26:21 -04004283
SJWf93f5f32020-05-05 07:27:56 -05004284 RID = addSPIRVInst(spv::OpLoad, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004285 break;
4286 }
4287 case Instruction::Store: {
4288 StoreInst *ST = cast<StoreInst>(&I);
4289 //
4290 // Generate OpStore.
4291 //
4292
alan-baker5b86ed72019-02-15 08:26:50 -05004293 if (ST->getValueOperand()->getType()->isPointerTy()) {
4294 // Storing a pointer requires variable pointers.
4295 setVariablePointersCapabilities(
4296 ST->getValueOperand()->getType()->getPointerAddressSpace());
4297 }
4298
David Neto22f144c2017-06-12 14:26:21 -04004299 // Ops[0] = Pointer ID
4300 // Ops[1] = Object ID
4301 // Ops[2] ... Ops[n] = Optional Memory Access (later???)
4302 //
4303 // TODO: Do we need to implement Optional Memory Access???
SJWf93f5f32020-05-05 07:27:56 -05004304 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05004305 Ops << ST->getPointerOperand() << ST->getValueOperand();
David Neto22f144c2017-06-12 14:26:21 -04004306
SJWf93f5f32020-05-05 07:27:56 -05004307 RID = addSPIRVInst(spv::OpStore, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004308 break;
4309 }
4310 case Instruction::AtomicCmpXchg: {
4311 I.print(errs());
4312 llvm_unreachable("Unsupported instruction???");
4313 break;
4314 }
4315 case Instruction::AtomicRMW: {
Neil Henning39672102017-09-29 14:33:13 +01004316 AtomicRMWInst *AtomicRMW = dyn_cast<AtomicRMWInst>(&I);
4317
4318 spv::Op opcode;
4319
4320 switch (AtomicRMW->getOperation()) {
4321 default:
4322 I.print(errs());
4323 llvm_unreachable("Unsupported instruction???");
4324 case llvm::AtomicRMWInst::Add:
4325 opcode = spv::OpAtomicIAdd;
4326 break;
4327 case llvm::AtomicRMWInst::Sub:
4328 opcode = spv::OpAtomicISub;
4329 break;
4330 case llvm::AtomicRMWInst::Xchg:
4331 opcode = spv::OpAtomicExchange;
4332 break;
4333 case llvm::AtomicRMWInst::Min:
4334 opcode = spv::OpAtomicSMin;
4335 break;
4336 case llvm::AtomicRMWInst::Max:
4337 opcode = spv::OpAtomicSMax;
4338 break;
4339 case llvm::AtomicRMWInst::UMin:
4340 opcode = spv::OpAtomicUMin;
4341 break;
4342 case llvm::AtomicRMWInst::UMax:
4343 opcode = spv::OpAtomicUMax;
4344 break;
4345 case llvm::AtomicRMWInst::And:
4346 opcode = spv::OpAtomicAnd;
4347 break;
4348 case llvm::AtomicRMWInst::Or:
4349 opcode = spv::OpAtomicOr;
4350 break;
4351 case llvm::AtomicRMWInst::Xor:
4352 opcode = spv::OpAtomicXor;
4353 break;
4354 }
4355
4356 //
4357 // Generate OpAtomic*.
4358 //
SJWf93f5f32020-05-05 07:27:56 -05004359 SPIRVOperandVec Ops;
Neil Henning39672102017-09-29 14:33:13 +01004360
SJW01901d92020-05-21 08:58:31 -05004361 Ops << I.getType() << AtomicRMW->getPointerOperand();
Neil Henning39672102017-09-29 14:33:13 +01004362
SJW806a5d82020-07-15 12:51:38 -05004363 const auto ConstantScopeDevice = getSPIRVInt32Constant(spv::ScopeDevice);
SJW01901d92020-05-21 08:58:31 -05004364 Ops << ConstantScopeDevice;
Neil Henning39672102017-09-29 14:33:13 +01004365
SJW806a5d82020-07-15 12:51:38 -05004366 const auto ConstantMemorySemantics =
4367 getSPIRVInt32Constant(spv::MemorySemanticsUniformMemoryMask |
4368 spv::MemorySemanticsSequentiallyConsistentMask);
SJW01901d92020-05-21 08:58:31 -05004369 Ops << ConstantMemorySemantics << AtomicRMW->getValOperand();
Neil Henning39672102017-09-29 14:33:13 +01004370
SJWf93f5f32020-05-05 07:27:56 -05004371 RID = addSPIRVInst(opcode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004372 break;
4373 }
4374 case Instruction::Fence: {
4375 I.print(errs());
4376 llvm_unreachable("Unsupported instruction???");
4377 break;
4378 }
4379 case Instruction::Call: {
4380 CallInst *Call = dyn_cast<CallInst>(&I);
SJW806a5d82020-07-15 12:51:38 -05004381 RID = GenerateInstructionFromCall(Call);
David Neto22f144c2017-06-12 14:26:21 -04004382 break;
4383 }
4384 case Instruction::Ret: {
4385 unsigned NumOps = I.getNumOperands();
4386 if (NumOps == 0) {
4387 //
4388 // Generate OpReturn.
4389 //
SJWf93f5f32020-05-05 07:27:56 -05004390 RID = addSPIRVInst(spv::OpReturn);
David Neto22f144c2017-06-12 14:26:21 -04004391 } else {
4392 //
4393 // Generate OpReturnValue.
4394 //
4395
4396 // Ops[0] = Return Value ID
SJWf93f5f32020-05-05 07:27:56 -05004397 SPIRVOperandVec Ops;
David Neto257c3892018-04-11 13:19:45 -04004398
SJW01901d92020-05-21 08:58:31 -05004399 Ops << I.getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04004400
SJWf93f5f32020-05-05 07:27:56 -05004401 RID = addSPIRVInst(spv::OpReturnValue, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004402 break;
4403 }
4404 break;
4405 }
4406 }
SJWf93f5f32020-05-05 07:27:56 -05004407
4408 // Register Instruction to ValueMap.
SJW01901d92020-05-21 08:58:31 -05004409 if (RID.isValid()) {
SJWf93f5f32020-05-05 07:27:56 -05004410 VMap[&I] = RID;
4411 }
David Neto22f144c2017-06-12 14:26:21 -04004412}
4413
4414void SPIRVProducerPass::GenerateFuncEpilogue() {
David Neto22f144c2017-06-12 14:26:21 -04004415
4416 //
4417 // Generate OpFunctionEnd
4418 //
SJWf93f5f32020-05-05 07:27:56 -05004419 addSPIRVInst(spv::OpFunctionEnd);
David Neto22f144c2017-06-12 14:26:21 -04004420}
4421
4422bool SPIRVProducerPass::is4xi8vec(Type *Ty) const {
alan-bakerb39c8262019-03-08 14:03:37 -05004423 // Don't specialize <4 x i8> if i8 is generally supported.
4424 if (clspv::Option::Int8Support())
4425 return false;
4426
David Neto22f144c2017-06-12 14:26:21 -04004427 LLVMContext &Context = Ty->getContext();
James Pricecf53df42020-04-20 14:41:24 -04004428 if (auto VecTy = dyn_cast<VectorType>(Ty)) {
4429 if (VecTy->getElementType() == Type::getInt8Ty(Context) &&
alan-baker5a8c3be2020-09-09 13:44:26 -04004430 VecTy->getElementCount().getKnownMinValue() == 4) {
David Neto22f144c2017-06-12 14:26:21 -04004431 return true;
4432 }
4433 }
4434
4435 return false;
4436}
4437
4438void SPIRVProducerPass::HandleDeferredInstruction() {
David Neto22f144c2017-06-12 14:26:21 -04004439 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
4440
SJW88ed5fe2020-05-11 12:40:57 -05004441 for (size_t i = 0; i < DeferredInsts.size(); ++i) {
4442 Value *Inst = DeferredInsts[i].first;
4443 SPIRVInstruction *Placeholder = DeferredInsts[i].second;
4444 SPIRVOperandVec Operands;
4445
4446 auto nextDeferred = [&i, &Inst, &DeferredInsts, &Placeholder]() {
4447 ++i;
4448 assert(DeferredInsts.size() > i);
4449 assert(Inst == DeferredInsts[i].first);
4450 Placeholder = DeferredInsts[i].second;
4451 };
David Neto22f144c2017-06-12 14:26:21 -04004452
4453 if (BranchInst *Br = dyn_cast<BranchInst>(Inst)) {
alan-baker06cad652019-12-03 17:56:47 -05004454 // Check whether this branch needs to be preceeded by merge instruction.
David Neto22f144c2017-06-12 14:26:21 -04004455 BasicBlock *BrBB = Br->getParent();
alan-baker06cad652019-12-03 17:56:47 -05004456 if (ContinueBlocks.count(BrBB)) {
David Neto22f144c2017-06-12 14:26:21 -04004457 //
4458 // Generate OpLoopMerge.
4459 //
4460 // Ops[0] = Merge Block ID
4461 // Ops[1] = Continue Target ID
4462 // Ops[2] = Selection Control
SJWf93f5f32020-05-05 07:27:56 -05004463 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004464
SJW01901d92020-05-21 08:58:31 -05004465 Ops << MergeBlocks[BrBB] << ContinueBlocks[BrBB]
4466 << spv::LoopControlMaskNone;
David Neto22f144c2017-06-12 14:26:21 -04004467
SJW88ed5fe2020-05-11 12:40:57 -05004468 replaceSPIRVInst(Placeholder, spv::OpLoopMerge, Ops);
4469
4470 nextDeferred();
4471
alan-baker06cad652019-12-03 17:56:47 -05004472 } else if (MergeBlocks.count(BrBB)) {
4473 //
4474 // Generate OpSelectionMerge.
4475 //
4476 // Ops[0] = Merge Block ID
4477 // Ops[1] = Selection Control
SJWf93f5f32020-05-05 07:27:56 -05004478 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004479
alan-baker06cad652019-12-03 17:56:47 -05004480 auto MergeBB = MergeBlocks[BrBB];
SJW01901d92020-05-21 08:58:31 -05004481 Ops << MergeBB << spv::SelectionControlMaskNone;
David Neto22f144c2017-06-12 14:26:21 -04004482
SJW88ed5fe2020-05-11 12:40:57 -05004483 replaceSPIRVInst(Placeholder, spv::OpSelectionMerge, Ops);
4484
4485 nextDeferred();
David Neto22f144c2017-06-12 14:26:21 -04004486 }
4487
4488 if (Br->isConditional()) {
4489 //
4490 // Generate OpBranchConditional.
4491 //
4492 // Ops[0] = Condition ID
4493 // Ops[1] = True Label ID
4494 // Ops[2] = False Label ID
4495 // Ops[3] ... Ops[n] = Branch weights (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05004496 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004497
SJW01901d92020-05-21 08:58:31 -05004498 Ops << Br->getCondition() << Br->getSuccessor(0) << Br->getSuccessor(1);
David Neto22f144c2017-06-12 14:26:21 -04004499
SJW88ed5fe2020-05-11 12:40:57 -05004500 replaceSPIRVInst(Placeholder, spv::OpBranchConditional, Ops);
4501
David Neto22f144c2017-06-12 14:26:21 -04004502 } else {
4503 //
4504 // Generate OpBranch.
4505 //
4506 // Ops[0] = Target Label ID
SJWf93f5f32020-05-05 07:27:56 -05004507 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004508
SJW01901d92020-05-21 08:58:31 -05004509 Ops << Br->getSuccessor(0);
David Neto22f144c2017-06-12 14:26:21 -04004510
SJW88ed5fe2020-05-11 12:40:57 -05004511 replaceSPIRVInst(Placeholder, spv::OpBranch, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004512 }
4513 } else if (PHINode *PHI = dyn_cast<PHINode>(Inst)) {
alan-baker5ed87542020-03-23 11:05:22 -04004514 if (PHI->getType()->isPointerTy() && !IsSamplerType(PHI->getType()) &&
4515 !IsImageType(PHI->getType())) {
alan-baker5b86ed72019-02-15 08:26:50 -05004516 // OpPhi on pointers requires variable pointers.
4517 setVariablePointersCapabilities(
4518 PHI->getType()->getPointerAddressSpace());
4519 if (!hasVariablePointers() && !selectFromSameObject(PHI)) {
SJW01901d92020-05-21 08:58:31 -05004520 setVariablePointers();
alan-baker5b86ed72019-02-15 08:26:50 -05004521 }
4522 }
4523
David Neto22f144c2017-06-12 14:26:21 -04004524 //
4525 // Generate OpPhi.
4526 //
4527 // Ops[0] = Result Type ID
4528 // Ops[1] ... Ops[n] = (Variable ID, Parent ID) pairs
SJWf93f5f32020-05-05 07:27:56 -05004529 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004530
SJW01901d92020-05-21 08:58:31 -05004531 Ops << PHI->getType();
David Neto22f144c2017-06-12 14:26:21 -04004532
SJW88ed5fe2020-05-11 12:40:57 -05004533 for (unsigned j = 0; j < PHI->getNumIncomingValues(); j++) {
SJW01901d92020-05-21 08:58:31 -05004534 Ops << PHI->getIncomingValue(j) << PHI->getIncomingBlock(j);
David Neto22f144c2017-06-12 14:26:21 -04004535 }
4536
SJW88ed5fe2020-05-11 12:40:57 -05004537 replaceSPIRVInst(Placeholder, spv::OpPhi, Ops);
4538
David Neto22f144c2017-06-12 14:26:21 -04004539 } else if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
4540 Function *Callee = Call->getCalledFunction();
David Neto3fbb4072017-10-16 11:28:14 -04004541 auto callee_name = Callee->getName();
David Neto22f144c2017-06-12 14:26:21 -04004542
SJW61531372020-06-09 07:31:08 -05004543 if (Builtins::Lookup(Callee) == Builtins::kClspvCompositeConstruct) {
David Netoab03f432017-11-03 17:00:44 -04004544
4545 // Generate an OpCompositeConstruct
SJWf93f5f32020-05-05 07:27:56 -05004546 SPIRVOperandVec Ops;
David Netoab03f432017-11-03 17:00:44 -04004547
4548 // The result type.
SJW01901d92020-05-21 08:58:31 -05004549 Ops << Call->getType();
David Netoab03f432017-11-03 17:00:44 -04004550
4551 for (Use &use : Call->arg_operands()) {
SJW01901d92020-05-21 08:58:31 -05004552 Ops << use.get();
David Netoab03f432017-11-03 17:00:44 -04004553 }
4554
SJW88ed5fe2020-05-11 12:40:57 -05004555 replaceSPIRVInst(Placeholder, spv::OpCompositeConstruct, Ops);
David Netoab03f432017-11-03 17:00:44 -04004556
David Neto22f144c2017-06-12 14:26:21 -04004557 } else {
alan-baker5b86ed72019-02-15 08:26:50 -05004558 if (Call->getType()->isPointerTy()) {
4559 // Functions returning pointers require variable pointers.
4560 setVariablePointersCapabilities(
4561 Call->getType()->getPointerAddressSpace());
4562 }
4563
David Neto22f144c2017-06-12 14:26:21 -04004564 //
4565 // Generate OpFunctionCall.
4566 //
4567
4568 // Ops[0] = Result Type ID
4569 // Ops[1] = Callee Function ID
4570 // Ops[2] ... Ops[n] = Argument 0, ... , Argument n
SJWf93f5f32020-05-05 07:27:56 -05004571 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004572
SJW01901d92020-05-21 08:58:31 -05004573 Ops << Call->getType();
David Neto22f144c2017-06-12 14:26:21 -04004574
SJW01901d92020-05-21 08:58:31 -05004575 SPIRVID CalleeID = getSPIRVValue(Callee);
SJW806a5d82020-07-15 12:51:38 -05004576 if (!CalleeID.isValid()) {
David Neto43568eb2017-10-13 18:25:25 -04004577 errs() << "Can't translate function call. Missing builtin? "
David Neto862b7d82018-06-14 18:48:37 -04004578 << callee_name << " in: " << *Call << "\n";
David Neto43568eb2017-10-13 18:25:25 -04004579 // TODO(dneto): Can we error out? Enabling this llvm_unreachable
4580 // causes an infinite loop. Instead, go ahead and generate
4581 // the bad function call. A validator will catch the 0-Id.
4582 // llvm_unreachable("Can't translate function call");
4583 }
David Neto22f144c2017-06-12 14:26:21 -04004584
SJW01901d92020-05-21 08:58:31 -05004585 Ops << CalleeID;
David Neto22f144c2017-06-12 14:26:21 -04004586
David Neto22f144c2017-06-12 14:26:21 -04004587 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
SJW88ed5fe2020-05-11 12:40:57 -05004588 for (unsigned j = 0; j < CalleeFTy->getNumParams(); j++) {
4589 auto *operand = Call->getOperand(j);
alan-bakerd4d50652019-12-03 17:17:15 -05004590 auto *operand_type = operand->getType();
4591 // Images and samplers can be passed as function parameters without
4592 // variable pointers.
4593 if (operand_type->isPointerTy() && !IsImageType(operand_type) &&
4594 !IsSamplerType(operand_type)) {
alan-baker5b86ed72019-02-15 08:26:50 -05004595 auto sc =
4596 GetStorageClass(operand->getType()->getPointerAddressSpace());
4597 if (sc == spv::StorageClassStorageBuffer) {
4598 // Passing SSBO by reference requires variable pointers storage
4599 // buffer.
SJW01901d92020-05-21 08:58:31 -05004600 setVariablePointersStorageBuffer();
alan-baker5b86ed72019-02-15 08:26:50 -05004601 } else if (sc == spv::StorageClassWorkgroup) {
4602 // Workgroup references require variable pointers if they are not
4603 // memory object declarations.
4604 if (auto *operand_call = dyn_cast<CallInst>(operand)) {
4605 // Workgroup accessor represents a variable reference.
SJW61531372020-06-09 07:31:08 -05004606 if (Builtins::Lookup(operand_call->getCalledFunction()) !=
4607 Builtins::kClspvLocal)
SJW01901d92020-05-21 08:58:31 -05004608 setVariablePointers();
alan-baker5b86ed72019-02-15 08:26:50 -05004609 } else {
4610 // Arguments are function parameters.
4611 if (!isa<Argument>(operand))
SJW01901d92020-05-21 08:58:31 -05004612 setVariablePointers();
alan-baker5b86ed72019-02-15 08:26:50 -05004613 }
4614 }
4615 }
SJW01901d92020-05-21 08:58:31 -05004616 Ops << operand;
David Neto22f144c2017-06-12 14:26:21 -04004617 }
4618
SJW88ed5fe2020-05-11 12:40:57 -05004619 replaceSPIRVInst(Placeholder, spv::OpFunctionCall, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004620 }
4621 }
4622 }
4623}
4624
SJW77b87ad2020-04-21 14:37:52 -05004625void SPIRVProducerPass::HandleDeferredDecorations() {
4626 const auto &DL = module->getDataLayout();
alan-baker5a8c3be2020-09-09 13:44:26 -04004627 if (getTypesNeedingArrayStride().empty()) {
David Neto1a1a0582017-07-07 12:01:44 -04004628 return;
David Netoc6f3ab22018-04-06 18:02:31 -04004629 }
David Neto1a1a0582017-07-07 12:01:44 -04004630
David Netoc6f3ab22018-04-06 18:02:31 -04004631 // Insert ArrayStride decorations on pointer types, due to OpPtrAccessChain
4632 // instructions we generated earlier.
David Neto85082642018-03-24 06:55:20 -07004633 for (auto *type : getTypesNeedingArrayStride()) {
4634 Type *elemTy = nullptr;
4635 if (auto *ptrTy = dyn_cast<PointerType>(type)) {
4636 elemTy = ptrTy->getElementType();
alan-bakerb6b09dc2018-11-08 16:59:28 -05004637 } else if (auto *arrayTy = dyn_cast<ArrayType>(type)) {
alan-baker8eb435a2020-04-08 00:42:06 -04004638 elemTy = arrayTy->getElementType();
4639 } else if (auto *vecTy = dyn_cast<VectorType>(type)) {
4640 elemTy = vecTy->getElementType();
David Neto85082642018-03-24 06:55:20 -07004641 } else {
4642 errs() << "Unhandled strided type " << *type << "\n";
4643 llvm_unreachable("Unhandled strided type");
4644 }
David Neto1a1a0582017-07-07 12:01:44 -04004645
4646 // Ops[0] = Target ID
4647 // Ops[1] = Decoration (ArrayStride)
4648 // Ops[2] = Stride number (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05004649 SPIRVOperandVec Ops;
David Neto1a1a0582017-07-07 12:01:44 -04004650
David Neto85082642018-03-24 06:55:20 -07004651 // Same as DL.getIndexedOffsetInType( elemTy, { 1 } );
Alan Bakerfcda9482018-10-02 17:09:59 -04004652 const uint32_t stride = static_cast<uint32_t>(GetTypeAllocSize(elemTy, DL));
David Neto257c3892018-04-11 13:19:45 -04004653
SJW01901d92020-05-21 08:58:31 -05004654 Ops << type << spv::DecorationArrayStride << stride;
David Neto1a1a0582017-07-07 12:01:44 -04004655
SJWf93f5f32020-05-05 07:27:56 -05004656 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Netoc6f3ab22018-04-06 18:02:31 -04004657 }
David Neto1a1a0582017-07-07 12:01:44 -04004658}
4659
SJW61531372020-06-09 07:31:08 -05004660glsl::ExtInst
4661SPIRVProducerPass::getExtInstEnum(const Builtins::FunctionInfo &func_info) {
SJW2c317da2020-03-23 07:39:13 -05004662
SJW61531372020-06-09 07:31:08 -05004663 switch (func_info.getType()) {
SJW2c317da2020-03-23 07:39:13 -05004664 case Builtins::kClamp: {
SJW61531372020-06-09 07:31:08 -05004665 auto param_type = func_info.getParameter(0);
SJW2c317da2020-03-23 07:39:13 -05004666 if (param_type.type_id == Type::FloatTyID) {
4667 return glsl::ExtInst::ExtInstFClamp;
4668 }
4669 return param_type.is_signed ? glsl::ExtInst::ExtInstSClamp
4670 : glsl::ExtInst::ExtInstUClamp;
4671 }
4672 case Builtins::kMax: {
SJW61531372020-06-09 07:31:08 -05004673 auto param_type = func_info.getParameter(0);
SJW2c317da2020-03-23 07:39:13 -05004674 if (param_type.type_id == Type::FloatTyID) {
4675 return glsl::ExtInst::ExtInstFMax;
4676 }
4677 return param_type.is_signed ? glsl::ExtInst::ExtInstSMax
4678 : glsl::ExtInst::ExtInstUMax;
4679 }
4680 case Builtins::kMin: {
SJW61531372020-06-09 07:31:08 -05004681 auto param_type = func_info.getParameter(0);
SJW2c317da2020-03-23 07:39:13 -05004682 if (param_type.type_id == Type::FloatTyID) {
4683 return glsl::ExtInst::ExtInstFMin;
4684 }
4685 return param_type.is_signed ? glsl::ExtInst::ExtInstSMin
4686 : glsl::ExtInst::ExtInstUMin;
4687 }
4688 case Builtins::kAbs:
4689 return glsl::ExtInst::ExtInstSAbs;
4690 case Builtins::kFmax:
Marco Antognini55d51862020-07-21 17:50:07 +01004691 return glsl::ExtInst::ExtInstNMax;
SJW2c317da2020-03-23 07:39:13 -05004692 case Builtins::kFmin:
Marco Antognini55d51862020-07-21 17:50:07 +01004693 return glsl::ExtInst::ExtInstNMin;
SJW2c317da2020-03-23 07:39:13 -05004694 case Builtins::kDegrees:
4695 return glsl::ExtInst::ExtInstDegrees;
4696 case Builtins::kRadians:
4697 return glsl::ExtInst::ExtInstRadians;
4698 case Builtins::kMix:
4699 return glsl::ExtInst::ExtInstFMix;
4700 case Builtins::kAcos:
4701 case Builtins::kAcospi:
4702 return glsl::ExtInst::ExtInstAcos;
4703 case Builtins::kAcosh:
4704 return glsl::ExtInst::ExtInstAcosh;
4705 case Builtins::kAsin:
4706 case Builtins::kAsinpi:
4707 return glsl::ExtInst::ExtInstAsin;
4708 case Builtins::kAsinh:
4709 return glsl::ExtInst::ExtInstAsinh;
4710 case Builtins::kAtan:
4711 case Builtins::kAtanpi:
4712 return glsl::ExtInst::ExtInstAtan;
4713 case Builtins::kAtanh:
4714 return glsl::ExtInst::ExtInstAtanh;
4715 case Builtins::kAtan2:
4716 case Builtins::kAtan2pi:
4717 return glsl::ExtInst::ExtInstAtan2;
4718 case Builtins::kCeil:
4719 return glsl::ExtInst::ExtInstCeil;
4720 case Builtins::kSin:
4721 case Builtins::kHalfSin:
4722 case Builtins::kNativeSin:
4723 return glsl::ExtInst::ExtInstSin;
4724 case Builtins::kSinh:
4725 return glsl::ExtInst::ExtInstSinh;
4726 case Builtins::kCos:
4727 case Builtins::kHalfCos:
4728 case Builtins::kNativeCos:
4729 return glsl::ExtInst::ExtInstCos;
4730 case Builtins::kCosh:
4731 return glsl::ExtInst::ExtInstCosh;
4732 case Builtins::kTan:
4733 case Builtins::kHalfTan:
4734 case Builtins::kNativeTan:
4735 return glsl::ExtInst::ExtInstTan;
4736 case Builtins::kTanh:
4737 return glsl::ExtInst::ExtInstTanh;
4738 case Builtins::kExp:
4739 case Builtins::kHalfExp:
4740 case Builtins::kNativeExp:
4741 return glsl::ExtInst::ExtInstExp;
4742 case Builtins::kExp2:
4743 case Builtins::kHalfExp2:
4744 case Builtins::kNativeExp2:
4745 return glsl::ExtInst::ExtInstExp2;
4746 case Builtins::kLog:
4747 case Builtins::kHalfLog:
4748 case Builtins::kNativeLog:
4749 return glsl::ExtInst::ExtInstLog;
4750 case Builtins::kLog2:
4751 case Builtins::kHalfLog2:
4752 case Builtins::kNativeLog2:
4753 return glsl::ExtInst::ExtInstLog2;
4754 case Builtins::kFabs:
4755 return glsl::ExtInst::ExtInstFAbs;
4756 case Builtins::kFma:
4757 return glsl::ExtInst::ExtInstFma;
4758 case Builtins::kFloor:
4759 return glsl::ExtInst::ExtInstFloor;
4760 case Builtins::kLdexp:
4761 return glsl::ExtInst::ExtInstLdexp;
4762 case Builtins::kPow:
4763 case Builtins::kPowr:
4764 case Builtins::kHalfPowr:
4765 case Builtins::kNativePowr:
4766 return glsl::ExtInst::ExtInstPow;
James Price38553362020-09-03 18:30:40 -04004767 case Builtins::kRint:
4768 return glsl::ExtInst::ExtInstRoundEven;
SJW2c317da2020-03-23 07:39:13 -05004769 case Builtins::kRound:
4770 return glsl::ExtInst::ExtInstRound;
4771 case Builtins::kSqrt:
4772 case Builtins::kHalfSqrt:
4773 case Builtins::kNativeSqrt:
4774 return glsl::ExtInst::ExtInstSqrt;
4775 case Builtins::kRsqrt:
4776 case Builtins::kHalfRsqrt:
4777 case Builtins::kNativeRsqrt:
4778 return glsl::ExtInst::ExtInstInverseSqrt;
4779 case Builtins::kTrunc:
4780 return glsl::ExtInst::ExtInstTrunc;
4781 case Builtins::kFrexp:
4782 return glsl::ExtInst::ExtInstFrexp;
SJW61531372020-06-09 07:31:08 -05004783 case Builtins::kClspvFract:
SJW2c317da2020-03-23 07:39:13 -05004784 case Builtins::kFract:
4785 return glsl::ExtInst::ExtInstFract;
4786 case Builtins::kSign:
4787 return glsl::ExtInst::ExtInstFSign;
4788 case Builtins::kLength:
4789 case Builtins::kFastLength:
4790 return glsl::ExtInst::ExtInstLength;
4791 case Builtins::kDistance:
4792 case Builtins::kFastDistance:
4793 return glsl::ExtInst::ExtInstDistance;
4794 case Builtins::kStep:
4795 return glsl::ExtInst::ExtInstStep;
4796 case Builtins::kSmoothstep:
4797 return glsl::ExtInst::ExtInstSmoothStep;
4798 case Builtins::kCross:
4799 return glsl::ExtInst::ExtInstCross;
4800 case Builtins::kNormalize:
4801 case Builtins::kFastNormalize:
4802 return glsl::ExtInst::ExtInstNormalize;
SJW61531372020-06-09 07:31:08 -05004803 case Builtins::kSpirvPack:
4804 return glsl::ExtInst::ExtInstPackHalf2x16;
4805 case Builtins::kSpirvUnpack:
4806 return glsl::ExtInst::ExtInstUnpackHalf2x16;
SJW2c317da2020-03-23 07:39:13 -05004807 default:
4808 break;
4809 }
4810
SJW61531372020-06-09 07:31:08 -05004811 if (func_info.getName().find("llvm.fmuladd.") == 0) {
4812 return glsl::ExtInst::ExtInstFma;
4813 }
4814 return kGlslExtInstBad;
David Neto3fbb4072017-10-16 11:28:14 -04004815}
4816
SJW61531372020-06-09 07:31:08 -05004817glsl::ExtInst SPIRVProducerPass::getIndirectExtInstEnum(
4818 const Builtins::FunctionInfo &func_info) {
4819 switch (func_info.getType()) {
SJW2c317da2020-03-23 07:39:13 -05004820 case Builtins::kClz:
4821 return glsl::ExtInst::ExtInstFindUMsb;
4822 case Builtins::kAcospi:
4823 return glsl::ExtInst::ExtInstAcos;
4824 case Builtins::kAsinpi:
4825 return glsl::ExtInst::ExtInstAsin;
4826 case Builtins::kAtanpi:
4827 return glsl::ExtInst::ExtInstAtan;
4828 case Builtins::kAtan2pi:
4829 return glsl::ExtInst::ExtInstAtan2;
4830 default:
4831 break;
4832 }
4833 return kGlslExtInstBad;
David Neto3fbb4072017-10-16 11:28:14 -04004834}
4835
SJW61531372020-06-09 07:31:08 -05004836glsl::ExtInst SPIRVProducerPass::getDirectOrIndirectExtInstEnum(
4837 const Builtins::FunctionInfo &func_info) {
4838 auto direct = getExtInstEnum(func_info);
David Neto3fbb4072017-10-16 11:28:14 -04004839 if (direct != kGlslExtInstBad)
4840 return direct;
SJW61531372020-06-09 07:31:08 -05004841 return getIndirectExtInstEnum(func_info);
David Neto22f144c2017-06-12 14:26:21 -04004842}
4843
David Neto22f144c2017-06-12 14:26:21 -04004844void SPIRVProducerPass::WriteOneWord(uint32_t Word) {
David Neto0676e6f2017-07-11 18:47:44 -04004845 binaryOut->write(reinterpret_cast<const char *>(&Word), sizeof(uint32_t));
David Neto22f144c2017-06-12 14:26:21 -04004846}
4847
SJW88ed5fe2020-05-11 12:40:57 -05004848void SPIRVProducerPass::WriteResultID(const SPIRVInstruction &Inst) {
SJW01901d92020-05-21 08:58:31 -05004849 WriteOneWord(Inst.getResultID().get());
David Neto22f144c2017-06-12 14:26:21 -04004850}
4851
SJW88ed5fe2020-05-11 12:40:57 -05004852void SPIRVProducerPass::WriteWordCountAndOpcode(const SPIRVInstruction &Inst) {
David Neto22f144c2017-06-12 14:26:21 -04004853 // High 16 bit : Word Count
4854 // Low 16 bit : Opcode
SJW88ed5fe2020-05-11 12:40:57 -05004855 uint32_t Word = Inst.getOpcode();
4856 const uint32_t count = Inst.getWordCount();
David Netoee2660d2018-06-28 16:31:29 -04004857 if (count > 65535) {
4858 errs() << "Word count limit of 65535 exceeded: " << count << "\n";
4859 llvm_unreachable("Word count too high");
4860 }
SJW88ed5fe2020-05-11 12:40:57 -05004861 Word |= Inst.getWordCount() << 16;
David Neto22f144c2017-06-12 14:26:21 -04004862 WriteOneWord(Word);
4863}
4864
SJW88ed5fe2020-05-11 12:40:57 -05004865void SPIRVProducerPass::WriteOperand(const SPIRVOperand &Op) {
4866 SPIRVOperandType OpTy = Op.getType();
David Neto22f144c2017-06-12 14:26:21 -04004867 switch (OpTy) {
4868 default: {
4869 llvm_unreachable("Unsupported SPIRV Operand Type???");
4870 break;
4871 }
4872 case SPIRVOperandType::NUMBERID: {
SJW88ed5fe2020-05-11 12:40:57 -05004873 WriteOneWord(Op.getNumID());
David Neto22f144c2017-06-12 14:26:21 -04004874 break;
4875 }
4876 case SPIRVOperandType::LITERAL_STRING: {
SJW88ed5fe2020-05-11 12:40:57 -05004877 std::string Str = Op.getLiteralStr();
David Neto22f144c2017-06-12 14:26:21 -04004878 const char *Data = Str.c_str();
4879 size_t WordSize = Str.size() / 4;
4880 for (unsigned Idx = 0; Idx < WordSize; Idx++) {
4881 WriteOneWord(*reinterpret_cast<const uint32_t *>(&Data[4 * Idx]));
4882 }
4883
4884 uint32_t Remainder = Str.size() % 4;
4885 uint32_t LastWord = 0;
4886 if (Remainder) {
4887 for (unsigned Idx = 0; Idx < Remainder; Idx++) {
4888 LastWord |= Data[4 * WordSize + Idx] << 8 * Idx;
4889 }
4890 }
4891
4892 WriteOneWord(LastWord);
4893 break;
4894 }
SJW88ed5fe2020-05-11 12:40:57 -05004895 case SPIRVOperandType::LITERAL_WORD: {
4896 WriteOneWord(Op.getLiteralNum()[0]);
4897 break;
4898 }
4899 case SPIRVOperandType::LITERAL_DWORD: {
4900 WriteOneWord(Op.getLiteralNum()[0]);
4901 WriteOneWord(Op.getLiteralNum()[1]);
David Neto22f144c2017-06-12 14:26:21 -04004902 break;
4903 }
4904 }
4905}
4906
4907void SPIRVProducerPass::WriteSPIRVBinary() {
SJW69939d52020-04-16 07:29:07 -05004908 for (int i = 0; i < kSectionCount; ++i) {
4909 WriteSPIRVBinary(SPIRVSections[i]);
4910 }
4911}
4912
4913void SPIRVProducerPass::WriteSPIRVBinary(SPIRVInstructionList &SPIRVInstList) {
David Neto22f144c2017-06-12 14:26:21 -04004914
SJW88ed5fe2020-05-11 12:40:57 -05004915 for (const auto &Inst : SPIRVInstList) {
4916 const auto &Ops = Inst.getOperands();
4917 spv::Op Opcode = static_cast<spv::Op>(Inst.getOpcode());
David Neto22f144c2017-06-12 14:26:21 -04004918
4919 switch (Opcode) {
4920 default: {
David Neto5c22a252018-03-15 16:07:41 -04004921 errs() << "Unsupported SPIR-V instruction opcode " << int(Opcode) << "\n";
David Neto22f144c2017-06-12 14:26:21 -04004922 llvm_unreachable("Unsupported SPIRV instruction");
4923 break;
4924 }
Marco Antognini68e5c512020-09-09 16:08:57 +01004925 case spv::OpUnreachable:
David Neto22f144c2017-06-12 14:26:21 -04004926 case spv::OpCapability:
4927 case spv::OpExtension:
4928 case spv::OpMemoryModel:
4929 case spv::OpEntryPoint:
4930 case spv::OpExecutionMode:
4931 case spv::OpSource:
4932 case spv::OpDecorate:
4933 case spv::OpMemberDecorate:
4934 case spv::OpBranch:
4935 case spv::OpBranchConditional:
4936 case spv::OpSelectionMerge:
4937 case spv::OpLoopMerge:
4938 case spv::OpStore:
4939 case spv::OpImageWrite:
4940 case spv::OpReturnValue:
4941 case spv::OpControlBarrier:
4942 case spv::OpMemoryBarrier:
4943 case spv::OpReturn:
4944 case spv::OpFunctionEnd:
4945 case spv::OpCopyMemory: {
4946 WriteWordCountAndOpcode(Inst);
4947 for (uint32_t i = 0; i < Ops.size(); i++) {
4948 WriteOperand(Ops[i]);
4949 }
4950 break;
4951 }
4952 case spv::OpTypeBool:
4953 case spv::OpTypeVoid:
4954 case spv::OpTypeSampler:
4955 case spv::OpLabel:
4956 case spv::OpExtInstImport:
4957 case spv::OpTypePointer:
4958 case spv::OpTypeRuntimeArray:
4959 case spv::OpTypeStruct:
4960 case spv::OpTypeImage:
4961 case spv::OpTypeSampledImage:
4962 case spv::OpTypeInt:
4963 case spv::OpTypeFloat:
4964 case spv::OpTypeArray:
4965 case spv::OpTypeVector:
alan-baker86ce19c2020-08-05 13:09:19 -04004966 case spv::OpTypeFunction:
4967 case spv::OpString: {
David Neto22f144c2017-06-12 14:26:21 -04004968 WriteWordCountAndOpcode(Inst);
4969 WriteResultID(Inst);
4970 for (uint32_t i = 0; i < Ops.size(); i++) {
4971 WriteOperand(Ops[i]);
4972 }
4973 break;
4974 }
4975 case spv::OpFunction:
4976 case spv::OpFunctionParameter:
4977 case spv::OpAccessChain:
4978 case spv::OpPtrAccessChain:
4979 case spv::OpInBoundsAccessChain:
4980 case spv::OpUConvert:
4981 case spv::OpSConvert:
4982 case spv::OpConvertFToU:
4983 case spv::OpConvertFToS:
4984 case spv::OpConvertUToF:
4985 case spv::OpConvertSToF:
4986 case spv::OpFConvert:
4987 case spv::OpConvertPtrToU:
4988 case spv::OpConvertUToPtr:
4989 case spv::OpBitcast:
alan-bakerc9c55ae2019-12-02 16:01:27 -05004990 case spv::OpFNegate:
David Neto22f144c2017-06-12 14:26:21 -04004991 case spv::OpIAdd:
4992 case spv::OpFAdd:
4993 case spv::OpISub:
4994 case spv::OpFSub:
4995 case spv::OpIMul:
4996 case spv::OpFMul:
4997 case spv::OpUDiv:
4998 case spv::OpSDiv:
4999 case spv::OpFDiv:
5000 case spv::OpUMod:
5001 case spv::OpSRem:
5002 case spv::OpFRem:
Kévin Petit8a560882019-03-21 15:24:34 +00005003 case spv::OpUMulExtended:
5004 case spv::OpSMulExtended:
David Neto22f144c2017-06-12 14:26:21 -04005005 case spv::OpBitwiseOr:
5006 case spv::OpBitwiseXor:
5007 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04005008 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04005009 case spv::OpShiftLeftLogical:
5010 case spv::OpShiftRightLogical:
5011 case spv::OpShiftRightArithmetic:
5012 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04005013 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04005014 case spv::OpCompositeExtract:
5015 case spv::OpVectorExtractDynamic:
5016 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04005017 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04005018 case spv::OpVectorInsertDynamic:
5019 case spv::OpVectorShuffle:
5020 case spv::OpIEqual:
5021 case spv::OpINotEqual:
5022 case spv::OpUGreaterThan:
5023 case spv::OpUGreaterThanEqual:
5024 case spv::OpULessThan:
5025 case spv::OpULessThanEqual:
5026 case spv::OpSGreaterThan:
5027 case spv::OpSGreaterThanEqual:
5028 case spv::OpSLessThan:
5029 case spv::OpSLessThanEqual:
5030 case spv::OpFOrdEqual:
5031 case spv::OpFOrdGreaterThan:
5032 case spv::OpFOrdGreaterThanEqual:
5033 case spv::OpFOrdLessThan:
5034 case spv::OpFOrdLessThanEqual:
5035 case spv::OpFOrdNotEqual:
5036 case spv::OpFUnordEqual:
5037 case spv::OpFUnordGreaterThan:
5038 case spv::OpFUnordGreaterThanEqual:
5039 case spv::OpFUnordLessThan:
5040 case spv::OpFUnordLessThanEqual:
5041 case spv::OpFUnordNotEqual:
5042 case spv::OpExtInst:
5043 case spv::OpIsInf:
5044 case spv::OpIsNan:
5045 case spv::OpAny:
5046 case spv::OpAll:
5047 case spv::OpUndef:
5048 case spv::OpConstantNull:
5049 case spv::OpLogicalOr:
5050 case spv::OpLogicalAnd:
5051 case spv::OpLogicalNot:
5052 case spv::OpLogicalNotEqual:
5053 case spv::OpConstantComposite:
5054 case spv::OpSpecConstantComposite:
5055 case spv::OpConstantTrue:
5056 case spv::OpConstantFalse:
5057 case spv::OpConstant:
5058 case spv::OpSpecConstant:
5059 case spv::OpVariable:
5060 case spv::OpFunctionCall:
5061 case spv::OpSampledImage:
alan-baker75090e42020-02-20 11:21:04 -05005062 case spv::OpImageFetch:
David Neto22f144c2017-06-12 14:26:21 -04005063 case spv::OpImageSampleExplicitLod:
David Neto5c22a252018-03-15 16:07:41 -04005064 case spv::OpImageQuerySize:
alan-bakerce179f12019-12-06 19:02:22 -05005065 case spv::OpImageQuerySizeLod:
David Neto22f144c2017-06-12 14:26:21 -04005066 case spv::OpSelect:
5067 case spv::OpPhi:
5068 case spv::OpLoad:
5069 case spv::OpAtomicIAdd:
5070 case spv::OpAtomicISub:
5071 case spv::OpAtomicExchange:
5072 case spv::OpAtomicIIncrement:
5073 case spv::OpAtomicIDecrement:
5074 case spv::OpAtomicCompareExchange:
5075 case spv::OpAtomicUMin:
5076 case spv::OpAtomicSMin:
5077 case spv::OpAtomicUMax:
5078 case spv::OpAtomicSMax:
5079 case spv::OpAtomicAnd:
5080 case spv::OpAtomicOr:
5081 case spv::OpAtomicXor:
SJW806a5d82020-07-15 12:51:38 -05005082 case spv::OpDot:
5083 case spv::OpGroupNonUniformAll:
5084 case spv::OpGroupNonUniformAny:
5085 case spv::OpGroupNonUniformBroadcast:
5086 case spv::OpGroupNonUniformIAdd:
5087 case spv::OpGroupNonUniformFAdd:
5088 case spv::OpGroupNonUniformSMin:
5089 case spv::OpGroupNonUniformUMin:
5090 case spv::OpGroupNonUniformFMin:
5091 case spv::OpGroupNonUniformSMax:
5092 case spv::OpGroupNonUniformUMax:
5093 case spv::OpGroupNonUniformFMax: {
David Neto22f144c2017-06-12 14:26:21 -04005094 WriteWordCountAndOpcode(Inst);
5095 WriteOperand(Ops[0]);
5096 WriteResultID(Inst);
5097 for (uint32_t i = 1; i < Ops.size(); i++) {
5098 WriteOperand(Ops[i]);
5099 }
5100 break;
5101 }
5102 }
5103 }
5104}
Alan Baker9bf93fb2018-08-28 16:59:26 -04005105
alan-bakerb6b09dc2018-11-08 16:59:28 -05005106bool SPIRVProducerPass::IsTypeNullable(const Type *type) const {
Alan Baker9bf93fb2018-08-28 16:59:26 -04005107 switch (type->getTypeID()) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05005108 case Type::HalfTyID:
5109 case Type::FloatTyID:
5110 case Type::DoubleTyID:
5111 case Type::IntegerTyID:
James Price59a1c752020-04-23 23:06:16 -04005112 case Type::FixedVectorTyID:
alan-bakerb6b09dc2018-11-08 16:59:28 -05005113 return true;
5114 case Type::PointerTyID: {
5115 const PointerType *pointer_type = cast<PointerType>(type);
5116 if (pointer_type->getPointerAddressSpace() !=
5117 AddressSpace::UniformConstant) {
5118 auto pointee_type = pointer_type->getPointerElementType();
5119 if (pointee_type->isStructTy() &&
5120 cast<StructType>(pointee_type)->isOpaque()) {
5121 // Images and samplers are not nullable.
5122 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04005123 }
Alan Baker9bf93fb2018-08-28 16:59:26 -04005124 }
alan-bakerb6b09dc2018-11-08 16:59:28 -05005125 return true;
5126 }
5127 case Type::ArrayTyID:
alan-baker8eb435a2020-04-08 00:42:06 -04005128 return IsTypeNullable(type->getArrayElementType());
alan-bakerb6b09dc2018-11-08 16:59:28 -05005129 case Type::StructTyID: {
5130 const StructType *struct_type = cast<StructType>(type);
5131 // Images and samplers are not nullable.
5132 if (struct_type->isOpaque())
Alan Baker9bf93fb2018-08-28 16:59:26 -04005133 return false;
alan-bakerb6b09dc2018-11-08 16:59:28 -05005134 for (const auto element : struct_type->elements()) {
5135 if (!IsTypeNullable(element))
5136 return false;
5137 }
5138 return true;
5139 }
5140 default:
5141 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04005142 }
5143}
Alan Bakerfcda9482018-10-02 17:09:59 -04005144
SJW77b87ad2020-04-21 14:37:52 -05005145void SPIRVProducerPass::PopulateUBOTypeMaps() {
Alan Bakerfcda9482018-10-02 17:09:59 -04005146 if (auto *offsets_md =
SJW77b87ad2020-04-21 14:37:52 -05005147 module->getNamedMetadata(clspv::RemappedTypeOffsetMetadataName())) {
Alan Bakerfcda9482018-10-02 17:09:59 -04005148 // Metdata is stored as key-value pair operands. The first element of each
5149 // operand is the type and the second is a vector of offsets.
5150 for (const auto *operand : offsets_md->operands()) {
5151 const auto *pair = cast<MDTuple>(operand);
5152 auto *type =
5153 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
5154 const auto *offset_vector = cast<MDTuple>(pair->getOperand(1));
5155 std::vector<uint32_t> offsets;
5156 for (const Metadata *offset_md : offset_vector->operands()) {
5157 const auto *constant_md = cast<ConstantAsMetadata>(offset_md);
alan-bakerb6b09dc2018-11-08 16:59:28 -05005158 offsets.push_back(static_cast<uint32_t>(
5159 cast<ConstantInt>(constant_md->getValue())->getZExtValue()));
Alan Bakerfcda9482018-10-02 17:09:59 -04005160 }
5161 RemappedUBOTypeOffsets.insert(std::make_pair(type, offsets));
5162 }
5163 }
5164
5165 if (auto *sizes_md =
SJW77b87ad2020-04-21 14:37:52 -05005166 module->getNamedMetadata(clspv::RemappedTypeSizesMetadataName())) {
Alan Bakerfcda9482018-10-02 17:09:59 -04005167 // Metadata is stored as key-value pair operands. The first element of each
5168 // operand is the type and the second is a triple of sizes: type size in
5169 // bits, store size and alloc size.
5170 for (const auto *operand : sizes_md->operands()) {
5171 const auto *pair = cast<MDTuple>(operand);
5172 auto *type =
5173 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
5174 const auto *size_triple = cast<MDTuple>(pair->getOperand(1));
5175 uint64_t type_size_in_bits =
5176 cast<ConstantInt>(
5177 cast<ConstantAsMetadata>(size_triple->getOperand(0))->getValue())
5178 ->getZExtValue();
5179 uint64_t type_store_size =
5180 cast<ConstantInt>(
5181 cast<ConstantAsMetadata>(size_triple->getOperand(1))->getValue())
5182 ->getZExtValue();
5183 uint64_t type_alloc_size =
5184 cast<ConstantInt>(
5185 cast<ConstantAsMetadata>(size_triple->getOperand(2))->getValue())
5186 ->getZExtValue();
5187 RemappedUBOTypeSizes.insert(std::make_pair(
5188 type, std::make_tuple(type_size_in_bits, type_store_size,
5189 type_alloc_size)));
5190 }
5191 }
5192}
5193
5194uint64_t SPIRVProducerPass::GetTypeSizeInBits(Type *type,
5195 const DataLayout &DL) {
5196 auto iter = RemappedUBOTypeSizes.find(type);
5197 if (iter != RemappedUBOTypeSizes.end()) {
5198 return std::get<0>(iter->second);
5199 }
5200
5201 return DL.getTypeSizeInBits(type);
5202}
5203
5204uint64_t SPIRVProducerPass::GetTypeStoreSize(Type *type, const DataLayout &DL) {
5205 auto iter = RemappedUBOTypeSizes.find(type);
5206 if (iter != RemappedUBOTypeSizes.end()) {
5207 return std::get<1>(iter->second);
5208 }
5209
5210 return DL.getTypeStoreSize(type);
5211}
5212
5213uint64_t SPIRVProducerPass::GetTypeAllocSize(Type *type, const DataLayout &DL) {
5214 auto iter = RemappedUBOTypeSizes.find(type);
5215 if (iter != RemappedUBOTypeSizes.end()) {
5216 return std::get<2>(iter->second);
5217 }
5218
5219 return DL.getTypeAllocSize(type);
5220}
alan-baker5b86ed72019-02-15 08:26:50 -05005221
Kévin Petitbbbda972020-03-03 19:16:31 +00005222uint32_t SPIRVProducerPass::GetExplicitLayoutStructMemberOffset(
5223 StructType *type, unsigned member, const DataLayout &DL) {
5224 const auto StructLayout = DL.getStructLayout(type);
5225 // Search for the correct offsets if this type was remapped.
5226 std::vector<uint32_t> *offsets = nullptr;
5227 auto iter = RemappedUBOTypeOffsets.find(type);
5228 if (iter != RemappedUBOTypeOffsets.end()) {
5229 offsets = &iter->second;
5230 }
5231 auto ByteOffset =
5232 static_cast<uint32_t>(StructLayout->getElementOffset(member));
5233 if (offsets) {
5234 ByteOffset = (*offsets)[member];
5235 }
5236
5237 return ByteOffset;
5238}
5239
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04005240void SPIRVProducerPass::setVariablePointersCapabilities(
5241 unsigned address_space) {
alan-baker5b86ed72019-02-15 08:26:50 -05005242 if (GetStorageClass(address_space) == spv::StorageClassStorageBuffer) {
SJW01901d92020-05-21 08:58:31 -05005243 setVariablePointersStorageBuffer();
alan-baker5b86ed72019-02-15 08:26:50 -05005244 } else {
SJW01901d92020-05-21 08:58:31 -05005245 setVariablePointers();
alan-baker5b86ed72019-02-15 08:26:50 -05005246 }
5247}
5248
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04005249Value *SPIRVProducerPass::GetBasePointer(Value *v) {
alan-baker5b86ed72019-02-15 08:26:50 -05005250 if (auto *gep = dyn_cast<GetElementPtrInst>(v)) {
5251 return GetBasePointer(gep->getPointerOperand());
5252 }
5253
5254 // Conservatively return |v|.
5255 return v;
5256}
5257
5258bool SPIRVProducerPass::sameResource(Value *lhs, Value *rhs) const {
5259 if (auto *lhs_call = dyn_cast<CallInst>(lhs)) {
5260 if (auto *rhs_call = dyn_cast<CallInst>(rhs)) {
SJW61531372020-06-09 07:31:08 -05005261 auto lhs_func_info = Builtins::Lookup(lhs_call->getCalledFunction());
5262 auto rhs_func_info = Builtins::Lookup(rhs_call->getCalledFunction());
5263 if (lhs_func_info.getType() == Builtins::kClspvResource &&
5264 rhs_func_info.getType() == Builtins::kClspvResource) {
alan-baker5b86ed72019-02-15 08:26:50 -05005265 // For resource accessors, match descriptor set and binding.
5266 if (lhs_call->getOperand(0) == rhs_call->getOperand(0) &&
5267 lhs_call->getOperand(1) == rhs_call->getOperand(1))
5268 return true;
SJW61531372020-06-09 07:31:08 -05005269 } else if (lhs_func_info.getType() == Builtins::kClspvLocal &&
5270 rhs_func_info.getType() == Builtins::kClspvLocal) {
alan-baker5b86ed72019-02-15 08:26:50 -05005271 // For workgroup resources, match spec id.
5272 if (lhs_call->getOperand(0) == rhs_call->getOperand(0))
5273 return true;
5274 }
5275 }
5276 }
5277
5278 return false;
5279}
5280
5281bool SPIRVProducerPass::selectFromSameObject(Instruction *inst) {
5282 assert(inst->getType()->isPointerTy());
5283 assert(GetStorageClass(inst->getType()->getPointerAddressSpace()) ==
5284 spv::StorageClassStorageBuffer);
5285 const bool hack_undef = clspv::Option::HackUndef();
5286 if (auto *select = dyn_cast<SelectInst>(inst)) {
5287 auto *true_base = GetBasePointer(select->getTrueValue());
5288 auto *false_base = GetBasePointer(select->getFalseValue());
5289
5290 if (true_base == false_base)
5291 return true;
5292
5293 // If either the true or false operand is a null, then we satisfy the same
5294 // object constraint.
5295 if (auto *true_cst = dyn_cast<Constant>(true_base)) {
5296 if (true_cst->isNullValue() || (hack_undef && isa<UndefValue>(true_base)))
5297 return true;
5298 }
5299
5300 if (auto *false_cst = dyn_cast<Constant>(false_base)) {
5301 if (false_cst->isNullValue() ||
5302 (hack_undef && isa<UndefValue>(false_base)))
5303 return true;
5304 }
5305
5306 if (sameResource(true_base, false_base))
5307 return true;
5308 } else if (auto *phi = dyn_cast<PHINode>(inst)) {
5309 Value *value = nullptr;
5310 bool ok = true;
5311 for (unsigned i = 0; ok && i != phi->getNumIncomingValues(); ++i) {
5312 auto *base = GetBasePointer(phi->getIncomingValue(i));
5313 // Null values satisfy the constraint of selecting of selecting from the
5314 // same object.
5315 if (!value) {
5316 if (auto *cst = dyn_cast<Constant>(base)) {
5317 if (!cst->isNullValue() && !(hack_undef && isa<UndefValue>(base)))
5318 value = base;
5319 } else {
5320 value = base;
5321 }
5322 } else if (base != value) {
5323 if (auto *base_cst = dyn_cast<Constant>(base)) {
5324 if (base_cst->isNullValue() || (hack_undef && isa<UndefValue>(base)))
5325 continue;
5326 }
5327
5328 if (sameResource(value, base))
5329 continue;
5330
5331 // Values don't represent the same base.
5332 ok = false;
5333 }
5334 }
5335
5336 return ok;
5337 }
5338
5339 // Conservatively return false.
5340 return false;
5341}
alan-bakere9308012019-03-15 10:25:13 -04005342
5343bool SPIRVProducerPass::CalledWithCoherentResource(Argument &Arg) {
5344 if (!Arg.getType()->isPointerTy() ||
5345 Arg.getType()->getPointerAddressSpace() != clspv::AddressSpace::Global) {
5346 // Only SSBOs need to be annotated as coherent.
5347 return false;
5348 }
5349
5350 DenseSet<Value *> visited;
5351 std::vector<Value *> stack;
5352 for (auto *U : Arg.getParent()->users()) {
5353 if (auto *call = dyn_cast<CallInst>(U)) {
5354 stack.push_back(call->getOperand(Arg.getArgNo()));
5355 }
5356 }
5357
5358 while (!stack.empty()) {
5359 Value *v = stack.back();
5360 stack.pop_back();
5361
5362 if (!visited.insert(v).second)
5363 continue;
5364
5365 auto *resource_call = dyn_cast<CallInst>(v);
5366 if (resource_call &&
SJW61531372020-06-09 07:31:08 -05005367 Builtins::Lookup(resource_call->getCalledFunction()).getType() ==
5368 Builtins::kClspvResource) {
alan-bakere9308012019-03-15 10:25:13 -04005369 // If this is a resource accessor function, check if the coherent operand
5370 // is set.
5371 const auto coherent =
5372 unsigned(dyn_cast<ConstantInt>(resource_call->getArgOperand(5))
5373 ->getZExtValue());
5374 if (coherent == 1)
5375 return true;
5376 } else if (auto *arg = dyn_cast<Argument>(v)) {
5377 // If this is a function argument, trace through its callers.
alan-bakere98f3f92019-04-08 15:06:36 -04005378 for (auto U : arg->getParent()->users()) {
alan-bakere9308012019-03-15 10:25:13 -04005379 if (auto *call = dyn_cast<CallInst>(U)) {
5380 stack.push_back(call->getOperand(arg->getArgNo()));
5381 }
5382 }
5383 } else if (auto *user = dyn_cast<User>(v)) {
5384 // If this is a user, traverse all operands that could lead to resource
5385 // variables.
5386 for (unsigned i = 0; i != user->getNumOperands(); ++i) {
5387 Value *operand = user->getOperand(i);
5388 if (operand->getType()->isPointerTy() &&
5389 operand->getType()->getPointerAddressSpace() ==
5390 clspv::AddressSpace::Global) {
5391 stack.push_back(operand);
5392 }
5393 }
5394 }
5395 }
5396
5397 // No coherent resource variables encountered.
5398 return false;
5399}
alan-baker06cad652019-12-03 17:56:47 -05005400
SJW77b87ad2020-04-21 14:37:52 -05005401void SPIRVProducerPass::PopulateStructuredCFGMaps() {
alan-baker06cad652019-12-03 17:56:47 -05005402 // First, track loop merges and continues.
5403 DenseSet<BasicBlock *> LoopMergesAndContinues;
SJW77b87ad2020-04-21 14:37:52 -05005404 for (auto &F : *module) {
alan-baker06cad652019-12-03 17:56:47 -05005405 if (F.isDeclaration())
5406 continue;
5407
5408 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
5409 const LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>(F).getLoopInfo();
5410 std::deque<BasicBlock *> order;
5411 DenseSet<BasicBlock *> visited;
5412 clspv::ComputeStructuredOrder(&*F.begin(), &DT, LI, &order, &visited);
5413
5414 for (auto BB : order) {
5415 auto terminator = BB->getTerminator();
5416 auto branch = dyn_cast<BranchInst>(terminator);
5417 if (LI.isLoopHeader(BB)) {
5418 auto L = LI.getLoopFor(BB);
5419 BasicBlock *ContinueBB = nullptr;
5420 BasicBlock *MergeBB = nullptr;
5421
5422 MergeBB = L->getExitBlock();
5423 if (!MergeBB) {
5424 // StructurizeCFG pass converts CFG into triangle shape and the cfg
5425 // has regions with single entry/exit. As a result, loop should not
5426 // have multiple exits.
5427 llvm_unreachable("Loop has multiple exits???");
5428 }
5429
5430 if (L->isLoopLatch(BB)) {
5431 ContinueBB = BB;
5432 } else {
5433 // From SPIR-V spec 2.11, Continue Target must dominate that back-edge
5434 // block.
5435 BasicBlock *Header = L->getHeader();
5436 BasicBlock *Latch = L->getLoopLatch();
5437 for (auto *loop_block : L->blocks()) {
5438 if (loop_block == Header) {
5439 continue;
5440 }
5441
5442 // Check whether block dominates block with back-edge.
5443 // The loop latch is the single block with a back-edge. If it was
5444 // possible, StructurizeCFG made the loop conform to this
5445 // requirement, otherwise |Latch| is a nullptr.
5446 if (DT.dominates(loop_block, Latch)) {
5447 ContinueBB = loop_block;
5448 }
5449 }
5450
5451 if (!ContinueBB) {
5452 llvm_unreachable("Wrong continue block from loop");
5453 }
5454 }
5455
5456 // Record the continue and merge blocks.
5457 MergeBlocks[BB] = MergeBB;
5458 ContinueBlocks[BB] = ContinueBB;
5459 LoopMergesAndContinues.insert(MergeBB);
5460 LoopMergesAndContinues.insert(ContinueBB);
5461 } else if (branch && branch->isConditional()) {
5462 auto L = LI.getLoopFor(BB);
5463 bool HasBackedge = false;
5464 while (L && !HasBackedge) {
5465 if (L->isLoopLatch(BB)) {
5466 HasBackedge = true;
5467 }
5468 L = L->getParentLoop();
5469 }
5470
5471 if (!HasBackedge) {
5472 // Only need a merge if the branch doesn't include a loop break or
5473 // continue.
5474 auto true_bb = branch->getSuccessor(0);
5475 auto false_bb = branch->getSuccessor(1);
5476 if (!LoopMergesAndContinues.count(true_bb) &&
5477 !LoopMergesAndContinues.count(false_bb)) {
5478 // StructurizeCFG pass already manipulated CFG. Just use false block
5479 // of branch instruction as merge block.
5480 MergeBlocks[BB] = false_bb;
5481 }
5482 }
5483 }
5484 }
5485 }
5486}
alan-baker86ce19c2020-08-05 13:09:19 -04005487
5488SPIRVID SPIRVProducerPass::getReflectionImport() {
5489 if (!ReflectionID.isValid()) {
5490 addSPIRVInst<kExtensions>(spv::OpExtension, "SPV_KHR_non_semantic_info");
5491 ReflectionID = addSPIRVInst<kImports>(spv::OpExtInstImport,
5492 "NonSemantic.ClspvReflection.1");
5493 }
5494 return ReflectionID;
5495}
5496
5497void SPIRVProducerPass::GenerateReflection() {
5498 GenerateKernelReflection();
5499 GeneratePushConstantReflection();
5500 GenerateSpecConstantReflection();
5501}
5502
5503void SPIRVProducerPass::GeneratePushConstantReflection() {
5504 if (auto GV = module->getGlobalVariable(clspv::PushConstantsVariableName())) {
5505 auto const &DL = module->getDataLayout();
5506 auto MD = GV->getMetadata(clspv::PushConstantsMetadataName());
5507 auto STy = cast<StructType>(GV->getValueType());
5508
5509 for (unsigned i = 0; i < STy->getNumElements(); i++) {
5510 auto pc = static_cast<clspv::PushConstant>(
5511 mdconst::extract<ConstantInt>(MD->getOperand(i))->getZExtValue());
5512 if (pc == PushConstant::KernelArgument)
5513 continue;
5514
5515 auto memberType = STy->getElementType(i);
5516 auto offset = GetExplicitLayoutStructMemberOffset(STy, i, DL);
5517 unsigned previousOffset = 0;
5518 if (i > 0) {
5519 previousOffset = GetExplicitLayoutStructMemberOffset(STy, i - 1, DL);
5520 }
5521 auto size = static_cast<uint32_t>(GetTypeSizeInBits(memberType, DL)) / 8;
5522 assert(isValidExplicitLayout(*module, STy, i,
5523 spv::StorageClassPushConstant, offset,
5524 previousOffset));
5525
5526 reflection::ExtInst pc_inst = reflection::ExtInstMax;
5527 switch (pc) {
5528 case PushConstant::GlobalOffset:
5529 pc_inst = reflection::ExtInstPushConstantGlobalOffset;
5530 break;
5531 case PushConstant::EnqueuedLocalSize:
5532 pc_inst = reflection::ExtInstPushConstantEnqueuedLocalSize;
5533 break;
5534 case PushConstant::GlobalSize:
5535 pc_inst = reflection::ExtInstPushConstantGlobalSize;
5536 break;
5537 case PushConstant::RegionOffset:
5538 pc_inst = reflection::ExtInstPushConstantRegionOffset;
5539 break;
5540 case PushConstant::NumWorkgroups:
5541 pc_inst = reflection::ExtInstPushConstantNumWorkgroups;
5542 break;
5543 case PushConstant::RegionGroupOffset:
5544 pc_inst = reflection::ExtInstPushConstantRegionGroupOffset;
5545 break;
5546 default:
5547 llvm_unreachable("Unhandled push constant");
5548 break;
5549 }
5550
5551 auto import_id = getReflectionImport();
5552 SPIRVOperandVec Ops;
5553 Ops << getSPIRVType(Type::getVoidTy(module->getContext())) << import_id
5554 << pc_inst << getSPIRVInt32Constant(offset)
5555 << getSPIRVInt32Constant(size);
5556 addSPIRVInst(spv::OpExtInst, Ops);
5557 }
5558 }
5559}
5560
5561void SPIRVProducerPass::GenerateSpecConstantReflection() {
5562 const uint32_t kMax = std::numeric_limits<uint32_t>::max();
5563 uint32_t wgsize_id[3] = {kMax, kMax, kMax};
5564 uint32_t global_offset_id[3] = {kMax, kMax, kMax};
5565 uint32_t work_dim_id = kMax;
5566 for (auto pair : clspv::GetSpecConstants(module)) {
5567 auto kind = pair.first;
5568 auto id = pair.second;
5569
5570 // Local memory size is only used for kernel arguments.
5571 if (kind == SpecConstant::kLocalMemorySize)
5572 continue;
5573
5574 switch (kind) {
5575 case SpecConstant::kWorkgroupSizeX:
5576 wgsize_id[0] = id;
5577 break;
5578 case SpecConstant::kWorkgroupSizeY:
5579 wgsize_id[1] = id;
5580 break;
5581 case SpecConstant::kWorkgroupSizeZ:
5582 wgsize_id[2] = id;
5583 break;
5584 case SpecConstant::kGlobalOffsetX:
5585 global_offset_id[0] = id;
5586 break;
5587 case SpecConstant::kGlobalOffsetY:
5588 global_offset_id[1] = id;
5589 break;
5590 case SpecConstant::kGlobalOffsetZ:
5591 global_offset_id[2] = id;
5592 break;
5593 case SpecConstant::kWorkDim:
5594 work_dim_id = id;
5595 break;
5596 default:
5597 llvm_unreachable("Unhandled spec constant");
5598 }
5599 }
5600
5601 auto import_id = getReflectionImport();
5602 auto void_id = getSPIRVType(Type::getVoidTy(module->getContext()));
5603 SPIRVOperandVec Ops;
5604 if (wgsize_id[0] != kMax) {
5605 assert(wgsize_id[1] != kMax);
5606 assert(wgsize_id[2] != kMax);
5607 Ops.clear();
5608 Ops << void_id << import_id << reflection::ExtInstSpecConstantWorkgroupSize
5609 << getSPIRVInt32Constant(wgsize_id[0])
5610 << getSPIRVInt32Constant(wgsize_id[1])
5611 << getSPIRVInt32Constant(wgsize_id[2]);
5612 addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
5613 }
5614 if (global_offset_id[0] != kMax) {
5615 assert(global_offset_id[1] != kMax);
5616 assert(global_offset_id[2] != kMax);
5617 Ops.clear();
5618 Ops << void_id << import_id << reflection::ExtInstSpecConstantGlobalOffset
5619 << getSPIRVInt32Constant(global_offset_id[0])
5620 << getSPIRVInt32Constant(global_offset_id[1])
5621 << getSPIRVInt32Constant(global_offset_id[2]);
5622 addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
5623 }
5624 if (work_dim_id != kMax) {
5625 Ops.clear();
5626 Ops << void_id << import_id << reflection::ExtInstSpecConstantWorkDim
5627 << getSPIRVInt32Constant(work_dim_id);
5628 addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
5629 }
5630}
5631
5632void SPIRVProducerPass::GenerateKernelReflection() {
5633 const auto &DL = module->getDataLayout();
5634 auto import_id = getReflectionImport();
5635 auto void_id = getSPIRVType(Type::getVoidTy(module->getContext()));
5636
5637 for (auto &F : *module) {
5638 if (F.isDeclaration() || F.getCallingConv() != CallingConv::SPIR_KERNEL) {
5639 continue;
5640 }
5641
5642 // OpString for the kernel name.
5643 auto kernel_name =
5644 addSPIRVInst<kDebug>(spv::OpString, F.getName().str().c_str());
5645
5646 // Kernel declaration
5647 // Ops[0] = void type
5648 // Ops[1] = reflection ext import
5649 // Ops[2] = function id
5650 // Ops[3] = kernel name
5651 SPIRVOperandVec Ops;
5652 Ops << void_id << import_id << reflection::ExtInstKernel << ValueMap[&F]
5653 << kernel_name;
5654 auto kernel_decl = addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
5655
5656 // Generate the required workgroup size property if it was specified.
5657 if (const MDNode *MD = F.getMetadata("reqd_work_group_size")) {
5658 uint32_t CurXDimCst = static_cast<uint32_t>(
5659 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
5660 uint32_t CurYDimCst = static_cast<uint32_t>(
5661 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
5662 uint32_t CurZDimCst = static_cast<uint32_t>(
5663 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
5664
5665 Ops.clear();
5666 Ops << void_id << import_id
5667 << reflection::ExtInstPropertyRequiredWorkgroupSize << kernel_decl
5668 << getSPIRVInt32Constant(CurXDimCst)
5669 << getSPIRVInt32Constant(CurYDimCst)
5670 << getSPIRVInt32Constant(CurZDimCst);
5671 addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
5672 }
5673
5674 auto &resource_var_at_index = FunctionToResourceVarsMap[&F];
5675 auto *func_ty = F.getFunctionType();
5676
5677 // If we've clustered POD arguments, then argument details are in metadata.
5678 // If an argument maps to a resource variable, then get descriptor set and
5679 // binding from the resource variable. Other info comes from the metadata.
5680 const auto *arg_map = F.getMetadata(clspv::KernelArgMapMetadataName());
5681 auto local_spec_id_md =
5682 module->getNamedMetadata(clspv::LocalSpecIdMetadataName());
5683 if (arg_map) {
5684 for (const auto &arg : arg_map->operands()) {
5685 const MDNode *arg_node = dyn_cast<MDNode>(arg.get());
5686 assert(arg_node->getNumOperands() == 6);
5687 const auto name =
5688 dyn_cast<MDString>(arg_node->getOperand(0))->getString();
5689 const auto old_index =
5690 dyn_extract<ConstantInt>(arg_node->getOperand(1))->getZExtValue();
5691 // Remapped argument index
5692 const int new_index = static_cast<int>(
5693 dyn_extract<ConstantInt>(arg_node->getOperand(2))->getSExtValue());
5694 const auto offset =
5695 dyn_extract<ConstantInt>(arg_node->getOperand(3))->getZExtValue();
5696 const auto size =
5697 dyn_extract<ConstantInt>(arg_node->getOperand(4))->getZExtValue();
5698 const auto argKind = clspv::GetArgKindFromName(
5699 dyn_cast<MDString>(arg_node->getOperand(5))->getString().str());
5700
5701 // If this is a local memory argument, find the right spec id for this
5702 // argument.
5703 int64_t spec_id = -1;
5704 if (argKind == clspv::ArgKind::Local) {
5705 for (auto spec_id_arg : local_spec_id_md->operands()) {
5706 if ((&F == dyn_cast<Function>(
5707 dyn_cast<ValueAsMetadata>(spec_id_arg->getOperand(0))
5708 ->getValue())) &&
5709 (static_cast<uint64_t>(new_index) ==
5710 mdconst::extract<ConstantInt>(spec_id_arg->getOperand(1))
5711 ->getZExtValue())) {
5712 spec_id =
5713 mdconst::extract<ConstantInt>(spec_id_arg->getOperand(2))
5714 ->getSExtValue();
5715 break;
5716 }
5717 }
5718 }
5719
5720 // Generate the specific argument instruction.
5721 const uint32_t ordinal = static_cast<uint32_t>(old_index);
5722 const uint32_t arg_offset = static_cast<uint32_t>(offset);
5723 const uint32_t arg_size = static_cast<uint32_t>(size);
5724 uint32_t elem_size = 0;
5725 uint32_t descriptor_set = 0;
5726 uint32_t binding = 0;
5727 if (spec_id > 0) {
5728 elem_size = static_cast<uint32_t>(
5729 GetTypeAllocSize(func_ty->getParamType(unsigned(new_index))
5730 ->getPointerElementType(),
5731 DL));
5732 } else if (new_index >= 0) {
5733 auto *info = resource_var_at_index[new_index];
5734 assert(info);
5735 descriptor_set = info->descriptor_set;
5736 binding = info->binding;
5737 }
5738 AddArgumentReflection(kernel_decl, name.str(), argKind, ordinal,
5739 descriptor_set, binding, arg_offset, arg_size,
5740 static_cast<uint32_t>(spec_id), elem_size);
5741 }
5742 } else {
5743 // There is no argument map.
5744 // Take descriptor info from the resource variable calls.
5745 // Take argument name and size from the arguments list.
5746
5747 SmallVector<Argument *, 4> arguments;
5748 for (auto &arg : F.args()) {
5749 arguments.push_back(&arg);
5750 }
5751
5752 unsigned arg_index = 0;
5753 for (auto *info : resource_var_at_index) {
5754 if (info) {
5755 auto arg = arguments[arg_index];
5756 unsigned arg_size = 0;
5757 if (info->arg_kind == clspv::ArgKind::Pod ||
5758 info->arg_kind == clspv::ArgKind::PodUBO ||
5759 info->arg_kind == clspv::ArgKind::PodPushConstant) {
5760 arg_size =
5761 static_cast<uint32_t>(DL.getTypeStoreSize(arg->getType()));
5762 }
5763
5764 // Local pointer arguments are unused in this case.
5765 // offset, spec_id and elem_size always 0.
5766 AddArgumentReflection(kernel_decl, arg->getName().str(),
5767 info->arg_kind, arg_index, info->descriptor_set,
5768 info->binding, 0, arg_size, 0, 0);
5769 }
5770 arg_index++;
5771 }
5772 // Generate mappings for pointer-to-local arguments.
5773 for (arg_index = 0; arg_index < arguments.size(); ++arg_index) {
5774 Argument *arg = arguments[arg_index];
5775 auto where = LocalArgSpecIds.find(arg);
5776 if (where != LocalArgSpecIds.end()) {
5777 auto &local_arg_info = LocalSpecIdInfoMap[where->second];
5778
5779 // descriptor_set, binding, offset and size are always 0.
5780 AddArgumentReflection(kernel_decl, arg->getName().str(),
5781 ArgKind::Local, arg_index, 0, 0, 0, 0,
5782 static_cast<uint32_t>(local_arg_info.spec_id),
5783 static_cast<uint32_t>(GetTypeAllocSize(
5784 local_arg_info.elem_type, DL)));
5785 }
5786 }
5787 }
5788 }
5789}
5790
5791void SPIRVProducerPass::AddArgumentReflection(
5792 SPIRVID kernel_decl, const std::string &name, clspv::ArgKind arg_kind,
5793 uint32_t ordinal, uint32_t descriptor_set, uint32_t binding,
5794 uint32_t offset, uint32_t size, uint32_t spec_id, uint32_t elem_size) {
5795 // Generate ArgumentInfo for this argument.
5796 // TODO: generate remaining optional operands.
5797 auto import_id = getReflectionImport();
5798 auto arg_name = addSPIRVInst<kDebug>(spv::OpString, name.c_str());
5799 auto void_id = getSPIRVType(Type::getVoidTy(module->getContext()));
5800 SPIRVOperandVec Ops;
5801 Ops << void_id << import_id << reflection::ExtInstArgumentInfo << arg_name;
5802 auto arg_info = addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
5803
5804 Ops.clear();
5805 Ops << void_id << import_id;
5806 reflection::ExtInst ext_inst = reflection::ExtInstMax;
5807 // Determine the extended instruction.
5808 switch (arg_kind) {
5809 case clspv::ArgKind::Buffer:
5810 ext_inst = reflection::ExtInstArgumentStorageBuffer;
5811 break;
5812 case clspv::ArgKind::BufferUBO:
5813 ext_inst = reflection::ExtInstArgumentUniform;
5814 break;
5815 case clspv::ArgKind::Local:
5816 ext_inst = reflection::ExtInstArgumentWorkgroup;
5817 break;
5818 case clspv::ArgKind::Pod:
5819 ext_inst = reflection::ExtInstArgumentPodStorageBuffer;
5820 break;
5821 case clspv::ArgKind::PodUBO:
5822 ext_inst = reflection::ExtInstArgumentPodUniform;
5823 break;
5824 case clspv::ArgKind::PodPushConstant:
5825 ext_inst = reflection::ExtInstArgumentPodPushConstant;
5826 break;
5827 case clspv::ArgKind::ReadOnlyImage:
5828 ext_inst = reflection::ExtInstArgumentSampledImage;
5829 break;
5830 case clspv::ArgKind::WriteOnlyImage:
5831 ext_inst = reflection::ExtInstArgumentStorageImage;
5832 break;
5833 case clspv::ArgKind::Sampler:
5834 ext_inst = reflection::ExtInstArgumentSampler;
5835 break;
5836 default:
5837 llvm_unreachable("Unhandled argument reflection");
5838 break;
5839 }
5840 Ops << ext_inst << kernel_decl << getSPIRVInt32Constant(ordinal);
5841
5842 // Add descriptor set and binding for applicable arguments.
5843 switch (arg_kind) {
5844 case clspv::ArgKind::Buffer:
5845 case clspv::ArgKind::BufferUBO:
5846 case clspv::ArgKind::Pod:
5847 case clspv::ArgKind::PodUBO:
5848 case clspv::ArgKind::ReadOnlyImage:
5849 case clspv::ArgKind::WriteOnlyImage:
5850 case clspv::ArgKind::Sampler:
5851 Ops << getSPIRVInt32Constant(descriptor_set)
5852 << getSPIRVInt32Constant(binding);
5853 break;
5854 default:
5855 break;
5856 }
5857
5858 // Add remaining operands for arguments.
5859 switch (arg_kind) {
5860 case clspv::ArgKind::Local:
5861 Ops << getSPIRVInt32Constant(spec_id) << getSPIRVInt32Constant(elem_size);
5862 break;
5863 case clspv::ArgKind::Pod:
5864 case clspv::ArgKind::PodUBO:
5865 case clspv::ArgKind::PodPushConstant:
5866 Ops << getSPIRVInt32Constant(offset) << getSPIRVInt32Constant(size);
5867 break;
5868 default:
5869 break;
5870 }
5871 Ops << arg_info;
5872 addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
5873}