blob: ae93892380992edc9ea4e7eab8daef5ee35326b3 [file] [log] [blame]
David Neto22f144c2017-06-12 14:26:21 -04001// Copyright 2017 The Clspv Authors. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#ifdef _MSC_VER
16#pragma warning(push, 0)
17#endif
18
David Neto156783e2017-07-05 15:39:41 -040019#include <cassert>
David Neto257c3892018-04-11 13:19:45 -040020#include <cstring>
David Neto118188e2018-08-24 11:27:54 -040021#include <iomanip>
22#include <list>
David Neto862b7d82018-06-14 18:48:37 -040023#include <memory>
David Neto118188e2018-08-24 11:27:54 -040024#include <set>
25#include <sstream>
26#include <string>
27#include <tuple>
28#include <unordered_set>
29#include <utility>
David Neto862b7d82018-06-14 18:48:37 -040030
David Neto118188e2018-08-24 11:27:54 -040031#include "llvm/ADT/StringSwitch.h"
32#include "llvm/ADT/UniqueVector.h"
33#include "llvm/Analysis/LoopInfo.h"
34#include "llvm/IR/Constants.h"
35#include "llvm/IR/Dominators.h"
36#include "llvm/IR/Instructions.h"
alan-baker5f2e88e2020-12-07 15:24:04 -050037#include "llvm/IR/Intrinsics.h"
David Neto118188e2018-08-24 11:27:54 -040038#include "llvm/IR/Metadata.h"
39#include "llvm/IR/Module.h"
alan-bakerf67468c2019-11-25 15:51:49 -050040#include "llvm/IR/ValueSymbolTable.h"
David Neto118188e2018-08-24 11:27:54 -040041#include "llvm/Pass.h"
42#include "llvm/Support/CommandLine.h"
Kévin Petitbbbda972020-03-03 19:16:31 +000043#include "llvm/Support/MathExtras.h"
David Neto118188e2018-08-24 11:27:54 -040044#include "llvm/Support/raw_ostream.h"
45#include "llvm/Transforms/Utils/Cloning.h"
David Neto22f144c2017-06-12 14:26:21 -040046
SJWf93f5f32020-05-05 07:27:56 -050047// enable spv::HasResultAndType
48#define SPV_ENABLE_UTILITY_CODE
alan-bakere0902602020-03-23 08:43:40 -040049#include "spirv/unified1/spirv.hpp"
David Neto118188e2018-08-24 11:27:54 -040050
David Neto85082642018-03-24 06:55:20 -070051#include "clspv/AddressSpace.h"
David Neto118188e2018-08-24 11:27:54 -040052#include "clspv/Option.h"
alan-baker86ce19c2020-08-05 13:09:19 -040053#include "clspv/PushConstant.h"
54#include "clspv/SpecConstant.h"
David Neto85082642018-03-24 06:55:20 -070055#include "clspv/spirv_c_strings.hpp"
56#include "clspv/spirv_glsl.hpp"
alan-baker86ce19c2020-08-05 13:09:19 -040057#include "clspv/spirv_reflection.hpp"
David Neto22f144c2017-06-12 14:26:21 -040058
David Neto4feb7a42017-10-06 17:29:42 -040059#include "ArgKind.h"
alan-bakerf67468c2019-11-25 15:51:49 -050060#include "Builtins.h"
alan-baker06cad652019-12-03 17:56:47 -050061#include "ComputeStructuredOrder.h"
David Neto85082642018-03-24 06:55:20 -070062#include "ConstantEmitter.h"
Alan Baker202c8c72018-08-13 13:47:44 -040063#include "Constants.h"
David Neto78383442018-06-15 20:31:56 -040064#include "DescriptorCounter.h"
alan-bakerc4579bb2020-04-29 14:15:50 -040065#include "Layout.h"
alan-baker56f7aff2019-05-22 08:06:42 -040066#include "NormalizeGlobalVariable.h"
Diego Novilloa4c44fa2019-04-11 10:56:15 -040067#include "Passes.h"
alan-bakera1be3322020-04-20 12:48:18 -040068#include "SpecConstant.h"
alan-bakerce179f12019-12-06 19:02:22 -050069#include "Types.h"
David Neto48f56a42017-10-06 16:44:25 -040070
David Neto22f144c2017-06-12 14:26:21 -040071#if defined(_MSC_VER)
72#pragma warning(pop)
73#endif
74
75using namespace llvm;
76using namespace clspv;
SJW173c7e92020-03-16 08:44:47 -050077using namespace clspv::Builtins;
SJW806a5d82020-07-15 12:51:38 -050078using namespace clspv::Option;
David Neto156783e2017-07-05 15:39:41 -040079using namespace mdconst;
David Neto22f144c2017-06-12 14:26:21 -040080
81namespace {
David Netocd8ca5f2017-10-02 23:34:11 -040082
David Neto862b7d82018-06-14 18:48:37 -040083cl::opt<bool> ShowResourceVars("show-rv", cl::init(false), cl::Hidden,
84 cl::desc("Show resource variable creation"));
85
alan-baker5ed87542020-03-23 11:05:22 -040086cl::opt<bool>
87 ShowProducerIR("show-producer-ir", cl::init(false), cl::ReallyHidden,
88 cl::desc("Dump the IR at the start of SPIRVProducer"));
89
David Neto862b7d82018-06-14 18:48:37 -040090// These hacks exist to help transition code generation algorithms
91// without making huge noise in detailed test output.
92const bool Hack_generate_runtime_array_stride_early = true;
93
David Neto3fbb4072017-10-16 11:28:14 -040094// The value of 1/pi. This value is from MSDN
95// https://msdn.microsoft.com/en-us/library/4hwaceh6.aspx
96const double kOneOverPi = 0.318309886183790671538;
97const glsl::ExtInst kGlslExtInstBad = static_cast<glsl::ExtInst>(0);
98
alan-baker86ce19c2020-08-05 13:09:19 -040099// SPIRV Module Sections (per 2.4 of the SPIR-V spec)
SJW69939d52020-04-16 07:29:07 -0500100// These are used to collect SPIRVInstructions by type on-the-fly.
101enum SPIRVSection {
102 kCapabilities,
103 kExtensions,
104 kImports,
105 kMemoryModel,
106 kEntryPoints,
107 kExecutionModes,
108
109 kDebug,
110 kAnnotations,
111
112 kTypes,
113 kConstants = kTypes,
114 kGlobalVariables,
115
116 kFunctions,
117
alan-baker86ce19c2020-08-05 13:09:19 -0400118 // This is not a section of the SPIR-V spec and should always immediately
119 // precede kSectionCount. It is a convenient place for the embedded
120 // reflection data.
121 kReflection,
SJW69939d52020-04-16 07:29:07 -0500122 kSectionCount
123};
124
SJW01901d92020-05-21 08:58:31 -0500125class SPIRVID {
126 uint32_t id;
127
128public:
129 SPIRVID(uint32_t _id = 0) : id(_id) {}
130 uint32_t get() const { return id; }
131 bool isValid() const { return id != 0; }
132 bool operator==(const SPIRVID &that) const { return id == that.id; }
SJW806a5d82020-07-15 12:51:38 -0500133 bool operator<(const SPIRVID &that) const { return id < that.id; }
SJW01901d92020-05-21 08:58:31 -0500134};
SJWf93f5f32020-05-05 07:27:56 -0500135
SJW88ed5fe2020-05-11 12:40:57 -0500136enum SPIRVOperandType { NUMBERID, LITERAL_WORD, LITERAL_DWORD, LITERAL_STRING };
David Neto22f144c2017-06-12 14:26:21 -0400137
138struct SPIRVOperand {
SJW88ed5fe2020-05-11 12:40:57 -0500139 explicit SPIRVOperand(SPIRVOperandType Ty, uint32_t Num) : Type(Ty) {
140 LiteralNum[0] = Num;
141 }
David Neto22f144c2017-06-12 14:26:21 -0400142 explicit SPIRVOperand(SPIRVOperandType Ty, const char *Str)
143 : Type(Ty), LiteralStr(Str) {}
144 explicit SPIRVOperand(SPIRVOperandType Ty, StringRef Str)
145 : Type(Ty), LiteralStr(Str) {}
SJW88ed5fe2020-05-11 12:40:57 -0500146 explicit SPIRVOperand(ArrayRef<uint32_t> NumVec) {
147 auto sz = NumVec.size();
148 assert(sz >= 1 && sz <= 2);
149 Type = sz == 1 ? LITERAL_WORD : LITERAL_DWORD;
150 LiteralNum[0] = NumVec[0];
151 if (sz == 2) {
152 LiteralNum[1] = NumVec[1];
153 }
154 }
David Neto22f144c2017-06-12 14:26:21 -0400155
alan-baker7506abb2020-09-10 15:02:55 -0400156 SPIRVOperandType getType() const { return Type; }
157 uint32_t getNumID() const { return LiteralNum[0]; }
158 std::string getLiteralStr() const { return LiteralStr; }
159 const uint32_t *getLiteralNum() const { return LiteralNum; }
David Neto22f144c2017-06-12 14:26:21 -0400160
David Neto87846742018-04-11 17:36:22 -0400161 uint32_t GetNumWords() const {
162 switch (Type) {
163 case NUMBERID:
SJW88ed5fe2020-05-11 12:40:57 -0500164 case LITERAL_WORD:
David Neto87846742018-04-11 17:36:22 -0400165 return 1;
SJW88ed5fe2020-05-11 12:40:57 -0500166 case LITERAL_DWORD:
167 return 2;
David Neto87846742018-04-11 17:36:22 -0400168 case LITERAL_STRING:
169 // Account for the terminating null character.
David Netoee2660d2018-06-28 16:31:29 -0400170 return uint32_t((LiteralStr.size() + 4) / 4);
David Neto87846742018-04-11 17:36:22 -0400171 }
172 llvm_unreachable("Unhandled case in SPIRVOperand::GetNumWords()");
173 }
174
David Neto22f144c2017-06-12 14:26:21 -0400175private:
176 SPIRVOperandType Type;
177 std::string LiteralStr;
SJW88ed5fe2020-05-11 12:40:57 -0500178 uint32_t LiteralNum[2];
David Neto22f144c2017-06-12 14:26:21 -0400179};
180
SJW88ed5fe2020-05-11 12:40:57 -0500181typedef SmallVector<SPIRVOperand, 4> SPIRVOperandVec;
David Netoc6f3ab22018-04-06 18:02:31 -0400182
David Neto22f144c2017-06-12 14:26:21 -0400183struct SPIRVInstruction {
SJWf93f5f32020-05-05 07:27:56 -0500184 // Primary constructor must have Opcode, initializes WordCount based on ResID.
185 SPIRVInstruction(spv::Op Opc, SPIRVID ResID = 0)
186 : Opcode(static_cast<uint16_t>(Opc)) {
187 setResult(ResID);
David Neto87846742018-04-11 17:36:22 -0400188 }
David Neto22f144c2017-06-12 14:26:21 -0400189
SJWf93f5f32020-05-05 07:27:56 -0500190 // Creates an instruction with an opcode and no result ID, and with the given
191 // operands. This calls primary constructor to initialize Opcode, WordCount.
192 // Takes ownership of the operands and clears |Ops|.
193 SPIRVInstruction(spv::Op Opc, SPIRVOperandVec &Ops) : SPIRVInstruction(Opc) {
194 setOperands(Ops);
David Netoef5ba2b2019-12-20 08:35:54 -0500195 }
SJWf93f5f32020-05-05 07:27:56 -0500196 // Creates an instruction with an opcode and no result ID, and with the given
197 // operands. This calls primary constructor to initialize Opcode, WordCount.
198 // Takes ownership of the operands and clears |Ops|.
199 SPIRVInstruction(spv::Op Opc, SPIRVID ResID, SPIRVOperandVec &Ops)
200 : SPIRVInstruction(Opc, ResID) {
201 setOperands(Ops);
David Netoef5ba2b2019-12-20 08:35:54 -0500202 }
David Netoef5ba2b2019-12-20 08:35:54 -0500203
David Netoee2660d2018-06-28 16:31:29 -0400204 uint32_t getWordCount() const { return WordCount; }
David Neto22f144c2017-06-12 14:26:21 -0400205 uint16_t getOpcode() const { return Opcode; }
SJW88ed5fe2020-05-11 12:40:57 -0500206 SPIRVID getResultID() const { return ResultID; }
207 const SPIRVOperandVec &getOperands() const { return Operands; }
David Neto22f144c2017-06-12 14:26:21 -0400208
209private:
SJW01901d92020-05-21 08:58:31 -0500210 void setResult(SPIRVID ResID = 0) {
211 WordCount = 1 + (ResID.isValid() ? 1 : 0);
SJWf93f5f32020-05-05 07:27:56 -0500212 ResultID = ResID;
213 }
214
215 void setOperands(SPIRVOperandVec &Ops) {
216 assert(Operands.empty());
217 Operands = std::move(Ops);
218 for (auto &opd : Operands) {
SJW88ed5fe2020-05-11 12:40:57 -0500219 WordCount += uint16_t(opd.GetNumWords());
SJWf93f5f32020-05-05 07:27:56 -0500220 }
221 }
222
223private:
David Netoee2660d2018-06-28 16:31:29 -0400224 uint32_t WordCount; // Check the 16-bit bound at code generation time.
David Neto22f144c2017-06-12 14:26:21 -0400225 uint16_t Opcode;
SJW88ed5fe2020-05-11 12:40:57 -0500226 SPIRVID ResultID;
SJWf93f5f32020-05-05 07:27:56 -0500227 SPIRVOperandVec Operands;
David Neto22f144c2017-06-12 14:26:21 -0400228};
229
230struct SPIRVProducerPass final : public ModulePass {
SJW01901d92020-05-21 08:58:31 -0500231 typedef DenseMap<Type *, SPIRVID> TypeMapType;
David Neto22f144c2017-06-12 14:26:21 -0400232 typedef UniqueVector<Type *> TypeList;
SJW88ed5fe2020-05-11 12:40:57 -0500233 typedef DenseMap<Value *, SPIRVID> ValueMapType;
SJW806a5d82020-07-15 12:51:38 -0500234 typedef std::list<SPIRVID> SPIRVIDListType;
SJW01901d92020-05-21 08:58:31 -0500235 typedef std::vector<std::pair<Value *, SPIRVID>> EntryPointVecType;
236 typedef std::set<uint32_t> CapabilitySetType;
SJW88ed5fe2020-05-11 12:40:57 -0500237 typedef std::list<SPIRVInstruction> SPIRVInstructionList;
SJW806a5d82020-07-15 12:51:38 -0500238 typedef std::map<spv::BuiltIn, SPIRVID> BuiltinConstantMapType;
SJW88ed5fe2020-05-11 12:40:57 -0500239 // A vector of pairs, each of which is:
David Neto87846742018-04-11 17:36:22 -0400240 // - the LLVM instruction that we will later generate SPIR-V code for
SJW88ed5fe2020-05-11 12:40:57 -0500241 // - the SPIR-V instruction placeholder that will be replaced
242 typedef std::vector<std::pair<Value *, SPIRVInstruction *>>
David Neto22f144c2017-06-12 14:26:21 -0400243 DeferredInstVecType;
244 typedef DenseMap<FunctionType *, std::pair<FunctionType *, uint32_t>>
245 GlobalConstFuncMapType;
246
David Neto44795152017-07-13 15:45:28 -0400247 explicit SPIRVProducerPass(
alan-bakerf5e5f692018-11-27 08:33:24 -0500248 raw_pwrite_stream &out,
alan-baker00e7a582019-06-07 12:54:21 -0400249 ArrayRef<std::pair<unsigned, std::string>> samplerMap,
David Neto44795152017-07-13 15:45:28 -0400250 bool outputCInitList)
SJW01901d92020-05-21 08:58:31 -0500251 : ModulePass(ID), module(nullptr), samplerMap(samplerMap), out(out),
David Neto0676e6f2017-07-11 18:47:44 -0400252 binaryTempOut(binaryTempUnderlyingVector), binaryOut(&out),
David Neto0676e6f2017-07-11 18:47:44 -0400253 outputCInitList(outputCInitList), patchBoundOffset(0), nextID(1),
alan-baker5b86ed72019-02-15 08:26:50 -0500254 OpExtInstImportID(0), HasVariablePointersStorageBuffer(false),
255 HasVariablePointers(false), SamplerTy(nullptr), WorkgroupSizeValueID(0),
SJW01901d92020-05-21 08:58:31 -0500256 WorkgroupSizeVarID(0) {
257 addCapability(spv::CapabilityShader);
258 Ptr = this;
259 }
David Neto22f144c2017-06-12 14:26:21 -0400260
James Price11010dc2019-12-19 13:53:09 -0500261 virtual ~SPIRVProducerPass() {
James Price11010dc2019-12-19 13:53:09 -0500262 }
263
David Neto22f144c2017-06-12 14:26:21 -0400264 void getAnalysisUsage(AnalysisUsage &AU) const override {
265 AU.addRequired<DominatorTreeWrapperPass>();
266 AU.addRequired<LoopInfoWrapperPass>();
267 }
268
269 virtual bool runOnModule(Module &module) override;
270
271 // output the SPIR-V header block
272 void outputHeader();
273
274 // patch the SPIR-V header block
275 void patchHeader();
276
SJW01901d92020-05-21 08:58:31 -0500277 CapabilitySetType &getCapabilitySet() { return CapabilitySet; }
David Neto22f144c2017-06-12 14:26:21 -0400278 TypeMapType &getImageTypeMap() { return ImageTypeMap; }
alan-baker7506abb2020-09-10 15:02:55 -0400279 TypeList &getTypeList() { return Types; }
David Neto22f144c2017-06-12 14:26:21 -0400280 ValueMapType &getValueMap() { return ValueMap; }
SJW69939d52020-04-16 07:29:07 -0500281 SPIRVInstructionList &getSPIRVInstList(SPIRVSection Section) {
282 return SPIRVSections[Section];
283 };
alan-baker7506abb2020-09-10 15:02:55 -0400284 EntryPointVecType &getEntryPointVec() { return EntryPointVec; }
285 DeferredInstVecType &getDeferredInstVec() { return DeferredInstVec; }
SJW806a5d82020-07-15 12:51:38 -0500286 SPIRVIDListType &getEntryPointInterfacesList() {
287 return EntryPointInterfacesList;
alan-baker7506abb2020-09-10 15:02:55 -0400288 }
SJW01901d92020-05-21 08:58:31 -0500289 SPIRVID getOpExtInstImportID();
alan-baker7506abb2020-09-10 15:02:55 -0400290 std::vector<SPIRVID> &getBuiltinDimVec() { return BuiltinDimensionVec; }
SJW2c317da2020-03-23 07:39:13 -0500291
alan-baker5b86ed72019-02-15 08:26:50 -0500292 bool hasVariablePointersStorageBuffer() {
293 return HasVariablePointersStorageBuffer;
294 }
SJW01901d92020-05-21 08:58:31 -0500295 void setVariablePointersStorageBuffer() {
296 if (!HasVariablePointersStorageBuffer) {
297 addCapability(spv::CapabilityVariablePointersStorageBuffer);
298 HasVariablePointersStorageBuffer = true;
299 }
alan-baker5b86ed72019-02-15 08:26:50 -0500300 }
alan-baker7506abb2020-09-10 15:02:55 -0400301 bool hasVariablePointers() { return HasVariablePointers; }
SJW01901d92020-05-21 08:58:31 -0500302 void setVariablePointers() {
303 if (!HasVariablePointers) {
304 addCapability(spv::CapabilityVariablePointers);
305 HasVariablePointers = true;
306 }
alan-baker7506abb2020-09-10 15:02:55 -0400307 }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500308 ArrayRef<std::pair<unsigned, std::string>> &getSamplerMap() {
309 return samplerMap;
310 }
David Neto22f144c2017-06-12 14:26:21 -0400311 GlobalConstFuncMapType &getGlobalConstFuncTypeMap() {
312 return GlobalConstFuncTypeMap;
313 }
314 SmallPtrSet<Value *, 16> &getGlobalConstArgSet() {
315 return GlobalConstArgumentSet;
316 }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500317 TypeList &getTypesNeedingArrayStride() { return TypesNeedingArrayStride; }
David Neto22f144c2017-06-12 14:26:21 -0400318
SJW77b87ad2020-04-21 14:37:52 -0500319 void GenerateLLVMIRInfo();
alan-bakerb6b09dc2018-11-08 16:59:28 -0500320 // Populate GlobalConstFuncTypeMap. Also, if module-scope __constant will
321 // *not* be converted to a storage buffer, replace each such global variable
322 // with one in the storage class expecgted by SPIR-V.
SJW77b87ad2020-04-21 14:37:52 -0500323 void FindGlobalConstVars();
David Neto862b7d82018-06-14 18:48:37 -0400324 // Populate ResourceVarInfoList, FunctionToResourceVarsMap, and
325 // ModuleOrderedResourceVars.
SJW77b87ad2020-04-21 14:37:52 -0500326 void FindResourceVars();
David Neto22f144c2017-06-12 14:26:21 -0400327 void FindTypePerGlobalVar(GlobalVariable &GV);
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
alan-bakerc3fd07f2020-10-22 09:48:49 -0400334 // Returns the canonical type of |type|.
335 //
336 // By default, clspv maps both __constant and __global address space pointers
337 // to StorageBuffer storage class. In order to prevent duplicate types from
338 // being generated, clspv uses the canonical type as a representative.
339 Type *CanonicalType(Type *type);
340
SJWf93f5f32020-05-05 07:27:56 -0500341 // Lookup or create Types, Constants.
342 // Returns SPIRVID once it has been created.
343 SPIRVID getSPIRVType(Type *Ty);
344 SPIRVID getSPIRVConstant(Constant *Cst);
SJW806a5d82020-07-15 12:51:38 -0500345 SPIRVID getSPIRVInt32Constant(uint32_t CstVal);
SJWf93f5f32020-05-05 07:27:56 -0500346 // Lookup SPIRVID of llvm::Value, may create Constant.
347 SPIRVID getSPIRVValue(Value *V);
348
SJW806a5d82020-07-15 12:51:38 -0500349 SPIRVID getSPIRVBuiltin(spv::BuiltIn BID, spv::Capability Cap);
350
David Neto19a1bad2017-08-25 15:01:41 -0400351 // Generates instructions for SPIR-V types corresponding to the LLVM types
352 // saved in the |Types| member. A type follows its subtypes. IDs are
353 // allocated sequentially starting with the current value of nextID, and
354 // with a type following its subtypes. Also updates nextID to just beyond
355 // the last generated ID.
SJW77b87ad2020-04-21 14:37:52 -0500356 void GenerateSPIRVTypes();
SJW77b87ad2020-04-21 14:37:52 -0500357 void GenerateModuleInfo();
David Neto22f144c2017-06-12 14:26:21 -0400358 void GenerateGlobalVar(GlobalVariable &GV);
SJW77b87ad2020-04-21 14:37:52 -0500359 void GenerateWorkgroupVars();
alan-baker86ce19c2020-08-05 13:09:19 -0400360 // Generate reflection instructions for resource variables associated with
David Neto862b7d82018-06-14 18:48:37 -0400361 // arguments to F.
SJW77b87ad2020-04-21 14:37:52 -0500362 void GenerateSamplers();
David Neto862b7d82018-06-14 18:48:37 -0400363 // Generate OpVariables for %clspv.resource.var.* calls.
SJW77b87ad2020-04-21 14:37:52 -0500364 void GenerateResourceVars();
David Neto22f144c2017-06-12 14:26:21 -0400365 void GenerateFuncPrologue(Function &F);
366 void GenerateFuncBody(Function &F);
David Netob6e2e062018-04-25 10:32:06 -0400367 void GenerateEntryPointInitialStores();
David Neto22f144c2017-06-12 14:26:21 -0400368 spv::Op GetSPIRVCmpOpcode(CmpInst *CmpI);
369 spv::Op GetSPIRVCastOpcode(Instruction &I);
370 spv::Op GetSPIRVBinaryOpcode(Instruction &I);
SJW806a5d82020-07-15 12:51:38 -0500371 SPIRVID GenerateClspvInstruction(CallInst *Call,
372 const FunctionInfo &FuncInfo);
373 SPIRVID GenerateImageInstruction(CallInst *Call,
374 const FunctionInfo &FuncInfo);
375 SPIRVID GenerateSubgroupInstruction(CallInst *Call,
376 const FunctionInfo &FuncInfo);
377 SPIRVID GenerateInstructionFromCall(CallInst *Call);
David Neto22f144c2017-06-12 14:26:21 -0400378 void GenerateInstruction(Instruction &I);
379 void GenerateFuncEpilogue();
380 void HandleDeferredInstruction();
SJW77b87ad2020-04-21 14:37:52 -0500381 void HandleDeferredDecorations();
David Neto22f144c2017-06-12 14:26:21 -0400382 bool is4xi8vec(Type *Ty) const;
383 spv::StorageClass GetStorageClass(unsigned AddrSpace) const;
David Neto862b7d82018-06-14 18:48:37 -0400384 spv::StorageClass GetStorageClassForArgKind(clspv::ArgKind arg_kind) const;
David Neto22f144c2017-06-12 14:26:21 -0400385 spv::BuiltIn GetBuiltin(StringRef globalVarName) const;
David Neto3fbb4072017-10-16 11:28:14 -0400386 // Returns the GLSL extended instruction enum that the given function
387 // call maps to. If none, then returns the 0 value, i.e. GLSLstd4580Bad.
SJW61531372020-06-09 07:31:08 -0500388 glsl::ExtInst getExtInstEnum(const Builtins::FunctionInfo &func_info);
David Neto3fbb4072017-10-16 11:28:14 -0400389 // Returns the GLSL extended instruction enum indirectly used by the given
390 // function. That is, to implement the given function, we use an extended
391 // instruction plus one more instruction. If none, then returns the 0 value,
392 // i.e. GLSLstd4580Bad.
SJW61531372020-06-09 07:31:08 -0500393 glsl::ExtInst getIndirectExtInstEnum(const Builtins::FunctionInfo &func_info);
David Neto3fbb4072017-10-16 11:28:14 -0400394 // Returns the single GLSL extended instruction used directly or
395 // indirectly by the given function call.
SJW61531372020-06-09 07:31:08 -0500396 glsl::ExtInst
397 getDirectOrIndirectExtInstEnum(const Builtins::FunctionInfo &func_info);
David Neto22f144c2017-06-12 14:26:21 -0400398 void WriteOneWord(uint32_t Word);
SJW88ed5fe2020-05-11 12:40:57 -0500399 void WriteResultID(const SPIRVInstruction &Inst);
400 void WriteWordCountAndOpcode(const SPIRVInstruction &Inst);
401 void WriteOperand(const SPIRVOperand &Op);
David Neto22f144c2017-06-12 14:26:21 -0400402 void WriteSPIRVBinary();
SJW69939d52020-04-16 07:29:07 -0500403 void WriteSPIRVBinary(SPIRVInstructionList &SPIRVInstList);
David Neto22f144c2017-06-12 14:26:21 -0400404
Alan Baker9bf93fb2018-08-28 16:59:26 -0400405 // Returns true if |type| is compatible with OpConstantNull.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500406 bool IsTypeNullable(const Type *type) const;
Alan Baker9bf93fb2018-08-28 16:59:26 -0400407
Alan Bakerfcda9482018-10-02 17:09:59 -0400408 // Populate UBO remapped type maps.
SJW77b87ad2020-04-21 14:37:52 -0500409 void PopulateUBOTypeMaps();
Alan Bakerfcda9482018-10-02 17:09:59 -0400410
alan-baker06cad652019-12-03 17:56:47 -0500411 // Populate the merge and continue block maps.
SJW77b87ad2020-04-21 14:37:52 -0500412 void PopulateStructuredCFGMaps();
alan-baker06cad652019-12-03 17:56:47 -0500413
Alan Bakerfcda9482018-10-02 17:09:59 -0400414 // Wrapped methods of DataLayout accessors. If |type| was remapped for UBOs,
415 // uses the internal map, otherwise it falls back on the data layout.
416 uint64_t GetTypeSizeInBits(Type *type, const DataLayout &DL);
Alan Bakerfcda9482018-10-02 17:09:59 -0400417 uint64_t GetTypeAllocSize(Type *type, const DataLayout &DL);
Kévin Petitbbbda972020-03-03 19:16:31 +0000418 uint32_t GetExplicitLayoutStructMemberOffset(StructType *type,
419 unsigned member,
420 const DataLayout &DL);
Alan Bakerfcda9482018-10-02 17:09:59 -0400421
alan-baker5b86ed72019-02-15 08:26:50 -0500422 // Returns the base pointer of |v|.
423 Value *GetBasePointer(Value *v);
424
SJW01901d92020-05-21 08:58:31 -0500425 // Add Capability if not already (e.g. CapabilityGroupNonUniformBroadcast)
426 void addCapability(uint32_t c) { CapabilitySet.emplace(c); }
427
alan-baker5b86ed72019-02-15 08:26:50 -0500428 // Sets |HasVariablePointersStorageBuffer| or |HasVariablePointers| base on
429 // |address_space|.
430 void setVariablePointersCapabilities(unsigned address_space);
431
432 // Returns true if |lhs| and |rhs| represent the same resource or workgroup
433 // variable.
434 bool sameResource(Value *lhs, Value *rhs) const;
435
436 // Returns true if |inst| is phi or select that selects from the same
437 // structure (or null).
438 bool selectFromSameObject(Instruction *inst);
439
alan-bakere9308012019-03-15 10:25:13 -0400440 // Returns true if |Arg| is called with a coherent resource.
441 bool CalledWithCoherentResource(Argument &Arg);
442
SJWf93f5f32020-05-05 07:27:56 -0500443 //
444 // Primary interface for adding SPIRVInstructions to a SPIRVSection.
445 template <enum SPIRVSection TSection = kFunctions>
446 SPIRVID addSPIRVInst(spv::Op Opcode, SPIRVOperandVec &Operands) {
447 bool has_result, has_result_type;
448 spv::HasResultAndType(Opcode, &has_result, &has_result_type);
449 SPIRVID RID = has_result ? incrNextID() : 0;
SJW88ed5fe2020-05-11 12:40:57 -0500450 SPIRVSections[TSection].emplace_back(Opcode, RID, Operands);
SJWf93f5f32020-05-05 07:27:56 -0500451 return RID;
452 }
453 template <enum SPIRVSection TSection = kFunctions>
454 SPIRVID addSPIRVInst(spv::Op Op) {
455 SPIRVOperandVec Ops;
456 return addSPIRVInst<TSection>(Op, Ops);
457 }
458 template <enum SPIRVSection TSection = kFunctions>
459 SPIRVID addSPIRVInst(spv::Op Op, uint32_t V) {
460 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -0500461 Ops.emplace_back(LITERAL_WORD, V);
SJWf93f5f32020-05-05 07:27:56 -0500462 return addSPIRVInst<TSection>(Op, Ops);
463 }
464 template <enum SPIRVSection TSection = kFunctions>
465 SPIRVID addSPIRVInst(spv::Op Op, const char *V) {
466 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -0500467 Ops.emplace_back(LITERAL_STRING, V);
SJWf93f5f32020-05-05 07:27:56 -0500468 return addSPIRVInst<TSection>(Op, Ops);
469 }
470
SJW88ed5fe2020-05-11 12:40:57 -0500471 //
472 // Add placeholder for llvm::Value that references future values.
473 // Must have result ID just in case final SPIRVInstruction requires.
474 SPIRVID addSPIRVPlaceholder(Value *I) {
475 SPIRVID RID = incrNextID();
476 SPIRVOperandVec Ops;
477 SPIRVSections[kFunctions].emplace_back(spv::OpExtInst, RID, Ops);
478 DeferredInstVec.push_back({I, &SPIRVSections[kFunctions].back()});
479 return RID;
480 }
481 // Replace placeholder with actual SPIRVInstruction on the final pass
482 // (HandleDeferredInstruction).
483 SPIRVID replaceSPIRVInst(SPIRVInstruction *I, spv::Op Opcode,
484 SPIRVOperandVec &Operands) {
485 bool has_result, has_result_type;
486 spv::HasResultAndType(Opcode, &has_result, &has_result_type);
487 SPIRVID RID = has_result ? I->getResultID() : 0;
488 *I = SPIRVInstruction(Opcode, RID, Operands);
489 return RID;
490 }
491
SJW806a5d82020-07-15 12:51:38 -0500492 //
493 // Add global variable and capture entry point interface
494 SPIRVID addSPIRVGlobalVariable(const SPIRVID &TypeID, spv::StorageClass SC,
495 const SPIRVID &InitID = SPIRVID());
496
alan-baker86ce19c2020-08-05 13:09:19 -0400497 SPIRVID getReflectionImport();
498 void GenerateReflection();
499 void GenerateKernelReflection();
500 void GeneratePushConstantReflection();
501 void GenerateSpecConstantReflection();
502 void AddArgumentReflection(SPIRVID kernel_decl, const std::string &name,
503 clspv::ArgKind arg_kind, uint32_t ordinal,
504 uint32_t descriptor_set, uint32_t binding,
505 uint32_t offset, uint32_t size, uint32_t spec_id,
506 uint32_t elem_size);
507
David Neto22f144c2017-06-12 14:26:21 -0400508private:
509 static char ID;
SJW77b87ad2020-04-21 14:37:52 -0500510
511 Module *module;
512
SJW01901d92020-05-21 08:58:31 -0500513 // Set of Capabilities required
514 CapabilitySetType CapabilitySet;
515
SJW806a5d82020-07-15 12:51:38 -0500516 // Map from clspv::BuiltinType to SPIRV Global Variable
517 BuiltinConstantMapType BuiltinConstantMap;
518
David Neto44795152017-07-13 15:45:28 -0400519 ArrayRef<std::pair<unsigned, std::string>> samplerMap;
David Neto22f144c2017-06-12 14:26:21 -0400520 raw_pwrite_stream &out;
David Neto0676e6f2017-07-11 18:47:44 -0400521
522 // TODO(dneto): Wouldn't it be better to always just emit a binary, and then
523 // convert to other formats on demand?
524
525 // When emitting a C initialization list, the WriteSPIRVBinary method
526 // will actually write its words to this vector via binaryTempOut.
527 SmallVector<char, 100> binaryTempUnderlyingVector;
528 raw_svector_ostream binaryTempOut;
529
530 // Binary output writes to this stream, which might be |out| or
531 // |binaryTempOut|. It's the latter when we really want to write a C
532 // initializer list.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400533 raw_pwrite_stream *binaryOut;
David Neto0676e6f2017-07-11 18:47:44 -0400534 const bool outputCInitList; // If true, output look like {0x7023, ... , 5}
David Neto22f144c2017-06-12 14:26:21 -0400535 uint64_t patchBoundOffset;
536 uint32_t nextID;
537
SJWf93f5f32020-05-05 07:27:56 -0500538 SPIRVID incrNextID() { return nextID++; }
539
alan-bakerf67468c2019-11-25 15:51:49 -0500540 // ID for OpTypeInt 32 1.
SJW01901d92020-05-21 08:58:31 -0500541 SPIRVID int32ID;
alan-bakerf67468c2019-11-25 15:51:49 -0500542 // ID for OpTypeVector %int 4.
SJW01901d92020-05-21 08:58:31 -0500543 SPIRVID v4int32ID;
alan-bakerf67468c2019-11-25 15:51:49 -0500544
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 TypeMapType TypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400547 // Maps an LLVM image type to its SPIR-V ID.
David Neto22f144c2017-06-12 14:26:21 -0400548 TypeMapType ImageTypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400549 // A unique-vector of LLVM types that map to a SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400550 TypeList Types;
David Neto19a1bad2017-08-25 15:01:41 -0400551 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400552 ValueMapType ValueMap;
SJW69939d52020-04-16 07:29:07 -0500553 SPIRVInstructionList SPIRVSections[kSectionCount];
David Neto862b7d82018-06-14 18:48:37 -0400554
David Neto22f144c2017-06-12 14:26:21 -0400555 EntryPointVecType EntryPointVec;
556 DeferredInstVecType DeferredInstVec;
SJW806a5d82020-07-15 12:51:38 -0500557 SPIRVIDListType EntryPointInterfacesList;
SJW01901d92020-05-21 08:58:31 -0500558 SPIRVID OpExtInstImportID;
559 std::vector<SPIRVID> BuiltinDimensionVec;
alan-baker5b86ed72019-02-15 08:26:50 -0500560 bool HasVariablePointersStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -0400561 bool HasVariablePointers;
562 Type *SamplerTy;
SJW01901d92020-05-21 08:58:31 -0500563 DenseMap<unsigned, SPIRVID> SamplerLiteralToIDMap;
David Netoc77d9e22018-03-24 06:30:28 -0700564
565 // If a function F has a pointer-to-__constant parameter, then this variable
David Neto9ed8e2f2018-03-24 06:47:24 -0700566 // will map F's type to (G, index of the parameter), where in a first phase
Marco Antognini7e338402021-03-15 12:48:37 +0000567 // G is F's type.
David Netoc77d9e22018-03-24 06:30:28 -0700568 // TODO(dneto): This doesn't seem general enough? A function might have
569 // more than one such parameter.
David Neto22f144c2017-06-12 14:26:21 -0400570 GlobalConstFuncMapType GlobalConstFuncTypeMap;
571 SmallPtrSet<Value *, 16> GlobalConstArgumentSet;
David Neto1a1a0582017-07-07 12:01:44 -0400572 // An ordered set of pointer types of Base arguments to OpPtrAccessChain,
David Neto85082642018-03-24 06:55:20 -0700573 // or array types, and which point into transparent memory (StorageBuffer
574 // storage class). These will require an ArrayStride decoration.
David Neto1a1a0582017-07-07 12:01:44 -0400575 // See SPV_KHR_variable_pointers rev 13.
David Neto85082642018-03-24 06:55:20 -0700576 TypeList TypesNeedingArrayStride;
David Netoa60b00b2017-09-15 16:34:09 -0400577
578 // This is truly ugly, but works around what look like driver bugs.
579 // For get_local_size, an earlier part of the flow has created a module-scope
580 // variable in Private address space to hold the value for the workgroup
581 // size. Its intializer is a uint3 value marked as builtin WorkgroupSize.
582 // When this is present, save the IDs of the initializer value and variable
583 // in these two variables. We only ever do a vector load from it, and
584 // when we see one of those, substitute just the value of the intializer.
585 // This mimics what Glslang does, and that's what drivers are used to.
David Neto66cfe642018-03-24 06:13:56 -0700586 // TODO(dneto): Remove this once drivers are fixed.
SJW01901d92020-05-21 08:58:31 -0500587 SPIRVID WorkgroupSizeValueID;
588 SPIRVID WorkgroupSizeVarID;
David Neto26aaf622017-10-23 18:11:53 -0400589
David Neto862b7d82018-06-14 18:48:37 -0400590 // Bookkeeping for mapping kernel arguments to resource variables.
591 struct ResourceVarInfo {
592 ResourceVarInfo(int index_arg, unsigned set_arg, unsigned binding_arg,
alan-bakere9308012019-03-15 10:25:13 -0400593 Function *fn, clspv::ArgKind arg_kind_arg, int coherent_arg)
David Neto862b7d82018-06-14 18:48:37 -0400594 : index(index_arg), descriptor_set(set_arg), binding(binding_arg),
alan-bakere9308012019-03-15 10:25:13 -0400595 var_fn(fn), arg_kind(arg_kind_arg), coherent(coherent_arg),
David Neto862b7d82018-06-14 18:48:37 -0400596 addr_space(fn->getReturnType()->getPointerAddressSpace()) {}
597 const int index; // Index into ResourceVarInfoList
598 const unsigned descriptor_set;
599 const unsigned binding;
600 Function *const var_fn; // The @clspv.resource.var.* function.
601 const clspv::ArgKind arg_kind;
alan-bakere9308012019-03-15 10:25:13 -0400602 const int coherent;
David Neto862b7d82018-06-14 18:48:37 -0400603 const unsigned addr_space; // The LLVM address space
604 // The SPIR-V ID of the OpVariable. Not populated at construction time.
SJW01901d92020-05-21 08:58:31 -0500605 SPIRVID var_id;
David Neto862b7d82018-06-14 18:48:37 -0400606 };
607 // A list of resource var info. Each one correponds to a module-scope
608 // resource variable we will have to create. Resource var indices are
609 // indices into this vector.
610 SmallVector<std::unique_ptr<ResourceVarInfo>, 8> ResourceVarInfoList;
611 // This is a vector of pointers of all the resource vars, but ordered by
612 // kernel function, and then by argument.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500613 UniqueVector<ResourceVarInfo *> ModuleOrderedResourceVars;
David Neto862b7d82018-06-14 18:48:37 -0400614 // Map a function to the ordered list of resource variables it uses, one for
615 // each argument. If an argument does not use a resource variable, it
616 // will have a null pointer entry.
617 using FunctionToResourceVarsMapType =
618 DenseMap<Function *, SmallVector<ResourceVarInfo *, 8>>;
619 FunctionToResourceVarsMapType FunctionToResourceVarsMap;
620
621 // What LLVM types map to SPIR-V types needing layout? These are the
622 // arrays and structures supporting storage buffers and uniform buffers.
623 TypeList TypesNeedingLayout;
624 // What LLVM struct types map to a SPIR-V struct type with Block decoration?
625 UniqueVector<StructType *> StructTypesNeedingBlock;
626 // For a call that represents a load from an opaque type (samplers, images),
627 // map it to the variable id it should load from.
SJW01901d92020-05-21 08:58:31 -0500628 DenseMap<CallInst *, SPIRVID> ResourceVarDeferredLoadCalls;
David Neto85082642018-03-24 06:55:20 -0700629
David Netoc6f3ab22018-04-06 18:02:31 -0400630 // An ordered list of the kernel arguments of type pointer-to-local.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500631 using LocalArgList = SmallVector<Argument *, 8>;
David Netoc6f3ab22018-04-06 18:02:31 -0400632 LocalArgList LocalArgs;
633 // Information about a pointer-to-local argument.
634 struct LocalArgInfo {
635 // The SPIR-V ID of the array variable.
SJW01901d92020-05-21 08:58:31 -0500636 SPIRVID variable_id;
David Netoc6f3ab22018-04-06 18:02:31 -0400637 // The element type of the
alan-bakerb6b09dc2018-11-08 16:59:28 -0500638 Type *elem_type;
David Netoc6f3ab22018-04-06 18:02:31 -0400639 // The ID of the array type.
SJW01901d92020-05-21 08:58:31 -0500640 SPIRVID array_size_id;
David Netoc6f3ab22018-04-06 18:02:31 -0400641 // The ID of the array type.
SJW01901d92020-05-21 08:58:31 -0500642 SPIRVID array_type_id;
David Netoc6f3ab22018-04-06 18:02:31 -0400643 // The ID of the pointer to the array type.
SJW01901d92020-05-21 08:58:31 -0500644 SPIRVID ptr_array_type_id;
David Netoc6f3ab22018-04-06 18:02:31 -0400645 // The specialization constant ID of the array size.
646 int spec_id;
647 };
Alan Baker202c8c72018-08-13 13:47:44 -0400648 // A mapping from Argument to its assigned SpecId.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500649 DenseMap<const Argument *, int> LocalArgSpecIds;
Alan Baker202c8c72018-08-13 13:47:44 -0400650 // A mapping from SpecId to its LocalArgInfo.
651 DenseMap<int, LocalArgInfo> LocalSpecIdInfoMap;
Alan Bakerfcda9482018-10-02 17:09:59 -0400652 // A mapping from a remapped type to its real offsets.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500653 DenseMap<Type *, std::vector<uint32_t>> RemappedUBOTypeOffsets;
Alan Bakerfcda9482018-10-02 17:09:59 -0400654 // A mapping from a remapped type to its real sizes.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500655 DenseMap<Type *, std::tuple<uint64_t, uint64_t, uint64_t>>
656 RemappedUBOTypeSizes;
alan-baker06cad652019-12-03 17:56:47 -0500657
658 // Maps basic block to its merge block.
659 DenseMap<BasicBlock *, BasicBlock *> MergeBlocks;
660 // Maps basic block to its continue block.
661 DenseMap<BasicBlock *, BasicBlock *> ContinueBlocks;
SJW01901d92020-05-21 08:58:31 -0500662
alan-baker86ce19c2020-08-05 13:09:19 -0400663 SPIRVID ReflectionID;
664 DenseMap<Function *, SPIRVID> KernelDeclarations;
665
SJW01901d92020-05-21 08:58:31 -0500666public:
667 static SPIRVProducerPass *Ptr;
David Neto22f144c2017-06-12 14:26:21 -0400668};
669
670char SPIRVProducerPass::ID;
SJW01901d92020-05-21 08:58:31 -0500671SPIRVProducerPass *SPIRVProducerPass::Ptr = nullptr;
David Netoc6f3ab22018-04-06 18:02:31 -0400672
alan-bakerb6b09dc2018-11-08 16:59:28 -0500673} // namespace
David Neto22f144c2017-06-12 14:26:21 -0400674
675namespace clspv {
alan-baker86ce19c2020-08-05 13:09:19 -0400676ModulePass *
677createSPIRVProducerPass(raw_pwrite_stream &out,
678 ArrayRef<std::pair<unsigned, std::string>> samplerMap,
679 bool outputCInitList) {
680 return new SPIRVProducerPass(out, samplerMap, outputCInitList);
David Neto22f144c2017-06-12 14:26:21 -0400681}
David Netoc2c368d2017-06-30 16:50:17 -0400682} // namespace clspv
David Neto22f144c2017-06-12 14:26:21 -0400683
SJW01901d92020-05-21 08:58:31 -0500684namespace {
685SPIRVOperandVec &operator<<(SPIRVOperandVec &list, uint32_t num) {
686 list.emplace_back(LITERAL_WORD, num);
687 return list;
688}
689
690SPIRVOperandVec &operator<<(SPIRVOperandVec &list, int32_t num) {
691 list.emplace_back(LITERAL_WORD, static_cast<uint32_t>(num));
692 return list;
693}
694
695SPIRVOperandVec &operator<<(SPIRVOperandVec &list, ArrayRef<uint32_t> num_vec) {
696 list.emplace_back(num_vec);
697 return list;
698}
699
700SPIRVOperandVec &operator<<(SPIRVOperandVec &list, StringRef str) {
701 list.emplace_back(LITERAL_STRING, str);
702 return list;
703}
704
705SPIRVOperandVec &operator<<(SPIRVOperandVec &list, Type *t) {
706 list.emplace_back(NUMBERID, SPIRVProducerPass::Ptr->getSPIRVType(t).get());
707 return list;
708}
709
710SPIRVOperandVec &operator<<(SPIRVOperandVec &list, Value *v) {
711 list.emplace_back(NUMBERID, SPIRVProducerPass::Ptr->getSPIRVValue(v).get());
712 return list;
713}
714
SJW806a5d82020-07-15 12:51:38 -0500715SPIRVOperandVec &operator<<(SPIRVOperandVec &list, const SPIRVID &v) {
SJW01901d92020-05-21 08:58:31 -0500716 list.emplace_back(NUMBERID, v.get());
717 return list;
718}
719} // namespace
720
SJW77b87ad2020-04-21 14:37:52 -0500721bool SPIRVProducerPass::runOnModule(Module &M) {
SJW01901d92020-05-21 08:58:31 -0500722 // TODO(sjw): Need to reset all data members for each Module, or better
723 // yet create a new SPIRVProducer for every module.. For now only
724 // allow 1 call.
725 assert(module == nullptr);
SJW77b87ad2020-04-21 14:37:52 -0500726 module = &M;
alan-baker5ed87542020-03-23 11:05:22 -0400727 if (ShowProducerIR) {
SJW77b87ad2020-04-21 14:37:52 -0500728 llvm::outs() << *module << "\n";
alan-baker5ed87542020-03-23 11:05:22 -0400729 }
David Neto0676e6f2017-07-11 18:47:44 -0400730 binaryOut = outputCInitList ? &binaryTempOut : &out;
731
SJW77b87ad2020-04-21 14:37:52 -0500732 PopulateUBOTypeMaps();
733 PopulateStructuredCFGMaps();
Alan Bakerfcda9482018-10-02 17:09:59 -0400734
David Neto22f144c2017-06-12 14:26:21 -0400735 // SPIR-V always begins with its header information
736 outputHeader();
737
738 // Gather information from the LLVM IR that we require.
SJW77b87ad2020-04-21 14:37:52 -0500739 GenerateLLVMIRInfo();
David Neto22f144c2017-06-12 14:26:21 -0400740
David Neto22f144c2017-06-12 14:26:21 -0400741 // Collect information on global variables too.
SJW77b87ad2020-04-21 14:37:52 -0500742 for (GlobalVariable &GV : module->globals()) {
David Neto22f144c2017-06-12 14:26:21 -0400743 // If the GV is one of our special __spirv_* variables, remove the
744 // initializer as it was only placed there to force LLVM to not throw the
745 // value away.
Kévin Petitbbbda972020-03-03 19:16:31 +0000746 if (GV.getName().startswith("__spirv_") ||
747 GV.getAddressSpace() == clspv::AddressSpace::PushConstant) {
David Neto22f144c2017-06-12 14:26:21 -0400748 GV.setInitializer(nullptr);
749 }
750
751 // Collect types' information from global variable.
752 FindTypePerGlobalVar(GV);
David Neto22f144c2017-06-12 14:26:21 -0400753 }
754
David Neto22f144c2017-06-12 14:26:21 -0400755 // Generate SPIRV instructions for types.
SJW77b87ad2020-04-21 14:37:52 -0500756 GenerateSPIRVTypes();
David Neto22f144c2017-06-12 14:26:21 -0400757
alan-baker09cb9802019-12-10 13:16:27 -0500758 // Generate literal samplers if necessary.
SJW77b87ad2020-04-21 14:37:52 -0500759 GenerateSamplers();
David Neto22f144c2017-06-12 14:26:21 -0400760
761 // Generate SPIRV variables.
SJW77b87ad2020-04-21 14:37:52 -0500762 for (GlobalVariable &GV : module->globals()) {
David Neto22f144c2017-06-12 14:26:21 -0400763 GenerateGlobalVar(GV);
764 }
SJW77b87ad2020-04-21 14:37:52 -0500765 GenerateResourceVars();
766 GenerateWorkgroupVars();
David Neto22f144c2017-06-12 14:26:21 -0400767
768 // Generate SPIRV instructions for each function.
SJW77b87ad2020-04-21 14:37:52 -0500769 for (Function &F : *module) {
David Neto22f144c2017-06-12 14:26:21 -0400770 if (F.isDeclaration()) {
771 continue;
772 }
773
774 // Generate Function Prologue.
775 GenerateFuncPrologue(F);
776
777 // Generate SPIRV instructions for function body.
778 GenerateFuncBody(F);
779
780 // Generate Function Epilogue.
781 GenerateFuncEpilogue();
782 }
783
784 HandleDeferredInstruction();
SJW77b87ad2020-04-21 14:37:52 -0500785 HandleDeferredDecorations();
alan-bakera1be3322020-04-20 12:48:18 -0400786
David Neto22f144c2017-06-12 14:26:21 -0400787 // Generate SPIRV module information.
SJW77b87ad2020-04-21 14:37:52 -0500788 GenerateModuleInfo();
David Neto22f144c2017-06-12 14:26:21 -0400789
alan-baker86ce19c2020-08-05 13:09:19 -0400790 // Generate embedded reflection information.
791 GenerateReflection();
792
alan-baker00e7a582019-06-07 12:54:21 -0400793 WriteSPIRVBinary();
David Neto22f144c2017-06-12 14:26:21 -0400794
795 // We need to patch the SPIR-V header to set bound correctly.
796 patchHeader();
David Neto0676e6f2017-07-11 18:47:44 -0400797
798 if (outputCInitList) {
799 bool first = true;
David Neto0676e6f2017-07-11 18:47:44 -0400800 std::ostringstream os;
801
David Neto57fb0b92017-08-04 15:35:09 -0400802 auto emit_word = [&os, &first](uint32_t word) {
David Neto0676e6f2017-07-11 18:47:44 -0400803 if (!first)
David Neto57fb0b92017-08-04 15:35:09 -0400804 os << ",\n";
805 os << word;
David Neto0676e6f2017-07-11 18:47:44 -0400806 first = false;
807 };
808
809 os << "{";
David Neto57fb0b92017-08-04 15:35:09 -0400810 const std::string str(binaryTempOut.str());
811 for (unsigned i = 0; i < str.size(); i += 4) {
812 const uint32_t a = static_cast<unsigned char>(str[i]);
813 const uint32_t b = static_cast<unsigned char>(str[i + 1]);
814 const uint32_t c = static_cast<unsigned char>(str[i + 2]);
815 const uint32_t d = static_cast<unsigned char>(str[i + 3]);
816 emit_word(a | (b << 8) | (c << 16) | (d << 24));
David Neto0676e6f2017-07-11 18:47:44 -0400817 }
818 os << "}\n";
819 out << os.str();
820 }
821
David Neto22f144c2017-06-12 14:26:21 -0400822 return false;
823}
824
825void SPIRVProducerPass::outputHeader() {
alan-baker00e7a582019-06-07 12:54:21 -0400826 binaryOut->write(reinterpret_cast<const char *>(&spv::MagicNumber),
827 sizeof(spv::MagicNumber));
SJW806a5d82020-07-15 12:51:38 -0500828 uint32_t minor = 0;
829 if (SpvVersion() == SPIRVVersion::SPIRV_1_3) {
830 minor = 3;
831 }
832 uint32_t version = (1 << 16) | (minor << 8);
833 binaryOut->write(reinterpret_cast<const char *>(&version), sizeof(version));
David Neto22f144c2017-06-12 14:26:21 -0400834
alan-baker0c18ab02019-06-12 10:23:21 -0400835 // use Google's vendor ID
836 const uint32_t vendor = 21 << 16;
alan-baker00e7a582019-06-07 12:54:21 -0400837 binaryOut->write(reinterpret_cast<const char *>(&vendor), sizeof(vendor));
David Neto22f144c2017-06-12 14:26:21 -0400838
alan-baker00e7a582019-06-07 12:54:21 -0400839 // we record where we need to come back to and patch in the bound value
840 patchBoundOffset = binaryOut->tell();
David Neto22f144c2017-06-12 14:26:21 -0400841
alan-baker00e7a582019-06-07 12:54:21 -0400842 // output a bad bound for now
843 binaryOut->write(reinterpret_cast<const char *>(&nextID), sizeof(nextID));
David Neto22f144c2017-06-12 14:26:21 -0400844
alan-baker00e7a582019-06-07 12:54:21 -0400845 // output the schema (reserved for use and must be 0)
846 const uint32_t schema = 0;
847 binaryOut->write(reinterpret_cast<const char *>(&schema), sizeof(schema));
David Neto22f144c2017-06-12 14:26:21 -0400848}
849
850void SPIRVProducerPass::patchHeader() {
alan-baker00e7a582019-06-07 12:54:21 -0400851 // for a binary we just write the value of nextID over bound
852 binaryOut->pwrite(reinterpret_cast<char *>(&nextID), sizeof(nextID),
853 patchBoundOffset);
David Neto22f144c2017-06-12 14:26:21 -0400854}
855
SJW77b87ad2020-04-21 14:37:52 -0500856void SPIRVProducerPass::GenerateLLVMIRInfo() {
David Neto22f144c2017-06-12 14:26:21 -0400857 // This function generates LLVM IR for function such as global variable for
858 // argument, constant and pointer type for argument access. These information
859 // is artificial one because we need Vulkan SPIR-V output. This function is
860 // executed ahead of FindType and FindConstant.
David Neto22f144c2017-06-12 14:26:21 -0400861
SJW77b87ad2020-04-21 14:37:52 -0500862 FindGlobalConstVars();
David Neto5c22a252018-03-15 16:07:41 -0400863
SJW77b87ad2020-04-21 14:37:52 -0500864 FindResourceVars();
David Neto22f144c2017-06-12 14:26:21 -0400865
SJW77b87ad2020-04-21 14:37:52 -0500866 FindTypesForSamplerMap();
867 FindTypesForResourceVars();
David Neto22f144c2017-06-12 14:26:21 -0400868}
869
SJW77b87ad2020-04-21 14:37:52 -0500870void SPIRVProducerPass::FindGlobalConstVars() {
871 clspv::NormalizeGlobalVariables(*module);
872 const DataLayout &DL = module->getDataLayout();
alan-baker56f7aff2019-05-22 08:06:42 -0400873
David Neto862b7d82018-06-14 18:48:37 -0400874 SmallVector<GlobalVariable *, 8> GVList;
875 SmallVector<GlobalVariable *, 8> DeadGVList;
SJW77b87ad2020-04-21 14:37:52 -0500876 for (GlobalVariable &GV : module->globals()) {
David Neto862b7d82018-06-14 18:48:37 -0400877 if (GV.getType()->getAddressSpace() == AddressSpace::Constant) {
878 if (GV.use_empty()) {
879 DeadGVList.push_back(&GV);
880 } else {
881 GVList.push_back(&GV);
882 }
883 }
884 }
885
886 // Remove dead global __constant variables.
887 for (auto GV : DeadGVList) {
888 GV->eraseFromParent();
889 }
890 DeadGVList.clear();
891
892 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
893 // For now, we only support a single storage buffer.
alan-baker7506abb2020-09-10 15:02:55 -0400894 if (!GVList.empty()) {
David Neto862b7d82018-06-14 18:48:37 -0400895 assert(GVList.size() == 1);
896 const auto *GV = GVList[0];
897 const auto constants_byte_size =
Alan Bakerfcda9482018-10-02 17:09:59 -0400898 (GetTypeSizeInBits(GV->getInitializer()->getType(), DL)) / 8;
David Neto862b7d82018-06-14 18:48:37 -0400899 const size_t kConstantMaxSize = 65536;
900 if (constants_byte_size > kConstantMaxSize) {
901 outs() << "Max __constant capacity of " << kConstantMaxSize
902 << " bytes exceeded: " << constants_byte_size << " bytes used\n";
903 llvm_unreachable("Max __constant capacity exceeded");
904 }
905 }
906 } else {
907 // Change global constant variable's address space to ModuleScopePrivate.
908 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
909 for (auto GV : GVList) {
910 // Create new gv with ModuleScopePrivate address space.
911 Type *NewGVTy = GV->getType()->getPointerElementType();
912 GlobalVariable *NewGV = new GlobalVariable(
SJW77b87ad2020-04-21 14:37:52 -0500913 *module, NewGVTy, false, GV->getLinkage(), GV->getInitializer(), "",
David Neto862b7d82018-06-14 18:48:37 -0400914 nullptr, GV->getThreadLocalMode(), AddressSpace::ModuleScopePrivate);
915 NewGV->takeName(GV);
916
917 const SmallVector<User *, 8> GVUsers(GV->user_begin(), GV->user_end());
918 SmallVector<User *, 8> CandidateUsers;
919
920 auto record_called_function_type_as_user =
921 [&GlobalConstFuncTyMap](Value *gv, CallInst *call) {
922 // Find argument index.
923 unsigned index = 0;
924 for (unsigned i = 0; i < call->getNumArgOperands(); i++) {
925 if (gv == call->getOperand(i)) {
926 // TODO(dneto): Should we break here?
927 index = i;
928 }
929 }
930
931 // Record function type with global constant.
932 GlobalConstFuncTyMap[call->getFunctionType()] =
933 std::make_pair(call->getFunctionType(), index);
934 };
935
936 for (User *GVU : GVUsers) {
937 if (CallInst *Call = dyn_cast<CallInst>(GVU)) {
938 record_called_function_type_as_user(GV, Call);
939 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(GVU)) {
940 // Check GEP users.
941 for (User *GEPU : GEP->users()) {
942 if (CallInst *GEPCall = dyn_cast<CallInst>(GEPU)) {
943 record_called_function_type_as_user(GEP, GEPCall);
944 }
945 }
946 }
947
948 CandidateUsers.push_back(GVU);
949 }
950
951 for (User *U : CandidateUsers) {
952 // Update users of gv with new gv.
alan-bakered80f572019-02-11 17:28:26 -0500953 if (!isa<Constant>(U)) {
954 // #254: Can't change operands of a constant, but this shouldn't be
955 // something that sticks around in the module.
956 U->replaceUsesOfWith(GV, NewGV);
957 }
David Neto862b7d82018-06-14 18:48:37 -0400958 }
959
960 // Delete original gv.
961 GV->eraseFromParent();
962 }
963 }
964}
965
SJW77b87ad2020-04-21 14:37:52 -0500966void SPIRVProducerPass::FindResourceVars() {
David Neto862b7d82018-06-14 18:48:37 -0400967 ResourceVarInfoList.clear();
968 FunctionToResourceVarsMap.clear();
969 ModuleOrderedResourceVars.reset();
970 // Normally, there is one resource variable per clspv.resource.var.*
971 // function, since that is unique'd by arg type and index. By design,
972 // we can share these resource variables across kernels because all
973 // kernels use the same descriptor set.
974 //
975 // But if the user requested distinct descriptor sets per kernel, then
976 // the descriptor allocator has made different (set,binding) pairs for
977 // the same (type,arg_index) pair. Since we can decorate a resource
978 // variable with only exactly one DescriptorSet and Binding, we are
979 // forced in this case to make distinct resource variables whenever
Kévin Petitbbbda972020-03-03 19:16:31 +0000980 // the same clspv.resource.var.X function is seen with disintct
David Neto862b7d82018-06-14 18:48:37 -0400981 // (set,binding) values.
982 const bool always_distinct_sets =
983 clspv::Option::DistinctKernelDescriptorSets();
SJW77b87ad2020-04-21 14:37:52 -0500984 for (Function &F : *module) {
David Neto862b7d82018-06-14 18:48:37 -0400985 // Rely on the fact the resource var functions have a stable ordering
986 // in the module.
SJW61531372020-06-09 07:31:08 -0500987 if (Builtins::Lookup(&F) == Builtins::kClspvResource) {
David Neto862b7d82018-06-14 18:48:37 -0400988 // Find all calls to this function with distinct set and binding pairs.
989 // Save them in ResourceVarInfoList.
990
991 // Determine uniqueness of the (set,binding) pairs only withing this
992 // one resource-var builtin function.
993 using SetAndBinding = std::pair<unsigned, unsigned>;
994 // Maps set and binding to the resource var info.
995 DenseMap<SetAndBinding, ResourceVarInfo *> set_and_binding_map;
996 bool first_use = true;
997 for (auto &U : F.uses()) {
998 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
999 const auto set = unsigned(
1000 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
1001 const auto binding = unsigned(
1002 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
1003 const auto arg_kind = clspv::ArgKind(
1004 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
1005 const auto arg_index = unsigned(
1006 dyn_cast<ConstantInt>(call->getArgOperand(3))->getZExtValue());
alan-bakere9308012019-03-15 10:25:13 -04001007 const auto coherent = unsigned(
1008 dyn_cast<ConstantInt>(call->getArgOperand(5))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04001009
1010 // Find or make the resource var info for this combination.
1011 ResourceVarInfo *rv = nullptr;
1012 if (always_distinct_sets) {
1013 // Make a new resource var any time we see a different
1014 // (set,binding) pair.
1015 SetAndBinding key{set, binding};
1016 auto where = set_and_binding_map.find(key);
1017 if (where == set_and_binding_map.end()) {
alan-baker7506abb2020-09-10 15:02:55 -04001018 rv = new ResourceVarInfo(
1019 static_cast<int>(ResourceVarInfoList.size()), set, binding,
1020 &F, arg_kind, coherent);
David Neto862b7d82018-06-14 18:48:37 -04001021 ResourceVarInfoList.emplace_back(rv);
1022 set_and_binding_map[key] = rv;
1023 } else {
1024 rv = where->second;
1025 }
1026 } else {
1027 // The default is to make exactly one resource for each
1028 // clspv.resource.var.* function.
1029 if (first_use) {
1030 first_use = false;
alan-baker7506abb2020-09-10 15:02:55 -04001031 rv = new ResourceVarInfo(
1032 static_cast<int>(ResourceVarInfoList.size()), set, binding,
1033 &F, arg_kind, coherent);
David Neto862b7d82018-06-14 18:48:37 -04001034 ResourceVarInfoList.emplace_back(rv);
1035 } else {
1036 rv = ResourceVarInfoList.back().get();
1037 }
1038 }
1039
1040 // Now populate FunctionToResourceVarsMap.
1041 auto &mapping =
1042 FunctionToResourceVarsMap[call->getParent()->getParent()];
1043 while (mapping.size() <= arg_index) {
1044 mapping.push_back(nullptr);
1045 }
1046 mapping[arg_index] = rv;
1047 }
1048 }
1049 }
1050 }
1051
1052 // Populate ModuleOrderedResourceVars.
SJW77b87ad2020-04-21 14:37:52 -05001053 for (Function &F : *module) {
David Neto862b7d82018-06-14 18:48:37 -04001054 auto where = FunctionToResourceVarsMap.find(&F);
1055 if (where != FunctionToResourceVarsMap.end()) {
1056 for (auto &rv : where->second) {
1057 if (rv != nullptr) {
1058 ModuleOrderedResourceVars.insert(rv);
1059 }
1060 }
1061 }
1062 }
1063 if (ShowResourceVars) {
1064 for (auto *info : ModuleOrderedResourceVars) {
1065 outs() << "MORV index " << info->index << " (" << info->descriptor_set
1066 << "," << info->binding << ") " << *(info->var_fn->getReturnType())
1067 << "\n";
1068 }
1069 }
1070}
1071
David Neto22f144c2017-06-12 14:26:21 -04001072void SPIRVProducerPass::FindTypePerGlobalVar(GlobalVariable &GV) {
1073 // Investigate global variable's type.
1074 FindType(GV.getType());
1075}
1076
SJW77b87ad2020-04-21 14:37:52 -05001077void SPIRVProducerPass::FindTypesForSamplerMap() {
David Neto862b7d82018-06-14 18:48:37 -04001078 // If we are using a sampler map, find the type of the sampler.
SJW77b87ad2020-04-21 14:37:52 -05001079 if (module->getFunction(clspv::LiteralSamplerFunction()) ||
alan-baker7506abb2020-09-10 15:02:55 -04001080 !getSamplerMap().empty()) {
James Pricecbe834f2020-12-01 13:42:25 -05001081 auto SamplerStructTy =
1082 StructType::getTypeByName(module->getContext(), "opencl.sampler_t");
David Neto862b7d82018-06-14 18:48:37 -04001083 if (!SamplerStructTy) {
SJW77b87ad2020-04-21 14:37:52 -05001084 SamplerStructTy =
1085 StructType::create(module->getContext(), "opencl.sampler_t");
David Neto862b7d82018-06-14 18:48:37 -04001086 }
1087
1088 SamplerTy = SamplerStructTy->getPointerTo(AddressSpace::UniformConstant);
1089
1090 FindType(SamplerTy);
1091 }
1092}
1093
SJW77b87ad2020-04-21 14:37:52 -05001094void SPIRVProducerPass::FindTypesForResourceVars() {
David Neto862b7d82018-06-14 18:48:37 -04001095 // Record types so they are generated.
1096 TypesNeedingLayout.reset();
1097 StructTypesNeedingBlock.reset();
1098
1099 // To match older clspv codegen, generate the float type first if required
1100 // for images.
1101 for (const auto *info : ModuleOrderedResourceVars) {
alan-bakerf6bc8252020-09-23 14:58:55 -04001102 if (info->arg_kind == clspv::ArgKind::SampledImage ||
1103 info->arg_kind == clspv::ArgKind::StorageImage) {
alan-bakerf67468c2019-11-25 15:51:49 -05001104 if (IsIntImageType(info->var_fn->getReturnType())) {
1105 // Nothing for now...
1106 } else if (IsUintImageType(info->var_fn->getReturnType())) {
SJW77b87ad2020-04-21 14:37:52 -05001107 FindType(Type::getInt32Ty(module->getContext()));
alan-bakerf67468c2019-11-25 15:51:49 -05001108 }
1109
1110 // We need "float" either for the sampled type or for the Lod operand.
SJW77b87ad2020-04-21 14:37:52 -05001111 FindType(Type::getFloatTy(module->getContext()));
David Neto862b7d82018-06-14 18:48:37 -04001112 }
1113 }
1114
1115 for (const auto *info : ModuleOrderedResourceVars) {
1116 Type *type = info->var_fn->getReturnType();
1117
1118 switch (info->arg_kind) {
1119 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04001120 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04001121 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1122 StructTypesNeedingBlock.insert(sty);
1123 } else {
1124 errs() << *type << "\n";
1125 llvm_unreachable("Buffer arguments must map to structures!");
1126 }
1127 break;
1128 case clspv::ArgKind::Pod:
alan-baker9b0ec3c2020-04-06 14:45:34 -04001129 case clspv::ArgKind::PodUBO:
1130 case clspv::ArgKind::PodPushConstant:
David Neto862b7d82018-06-14 18:48:37 -04001131 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1132 StructTypesNeedingBlock.insert(sty);
1133 } else {
1134 errs() << *type << "\n";
1135 llvm_unreachable("POD arguments must map to structures!");
1136 }
1137 break;
alan-bakerf6bc8252020-09-23 14:58:55 -04001138 case clspv::ArgKind::SampledImage:
1139 case clspv::ArgKind::StorageImage:
David Neto862b7d82018-06-14 18:48:37 -04001140 case clspv::ArgKind::Sampler:
1141 // Sampler and image types map to the pointee type but
1142 // in the uniform constant address space.
1143 type = PointerType::get(type->getPointerElementType(),
1144 clspv::AddressSpace::UniformConstant);
1145 break;
1146 default:
1147 break;
1148 }
1149
1150 // The converted type is the type of the OpVariable we will generate.
1151 // If the pointee type is an array of size zero, FindType will convert it
1152 // to a runtime array.
1153 FindType(type);
1154 }
1155
alan-bakerdcd97412019-09-16 15:32:30 -04001156 // If module constants are clustered in a storage buffer then that struct
1157 // needs layout decorations.
1158 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
SJW77b87ad2020-04-21 14:37:52 -05001159 for (GlobalVariable &GV : module->globals()) {
alan-bakerdcd97412019-09-16 15:32:30 -04001160 PointerType *PTy = cast<PointerType>(GV.getType());
1161 const auto AS = PTy->getAddressSpace();
1162 const bool module_scope_constant_external_init =
1163 (AS == AddressSpace::Constant) && GV.hasInitializer();
1164 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
1165 if (module_scope_constant_external_init &&
1166 spv::BuiltInMax == BuiltinType) {
1167 StructTypesNeedingBlock.insert(
1168 cast<StructType>(PTy->getPointerElementType()));
1169 }
1170 }
1171 }
1172
SJW77b87ad2020-04-21 14:37:52 -05001173 for (const GlobalVariable &GV : module->globals()) {
Kévin Petitbbbda972020-03-03 19:16:31 +00001174 if (GV.getAddressSpace() == clspv::AddressSpace::PushConstant) {
1175 auto Ty = cast<PointerType>(GV.getType())->getPointerElementType();
1176 assert(Ty->isStructTy() && "Push constants have to be structures.");
1177 auto STy = cast<StructType>(Ty);
1178 StructTypesNeedingBlock.insert(STy);
1179 }
1180 }
1181
David Neto862b7d82018-06-14 18:48:37 -04001182 // Traverse the arrays and structures underneath each Block, and
1183 // mark them as needing layout.
1184 std::vector<Type *> work_list(StructTypesNeedingBlock.begin(),
1185 StructTypesNeedingBlock.end());
1186 while (!work_list.empty()) {
1187 Type *type = work_list.back();
1188 work_list.pop_back();
1189 TypesNeedingLayout.insert(type);
1190 switch (type->getTypeID()) {
1191 case Type::ArrayTyID:
1192 work_list.push_back(type->getArrayElementType());
1193 if (!Hack_generate_runtime_array_stride_early) {
1194 // Remember this array type for deferred decoration.
1195 TypesNeedingArrayStride.insert(type);
1196 }
1197 break;
1198 case Type::StructTyID:
1199 for (auto *elem_ty : cast<StructType>(type)->elements()) {
1200 work_list.push_back(elem_ty);
1201 }
1202 default:
1203 // This type and its contained types don't get layout.
1204 break;
1205 }
1206 }
1207}
1208
SJWf93f5f32020-05-05 07:27:56 -05001209void SPIRVProducerPass::GenerateWorkgroupVars() {
Alan Baker202c8c72018-08-13 13:47:44 -04001210 // The SpecId assignment for pointer-to-local arguments is recorded in
1211 // module-level metadata. Translate that information into local argument
1212 // information.
SJWf93f5f32020-05-05 07:27:56 -05001213 LLVMContext &Context = module->getContext();
SJW77b87ad2020-04-21 14:37:52 -05001214 NamedMDNode *nmd = module->getNamedMetadata(clspv::LocalSpecIdMetadataName());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001215 if (!nmd)
1216 return;
Alan Baker202c8c72018-08-13 13:47:44 -04001217 for (auto operand : nmd->operands()) {
1218 MDTuple *tuple = cast<MDTuple>(operand);
1219 ValueAsMetadata *fn_md = cast<ValueAsMetadata>(tuple->getOperand(0));
1220 Function *func = cast<Function>(fn_md->getValue());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001221 ConstantAsMetadata *arg_index_md =
1222 cast<ConstantAsMetadata>(tuple->getOperand(1));
1223 int arg_index = static_cast<int>(
1224 cast<ConstantInt>(arg_index_md->getValue())->getSExtValue());
1225 Argument *arg = &*(func->arg_begin() + arg_index);
Alan Baker202c8c72018-08-13 13:47:44 -04001226
1227 ConstantAsMetadata *spec_id_md =
1228 cast<ConstantAsMetadata>(tuple->getOperand(2));
alan-bakerb6b09dc2018-11-08 16:59:28 -05001229 int spec_id = static_cast<int>(
1230 cast<ConstantInt>(spec_id_md->getValue())->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04001231
Alan Baker202c8c72018-08-13 13:47:44 -04001232 LocalArgSpecIds[arg] = spec_id;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001233 if (LocalSpecIdInfoMap.count(spec_id))
1234 continue;
Alan Baker202c8c72018-08-13 13:47:44 -04001235
SJWf93f5f32020-05-05 07:27:56 -05001236 // Generate the spec constant.
1237 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05001238 Ops << Type::getInt32Ty(Context) << 1;
SJWf93f5f32020-05-05 07:27:56 -05001239 SPIRVID ArraySizeID = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
Alan Baker202c8c72018-08-13 13:47:44 -04001240
SJWf93f5f32020-05-05 07:27:56 -05001241 // Generate the array type.
1242 Type *ElemTy = arg->getType()->getPointerElementType();
1243 Ops.clear();
1244 // The element type must have been created.
SJW01901d92020-05-21 08:58:31 -05001245 Ops << ElemTy << ArraySizeID;
SJWf93f5f32020-05-05 07:27:56 -05001246
1247 SPIRVID ArrayTypeID = addSPIRVInst<kTypes>(spv::OpTypeArray, Ops);
1248
1249 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05001250 Ops << spv::StorageClassWorkgroup << ArrayTypeID;
SJWf93f5f32020-05-05 07:27:56 -05001251 SPIRVID PtrArrayTypeID = addSPIRVInst<kTypes>(spv::OpTypePointer, Ops);
1252
1253 // Generate OpVariable.
1254 //
1255 // Ops[0] : Result Type ID
1256 // Ops[1] : Storage Class
SJW806a5d82020-07-15 12:51:38 -05001257 SPIRVID VariableID =
1258 addSPIRVGlobalVariable(PtrArrayTypeID, spv::StorageClassWorkgroup);
SJWf93f5f32020-05-05 07:27:56 -05001259
1260 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05001261 Ops << ArraySizeID << spv::DecorationSpecId << spec_id;
SJWf93f5f32020-05-05 07:27:56 -05001262 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
1263
1264 LocalArgInfo info{VariableID, ElemTy, ArraySizeID,
1265 ArrayTypeID, PtrArrayTypeID, spec_id};
1266 LocalSpecIdInfoMap[spec_id] = info;
Alan Baker202c8c72018-08-13 13:47:44 -04001267 }
1268}
1269
David Neto22f144c2017-06-12 14:26:21 -04001270void SPIRVProducerPass::FindType(Type *Ty) {
1271 TypeList &TyList = getTypeList();
1272
1273 if (0 != TyList.idFor(Ty)) {
1274 return;
1275 }
1276
1277 if (Ty->isPointerTy()) {
1278 auto AddrSpace = Ty->getPointerAddressSpace();
1279 if ((AddressSpace::Constant == AddrSpace) ||
1280 (AddressSpace::Global == AddrSpace)) {
1281 auto PointeeTy = Ty->getPointerElementType();
1282
1283 if (PointeeTy->isStructTy() &&
1284 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1285 FindType(PointeeTy);
1286 auto ActualPointerTy =
1287 PointeeTy->getPointerTo(AddressSpace::UniformConstant);
1288 FindType(ActualPointerTy);
1289 return;
1290 }
1291 }
1292 }
1293
David Neto862b7d82018-06-14 18:48:37 -04001294 // By convention, LLVM array type with 0 elements will map to
1295 // OpTypeRuntimeArray. Otherwise, it will map to OpTypeArray, which
1296 // has a constant number of elements. We need to support type of the
1297 // constant.
1298 if (auto *arrayTy = dyn_cast<ArrayType>(Ty)) {
1299 if (arrayTy->getNumElements() > 0) {
1300 LLVMContext &Context = Ty->getContext();
1301 FindType(Type::getInt32Ty(Context));
1302 }
David Neto22f144c2017-06-12 14:26:21 -04001303 }
1304
1305 for (Type *SubTy : Ty->subtypes()) {
1306 FindType(SubTy);
1307 }
1308
1309 TyList.insert(Ty);
1310}
1311
David Neto22f144c2017-06-12 14:26:21 -04001312spv::StorageClass SPIRVProducerPass::GetStorageClass(unsigned AddrSpace) const {
1313 switch (AddrSpace) {
1314 default:
1315 llvm_unreachable("Unsupported OpenCL address space");
1316 case AddressSpace::Private:
1317 return spv::StorageClassFunction;
1318 case AddressSpace::Global:
David Neto22f144c2017-06-12 14:26:21 -04001319 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001320 case AddressSpace::Constant:
1321 return clspv::Option::ConstantArgsInUniformBuffer()
1322 ? spv::StorageClassUniform
1323 : spv::StorageClassStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -04001324 case AddressSpace::Input:
1325 return spv::StorageClassInput;
1326 case AddressSpace::Local:
1327 return spv::StorageClassWorkgroup;
1328 case AddressSpace::UniformConstant:
1329 return spv::StorageClassUniformConstant;
David Neto9ed8e2f2018-03-24 06:47:24 -07001330 case AddressSpace::Uniform:
David Netoe439d702018-03-23 13:14:08 -07001331 return spv::StorageClassUniform;
David Neto22f144c2017-06-12 14:26:21 -04001332 case AddressSpace::ModuleScopePrivate:
1333 return spv::StorageClassPrivate;
Kévin Petitbbbda972020-03-03 19:16:31 +00001334 case AddressSpace::PushConstant:
1335 return spv::StorageClassPushConstant;
David Neto22f144c2017-06-12 14:26:21 -04001336 }
1337}
1338
David Neto862b7d82018-06-14 18:48:37 -04001339spv::StorageClass
1340SPIRVProducerPass::GetStorageClassForArgKind(clspv::ArgKind arg_kind) const {
1341 switch (arg_kind) {
1342 case clspv::ArgKind::Buffer:
1343 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001344 case clspv::ArgKind::BufferUBO:
1345 return spv::StorageClassUniform;
David Neto862b7d82018-06-14 18:48:37 -04001346 case clspv::ArgKind::Pod:
alan-baker9b0ec3c2020-04-06 14:45:34 -04001347 return spv::StorageClassStorageBuffer;
1348 case clspv::ArgKind::PodUBO:
1349 return spv::StorageClassUniform;
1350 case clspv::ArgKind::PodPushConstant:
1351 return spv::StorageClassPushConstant;
David Neto862b7d82018-06-14 18:48:37 -04001352 case clspv::ArgKind::Local:
1353 return spv::StorageClassWorkgroup;
alan-bakerf6bc8252020-09-23 14:58:55 -04001354 case clspv::ArgKind::SampledImage:
1355 case clspv::ArgKind::StorageImage:
David Neto862b7d82018-06-14 18:48:37 -04001356 case clspv::ArgKind::Sampler:
1357 return spv::StorageClassUniformConstant;
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001358 default:
1359 llvm_unreachable("Unsupported storage class for argument kind");
David Neto862b7d82018-06-14 18:48:37 -04001360 }
1361}
1362
David Neto22f144c2017-06-12 14:26:21 -04001363spv::BuiltIn SPIRVProducerPass::GetBuiltin(StringRef Name) const {
1364 return StringSwitch<spv::BuiltIn>(Name)
1365 .Case("__spirv_GlobalInvocationId", spv::BuiltInGlobalInvocationId)
1366 .Case("__spirv_LocalInvocationId", spv::BuiltInLocalInvocationId)
1367 .Case("__spirv_WorkgroupSize", spv::BuiltInWorkgroupSize)
1368 .Case("__spirv_NumWorkgroups", spv::BuiltInNumWorkgroups)
1369 .Case("__spirv_WorkgroupId", spv::BuiltInWorkgroupId)
alan-bakerbed3a882020-04-21 14:42:41 -04001370 .Case("__spirv_WorkDim", spv::BuiltInWorkDim)
alan-bakere1996972020-05-04 08:38:12 -04001371 .Case("__spirv_GlobalOffset", spv::BuiltInGlobalOffset)
David Neto22f144c2017-06-12 14:26:21 -04001372 .Default(spv::BuiltInMax);
1373}
1374
SJW01901d92020-05-21 08:58:31 -05001375SPIRVID SPIRVProducerPass::getOpExtInstImportID() {
1376 if (OpExtInstImportID == 0) {
1377 //
1378 // Generate OpExtInstImport.
1379 //
1380 // Ops[0] ... Ops[n] = Name (Literal String)
David Neto22f144c2017-06-12 14:26:21 -04001381
SJW01901d92020-05-21 08:58:31 -05001382 OpExtInstImportID =
1383 addSPIRVInst<kImports>(spv::OpExtInstImport, "GLSL.std.450");
1384 }
1385 return OpExtInstImportID;
SJWf93f5f32020-05-05 07:27:56 -05001386}
1387
SJW806a5d82020-07-15 12:51:38 -05001388SPIRVID SPIRVProducerPass::addSPIRVGlobalVariable(const SPIRVID &TypeID,
1389 spv::StorageClass SC,
1390 const SPIRVID &InitID) {
1391 // Generate OpVariable.
1392 //
1393 // Ops[0] : Result Type ID
1394 // Ops[1] : Storage Class
1395 // Ops[2] : Initialization Value ID (optional)
1396
1397 SPIRVOperandVec Ops;
1398 Ops << TypeID << SC;
1399 if (InitID.isValid()) {
1400 Ops << InitID;
1401 }
1402
1403 SPIRVID VID = addSPIRVInst<kGlobalVariables>(spv::OpVariable, Ops);
1404
1405 if (SC == spv::StorageClassInput) {
1406 getEntryPointInterfacesList().push_back(VID);
1407 }
1408
1409 return VID;
1410}
1411
alan-bakerc3fd07f2020-10-22 09:48:49 -04001412Type *SPIRVProducerPass::CanonicalType(Type *type) {
1413 if (type->getNumContainedTypes() != 0) {
1414 switch (type->getTypeID()) {
1415 case Type::PointerTyID: {
1416 // For the purposes of our Vulkan SPIR-V type system, constant and global
1417 // are conflated.
1418 auto *ptr_ty = cast<PointerType>(type);
1419 unsigned AddrSpace = ptr_ty->getAddressSpace();
1420 if (AddressSpace::Constant == AddrSpace) {
1421 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1422 AddrSpace = AddressSpace::Global;
1423 // The canonical type of __constant is __global unless constants are
1424 // passed in uniform buffers.
1425 auto *GlobalTy =
1426 ptr_ty->getPointerElementType()->getPointerTo(AddrSpace);
1427 return GlobalTy;
1428 }
1429 }
1430 break;
1431 }
1432 case Type::StructTyID: {
1433 SmallVector<Type *, 8> subtypes;
1434 bool changed = false;
1435 for (auto *subtype : type->subtypes()) {
1436 auto canonical = CanonicalType(subtype);
1437 subtypes.push_back(canonical);
1438 if (canonical != subtype) {
1439 changed = true;
1440 }
1441 }
1442 if (changed) {
1443 return StructType::get(type->getContext(), subtypes,
1444 cast<StructType>(type)->isPacked());
1445 }
1446 break;
1447 }
1448 case Type::ArrayTyID: {
1449 auto *elem_ty = type->getArrayElementType();
1450 auto *equiv_elem_ty = CanonicalType(elem_ty);
1451 if (equiv_elem_ty != elem_ty) {
1452 return ArrayType::get(equiv_elem_ty,
1453 cast<ArrayType>(type)->getNumElements());
1454 }
1455 break;
1456 }
1457 case Type::FunctionTyID: {
1458 auto *func_ty = cast<FunctionType>(type);
1459 auto *return_ty = CanonicalType(func_ty->getReturnType());
1460 SmallVector<Type *, 8> params;
1461 for (unsigned i = 0; i < func_ty->getNumParams(); ++i) {
1462 params.push_back(CanonicalType(func_ty->getParamType(i)));
1463 }
1464 return FunctionType::get(return_ty, params, func_ty->isVarArg());
1465 }
1466 default:
1467 break;
1468 }
1469 }
1470
1471 return type;
1472}
1473
SJW01901d92020-05-21 08:58:31 -05001474SPIRVID SPIRVProducerPass::getSPIRVType(Type *Ty) {
SJWf93f5f32020-05-05 07:27:56 -05001475 auto TI = TypeMap.find(Ty);
1476 if (TI != TypeMap.end()) {
SJW01901d92020-05-21 08:58:31 -05001477 assert(TI->second.isValid());
SJWf93f5f32020-05-05 07:27:56 -05001478 return TI->second;
1479 }
1480
alan-bakerc3fd07f2020-10-22 09:48:49 -04001481 auto Canonical = CanonicalType(Ty);
1482 if (Canonical != Ty) {
1483 auto CanonicalTI = TypeMap.find(Canonical);
1484 if (CanonicalTI != TypeMap.end()) {
1485 assert(CanonicalTI->second.isValid());
1486 return CanonicalTI->second;
1487 }
1488 }
1489
1490 // Perform the mapping with the canonical type.
1491
SJWf93f5f32020-05-05 07:27:56 -05001492 const auto &DL = module->getDataLayout();
1493
SJW01901d92020-05-21 08:58:31 -05001494 SPIRVID RID;
SJWf93f5f32020-05-05 07:27:56 -05001495
alan-bakerc3fd07f2020-10-22 09:48:49 -04001496 switch (Canonical->getTypeID()) {
SJWf93f5f32020-05-05 07:27:56 -05001497 default: {
alan-bakerc3fd07f2020-10-22 09:48:49 -04001498 Canonical->print(errs());
SJWf93f5f32020-05-05 07:27:56 -05001499 llvm_unreachable("Unsupported type???");
1500 break;
1501 }
1502 case Type::MetadataTyID:
1503 case Type::LabelTyID: {
1504 // Ignore these types.
1505 break;
1506 }
1507 case Type::PointerTyID: {
alan-bakerc3fd07f2020-10-22 09:48:49 -04001508 PointerType *PTy = cast<PointerType>(Canonical);
SJWf93f5f32020-05-05 07:27:56 -05001509 unsigned AddrSpace = PTy->getAddressSpace();
1510
1511 if (AddrSpace != AddressSpace::UniformConstant) {
1512 auto PointeeTy = PTy->getElementType();
1513 if (PointeeTy->isStructTy() &&
1514 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1515 // TODO(sjw): assert always an image?
1516 RID = getSPIRVType(PointeeTy);
1517 break;
1518 }
1519 }
1520
SJWf93f5f32020-05-05 07:27:56 -05001521 //
1522 // Generate OpTypePointer.
1523 //
1524
1525 // OpTypePointer
1526 // Ops[0] = Storage Class
1527 // Ops[1] = Element Type ID
1528 SPIRVOperandVec Ops;
1529
SJW01901d92020-05-21 08:58:31 -05001530 Ops << GetStorageClass(AddrSpace) << PTy->getElementType();
SJWf93f5f32020-05-05 07:27:56 -05001531
1532 RID = addSPIRVInst<kTypes>(spv::OpTypePointer, Ops);
1533 break;
1534 }
1535 case Type::StructTyID: {
alan-bakerc3fd07f2020-10-22 09:48:49 -04001536 StructType *STy = cast<StructType>(Canonical);
SJWf93f5f32020-05-05 07:27:56 -05001537
1538 // Handle sampler type.
1539 if (STy->isOpaque()) {
1540 if (STy->getName().equals("opencl.sampler_t")) {
1541 //
1542 // Generate OpTypeSampler
1543 //
1544 // Empty Ops.
1545
1546 RID = addSPIRVInst<kTypes>(spv::OpTypeSampler);
1547 break;
1548 } else if (STy->getName().startswith("opencl.image1d_ro_t") ||
alan-bakerf6bc8252020-09-23 14:58:55 -04001549 STy->getName().startswith("opencl.image1d_rw_t") ||
SJWf93f5f32020-05-05 07:27:56 -05001550 STy->getName().startswith("opencl.image1d_wo_t") ||
1551 STy->getName().startswith("opencl.image1d_array_ro_t") ||
alan-bakerf6bc8252020-09-23 14:58:55 -04001552 STy->getName().startswith("opencl.image1d_array_rw_t") ||
SJWf93f5f32020-05-05 07:27:56 -05001553 STy->getName().startswith("opencl.image1d_array_wo_t") ||
1554 STy->getName().startswith("opencl.image2d_ro_t") ||
alan-bakerf6bc8252020-09-23 14:58:55 -04001555 STy->getName().startswith("opencl.image2d_rw_t") ||
SJWf93f5f32020-05-05 07:27:56 -05001556 STy->getName().startswith("opencl.image2d_wo_t") ||
1557 STy->getName().startswith("opencl.image2d_array_ro_t") ||
alan-bakerf6bc8252020-09-23 14:58:55 -04001558 STy->getName().startswith("opencl.image2d_array_rw_t") ||
SJWf93f5f32020-05-05 07:27:56 -05001559 STy->getName().startswith("opencl.image2d_array_wo_t") ||
1560 STy->getName().startswith("opencl.image3d_ro_t") ||
alan-bakerf6bc8252020-09-23 14:58:55 -04001561 STy->getName().startswith("opencl.image3d_rw_t") ||
SJWf93f5f32020-05-05 07:27:56 -05001562 STy->getName().startswith("opencl.image3d_wo_t")) {
SJW01901d92020-05-21 08:58:31 -05001563 if (STy->getName().startswith("opencl.image1d_")) {
1564 if (STy->getName().contains(".sampled"))
1565 addCapability(spv::CapabilitySampled1D);
1566 else
1567 addCapability(spv::CapabilityImage1D);
1568 }
1569
SJWf93f5f32020-05-05 07:27:56 -05001570 //
1571 // Generate OpTypeImage
1572 //
1573 // Ops[0] = Sampled Type ID
1574 // Ops[1] = Dim ID
1575 // Ops[2] = Depth (Literal Number)
1576 // Ops[3] = Arrayed (Literal Number)
1577 // Ops[4] = MS (Literal Number)
1578 // Ops[5] = Sampled (Literal Number)
1579 // Ops[6] = Image Format ID
1580 //
1581 SPIRVOperandVec Ops;
1582
SJW01901d92020-05-21 08:58:31 -05001583 SPIRVID SampledTyID;
SJWf93f5f32020-05-05 07:27:56 -05001584 if (STy->getName().contains(".float")) {
alan-bakerc3fd07f2020-10-22 09:48:49 -04001585 SampledTyID = getSPIRVType(Type::getFloatTy(Canonical->getContext()));
SJWf93f5f32020-05-05 07:27:56 -05001586 } else if (STy->getName().contains(".uint")) {
alan-bakerc3fd07f2020-10-22 09:48:49 -04001587 SampledTyID = getSPIRVType(Type::getInt32Ty(Canonical->getContext()));
SJWf93f5f32020-05-05 07:27:56 -05001588 } else if (STy->getName().contains(".int")) {
1589 // Generate a signed 32-bit integer if necessary.
1590 if (int32ID == 0) {
1591 SPIRVOperandVec intOps;
SJW01901d92020-05-21 08:58:31 -05001592 intOps << 32 << 1;
SJWf93f5f32020-05-05 07:27:56 -05001593 int32ID = addSPIRVInst<kTypes>(spv::OpTypeInt, intOps);
1594 }
1595 SampledTyID = int32ID;
1596
1597 // Generate a vec4 of the signed int if necessary.
1598 if (v4int32ID == 0) {
1599 SPIRVOperandVec vecOps;
SJW01901d92020-05-21 08:58:31 -05001600 vecOps << int32ID << 4;
SJWf93f5f32020-05-05 07:27:56 -05001601 v4int32ID = addSPIRVInst<kTypes>(spv::OpTypeVector, vecOps);
1602 }
1603 } else {
1604 // This was likely an UndefValue.
alan-bakerc3fd07f2020-10-22 09:48:49 -04001605 SampledTyID = getSPIRVType(Type::getFloatTy(Canonical->getContext()));
SJWf93f5f32020-05-05 07:27:56 -05001606 }
SJW01901d92020-05-21 08:58:31 -05001607 Ops << SampledTyID;
SJWf93f5f32020-05-05 07:27:56 -05001608
1609 spv::Dim DimID = spv::Dim2D;
1610 if (STy->getName().startswith("opencl.image1d_ro_t") ||
alan-bakerf6bc8252020-09-23 14:58:55 -04001611 STy->getName().startswith("opencl.image1d_rw_t") ||
SJWf93f5f32020-05-05 07:27:56 -05001612 STy->getName().startswith("opencl.image1d_wo_t") ||
1613 STy->getName().startswith("opencl.image1d_array_ro_t") ||
alan-bakerf6bc8252020-09-23 14:58:55 -04001614 STy->getName().startswith("opencl.image1d_array_rw_t") ||
SJWf93f5f32020-05-05 07:27:56 -05001615 STy->getName().startswith("opencl.image1d_array_wo_t")) {
1616 DimID = spv::Dim1D;
1617 } else if (STy->getName().startswith("opencl.image3d_ro_t") ||
alan-bakerf6bc8252020-09-23 14:58:55 -04001618 STy->getName().startswith("opencl.image3d_rw_t") ||
SJWf93f5f32020-05-05 07:27:56 -05001619 STy->getName().startswith("opencl.image3d_wo_t")) {
1620 DimID = spv::Dim3D;
1621 }
SJW01901d92020-05-21 08:58:31 -05001622 Ops << DimID;
SJWf93f5f32020-05-05 07:27:56 -05001623
1624 // TODO: Set up Depth.
SJW01901d92020-05-21 08:58:31 -05001625 Ops << 0;
SJWf93f5f32020-05-05 07:27:56 -05001626
1627 uint32_t arrayed = STy->getName().contains("_array_") ? 1 : 0;
SJW01901d92020-05-21 08:58:31 -05001628 Ops << arrayed;
SJWf93f5f32020-05-05 07:27:56 -05001629
1630 // TODO: Set up MS.
SJW01901d92020-05-21 08:58:31 -05001631 Ops << 0;
SJWf93f5f32020-05-05 07:27:56 -05001632
1633 // Set up Sampled.
1634 //
1635 // From Spec
1636 //
1637 // 0 indicates this is only known at run time, not at compile time
1638 // 1 indicates will be used with sampler
1639 // 2 indicates will be used without a sampler (a storage image)
1640 uint32_t Sampled = 1;
1641 if (!STy->getName().contains(".sampled")) {
1642 Sampled = 2;
1643 }
SJW01901d92020-05-21 08:58:31 -05001644 Ops << Sampled;
SJWf93f5f32020-05-05 07:27:56 -05001645
1646 // TODO: Set up Image Format.
SJW01901d92020-05-21 08:58:31 -05001647 Ops << spv::ImageFormatUnknown;
SJWf93f5f32020-05-05 07:27:56 -05001648 RID = addSPIRVInst<kTypes>(spv::OpTypeImage, Ops);
1649
alan-bakerf6bc8252020-09-23 14:58:55 -04001650 // Only need a sampled version of the type if it is used with a sampler.
1651 if (Sampled == 1) {
1652 Ops.clear();
1653 Ops << RID;
alan-bakerc3fd07f2020-10-22 09:48:49 -04001654 getImageTypeMap()[Canonical] =
alan-bakerf6bc8252020-09-23 14:58:55 -04001655 addSPIRVInst<kTypes>(spv::OpTypeSampledImage, Ops);
1656 }
SJWf93f5f32020-05-05 07:27:56 -05001657 break;
1658 }
1659 }
1660
1661 //
1662 // Generate OpTypeStruct
1663 //
1664 // Ops[0] ... Ops[n] = Member IDs
1665 SPIRVOperandVec Ops;
1666
1667 for (auto *EleTy : STy->elements()) {
SJW01901d92020-05-21 08:58:31 -05001668 Ops << EleTy;
SJWf93f5f32020-05-05 07:27:56 -05001669 }
1670
1671 RID = addSPIRVInst<kTypes>(spv::OpTypeStruct, Ops);
1672
alan-bakerc3fd07f2020-10-22 09:48:49 -04001673 // Generate OpMemberDecorate unless we are generating it for the canonical
1674 // type.
1675 StructType *canonical = cast<StructType>(CanonicalType(STy));
1676 if (TypesNeedingLayout.idFor(STy) &&
1677 (canonical == STy || !TypesNeedingLayout.idFor(canonical))) {
SJWf93f5f32020-05-05 07:27:56 -05001678 for (unsigned MemberIdx = 0; MemberIdx < STy->getNumElements();
1679 MemberIdx++) {
1680 // Ops[0] = Structure Type ID
1681 // Ops[1] = Member Index(Literal Number)
1682 // Ops[2] = Decoration (Offset)
1683 // Ops[3] = Byte Offset (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05001684 const auto ByteOffset =
1685 GetExplicitLayoutStructMemberOffset(STy, MemberIdx, DL);
1686
SJW01901d92020-05-21 08:58:31 -05001687 Ops.clear();
1688 Ops << RID << MemberIdx << spv::DecorationOffset << ByteOffset;
SJWf93f5f32020-05-05 07:27:56 -05001689
1690 addSPIRVInst<kAnnotations>(spv::OpMemberDecorate, Ops);
1691 }
1692 }
1693
alan-bakerc3fd07f2020-10-22 09:48:49 -04001694 // Generate OpDecorate unless we are generating it for the canonical type.
1695 if (StructTypesNeedingBlock.idFor(STy) &&
1696 (canonical == STy || !StructTypesNeedingBlock.idFor(canonical))) {
SJWf93f5f32020-05-05 07:27:56 -05001697 Ops.clear();
1698 // Use Block decorations with StorageBuffer storage class.
SJW01901d92020-05-21 08:58:31 -05001699 Ops << RID << spv::DecorationBlock;
SJWf93f5f32020-05-05 07:27:56 -05001700
1701 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
1702 }
1703 break;
1704 }
1705 case Type::IntegerTyID: {
alan-bakerc3fd07f2020-10-22 09:48:49 -04001706 uint32_t bit_width =
1707 static_cast<uint32_t>(Canonical->getPrimitiveSizeInBits());
SJWf93f5f32020-05-05 07:27:56 -05001708
alan-bakere2a62752020-07-09 22:53:23 -04001709 if (clspv::Option::Int8Support() && bit_width == 8) {
SJW01901d92020-05-21 08:58:31 -05001710 addCapability(spv::CapabilityInt8);
alan-bakere2a62752020-07-09 22:53:23 -04001711 } else if (bit_width == 16) {
SJW01901d92020-05-21 08:58:31 -05001712 addCapability(spv::CapabilityInt16);
alan-bakere2a62752020-07-09 22:53:23 -04001713 } else if (bit_width == 64) {
SJW01901d92020-05-21 08:58:31 -05001714 addCapability(spv::CapabilityInt64);
1715 }
1716
alan-bakere2a62752020-07-09 22:53:23 -04001717 if (bit_width == 1) {
SJWf93f5f32020-05-05 07:27:56 -05001718 RID = addSPIRVInst<kTypes>(spv::OpTypeBool);
1719 } else {
alan-bakere2a62752020-07-09 22:53:23 -04001720 if (!clspv::Option::Int8Support() && bit_width == 8) {
SJWf93f5f32020-05-05 07:27:56 -05001721 // i8 is added to TypeMap as i32.
alan-bakerc3fd07f2020-10-22 09:48:49 -04001722 RID = getSPIRVType(Type::getIntNTy(Canonical->getContext(), 32));
SJWf93f5f32020-05-05 07:27:56 -05001723 } else {
1724 SPIRVOperandVec Ops;
alan-bakere2a62752020-07-09 22:53:23 -04001725 Ops << bit_width << 0 /* not signed */;
SJWf93f5f32020-05-05 07:27:56 -05001726 RID = addSPIRVInst<kTypes>(spv::OpTypeInt, Ops);
1727 }
1728 }
1729 break;
1730 }
1731 case Type::HalfTyID:
1732 case Type::FloatTyID:
1733 case Type::DoubleTyID: {
alan-bakerc3fd07f2020-10-22 09:48:49 -04001734 uint32_t bit_width =
1735 static_cast<uint32_t>(Canonical->getPrimitiveSizeInBits());
alan-bakere2a62752020-07-09 22:53:23 -04001736 if (bit_width == 16) {
SJW01901d92020-05-21 08:58:31 -05001737 addCapability(spv::CapabilityFloat16);
alan-bakere2a62752020-07-09 22:53:23 -04001738 } else if (bit_width == 64) {
SJW01901d92020-05-21 08:58:31 -05001739 addCapability(spv::CapabilityFloat64);
1740 }
1741
SJWf93f5f32020-05-05 07:27:56 -05001742 SPIRVOperandVec Ops;
alan-bakere2a62752020-07-09 22:53:23 -04001743 Ops << bit_width;
SJWf93f5f32020-05-05 07:27:56 -05001744
1745 RID = addSPIRVInst<kTypes>(spv::OpTypeFloat, Ops);
1746 break;
1747 }
1748 case Type::ArrayTyID: {
alan-bakerc3fd07f2020-10-22 09:48:49 -04001749 ArrayType *ArrTy = cast<ArrayType>(Canonical);
SJWf93f5f32020-05-05 07:27:56 -05001750 const uint64_t Length = ArrTy->getArrayNumElements();
1751 if (Length == 0) {
1752 // By convention, map it to a RuntimeArray.
1753
1754 Type *EleTy = ArrTy->getArrayElementType();
1755
1756 //
1757 // Generate OpTypeRuntimeArray.
1758 //
1759 // OpTypeRuntimeArray
1760 // Ops[0] = Element Type ID
1761 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05001762 Ops << EleTy;
SJWf93f5f32020-05-05 07:27:56 -05001763
1764 RID = addSPIRVInst<kTypes>(spv::OpTypeRuntimeArray, Ops);
1765
1766 if (Hack_generate_runtime_array_stride_early) {
1767 // Generate OpDecorate.
1768
1769 // Ops[0] = Target ID
1770 // Ops[1] = Decoration (ArrayStride)
1771 // Ops[2] = Stride Number(Literal Number)
1772 Ops.clear();
1773
SJW01901d92020-05-21 08:58:31 -05001774 Ops << RID << spv::DecorationArrayStride
1775 << static_cast<uint32_t>(GetTypeAllocSize(EleTy, DL));
SJWf93f5f32020-05-05 07:27:56 -05001776
1777 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
1778 }
1779
1780 } else {
1781
1782 //
1783 // Generate OpConstant and OpTypeArray.
1784 //
1785
1786 //
1787 // Generate OpConstant for array length.
1788 //
1789 // Add constant for length to constant list.
1790 Constant *CstLength =
1791 ConstantInt::get(Type::getInt32Ty(module->getContext()), Length);
SJWf93f5f32020-05-05 07:27:56 -05001792
1793 // Remember to generate ArrayStride later
alan-bakerc3fd07f2020-10-22 09:48:49 -04001794 getTypesNeedingArrayStride().insert(Canonical);
SJWf93f5f32020-05-05 07:27:56 -05001795
1796 //
1797 // Generate OpTypeArray.
1798 //
1799 // Ops[0] = Element Type ID
1800 // Ops[1] = Array Length Constant ID
1801 SPIRVOperandVec Ops;
1802
SJW01901d92020-05-21 08:58:31 -05001803 Ops << ArrTy->getElementType() << CstLength;
SJWf93f5f32020-05-05 07:27:56 -05001804
1805 RID = addSPIRVInst<kTypes>(spv::OpTypeArray, Ops);
1806 }
1807 break;
1808 }
1809 case Type::FixedVectorTyID: {
alan-bakerc3fd07f2020-10-22 09:48:49 -04001810 auto VecTy = cast<VectorType>(Canonical);
SJWf93f5f32020-05-05 07:27:56 -05001811 // <4 x i8> is changed to i32 if i8 is not generally supported.
1812 if (!clspv::Option::Int8Support() &&
1813 VecTy->getElementType() == Type::getInt8Ty(module->getContext())) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001814 if (VecTy->getElementCount().getKnownMinValue() == 4) {
SJWf93f5f32020-05-05 07:27:56 -05001815 RID = getSPIRVType(VecTy->getElementType());
1816 break;
1817 } else {
alan-bakerc3fd07f2020-10-22 09:48:49 -04001818 Canonical->print(errs());
SJWf93f5f32020-05-05 07:27:56 -05001819 llvm_unreachable("Support above i8 vector type");
1820 }
1821 }
1822
1823 // Ops[0] = Component Type ID
1824 // Ops[1] = Component Count (Literal Number)
1825 SPIRVOperandVec Ops;
alan-baker5a8c3be2020-09-09 13:44:26 -04001826 Ops << VecTy->getElementType()
1827 << VecTy->getElementCount().getKnownMinValue();
SJWf93f5f32020-05-05 07:27:56 -05001828
1829 RID = addSPIRVInst<kTypes>(spv::OpTypeVector, Ops);
1830 break;
1831 }
1832 case Type::VoidTyID: {
1833 RID = addSPIRVInst<kTypes>(spv::OpTypeVoid);
1834 break;
1835 }
1836 case Type::FunctionTyID: {
1837 // Generate SPIRV instruction for function type.
alan-bakerc3fd07f2020-10-22 09:48:49 -04001838 FunctionType *FTy = cast<FunctionType>(Canonical);
SJWf93f5f32020-05-05 07:27:56 -05001839
1840 // Ops[0] = Return Type ID
1841 // Ops[1] ... Ops[n] = Parameter Type IDs
1842 SPIRVOperandVec Ops;
1843
1844 // Find SPIRV instruction for return type
SJW01901d92020-05-21 08:58:31 -05001845 Ops << FTy->getReturnType();
SJWf93f5f32020-05-05 07:27:56 -05001846
1847 // Find SPIRV instructions for parameter types
1848 for (unsigned k = 0; k < FTy->getNumParams(); k++) {
1849 // Find SPIRV instruction for parameter type.
1850 auto ParamTy = FTy->getParamType(k);
1851 if (ParamTy->isPointerTy()) {
1852 auto PointeeTy = ParamTy->getPointerElementType();
1853 if (PointeeTy->isStructTy() &&
1854 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1855 ParamTy = PointeeTy;
1856 }
1857 }
1858
SJW01901d92020-05-21 08:58:31 -05001859 Ops << ParamTy;
SJWf93f5f32020-05-05 07:27:56 -05001860 }
1861
1862 RID = addSPIRVInst<kTypes>(spv::OpTypeFunction, Ops);
1863 break;
1864 }
1865 }
1866
SJW01901d92020-05-21 08:58:31 -05001867 if (RID.isValid()) {
alan-bakerc3fd07f2020-10-22 09:48:49 -04001868 TypeMap[Canonical] = RID;
1869 if (Ty != Canonical) {
1870 // Speed up future lookups of this type by also caching the non-canonical
1871 // type.
1872 TypeMap[Ty] = RID;
1873 }
SJWf93f5f32020-05-05 07:27:56 -05001874 }
1875 return RID;
David Neto22f144c2017-06-12 14:26:21 -04001876}
1877
SJW77b87ad2020-04-21 14:37:52 -05001878void SPIRVProducerPass::GenerateSPIRVTypes() {
David Neto22f144c2017-06-12 14:26:21 -04001879 for (Type *Ty : getTypeList()) {
SJWf93f5f32020-05-05 07:27:56 -05001880 getSPIRVType(Ty);
David Netoc6f3ab22018-04-06 18:02:31 -04001881 }
David Neto22f144c2017-06-12 14:26:21 -04001882}
1883
SJW806a5d82020-07-15 12:51:38 -05001884SPIRVID SPIRVProducerPass::getSPIRVInt32Constant(uint32_t CstVal) {
1885 Type *i32 = Type::getInt32Ty(module->getContext());
1886 Constant *Cst = ConstantInt::get(i32, CstVal);
1887 return getSPIRVValue(Cst);
1888}
1889
SJWf93f5f32020-05-05 07:27:56 -05001890SPIRVID SPIRVProducerPass::getSPIRVConstant(Constant *Cst) {
David Neto22f144c2017-06-12 14:26:21 -04001891 ValueMapType &VMap = getValueMap();
David Neto482550a2018-03-24 05:21:07 -07001892 const bool hack_undef = clspv::Option::HackUndef();
David Neto22f144c2017-06-12 14:26:21 -04001893
SJW01901d92020-05-21 08:58:31 -05001894 SPIRVID RID;
David Neto22f144c2017-06-12 14:26:21 -04001895
SJWf93f5f32020-05-05 07:27:56 -05001896 //
1897 // Generate OpConstant.
1898 //
1899 // Ops[0] = Result Type ID
1900 // Ops[1] .. Ops[n] = Values LiteralNumber
1901 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04001902
SJW01901d92020-05-21 08:58:31 -05001903 Ops << Cst->getType();
David Neto22f144c2017-06-12 14:26:21 -04001904
SJWf93f5f32020-05-05 07:27:56 -05001905 std::vector<uint32_t> LiteralNum;
1906 spv::Op Opcode = spv::OpNop;
David Neto22f144c2017-06-12 14:26:21 -04001907
SJWf93f5f32020-05-05 07:27:56 -05001908 if (isa<UndefValue>(Cst)) {
David Neto22f144c2017-06-12 14:26:21 -04001909 // Ops[0] = Result Type ID
SJWf93f5f32020-05-05 07:27:56 -05001910 Opcode = spv::OpUndef;
1911 if (hack_undef && IsTypeNullable(Cst->getType())) {
1912 Opcode = spv::OpConstantNull;
1913 }
1914 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(Cst)) {
alan-bakere2a62752020-07-09 22:53:23 -04001915 unsigned bit_width = CI->getBitWidth();
1916 if (bit_width == 1) {
SJWf93f5f32020-05-05 07:27:56 -05001917 // If the bitwidth of constant is 1, generate OpConstantTrue or
1918 // OpConstantFalse.
1919 if (CI->getZExtValue()) {
1920 // Ops[0] = Result Type ID
1921 Opcode = spv::OpConstantTrue;
David Neto22f144c2017-06-12 14:26:21 -04001922 } else {
SJWf93f5f32020-05-05 07:27:56 -05001923 // Ops[0] = Result Type ID
1924 Opcode = spv::OpConstantFalse;
David Neto22f144c2017-06-12 14:26:21 -04001925 }
SJWf93f5f32020-05-05 07:27:56 -05001926 } else {
1927 auto V = CI->getZExtValue();
1928 LiteralNum.push_back(V & 0xFFFFFFFF);
1929
alan-bakere2a62752020-07-09 22:53:23 -04001930 if (bit_width > 32) {
SJWf93f5f32020-05-05 07:27:56 -05001931 LiteralNum.push_back(V >> 32);
David Neto22f144c2017-06-12 14:26:21 -04001932 }
1933
1934 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04001935
SJW01901d92020-05-21 08:58:31 -05001936 Ops << LiteralNum;
SJWf93f5f32020-05-05 07:27:56 -05001937 }
1938 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Cst)) {
1939 uint64_t FPVal = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1940 Type *CFPTy = CFP->getType();
1941 if (CFPTy->isFloatTy()) {
1942 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
1943 } else if (CFPTy->isDoubleTy()) {
1944 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
1945 LiteralNum.push_back(FPVal >> 32);
1946 } else if (CFPTy->isHalfTy()) {
1947 LiteralNum.push_back(FPVal & 0xFFFF);
1948 } else {
1949 CFPTy->print(errs());
1950 llvm_unreachable("Implement this ConstantFP Type");
1951 }
David Neto22f144c2017-06-12 14:26:21 -04001952
SJWf93f5f32020-05-05 07:27:56 -05001953 Opcode = spv::OpConstant;
David Neto49351ac2017-08-26 17:32:20 -04001954
SJW01901d92020-05-21 08:58:31 -05001955 Ops << LiteralNum;
SJWf93f5f32020-05-05 07:27:56 -05001956 } else if (isa<ConstantDataSequential>(Cst) &&
1957 cast<ConstantDataSequential>(Cst)->isString()) {
1958 Cst->print(errs());
1959 llvm_unreachable("Implement this Constant");
David Neto49351ac2017-08-26 17:32:20 -04001960
SJWf93f5f32020-05-05 07:27:56 -05001961 } else if (const ConstantDataSequential *CDS =
1962 dyn_cast<ConstantDataSequential>(Cst)) {
1963 // Let's convert <4 x i8> constant to int constant specially.
1964 // This case occurs when all the values are specified as constant
1965 // ints.
1966 Type *CstTy = Cst->getType();
1967 if (is4xi8vec(CstTy)) {
SJWf93f5f32020-05-05 07:27:56 -05001968 //
1969 // Generate OpConstant with OpTypeInt 32 0.
1970 //
1971 uint32_t IntValue = 0;
1972 for (unsigned k = 0; k < 4; k++) {
1973 const uint64_t Val = CDS->getElementAsInteger(k);
1974 IntValue = (IntValue << 8) | (Val & 0xffu);
David Neto49351ac2017-08-26 17:32:20 -04001975 }
1976
SJW806a5d82020-07-15 12:51:38 -05001977 RID = getSPIRVInt32Constant(IntValue);
SJWf93f5f32020-05-05 07:27:56 -05001978 } else {
1979
David Neto49351ac2017-08-26 17:32:20 -04001980 // A normal constant-data-sequential case.
David Neto22f144c2017-06-12 14:26:21 -04001981 for (unsigned k = 0; k < CDS->getNumElements(); k++) {
SJW01901d92020-05-21 08:58:31 -05001982 Ops << CDS->getElementAsConstant(k);
David Neto22f144c2017-06-12 14:26:21 -04001983 }
1984
1985 Opcode = spv::OpConstantComposite;
SJWf93f5f32020-05-05 07:27:56 -05001986 }
1987 } else if (const ConstantAggregate *CA = dyn_cast<ConstantAggregate>(Cst)) {
1988 // Let's convert <4 x i8> constant to int constant specially.
1989 // This case occurs when at least one of the values is an undef.
1990 Type *CstTy = Cst->getType();
1991 if (is4xi8vec(CstTy)) {
SJWf93f5f32020-05-05 07:27:56 -05001992 //
1993 // Generate OpConstant with OpTypeInt 32 0.
1994 //
1995 uint32_t IntValue = 0;
1996 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end();
1997 I != E; ++I) {
1998 uint64_t Val = 0;
1999 const Value *CV = *I;
2000 if (auto *CI2 = dyn_cast<ConstantInt>(CV)) {
2001 Val = CI2->getZExtValue();
David Neto22f144c2017-06-12 14:26:21 -04002002 }
SJWf93f5f32020-05-05 07:27:56 -05002003 IntValue = (IntValue << 8) | (Val & 0xffu);
David Neto22f144c2017-06-12 14:26:21 -04002004 }
2005
SJW806a5d82020-07-15 12:51:38 -05002006 RID = getSPIRVInt32Constant(IntValue);
SJWf93f5f32020-05-05 07:27:56 -05002007 } else {
2008
David Neto22f144c2017-06-12 14:26:21 -04002009 // We use a constant composite in SPIR-V for our constant aggregate in
2010 // LLVM.
2011 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002012
2013 for (unsigned k = 0; k < CA->getNumOperands(); k++) {
David Neto22f144c2017-06-12 14:26:21 -04002014 // And add an operand to the composite we are constructing
SJW01901d92020-05-21 08:58:31 -05002015 Ops << CA->getAggregateElement(k);
David Neto22f144c2017-06-12 14:26:21 -04002016 }
David Neto22f144c2017-06-12 14:26:21 -04002017 }
SJWf93f5f32020-05-05 07:27:56 -05002018 } else if (Cst->isNullValue()) {
2019 Opcode = spv::OpConstantNull;
2020 } else {
2021 Cst->print(errs());
2022 llvm_unreachable("Unsupported Constant???");
2023 }
David Neto22f144c2017-06-12 14:26:21 -04002024
SJWf93f5f32020-05-05 07:27:56 -05002025 if (Opcode == spv::OpConstantNull && Cst->getType()->isPointerTy()) {
2026 // Null pointer requires variable pointers.
2027 setVariablePointersCapabilities(Cst->getType()->getPointerAddressSpace());
2028 }
alan-baker5b86ed72019-02-15 08:26:50 -05002029
SJWf93f5f32020-05-05 07:27:56 -05002030 if (RID == 0) {
2031 RID = addSPIRVInst<kConstants>(Opcode, Ops);
2032 }
2033
2034 VMap[Cst] = RID;
2035
2036 return RID;
2037}
2038
2039SPIRVID SPIRVProducerPass::getSPIRVValue(Value *V) {
2040 auto II = ValueMap.find(V);
2041 if (II != ValueMap.end()) {
SJW01901d92020-05-21 08:58:31 -05002042 assert(II->second.isValid());
SJWf93f5f32020-05-05 07:27:56 -05002043 return II->second;
2044 }
2045 if (Constant *Cst = dyn_cast<Constant>(V)) {
2046 return getSPIRVConstant(Cst);
2047 } else {
2048 llvm_unreachable("Variable not found");
2049 }
2050}
2051
SJW77b87ad2020-04-21 14:37:52 -05002052void SPIRVProducerPass::GenerateSamplers() {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002053 auto &sampler_map = getSamplerMap();
alan-baker09cb9802019-12-10 13:16:27 -05002054 SamplerLiteralToIDMap.clear();
David Neto862b7d82018-06-14 18:48:37 -04002055 DenseMap<unsigned, unsigned> SamplerLiteralToDescriptorSetMap;
2056 DenseMap<unsigned, unsigned> SamplerLiteralToBindingMap;
David Neto22f144c2017-06-12 14:26:21 -04002057
David Neto862b7d82018-06-14 18:48:37 -04002058 // We might have samplers in the sampler map that are not used
2059 // in the translation unit. We need to allocate variables
2060 // for them and bindings too.
2061 DenseSet<unsigned> used_bindings;
David Neto22f144c2017-06-12 14:26:21 -04002062
SJW77b87ad2020-04-21 14:37:52 -05002063 auto *var_fn = module->getFunction(clspv::LiteralSamplerFunction());
alan-baker09cb9802019-12-10 13:16:27 -05002064 // Return if there are no literal samplers.
alan-bakerb6b09dc2018-11-08 16:59:28 -05002065 if (!var_fn)
2066 return;
alan-baker09cb9802019-12-10 13:16:27 -05002067
David Neto862b7d82018-06-14 18:48:37 -04002068 for (auto user : var_fn->users()) {
2069 // Populate SamplerLiteralToDescriptorSetMap and
2070 // SamplerLiteralToBindingMap.
2071 //
2072 // Look for calls like
2073 // call %opencl.sampler_t addrspace(2)*
2074 // @clspv.sampler.var.literal(
2075 // i32 descriptor,
2076 // i32 binding,
alan-baker09cb9802019-12-10 13:16:27 -05002077 // i32 (index-into-sampler-map|sampler_mask))
alan-bakerb6b09dc2018-11-08 16:59:28 -05002078 if (auto *call = dyn_cast<CallInst>(user)) {
alan-baker09cb9802019-12-10 13:16:27 -05002079 const auto third_param = static_cast<unsigned>(
alan-bakerb6b09dc2018-11-08 16:59:28 -05002080 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
alan-baker09cb9802019-12-10 13:16:27 -05002081 auto sampler_value = third_param;
2082 if (clspv::Option::UseSamplerMap()) {
2083 if (third_param >= sampler_map.size()) {
2084 errs() << "Out of bounds index to sampler map: " << third_param;
2085 llvm_unreachable("bad sampler init: out of bounds");
2086 }
2087 sampler_value = sampler_map[third_param].first;
David Neto862b7d82018-06-14 18:48:37 -04002088 }
2089
David Neto862b7d82018-06-14 18:48:37 -04002090 const auto descriptor_set = static_cast<unsigned>(
2091 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
2092 const auto binding = static_cast<unsigned>(
2093 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
2094
2095 SamplerLiteralToDescriptorSetMap[sampler_value] = descriptor_set;
2096 SamplerLiteralToBindingMap[sampler_value] = binding;
2097 used_bindings.insert(binding);
2098 }
2099 }
2100
alan-baker09cb9802019-12-10 13:16:27 -05002101 DenseSet<size_t> seen;
2102 for (auto user : var_fn->users()) {
2103 if (!isa<CallInst>(user))
2104 continue;
2105
2106 auto call = cast<CallInst>(user);
2107 const unsigned third_param = static_cast<unsigned>(
2108 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
2109
2110 // Already allocated a variable for this value.
2111 if (!seen.insert(third_param).second)
2112 continue;
2113
2114 auto sampler_value = third_param;
2115 if (clspv::Option::UseSamplerMap()) {
2116 sampler_value = sampler_map[third_param].first;
2117 }
2118
SJW806a5d82020-07-15 12:51:38 -05002119 auto sampler_var_id = addSPIRVGlobalVariable(
2120 getSPIRVType(SamplerTy), spv::StorageClassUniformConstant);
David Neto22f144c2017-06-12 14:26:21 -04002121
alan-baker09cb9802019-12-10 13:16:27 -05002122 SamplerLiteralToIDMap[sampler_value] = sampler_var_id;
David Neto22f144c2017-06-12 14:26:21 -04002123
David Neto862b7d82018-06-14 18:48:37 -04002124 unsigned descriptor_set;
2125 unsigned binding;
alan-baker09cb9802019-12-10 13:16:27 -05002126 if (SamplerLiteralToBindingMap.find(sampler_value) ==
alan-bakerb6b09dc2018-11-08 16:59:28 -05002127 SamplerLiteralToBindingMap.end()) {
David Neto862b7d82018-06-14 18:48:37 -04002128 // This sampler is not actually used. Find the next one.
alan-baker7506abb2020-09-10 15:02:55 -04002129 for (binding = 0; used_bindings.count(binding); binding++) {
2130 }
David Neto862b7d82018-06-14 18:48:37 -04002131 descriptor_set = 0; // Literal samplers always use descriptor set 0.
2132 used_bindings.insert(binding);
2133 } else {
alan-baker09cb9802019-12-10 13:16:27 -05002134 descriptor_set = SamplerLiteralToDescriptorSetMap[sampler_value];
2135 binding = SamplerLiteralToBindingMap[sampler_value];
alan-bakercff80152019-06-15 00:38:00 -04002136
alan-baker86ce19c2020-08-05 13:09:19 -04002137 auto import_id = getReflectionImport();
2138 SPIRVOperandVec Ops;
2139 Ops << getSPIRVType(Type::getVoidTy(module->getContext())) << import_id
2140 << reflection::ExtInstLiteralSampler
2141 << getSPIRVInt32Constant(descriptor_set)
2142 << getSPIRVInt32Constant(binding)
2143 << getSPIRVInt32Constant(sampler_value);
2144 addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
David Neto862b7d82018-06-14 18:48:37 -04002145 }
2146
SJW69939d52020-04-16 07:29:07 -05002147 // Ops[0] = Target ID
2148 // Ops[1] = Decoration (DescriptorSet)
2149 // Ops[2] = LiteralNumber according to Decoration
SJW806a5d82020-07-15 12:51:38 -05002150 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05002151 Ops << sampler_var_id << spv::DecorationDescriptorSet << descriptor_set;
David Neto22f144c2017-06-12 14:26:21 -04002152
SJWf93f5f32020-05-05 07:27:56 -05002153 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002154
2155 // Ops[0] = Target ID
2156 // Ops[1] = Decoration (Binding)
2157 // Ops[2] = LiteralNumber according to Decoration
2158 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002159 Ops << sampler_var_id << spv::DecorationBinding << binding;
David Neto22f144c2017-06-12 14:26:21 -04002160
SJWf93f5f32020-05-05 07:27:56 -05002161 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002162 }
David Neto862b7d82018-06-14 18:48:37 -04002163}
David Neto22f144c2017-06-12 14:26:21 -04002164
SJW77b87ad2020-04-21 14:37:52 -05002165void SPIRVProducerPass::GenerateResourceVars() {
David Neto862b7d82018-06-14 18:48:37 -04002166 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04002167
David Neto862b7d82018-06-14 18:48:37 -04002168 // Generate variables. Make one for each of resource var info object.
2169 for (auto *info : ModuleOrderedResourceVars) {
2170 Type *type = info->var_fn->getReturnType();
2171 // Remap the address space for opaque types.
2172 switch (info->arg_kind) {
2173 case clspv::ArgKind::Sampler:
alan-bakerf6bc8252020-09-23 14:58:55 -04002174 case clspv::ArgKind::SampledImage:
2175 case clspv::ArgKind::StorageImage:
David Neto862b7d82018-06-14 18:48:37 -04002176 type = PointerType::get(type->getPointerElementType(),
2177 clspv::AddressSpace::UniformConstant);
2178 break;
2179 default:
2180 break;
2181 }
David Neto22f144c2017-06-12 14:26:21 -04002182
David Neto862b7d82018-06-14 18:48:37 -04002183 const auto sc = GetStorageClassForArgKind(info->arg_kind);
David Neto22f144c2017-06-12 14:26:21 -04002184
SJW806a5d82020-07-15 12:51:38 -05002185 info->var_id = addSPIRVGlobalVariable(getSPIRVType(type), sc);
David Neto862b7d82018-06-14 18:48:37 -04002186
2187 // Map calls to the variable-builtin-function.
2188 for (auto &U : info->var_fn->uses()) {
2189 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
2190 const auto set = unsigned(
2191 dyn_cast<ConstantInt>(call->getOperand(0))->getZExtValue());
2192 const auto binding = unsigned(
2193 dyn_cast<ConstantInt>(call->getOperand(1))->getZExtValue());
2194 if (set == info->descriptor_set && binding == info->binding) {
2195 switch (info->arg_kind) {
2196 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002197 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002198 case clspv::ArgKind::Pod:
alan-baker9b0ec3c2020-04-06 14:45:34 -04002199 case clspv::ArgKind::PodUBO:
2200 case clspv::ArgKind::PodPushConstant:
David Neto862b7d82018-06-14 18:48:37 -04002201 // The call maps to the variable directly.
2202 VMap[call] = info->var_id;
2203 break;
2204 case clspv::ArgKind::Sampler:
alan-bakerf6bc8252020-09-23 14:58:55 -04002205 case clspv::ArgKind::SampledImage:
2206 case clspv::ArgKind::StorageImage:
David Neto862b7d82018-06-14 18:48:37 -04002207 // The call maps to a load we generate later.
2208 ResourceVarDeferredLoadCalls[call] = info->var_id;
2209 break;
2210 default:
2211 llvm_unreachable("Unhandled arg kind");
2212 }
2213 }
David Neto22f144c2017-06-12 14:26:21 -04002214 }
David Neto862b7d82018-06-14 18:48:37 -04002215 }
2216 }
David Neto22f144c2017-06-12 14:26:21 -04002217
David Neto862b7d82018-06-14 18:48:37 -04002218 // Generate associated decorations.
SJWf93f5f32020-05-05 07:27:56 -05002219 SPIRVOperandVec Ops;
David Neto862b7d82018-06-14 18:48:37 -04002220 for (auto *info : ModuleOrderedResourceVars) {
alan-baker9b0ec3c2020-04-06 14:45:34 -04002221 // Push constants don't need descriptor set or binding decorations.
2222 if (info->arg_kind == clspv::ArgKind::PodPushConstant)
2223 continue;
2224
David Neto862b7d82018-06-14 18:48:37 -04002225 // Decorate with DescriptorSet and Binding.
2226 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002227 Ops << info->var_id << spv::DecorationDescriptorSet << info->descriptor_set;
SJWf93f5f32020-05-05 07:27:56 -05002228 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto862b7d82018-06-14 18:48:37 -04002229
2230 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002231 Ops << info->var_id << spv::DecorationBinding << info->binding;
SJWf93f5f32020-05-05 07:27:56 -05002232 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto862b7d82018-06-14 18:48:37 -04002233
alan-bakere9308012019-03-15 10:25:13 -04002234 if (info->coherent) {
2235 // Decorate with Coherent if required for the variable.
2236 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002237 Ops << info->var_id << spv::DecorationCoherent;
SJWf93f5f32020-05-05 07:27:56 -05002238 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
alan-bakere9308012019-03-15 10:25:13 -04002239 }
2240
David Neto862b7d82018-06-14 18:48:37 -04002241 // Generate NonWritable and NonReadable
2242 switch (info->arg_kind) {
2243 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002244 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002245 if (info->var_fn->getReturnType()->getPointerAddressSpace() ==
2246 clspv::AddressSpace::Constant) {
2247 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002248 Ops << info->var_id << spv::DecorationNonWritable;
SJWf93f5f32020-05-05 07:27:56 -05002249 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002250 }
David Neto862b7d82018-06-14 18:48:37 -04002251 break;
alan-bakerf6bc8252020-09-23 14:58:55 -04002252 case clspv::ArgKind::StorageImage: {
2253 auto *type = info->var_fn->getReturnType();
2254 auto *struct_ty = cast<StructType>(type->getPointerElementType());
2255 // TODO(alan-baker): This is conservative. If compiling for OpenCL 2.0 or
2256 // above, the compiler treats all write_only images as read_write images.
2257 if (struct_ty->getName().contains("_wo_t")) {
2258 Ops.clear();
2259 Ops << info->var_id << spv::DecorationNonReadable;
2260 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
2261 }
David Neto862b7d82018-06-14 18:48:37 -04002262 break;
alan-bakerf6bc8252020-09-23 14:58:55 -04002263 }
David Neto862b7d82018-06-14 18:48:37 -04002264 default:
2265 break;
David Neto22f144c2017-06-12 14:26:21 -04002266 }
2267 }
2268}
2269
2270void SPIRVProducerPass::GenerateGlobalVar(GlobalVariable &GV) {
David Neto22f144c2017-06-12 14:26:21 -04002271 ValueMapType &VMap = getValueMap();
SJW01901d92020-05-21 08:58:31 -05002272 std::vector<SPIRVID> &BuiltinDimVec = getBuiltinDimVec();
David Neto85082642018-03-24 06:55:20 -07002273 const DataLayout &DL = GV.getParent()->getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04002274
2275 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
2276 Type *Ty = GV.getType();
2277 PointerType *PTy = cast<PointerType>(Ty);
2278
SJW01901d92020-05-21 08:58:31 -05002279 SPIRVID InitializerID;
David Neto22f144c2017-06-12 14:26:21 -04002280
2281 // Workgroup size is handled differently (it goes into a constant)
2282 if (spv::BuiltInWorkgroupSize == BuiltinType) {
David Neto22f144c2017-06-12 14:26:21 -04002283 uint32_t PrevXDimCst = 0xFFFFFFFF;
2284 uint32_t PrevYDimCst = 0xFFFFFFFF;
2285 uint32_t PrevZDimCst = 0xFFFFFFFF;
alan-baker3b609772020-09-03 19:10:17 -04002286 bool HasMD = true;
David Neto22f144c2017-06-12 14:26:21 -04002287 for (Function &Func : *GV.getParent()) {
2288 if (Func.isDeclaration()) {
2289 continue;
2290 }
2291
2292 // We only need to check kernels.
2293 if (Func.getCallingConv() != CallingConv::SPIR_KERNEL) {
2294 continue;
2295 }
2296
2297 if (const MDNode *MD =
2298 dyn_cast<Function>(&Func)->getMetadata("reqd_work_group_size")) {
2299 uint32_t CurXDimCst = static_cast<uint32_t>(
2300 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
2301 uint32_t CurYDimCst = static_cast<uint32_t>(
2302 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
2303 uint32_t CurZDimCst = static_cast<uint32_t>(
2304 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
2305
2306 if (PrevXDimCst == 0xFFFFFFFF && PrevYDimCst == 0xFFFFFFFF &&
2307 PrevZDimCst == 0xFFFFFFFF) {
2308 PrevXDimCst = CurXDimCst;
2309 PrevYDimCst = CurYDimCst;
2310 PrevZDimCst = CurZDimCst;
2311 } else if (CurXDimCst != PrevXDimCst || CurYDimCst != PrevYDimCst ||
2312 CurZDimCst != PrevZDimCst) {
alan-baker3b609772020-09-03 19:10:17 -04002313 HasMD = false;
2314 continue;
David Neto22f144c2017-06-12 14:26:21 -04002315 } else {
2316 continue;
2317 }
2318
2319 //
2320 // Generate OpConstantComposite.
2321 //
2322 // Ops[0] : Result Type ID
2323 // Ops[1] : Constant size for x dimension.
2324 // Ops[2] : Constant size for y dimension.
2325 // Ops[3] : Constant size for z dimension.
SJWf93f5f32020-05-05 07:27:56 -05002326 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04002327
SJW01901d92020-05-21 08:58:31 -05002328 SPIRVID XDimCstID =
SJWf93f5f32020-05-05 07:27:56 -05002329 getSPIRVValue(mdconst::extract<ConstantInt>(MD->getOperand(0)));
SJW01901d92020-05-21 08:58:31 -05002330 SPIRVID YDimCstID =
SJWf93f5f32020-05-05 07:27:56 -05002331 getSPIRVValue(mdconst::extract<ConstantInt>(MD->getOperand(1)));
SJW01901d92020-05-21 08:58:31 -05002332 SPIRVID ZDimCstID =
SJWf93f5f32020-05-05 07:27:56 -05002333 getSPIRVValue(mdconst::extract<ConstantInt>(MD->getOperand(2)));
David Neto22f144c2017-06-12 14:26:21 -04002334
SJW01901d92020-05-21 08:58:31 -05002335 Ops << Ty->getPointerElementType() << XDimCstID << YDimCstID
2336 << ZDimCstID;
David Neto22f144c2017-06-12 14:26:21 -04002337
SJWf93f5f32020-05-05 07:27:56 -05002338 InitializerID =
2339 addSPIRVInst<kGlobalVariables>(spv::OpConstantComposite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002340 } else {
alan-baker3b609772020-09-03 19:10:17 -04002341 HasMD = false;
David Neto22f144c2017-06-12 14:26:21 -04002342 }
2343 }
2344
2345 // If all kernels do not have metadata for reqd_work_group_size, generate
2346 // OpSpecConstants for x/y/z dimension.
Kévin Petit21c23c62020-04-29 01:38:28 +01002347 if (!HasMD || clspv::Option::NonUniformNDRangeSupported()) {
David Neto22f144c2017-06-12 14:26:21 -04002348 //
2349 // Generate OpSpecConstants for x/y/z dimension.
2350 //
2351 // Ops[0] : Result Type ID
2352 // Ops[1] : Constant size for x/y/z dimension (Literal Number).
David Neto22f144c2017-06-12 14:26:21 -04002353
alan-bakera1be3322020-04-20 12:48:18 -04002354 // Allocate spec constants for workgroup size.
SJW77b87ad2020-04-21 14:37:52 -05002355 clspv::AddWorkgroupSpecConstants(module);
alan-bakera1be3322020-04-20 12:48:18 -04002356
SJWf93f5f32020-05-05 07:27:56 -05002357 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05002358 SPIRVID result_type_id = getSPIRVType(
SJWf93f5f32020-05-05 07:27:56 -05002359 dyn_cast<VectorType>(Ty->getPointerElementType())->getElementType());
David Neto22f144c2017-06-12 14:26:21 -04002360
David Neto257c3892018-04-11 13:19:45 -04002361 // X Dimension
SJW01901d92020-05-21 08:58:31 -05002362 Ops << result_type_id << 1;
2363 SPIRVID XDimCstID = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002364
2365 // Y Dimension
2366 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002367 Ops << result_type_id << 1;
2368 SPIRVID YDimCstID = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002369
2370 // Z Dimension
2371 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002372 Ops << result_type_id << 1;
2373 SPIRVID ZDimCstID = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002374
David Neto257c3892018-04-11 13:19:45 -04002375 BuiltinDimVec.push_back(XDimCstID);
2376 BuiltinDimVec.push_back(YDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002377 BuiltinDimVec.push_back(ZDimCstID);
2378
David Neto22f144c2017-06-12 14:26:21 -04002379 //
2380 // Generate OpSpecConstantComposite.
2381 //
2382 // Ops[0] : Result Type ID
2383 // Ops[1] : Constant size for x dimension.
2384 // Ops[2] : Constant size for y dimension.
2385 // Ops[3] : Constant size for z dimension.
David Neto22f144c2017-06-12 14:26:21 -04002386 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002387 Ops << Ty->getPointerElementType() << XDimCstID << YDimCstID << ZDimCstID;
David Neto22f144c2017-06-12 14:26:21 -04002388
SJWf93f5f32020-05-05 07:27:56 -05002389 InitializerID =
2390 addSPIRVInst<kConstants>(spv::OpSpecConstantComposite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002391 }
alan-bakerbed3a882020-04-21 14:42:41 -04002392 } else if (BuiltinType == spv::BuiltInWorkDim) {
2393 // 1. Generate a specialization constant with a default of 3.
2394 // 2. Allocate and annotate a SpecId for the constant.
2395 // 3. Use the spec constant as the initializer for the variable.
SJWf93f5f32020-05-05 07:27:56 -05002396 SPIRVOperandVec Ops;
alan-bakerbed3a882020-04-21 14:42:41 -04002397
2398 //
2399 // Generate OpSpecConstant.
2400 //
2401 // Ops[0] : Result Type ID
2402 // Ops[1] : Default literal value
alan-bakerbed3a882020-04-21 14:42:41 -04002403
SJW01901d92020-05-21 08:58:31 -05002404 Ops << IntegerType::get(GV.getContext(), 32) << 3;
alan-bakerbed3a882020-04-21 14:42:41 -04002405
SJWf93f5f32020-05-05 07:27:56 -05002406 InitializerID = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
alan-bakerbed3a882020-04-21 14:42:41 -04002407
2408 //
2409 // Generate SpecId decoration.
2410 //
2411 // Ops[0] : target
2412 // Ops[1] : decoration
2413 // Ops[2] : SpecId
Alan Baker75ccc252020-04-21 17:11:52 -04002414 auto spec_id = AllocateSpecConstant(module, SpecConstant::kWorkDim);
alan-bakerbed3a882020-04-21 14:42:41 -04002415 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002416 Ops << InitializerID << spv::DecorationSpecId << spec_id;
alan-bakerbed3a882020-04-21 14:42:41 -04002417
SJWf93f5f32020-05-05 07:27:56 -05002418 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002419 } else if (BuiltinType == spv::BuiltInGlobalOffset) {
2420 // 1. Generate a spec constant with a default of {0, 0, 0}.
2421 // 2. Allocate and annotate SpecIds for the constants.
2422 // 3. Use the spec constant as the initializer for the variable.
SJWf93f5f32020-05-05 07:27:56 -05002423 SPIRVOperandVec Ops;
alan-bakere1996972020-05-04 08:38:12 -04002424
2425 //
2426 // Generate OpSpecConstant for each dimension.
2427 //
2428 // Ops[0] : Result Type ID
2429 // Ops[1] : Default literal value
2430 //
SJW01901d92020-05-21 08:58:31 -05002431 Ops << IntegerType::get(GV.getContext(), 32) << 0;
2432 SPIRVID x_id = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002433
alan-bakere1996972020-05-04 08:38:12 -04002434 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002435 Ops << IntegerType::get(GV.getContext(), 32) << 0;
2436 SPIRVID y_id = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002437
alan-bakere1996972020-05-04 08:38:12 -04002438 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002439 Ops << IntegerType::get(GV.getContext(), 32) << 0;
2440 SPIRVID z_id = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002441
2442 //
2443 // Generate SpecId decoration for each dimension.
2444 //
2445 // Ops[0] : target
2446 // Ops[1] : decoration
2447 // Ops[2] : SpecId
2448 //
2449 auto spec_id = AllocateSpecConstant(module, SpecConstant::kGlobalOffsetX);
2450 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002451 Ops << x_id << spv::DecorationSpecId << spec_id;
SJWf93f5f32020-05-05 07:27:56 -05002452 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002453
2454 spec_id = AllocateSpecConstant(module, SpecConstant::kGlobalOffsetY);
2455 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002456 Ops << y_id << spv::DecorationSpecId << spec_id;
SJWf93f5f32020-05-05 07:27:56 -05002457 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002458
2459 spec_id = AllocateSpecConstant(module, SpecConstant::kGlobalOffsetZ);
2460 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002461 Ops << z_id << spv::DecorationSpecId << spec_id;
SJWf93f5f32020-05-05 07:27:56 -05002462 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002463
2464 //
2465 // Generate OpSpecConstantComposite.
2466 //
2467 // Ops[0] : type id
2468 // Ops[1..n-1] : elements
2469 //
alan-bakere1996972020-05-04 08:38:12 -04002470 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002471 Ops << GV.getType()->getPointerElementType() << x_id << y_id << z_id;
SJWf93f5f32020-05-05 07:27:56 -05002472 InitializerID = addSPIRVInst<kConstants>(spv::OpSpecConstantComposite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002473 }
2474
David Neto85082642018-03-24 06:55:20 -07002475 const auto AS = PTy->getAddressSpace();
SJW806a5d82020-07-15 12:51:38 -05002476 const auto spvSC = GetStorageClass(AS);
David Neto22f144c2017-06-12 14:26:21 -04002477
David Neto85082642018-03-24 06:55:20 -07002478 const bool module_scope_constant_external_init =
David Neto862b7d82018-06-14 18:48:37 -04002479 (AS == AddressSpace::Constant) && GV.hasInitializer() &&
David Neto85082642018-03-24 06:55:20 -07002480 clspv::Option::ModuleConstantsInStorageBuffer();
2481
Kévin Petit23d5f182019-08-13 16:21:29 +01002482 if (GV.hasInitializer()) {
2483 auto GVInit = GV.getInitializer();
2484 if (!isa<UndefValue>(GVInit) && !module_scope_constant_external_init) {
SJWf93f5f32020-05-05 07:27:56 -05002485 InitializerID = getSPIRVValue(GVInit);
David Neto85082642018-03-24 06:55:20 -07002486 }
2487 }
Kévin Petit23d5f182019-08-13 16:21:29 +01002488
SJW806a5d82020-07-15 12:51:38 -05002489 SPIRVID var_id =
2490 addSPIRVGlobalVariable(getSPIRVType(Ty), spvSC, InitializerID);
David Neto85082642018-03-24 06:55:20 -07002491
SJWf93f5f32020-05-05 07:27:56 -05002492 VMap[&GV] = var_id;
David Neto22f144c2017-06-12 14:26:21 -04002493
alan-bakere1996972020-05-04 08:38:12 -04002494 auto IsOpenCLBuiltin = [](spv::BuiltIn builtin) {
2495 return builtin == spv::BuiltInWorkDim ||
2496 builtin == spv::BuiltInGlobalOffset;
2497 };
2498
alan-bakere1996972020-05-04 08:38:12 -04002499 // If we have a builtin (not an OpenCL builtin).
2500 if (spv::BuiltInMax != BuiltinType && !IsOpenCLBuiltin(BuiltinType)) {
David Neto22f144c2017-06-12 14:26:21 -04002501 //
2502 // Generate OpDecorate.
2503 //
2504 // DOps[0] = Target ID
2505 // DOps[1] = Decoration (Builtin)
2506 // DOps[2] = BuiltIn ID
SJW01901d92020-05-21 08:58:31 -05002507 SPIRVID ResultID;
David Neto22f144c2017-06-12 14:26:21 -04002508
2509 // WorkgroupSize is different, we decorate the constant composite that has
2510 // its value, rather than the variable that we use to access the value.
2511 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2512 ResultID = InitializerID;
David Netoa60b00b2017-09-15 16:34:09 -04002513 // Save both the value and variable IDs for later.
2514 WorkgroupSizeValueID = InitializerID;
SJWf93f5f32020-05-05 07:27:56 -05002515 WorkgroupSizeVarID = getSPIRVValue(&GV);
David Neto22f144c2017-06-12 14:26:21 -04002516 } else {
SJWf93f5f32020-05-05 07:27:56 -05002517 ResultID = getSPIRVValue(&GV);
David Neto22f144c2017-06-12 14:26:21 -04002518 }
2519
SJW806a5d82020-07-15 12:51:38 -05002520 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05002521 Ops << ResultID << spv::DecorationBuiltIn << BuiltinType;
David Neto22f144c2017-06-12 14:26:21 -04002522
SJW01901d92020-05-21 08:58:31 -05002523 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto85082642018-03-24 06:55:20 -07002524 } else if (module_scope_constant_external_init) {
2525 // This module scope constant is initialized from a storage buffer with data
2526 // provided by the host at binding 0 of the next descriptor set.
SJW77b87ad2020-04-21 14:37:52 -05002527 const uint32_t descriptor_set = TakeDescriptorIndex(module);
David Neto85082642018-03-24 06:55:20 -07002528
alan-baker86ce19c2020-08-05 13:09:19 -04002529 // Emit the intializer as a reflection instruction.
David Neto85082642018-03-24 06:55:20 -07002530 // Use "kind,buffer" to indicate storage buffer. We might want to expand
2531 // that later to other types, like uniform buffer.
alan-bakerf5e5f692018-11-27 08:33:24 -05002532 std::string hexbytes;
2533 llvm::raw_string_ostream str(hexbytes);
2534 clspv::ConstantEmitter(DL, str).Emit(GV.getInitializer());
alan-baker86ce19c2020-08-05 13:09:19 -04002535
2536 // Reflection instruction for constant data.
2537 SPIRVOperandVec Ops;
2538 auto data_id = addSPIRVInst<kDebug>(spv::OpString, str.str().c_str());
2539 Ops << getSPIRVType(Type::getVoidTy(module->getContext()))
2540 << getReflectionImport() << reflection::ExtInstConstantDataStorageBuffer
2541 << getSPIRVInt32Constant(descriptor_set) << getSPIRVInt32Constant(0)
2542 << data_id;
2543 addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
David Neto85082642018-03-24 06:55:20 -07002544
David Neto85082642018-03-24 06:55:20 -07002545 // OpDecorate %var DescriptorSet <descriptor_set>
alan-baker86ce19c2020-08-05 13:09:19 -04002546 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002547 Ops << var_id << spv::DecorationDescriptorSet << descriptor_set;
2548 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
SJW69939d52020-04-16 07:29:07 -05002549
2550 // OpDecorate %var Binding <binding>
SJW01901d92020-05-21 08:58:31 -05002551 Ops.clear();
2552 Ops << var_id << spv::DecorationBinding << 0;
2553 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Netoc6f3ab22018-04-06 18:02:31 -04002554 }
2555}
2556
David Neto22f144c2017-06-12 14:26:21 -04002557void SPIRVProducerPass::GenerateFuncPrologue(Function &F) {
David Neto22f144c2017-06-12 14:26:21 -04002558 ValueMapType &VMap = getValueMap();
2559 EntryPointVecType &EntryPoints = getEntryPointVec();
David Neto22f144c2017-06-12 14:26:21 -04002560 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
2561 auto &GlobalConstArgSet = getGlobalConstArgSet();
2562
2563 FunctionType *FTy = F.getFunctionType();
2564
2565 //
David Neto22f144c2017-06-12 14:26:21 -04002566 // Generate OPFunction.
2567 //
2568
2569 // FOps[0] : Result Type ID
2570 // FOps[1] : Function Control
2571 // FOps[2] : Function Type ID
SJWf93f5f32020-05-05 07:27:56 -05002572 SPIRVOperandVec FOps;
David Neto22f144c2017-06-12 14:26:21 -04002573
2574 // Find SPIRV instruction for return type.
SJW01901d92020-05-21 08:58:31 -05002575 FOps << FTy->getReturnType();
David Neto22f144c2017-06-12 14:26:21 -04002576
2577 // Check function attributes for SPIRV Function Control.
2578 uint32_t FuncControl = spv::FunctionControlMaskNone;
2579 if (F.hasFnAttribute(Attribute::AlwaysInline)) {
2580 FuncControl |= spv::FunctionControlInlineMask;
2581 }
2582 if (F.hasFnAttribute(Attribute::NoInline)) {
2583 FuncControl |= spv::FunctionControlDontInlineMask;
2584 }
2585 // TODO: Check llvm attribute for Function Control Pure.
2586 if (F.hasFnAttribute(Attribute::ReadOnly)) {
2587 FuncControl |= spv::FunctionControlPureMask;
2588 }
2589 // TODO: Check llvm attribute for Function Control Const.
2590 if (F.hasFnAttribute(Attribute::ReadNone)) {
2591 FuncControl |= spv::FunctionControlConstMask;
2592 }
2593
SJW01901d92020-05-21 08:58:31 -05002594 FOps << FuncControl;
David Neto22f144c2017-06-12 14:26:21 -04002595
SJW01901d92020-05-21 08:58:31 -05002596 SPIRVID FTyID;
David Neto22f144c2017-06-12 14:26:21 -04002597 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
2598 SmallVector<Type *, 4> NewFuncParamTys;
2599 FunctionType *NewFTy =
2600 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
SJWf93f5f32020-05-05 07:27:56 -05002601 FTyID = getSPIRVType(NewFTy);
David Neto22f144c2017-06-12 14:26:21 -04002602 } else {
David Neto9ed8e2f2018-03-24 06:47:24 -07002603 // Handle regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04002604 if (GlobalConstFuncTyMap.count(FTy)) {
SJWf93f5f32020-05-05 07:27:56 -05002605 FTyID = getSPIRVType(GlobalConstFuncTyMap[FTy].first);
David Neto22f144c2017-06-12 14:26:21 -04002606 } else {
SJWf93f5f32020-05-05 07:27:56 -05002607 FTyID = getSPIRVType(FTy);
David Neto22f144c2017-06-12 14:26:21 -04002608 }
2609 }
2610
SJW01901d92020-05-21 08:58:31 -05002611 FOps << FTyID;
David Neto22f144c2017-06-12 14:26:21 -04002612
SJWf93f5f32020-05-05 07:27:56 -05002613 // Generate SPIRV instruction for function.
2614 SPIRVID FID = addSPIRVInst(spv::OpFunction, FOps);
2615 VMap[&F] = FID;
David Neto22f144c2017-06-12 14:26:21 -04002616
SJWf93f5f32020-05-05 07:27:56 -05002617 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
2618 EntryPoints.push_back(std::make_pair(&F, FID));
2619 }
David Neto22f144c2017-06-12 14:26:21 -04002620
David Neto482550a2018-03-24 05:21:07 -07002621 if (clspv::Option::ShowIDs()) {
SJW01901d92020-05-21 08:58:31 -05002622 errs() << "Function " << F.getName() << " is " << FID.get() << "\n";
David Netob05675d2018-02-16 12:37:49 -05002623 }
David Neto22f144c2017-06-12 14:26:21 -04002624
2625 //
2626 // Generate OpFunctionParameter for Normal function.
2627 //
David Neto22f144c2017-06-12 14:26:21 -04002628 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
alan-bakere9308012019-03-15 10:25:13 -04002629
David Neto22f144c2017-06-12 14:26:21 -04002630 // Iterate Argument for name instead of param type from function type.
2631 unsigned ArgIdx = 0;
2632 for (Argument &Arg : F.args()) {
David Neto22f144c2017-06-12 14:26:21 -04002633 // ParamOps[0] : Result Type ID
SJW01901d92020-05-21 08:58:31 -05002634 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04002635
2636 // Find SPIRV instruction for parameter type.
SJW01901d92020-05-21 08:58:31 -05002637 SPIRVID ParamTyID = getSPIRVType(Arg.getType());
David Neto22f144c2017-06-12 14:26:21 -04002638 if (PointerType *PTy = dyn_cast<PointerType>(Arg.getType())) {
2639 if (GlobalConstFuncTyMap.count(FTy)) {
2640 if (ArgIdx == GlobalConstFuncTyMap[FTy].second) {
2641 Type *EleTy = PTy->getPointerElementType();
2642 Type *ArgTy =
2643 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
SJWf93f5f32020-05-05 07:27:56 -05002644 ParamTyID = getSPIRVType(ArgTy);
David Neto22f144c2017-06-12 14:26:21 -04002645 GlobalConstArgSet.insert(&Arg);
2646 }
2647 }
2648 }
SJW01901d92020-05-21 08:58:31 -05002649 Ops << ParamTyID;
David Neto22f144c2017-06-12 14:26:21 -04002650
2651 // Generate SPIRV instruction for parameter.
SJW01901d92020-05-21 08:58:31 -05002652 SPIRVID param_id = addSPIRVInst(spv::OpFunctionParameter, Ops);
SJWf93f5f32020-05-05 07:27:56 -05002653 VMap[&Arg] = param_id;
2654
2655 if (CalledWithCoherentResource(Arg)) {
2656 // If the arg is passed a coherent resource ever, then decorate this
2657 // parameter with Coherent too.
SJW01901d92020-05-21 08:58:31 -05002658 Ops.clear();
2659 Ops << param_id << spv::DecorationCoherent;
2660 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
SJWf93f5f32020-05-05 07:27:56 -05002661 }
David Neto22f144c2017-06-12 14:26:21 -04002662
2663 ArgIdx++;
2664 }
2665 }
2666}
2667
SJW77b87ad2020-04-21 14:37:52 -05002668void SPIRVProducerPass::GenerateModuleInfo() {
David Neto22f144c2017-06-12 14:26:21 -04002669 EntryPointVecType &EntryPoints = getEntryPointVec();
SJW806a5d82020-07-15 12:51:38 -05002670 auto &EntryPointInterfaces = getEntryPointInterfacesList();
SJW01901d92020-05-21 08:58:31 -05002671 std::vector<SPIRVID> &BuiltinDimVec = getBuiltinDimVec();
David Neto22f144c2017-06-12 14:26:21 -04002672
SJWf93f5f32020-05-05 07:27:56 -05002673 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04002674
SJW01901d92020-05-21 08:58:31 -05002675 for (auto Capability : CapabilitySet) {
David Neto22f144c2017-06-12 14:26:21 -04002676 //
SJW01901d92020-05-21 08:58:31 -05002677 // Generate OpCapability
David Neto22f144c2017-06-12 14:26:21 -04002678 //
2679 // Ops[0] = Capability
SJW01901d92020-05-21 08:58:31 -05002680 addSPIRVInst<kCapabilities>(spv::OpCapability, Capability);
alan-baker5b86ed72019-02-15 08:26:50 -05002681 }
2682
2683 // Always add the storage buffer extension
2684 {
David Neto22f144c2017-06-12 14:26:21 -04002685 //
2686 // Generate OpExtension.
2687 //
2688 // Ops[0] = Name (Literal String)
2689 //
SJWf93f5f32020-05-05 07:27:56 -05002690 addSPIRVInst<kExtensions>(spv::OpExtension,
2691 "SPV_KHR_storage_buffer_storage_class");
alan-baker5b86ed72019-02-15 08:26:50 -05002692 }
David Neto22f144c2017-06-12 14:26:21 -04002693
alan-baker5b86ed72019-02-15 08:26:50 -05002694 if (hasVariablePointers() || hasVariablePointersStorageBuffer()) {
2695 //
2696 // Generate OpExtension.
2697 //
2698 // Ops[0] = Name (Literal String)
2699 //
SJWf93f5f32020-05-05 07:27:56 -05002700 addSPIRVInst<kExtensions>(spv::OpExtension, "SPV_KHR_variable_pointers");
David Neto22f144c2017-06-12 14:26:21 -04002701 }
2702
2703 //
2704 // Generate OpMemoryModel
2705 //
2706 // Memory model for Vulkan will always be GLSL450.
2707
2708 // Ops[0] = Addressing Model
2709 // Ops[1] = Memory Model
2710 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002711 Ops << spv::AddressingModelLogical << spv::MemoryModelGLSL450;
David Neto22f144c2017-06-12 14:26:21 -04002712
SJWf93f5f32020-05-05 07:27:56 -05002713 addSPIRVInst<kMemoryModel>(spv::OpMemoryModel, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002714
2715 //
2716 // Generate OpEntryPoint
2717 //
2718 for (auto EntryPoint : EntryPoints) {
2719 // Ops[0] = Execution Model
2720 // Ops[1] = EntryPoint ID
2721 // Ops[2] = Name (Literal String)
2722 // ...
2723 //
2724 // TODO: Do we need to consider Interface ID for forward references???
2725 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05002726 const StringRef &name = EntryPoint.first->getName();
SJW01901d92020-05-21 08:58:31 -05002727 Ops << spv::ExecutionModelGLCompute << EntryPoint.second << name;
David Neto22f144c2017-06-12 14:26:21 -04002728
SJW806a5d82020-07-15 12:51:38 -05002729 for (auto &Interface : EntryPointInterfaces) {
SJW01901d92020-05-21 08:58:31 -05002730 Ops << Interface;
David Neto22f144c2017-06-12 14:26:21 -04002731 }
2732
SJWf93f5f32020-05-05 07:27:56 -05002733 addSPIRVInst<kEntryPoints>(spv::OpEntryPoint, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002734 }
2735
alan-baker3b609772020-09-03 19:10:17 -04002736 if (BuiltinDimVec.empty()) {
2737 for (auto EntryPoint : EntryPoints) {
2738 const MDNode *MD = dyn_cast<Function>(EntryPoint.first)
2739 ->getMetadata("reqd_work_group_size");
2740 if ((MD != nullptr) && !clspv::Option::NonUniformNDRangeSupported()) {
2741 //
2742 // Generate OpExecutionMode
2743 //
David Neto22f144c2017-06-12 14:26:21 -04002744
alan-baker3b609772020-09-03 19:10:17 -04002745 // Ops[0] = Entry Point ID
2746 // Ops[1] = Execution Mode
2747 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
2748 Ops.clear();
2749 Ops << EntryPoint.second << spv::ExecutionModeLocalSize;
2750
2751 uint32_t XDim = static_cast<uint32_t>(
2752 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
2753 uint32_t YDim = static_cast<uint32_t>(
2754 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
2755 uint32_t ZDim = static_cast<uint32_t>(
2756 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
2757
2758 Ops << XDim << YDim << ZDim;
2759
2760 addSPIRVInst<kExecutionModes>(spv::OpExecutionMode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002761 }
David Neto22f144c2017-06-12 14:26:21 -04002762 }
2763 }
2764
2765 //
2766 // Generate OpSource.
2767 //
2768 // Ops[0] = SourceLanguage ID
2769 // Ops[1] = Version (LiteralNum)
2770 //
SJW01901d92020-05-21 08:58:31 -05002771 uint32_t LangID = spv::SourceLanguageUnknown;
2772 uint32_t LangVer = 0;
Kévin Petitf0515712020-01-07 18:29:20 +00002773 switch (clspv::Option::Language()) {
2774 case clspv::Option::SourceLanguage::OpenCL_C_10:
SJW01901d92020-05-21 08:58:31 -05002775 LangID = spv::SourceLanguageOpenCL_C;
2776 LangVer = 100;
Kévin Petitf0515712020-01-07 18:29:20 +00002777 break;
2778 case clspv::Option::SourceLanguage::OpenCL_C_11:
SJW01901d92020-05-21 08:58:31 -05002779 LangID = spv::SourceLanguageOpenCL_C;
2780 LangVer = 110;
Kévin Petitf0515712020-01-07 18:29:20 +00002781 break;
2782 case clspv::Option::SourceLanguage::OpenCL_C_12:
SJW01901d92020-05-21 08:58:31 -05002783 LangID = spv::SourceLanguageOpenCL_C;
2784 LangVer = 120;
Kévin Petitf0515712020-01-07 18:29:20 +00002785 break;
2786 case clspv::Option::SourceLanguage::OpenCL_C_20:
SJW01901d92020-05-21 08:58:31 -05002787 LangID = spv::SourceLanguageOpenCL_C;
2788 LangVer = 200;
Kévin Petitf0515712020-01-07 18:29:20 +00002789 break;
Kévin Petit77838ff2020-10-19 18:54:51 +01002790 case clspv::Option::SourceLanguage::OpenCL_C_30:
2791 LangID = spv::SourceLanguageOpenCL_C;
2792 LangVer = 300;
2793 break;
Kévin Petitf0515712020-01-07 18:29:20 +00002794 case clspv::Option::SourceLanguage::OpenCL_CPP:
SJW01901d92020-05-21 08:58:31 -05002795 LangID = spv::SourceLanguageOpenCL_CPP;
2796 LangVer = 100;
Kévin Petitf0515712020-01-07 18:29:20 +00002797 break;
2798 default:
Kévin Petitf0515712020-01-07 18:29:20 +00002799 break;
Kévin Petit0fc88042019-04-09 23:25:02 +01002800 }
David Neto22f144c2017-06-12 14:26:21 -04002801
SJW01901d92020-05-21 08:58:31 -05002802 Ops.clear();
2803 Ops << LangID << LangVer;
SJWf93f5f32020-05-05 07:27:56 -05002804 addSPIRVInst<kDebug>(spv::OpSource, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002805
2806 if (!BuiltinDimVec.empty()) {
2807 //
2808 // Generate OpDecorates for x/y/z dimension.
2809 //
2810 // Ops[0] = Target ID
2811 // Ops[1] = Decoration (SpecId)
David Neto257c3892018-04-11 13:19:45 -04002812 // Ops[2] = Specialization Constant ID (Literal Number)
David Neto22f144c2017-06-12 14:26:21 -04002813
2814 // X Dimension
2815 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002816 Ops << BuiltinDimVec[0] << spv::DecorationSpecId << 0;
SJWf93f5f32020-05-05 07:27:56 -05002817 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002818
2819 // Y Dimension
2820 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002821 Ops << BuiltinDimVec[1] << spv::DecorationSpecId << 1;
SJWf93f5f32020-05-05 07:27:56 -05002822 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002823
2824 // Z Dimension
2825 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002826 Ops << BuiltinDimVec[2] << spv::DecorationSpecId << 2;
SJWf93f5f32020-05-05 07:27:56 -05002827 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002828 }
2829}
2830
David Netob6e2e062018-04-25 10:32:06 -04002831void SPIRVProducerPass::GenerateEntryPointInitialStores() {
2832 // Work around a driver bug. Initializers on Private variables might not
2833 // work. So the start of the kernel should store the initializer value to the
2834 // variables. Yes, *every* entry point pays this cost if *any* entry point
2835 // uses this builtin. At this point I judge this to be an acceptable tradeoff
2836 // of complexity vs. runtime, for a broken driver.
alan-bakerb6b09dc2018-11-08 16:59:28 -05002837 // TODO(dneto): Remove this at some point once fixed drivers are widely
2838 // available.
SJW01901d92020-05-21 08:58:31 -05002839 if (WorkgroupSizeVarID.isValid()) {
2840 assert(WorkgroupSizeValueID.isValid());
David Netob6e2e062018-04-25 10:32:06 -04002841
SJWf93f5f32020-05-05 07:27:56 -05002842 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05002843 Ops << WorkgroupSizeVarID << WorkgroupSizeValueID;
David Netob6e2e062018-04-25 10:32:06 -04002844
SJWf93f5f32020-05-05 07:27:56 -05002845 addSPIRVInst(spv::OpStore, Ops);
David Netob6e2e062018-04-25 10:32:06 -04002846 }
2847}
2848
David Neto22f144c2017-06-12 14:26:21 -04002849void SPIRVProducerPass::GenerateFuncBody(Function &F) {
David Neto22f144c2017-06-12 14:26:21 -04002850 ValueMapType &VMap = getValueMap();
2851
David Netob6e2e062018-04-25 10:32:06 -04002852 const bool IsKernel = F.getCallingConv() == CallingConv::SPIR_KERNEL;
David Neto22f144c2017-06-12 14:26:21 -04002853
2854 for (BasicBlock &BB : F) {
2855 // Register BasicBlock to ValueMap.
David Neto22f144c2017-06-12 14:26:21 -04002856
2857 //
2858 // Generate OpLabel for Basic Block.
2859 //
SJWf93f5f32020-05-05 07:27:56 -05002860 VMap[&BB] = addSPIRVInst(spv::OpLabel);
David Neto22f144c2017-06-12 14:26:21 -04002861
David Neto6dcd4712017-06-23 11:06:47 -04002862 // OpVariable instructions must come first.
2863 for (Instruction &I : BB) {
alan-baker5b86ed72019-02-15 08:26:50 -05002864 if (auto *alloca = dyn_cast<AllocaInst>(&I)) {
2865 // Allocating a pointer requires variable pointers.
2866 if (alloca->getAllocatedType()->isPointerTy()) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002867 setVariablePointersCapabilities(
2868 alloca->getAllocatedType()->getPointerAddressSpace());
alan-baker5b86ed72019-02-15 08:26:50 -05002869 }
David Neto6dcd4712017-06-23 11:06:47 -04002870 GenerateInstruction(I);
2871 }
2872 }
2873
David Neto22f144c2017-06-12 14:26:21 -04002874 if (&BB == &F.getEntryBlock() && IsKernel) {
David Netob6e2e062018-04-25 10:32:06 -04002875 if (clspv::Option::HackInitializers()) {
2876 GenerateEntryPointInitialStores();
2877 }
David Neto22f144c2017-06-12 14:26:21 -04002878 }
2879
2880 for (Instruction &I : BB) {
David Neto6dcd4712017-06-23 11:06:47 -04002881 if (!isa<AllocaInst>(I)) {
2882 GenerateInstruction(I);
2883 }
David Neto22f144c2017-06-12 14:26:21 -04002884 }
2885 }
2886}
2887
2888spv::Op SPIRVProducerPass::GetSPIRVCmpOpcode(CmpInst *I) {
2889 const std::map<CmpInst::Predicate, spv::Op> Map = {
2890 {CmpInst::ICMP_EQ, spv::OpIEqual},
2891 {CmpInst::ICMP_NE, spv::OpINotEqual},
2892 {CmpInst::ICMP_UGT, spv::OpUGreaterThan},
2893 {CmpInst::ICMP_UGE, spv::OpUGreaterThanEqual},
2894 {CmpInst::ICMP_ULT, spv::OpULessThan},
2895 {CmpInst::ICMP_ULE, spv::OpULessThanEqual},
2896 {CmpInst::ICMP_SGT, spv::OpSGreaterThan},
2897 {CmpInst::ICMP_SGE, spv::OpSGreaterThanEqual},
2898 {CmpInst::ICMP_SLT, spv::OpSLessThan},
2899 {CmpInst::ICMP_SLE, spv::OpSLessThanEqual},
2900 {CmpInst::FCMP_OEQ, spv::OpFOrdEqual},
2901 {CmpInst::FCMP_OGT, spv::OpFOrdGreaterThan},
2902 {CmpInst::FCMP_OGE, spv::OpFOrdGreaterThanEqual},
2903 {CmpInst::FCMP_OLT, spv::OpFOrdLessThan},
2904 {CmpInst::FCMP_OLE, spv::OpFOrdLessThanEqual},
2905 {CmpInst::FCMP_ONE, spv::OpFOrdNotEqual},
2906 {CmpInst::FCMP_UEQ, spv::OpFUnordEqual},
2907 {CmpInst::FCMP_UGT, spv::OpFUnordGreaterThan},
2908 {CmpInst::FCMP_UGE, spv::OpFUnordGreaterThanEqual},
2909 {CmpInst::FCMP_ULT, spv::OpFUnordLessThan},
2910 {CmpInst::FCMP_ULE, spv::OpFUnordLessThanEqual},
2911 {CmpInst::FCMP_UNE, spv::OpFUnordNotEqual}};
2912
2913 assert(0 != Map.count(I->getPredicate()));
2914
2915 return Map.at(I->getPredicate());
2916}
2917
2918spv::Op SPIRVProducerPass::GetSPIRVCastOpcode(Instruction &I) {
2919 const std::map<unsigned, spv::Op> Map{
2920 {Instruction::Trunc, spv::OpUConvert},
2921 {Instruction::ZExt, spv::OpUConvert},
2922 {Instruction::SExt, spv::OpSConvert},
2923 {Instruction::FPToUI, spv::OpConvertFToU},
2924 {Instruction::FPToSI, spv::OpConvertFToS},
2925 {Instruction::UIToFP, spv::OpConvertUToF},
2926 {Instruction::SIToFP, spv::OpConvertSToF},
2927 {Instruction::FPTrunc, spv::OpFConvert},
2928 {Instruction::FPExt, spv::OpFConvert},
2929 {Instruction::BitCast, spv::OpBitcast}};
2930
2931 assert(0 != Map.count(I.getOpcode()));
2932
2933 return Map.at(I.getOpcode());
2934}
2935
2936spv::Op SPIRVProducerPass::GetSPIRVBinaryOpcode(Instruction &I) {
Kévin Petit24272b62018-10-18 19:16:12 +00002937 if (I.getType()->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04002938 switch (I.getOpcode()) {
2939 default:
2940 break;
2941 case Instruction::Or:
2942 return spv::OpLogicalOr;
2943 case Instruction::And:
2944 return spv::OpLogicalAnd;
2945 case Instruction::Xor:
2946 return spv::OpLogicalNotEqual;
2947 }
2948 }
2949
alan-bakerb6b09dc2018-11-08 16:59:28 -05002950 const std::map<unsigned, spv::Op> Map{
David Neto22f144c2017-06-12 14:26:21 -04002951 {Instruction::Add, spv::OpIAdd},
2952 {Instruction::FAdd, spv::OpFAdd},
2953 {Instruction::Sub, spv::OpISub},
2954 {Instruction::FSub, spv::OpFSub},
2955 {Instruction::Mul, spv::OpIMul},
2956 {Instruction::FMul, spv::OpFMul},
2957 {Instruction::UDiv, spv::OpUDiv},
2958 {Instruction::SDiv, spv::OpSDiv},
2959 {Instruction::FDiv, spv::OpFDiv},
2960 {Instruction::URem, spv::OpUMod},
2961 {Instruction::SRem, spv::OpSRem},
2962 {Instruction::FRem, spv::OpFRem},
2963 {Instruction::Or, spv::OpBitwiseOr},
2964 {Instruction::Xor, spv::OpBitwiseXor},
2965 {Instruction::And, spv::OpBitwiseAnd},
2966 {Instruction::Shl, spv::OpShiftLeftLogical},
2967 {Instruction::LShr, spv::OpShiftRightLogical},
2968 {Instruction::AShr, spv::OpShiftRightArithmetic}};
2969
2970 assert(0 != Map.count(I.getOpcode()));
2971
2972 return Map.at(I.getOpcode());
2973}
2974
SJW806a5d82020-07-15 12:51:38 -05002975SPIRVID SPIRVProducerPass::getSPIRVBuiltin(spv::BuiltIn BID,
2976 spv::Capability Cap) {
2977 SPIRVID RID;
2978
2979 auto ii = BuiltinConstantMap.find(BID);
2980
2981 if (ii != BuiltinConstantMap.end()) {
2982 return ii->second;
2983 } else {
SJW806a5d82020-07-15 12:51:38 -05002984 addCapability(Cap);
2985
2986 Type *type = PointerType::get(IntegerType::get(module->getContext(), 32),
2987 AddressSpace::Input);
2988
2989 RID = addSPIRVGlobalVariable(getSPIRVType(type), spv::StorageClassInput);
2990
2991 BuiltinConstantMap[BID] = RID;
2992
2993 //
2994 // Generate OpDecorate.
2995 //
2996 // Ops[0] : target
2997 // Ops[1] : decoration
2998 // Ops[2] : SpecId
2999 SPIRVOperandVec Ops;
3000 Ops << RID << spv::DecorationBuiltIn << static_cast<int>(BID);
3001
3002 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
3003 }
3004
3005 return RID;
3006}
3007
3008SPIRVID
3009SPIRVProducerPass::GenerateClspvInstruction(CallInst *Call,
3010 const FunctionInfo &FuncInfo) {
3011 SPIRVID RID;
3012
3013 switch (FuncInfo.getType()) {
3014 case Builtins::kClspvCompositeConstruct:
3015 RID = addSPIRVPlaceholder(Call);
3016 break;
3017 case Builtins::kClspvResource: {
3018 if (ResourceVarDeferredLoadCalls.count(Call) && Call->hasNUsesOrMore(1)) {
3019 // Generate an OpLoad
3020 SPIRVOperandVec Ops;
3021
3022 Ops << Call->getType()->getPointerElementType()
3023 << ResourceVarDeferredLoadCalls[Call];
3024
3025 RID = addSPIRVInst(spv::OpLoad, Ops);
3026
3027 } else {
3028 // This maps to an OpVariable we've already generated.
3029 // No code is generated for the call.
3030 }
3031 break;
3032 }
3033 case Builtins::kClspvLocal: {
3034 // Don't codegen an instruction here, but instead map this call directly
3035 // to the workgroup variable id.
3036 int spec_id = static_cast<int>(
3037 cast<ConstantInt>(Call->getOperand(0))->getSExtValue());
3038 const auto &info = LocalSpecIdInfoMap[spec_id];
3039 RID = info.variable_id;
3040 break;
3041 }
3042 case Builtins::kClspvSamplerVarLiteral: {
3043 // Sampler initializers become a load of the corresponding sampler.
3044 // Map this to a load from the variable.
3045 const auto third_param = static_cast<unsigned>(
3046 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue());
3047 auto sampler_value = third_param;
3048 if (clspv::Option::UseSamplerMap()) {
3049 sampler_value = getSamplerMap()[third_param].first;
3050 }
3051
3052 // Generate an OpLoad
3053 SPIRVOperandVec Ops;
3054
3055 Ops << SamplerTy->getPointerElementType()
3056 << SamplerLiteralToIDMap[sampler_value];
3057
3058 RID = addSPIRVInst(spv::OpLoad, Ops);
3059 break;
3060 }
3061 case Builtins::kSpirvAtomicXor: {
3062 // Handle SPIR-V intrinsics
3063 SPIRVOperandVec Ops;
3064
3065 if (!Call->getType()->isVoidTy()) {
3066 Ops << Call->getType();
3067 }
3068
3069 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
3070 Ops << Call->getArgOperand(i);
3071 }
3072
3073 RID = addSPIRVInst(spv::OpAtomicXor, Ops);
3074 break;
3075 }
3076 case Builtins::kSpirvOp: {
3077 // Handle SPIR-V intrinsics
3078 auto *arg0 = dyn_cast<ConstantInt>(Call->getArgOperand(0));
3079 spv::Op opcode = static_cast<spv::Op>(arg0->getZExtValue());
3080 if (opcode != spv::OpNop) {
3081 SPIRVOperandVec Ops;
3082
3083 if (!Call->getType()->isVoidTy()) {
3084 Ops << Call->getType();
3085 }
3086
3087 for (unsigned i = 1; i < Call->getNumArgOperands(); i++) {
3088 Ops << Call->getArgOperand(i);
3089 }
3090
3091 RID = addSPIRVInst(opcode, Ops);
3092 }
3093 break;
3094 }
3095 case Builtins::kSpirvCopyMemory: {
3096 //
3097 // Generate OpCopyMemory.
3098 //
3099
3100 // Ops[0] = Dst ID
3101 // Ops[1] = Src ID
3102 // Ops[2] = Memory Access
3103 // Ops[3] = Alignment
3104
3105 auto IsVolatile =
3106 dyn_cast<ConstantInt>(Call->getArgOperand(3))->getZExtValue() != 0;
3107
3108 auto VolatileMemoryAccess = (IsVolatile) ? spv::MemoryAccessVolatileMask
3109 : spv::MemoryAccessMaskNone;
3110
3111 auto MemoryAccess = VolatileMemoryAccess | spv::MemoryAccessAlignedMask;
3112
3113 auto Alignment =
3114 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
3115
3116 SPIRVOperandVec Ops;
3117 Ops << Call->getArgOperand(0) << Call->getArgOperand(1) << MemoryAccess
3118 << static_cast<uint32_t>(Alignment);
3119
3120 RID = addSPIRVInst(spv::OpCopyMemory, Ops);
3121 break;
3122 }
3123 default:
3124 llvm_unreachable("Unknown CLSPV Instruction");
3125 break;
3126 }
3127 return RID;
3128}
3129
3130SPIRVID
3131SPIRVProducerPass::GenerateImageInstruction(CallInst *Call,
3132 const FunctionInfo &FuncInfo) {
3133 SPIRVID RID;
3134
3135 LLVMContext &Context = module->getContext();
3136 switch (FuncInfo.getType()) {
3137 case Builtins::kReadImagef:
3138 case Builtins::kReadImageh:
3139 case Builtins::kReadImagei:
3140 case Builtins::kReadImageui: {
3141 // read_image is converted to OpSampledImage and OpImageSampleExplicitLod.
3142 // Additionally, OpTypeSampledImage is generated.
alan-bakerf6bc8252020-09-23 14:58:55 -04003143 const auto image_ty = Call->getArgOperand(0)->getType();
SJW806a5d82020-07-15 12:51:38 -05003144 const auto &pi = FuncInfo.getParameter(1);
3145 if (pi.isSampler()) {
3146 //
3147 // Generate OpSampledImage.
3148 //
3149 // Ops[0] = Result Type ID
3150 // Ops[1] = Image ID
3151 // Ops[2] = Sampler ID
3152 //
3153 SPIRVOperandVec Ops;
3154
3155 Value *Image = Call->getArgOperand(0);
3156 Value *Sampler = Call->getArgOperand(1);
3157 Value *Coordinate = Call->getArgOperand(2);
3158
3159 TypeMapType &OpImageTypeMap = getImageTypeMap();
3160 Type *ImageTy = Image->getType()->getPointerElementType();
3161 SPIRVID ImageTyID = OpImageTypeMap[ImageTy];
3162
3163 Ops << ImageTyID << Image << Sampler;
3164
3165 SPIRVID SampledImageID = addSPIRVInst(spv::OpSampledImage, Ops);
3166
3167 //
3168 // Generate OpImageSampleExplicitLod.
3169 //
3170 // Ops[0] = Result Type ID
3171 // Ops[1] = Sampled Image ID
3172 // Ops[2] = Coordinate ID
3173 // Ops[3] = Image Operands Type ID
3174 // Ops[4] ... Ops[n] = Operands ID
3175 //
3176 Ops.clear();
3177
3178 const bool is_int_image = IsIntImageType(Image->getType());
3179 SPIRVID result_type;
3180 if (is_int_image) {
3181 result_type = v4int32ID;
3182 } else {
3183 result_type = getSPIRVType(Call->getType());
3184 }
3185
3186 Constant *CstFP0 = ConstantFP::get(Context, APFloat(0.0f));
3187 Ops << result_type << SampledImageID << Coordinate
3188 << spv::ImageOperandsLodMask << CstFP0;
3189
3190 RID = addSPIRVInst(spv::OpImageSampleExplicitLod, Ops);
3191
3192 if (is_int_image) {
3193 // Generate the bitcast.
3194 Ops.clear();
3195 Ops << Call->getType() << RID;
3196 RID = addSPIRVInst(spv::OpBitcast, Ops);
3197 }
alan-bakerf6bc8252020-09-23 14:58:55 -04003198 } else if (IsStorageImageType(image_ty)) {
3199 // read_image on a storage image is mapped to OpImageRead.
3200 Value *Image = Call->getArgOperand(0);
3201 Value *Coordinate = Call->getArgOperand(1);
3202
3203 //
3204 // Generate OpImageRead
3205 //
3206 // Ops[0] = Result Type ID
3207 // Ops[1] = Image ID
3208 // Ops[2] = Coordinate
3209 // No optional image operands.
3210 //
3211 SPIRVOperandVec Ops;
3212
3213 const bool is_int_image = IsIntImageType(Image->getType());
3214 SPIRVID result_type;
3215 if (is_int_image) {
3216 result_type = v4int32ID;
3217 } else {
3218 result_type = getSPIRVType(Call->getType());
3219 }
3220
3221 Ops << result_type << Image << Coordinate;
3222 RID = addSPIRVInst(spv::OpImageRead, Ops);
3223
3224 if (is_int_image) {
3225 // Generate the bitcast.
3226 Ops.clear();
3227 Ops << Call->getType() << RID;
3228 RID = addSPIRVInst(spv::OpBitcast, Ops);
3229 }
3230
3231 // OpImageRead requires StorageImageReadWithoutFormat.
3232 addCapability(spv::CapabilityStorageImageReadWithoutFormat);
SJW806a5d82020-07-15 12:51:38 -05003233 } else {
alan-bakerf6bc8252020-09-23 14:58:55 -04003234 // read_image on a sampled image (without a sampler) is mapped to
3235 // OpImageFetch.
SJW806a5d82020-07-15 12:51:38 -05003236 Value *Image = Call->getArgOperand(0);
3237 Value *Coordinate = Call->getArgOperand(1);
3238
3239 //
3240 // Generate OpImageFetch
3241 //
3242 // Ops[0] = Result Type ID
3243 // Ops[1] = Image ID
3244 // Ops[2] = Coordinate ID
3245 // Ops[3] = Lod
3246 // Ops[4] = 0
3247 //
3248 SPIRVOperandVec Ops;
3249
3250 const bool is_int_image = IsIntImageType(Image->getType());
3251 SPIRVID result_type;
3252 if (is_int_image) {
3253 result_type = v4int32ID;
3254 } else {
3255 result_type = getSPIRVType(Call->getType());
3256 }
3257
3258 Ops << result_type << Image << Coordinate << spv::ImageOperandsLodMask
3259 << getSPIRVInt32Constant(0);
3260
3261 RID = addSPIRVInst(spv::OpImageFetch, Ops);
3262
3263 if (is_int_image) {
3264 // Generate the bitcast.
3265 Ops.clear();
3266 Ops << Call->getType() << RID;
3267 RID = addSPIRVInst(spv::OpBitcast, Ops);
3268 }
3269 }
3270 break;
3271 }
3272
3273 case Builtins::kWriteImagef:
3274 case Builtins::kWriteImageh:
3275 case Builtins::kWriteImagei:
3276 case Builtins::kWriteImageui: {
3277 // write_image is mapped to OpImageWrite.
3278 //
3279 // Generate OpImageWrite.
3280 //
3281 // Ops[0] = Image ID
3282 // Ops[1] = Coordinate ID
3283 // Ops[2] = Texel ID
3284 // Ops[3] = (Optional) Image Operands Type (Literal Number)
3285 // Ops[4] ... Ops[n] = (Optional) Operands ID
3286 //
3287 SPIRVOperandVec Ops;
3288
3289 Value *Image = Call->getArgOperand(0);
3290 Value *Coordinate = Call->getArgOperand(1);
3291 Value *Texel = Call->getArgOperand(2);
3292
3293 SPIRVID TexelID = getSPIRVValue(Texel);
3294
3295 const bool is_int_image = IsIntImageType(Image->getType());
3296 if (is_int_image) {
3297 // Generate a bitcast to v4int and use it as the texel value.
3298 Ops << v4int32ID << TexelID;
3299 TexelID = addSPIRVInst(spv::OpBitcast, Ops);
3300 Ops.clear();
3301 }
3302 Ops << Image << Coordinate << TexelID;
SJW806a5d82020-07-15 12:51:38 -05003303 RID = addSPIRVInst(spv::OpImageWrite, Ops);
alan-bakerf6bc8252020-09-23 14:58:55 -04003304
3305 // Image writes require StorageImageWriteWithoutFormat.
3306 addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
SJW806a5d82020-07-15 12:51:38 -05003307 break;
3308 }
3309
3310 case Builtins::kGetImageHeight:
3311 case Builtins::kGetImageWidth:
3312 case Builtins::kGetImageDepth:
3313 case Builtins::kGetImageDim: {
3314 // get_image_* is mapped to OpImageQuerySize or OpImageQuerySizeLod
3315 addCapability(spv::CapabilityImageQuery);
3316
3317 //
3318 // Generate OpImageQuerySize[Lod]
3319 //
3320 // Ops[0] = Image ID
3321 //
3322 // Result type has components equal to the dimensionality of the image,
3323 // plus 1 if the image is arrayed.
3324 //
3325 // %sizes = OpImageQuerySize[Lod] %uint[2|3|4] %im [%uint_0]
3326 SPIRVOperandVec Ops;
3327
3328 // Implement:
3329 // %sizes = OpImageQuerySize[Lod] %uint[2|3|4] %im [%uint_0]
3330 SPIRVID SizesTypeID;
3331
3332 Value *Image = Call->getArgOperand(0);
3333 const uint32_t dim = ImageDimensionality(Image->getType());
3334 const uint32_t components =
3335 dim + (IsArrayImageType(Image->getType()) ? 1 : 0);
3336 if (components == 1) {
3337 SizesTypeID = getSPIRVType(Type::getInt32Ty(Context));
3338 } else {
3339 SizesTypeID = getSPIRVType(
3340 FixedVectorType::get(Type::getInt32Ty(Context), components));
3341 }
3342 Ops << SizesTypeID << Image;
3343 spv::Op query_opcode = spv::OpImageQuerySize;
3344 if (IsSampledImageType(Image->getType())) {
3345 query_opcode = spv::OpImageQuerySizeLod;
3346 // Need explicit 0 for Lod operand.
3347 Ops << getSPIRVInt32Constant(0);
3348 }
3349
3350 RID = addSPIRVInst(query_opcode, Ops);
3351
3352 // May require an extra instruction to create the appropriate result of
3353 // the builtin function.
3354 if (FuncInfo.getType() == Builtins::kGetImageDim) {
3355 if (dim == 3) {
3356 // get_image_dim returns an int4 for 3D images.
3357 //
3358
3359 // Implement:
3360 // %result = OpCompositeConstruct %uint4 %sizes %uint_0
3361 Ops.clear();
3362 Ops << FixedVectorType::get(Type::getInt32Ty(Context), 4) << RID
3363 << getSPIRVInt32Constant(0);
3364
3365 RID = addSPIRVInst(spv::OpCompositeConstruct, Ops);
3366 } else if (dim != components) {
3367 // get_image_dim return an int2 regardless of the arrayedness of the
3368 // image. If the image is arrayed an element must be dropped from the
3369 // query result.
3370 //
3371
3372 // Implement:
3373 // %result = OpVectorShuffle %uint2 %sizes %sizes 0 1
3374 Ops.clear();
3375 Ops << FixedVectorType::get(Type::getInt32Ty(Context), 2) << RID << RID
3376 << 0 << 1;
3377
3378 RID = addSPIRVInst(spv::OpVectorShuffle, Ops);
3379 }
3380 } else if (components > 1) {
3381 // Implement:
3382 // %result = OpCompositeExtract %uint %sizes <component number>
3383 Ops.clear();
3384 Ops << Call->getType() << RID;
3385
3386 uint32_t component = 0;
3387 if (FuncInfo.getType() == Builtins::kGetImageHeight)
3388 component = 1;
3389 else if (FuncInfo.getType() == Builtins::kGetImageDepth)
3390 component = 2;
3391 Ops << component;
3392
3393 RID = addSPIRVInst(spv::OpCompositeExtract, Ops);
3394 }
3395 break;
3396 }
3397 default:
3398 llvm_unreachable("Unsupported Image builtin");
3399 }
3400
3401 return RID;
3402}
3403
3404SPIRVID
3405SPIRVProducerPass::GenerateSubgroupInstruction(CallInst *Call,
3406 const FunctionInfo &FuncInfo) {
3407 SPIRVID RID;
3408
3409 // requires SPIRV version 1.3 or greater
3410 if (SpvVersion() != SPIRVVersion::SPIRV_1_3) {
3411 // llvm_unreachable("SubGroups extension requires SPIRV 1.3 or greater");
3412 // TODO(sjw): error out gracefully
3413 }
3414
3415 auto loadBuiltin = [this, Call](spv::BuiltIn spvBI,
3416 spv::Capability spvCap =
3417 spv::CapabilityGroupNonUniform) {
3418 SPIRVOperandVec Ops;
3419 Ops << Call->getType() << this->getSPIRVBuiltin(spvBI, spvCap);
3420
3421 return addSPIRVInst(spv::OpLoad, Ops);
3422 };
3423
3424 spv::Op op = spv::OpNop;
3425 switch (FuncInfo.getType()) {
3426 case Builtins::kGetSubGroupSize:
3427 return loadBuiltin(spv::BuiltInSubgroupSize);
3428 case Builtins::kGetNumSubGroups:
3429 return loadBuiltin(spv::BuiltInNumSubgroups);
3430 case Builtins::kGetSubGroupId:
3431 return loadBuiltin(spv::BuiltInSubgroupId);
3432 case Builtins::kGetSubGroupLocalId:
3433 return loadBuiltin(spv::BuiltInSubgroupLocalInvocationId);
3434
3435 case Builtins::kSubGroupBroadcast:
3436 if (SpvVersion() < SPIRVVersion::SPIRV_1_5 &&
3437 !dyn_cast<ConstantInt>(Call->getOperand(1))) {
3438 llvm_unreachable("sub_group_broadcast requires constant lane Id for "
3439 "SPIRV version < 1.5");
3440 }
3441 addCapability(spv::CapabilityGroupNonUniformBallot);
3442 op = spv::OpGroupNonUniformBroadcast;
3443 break;
3444
3445 case Builtins::kSubGroupAll:
3446 addCapability(spv::CapabilityGroupNonUniformVote);
3447 op = spv::OpGroupNonUniformAll;
3448 break;
3449 case Builtins::kSubGroupAny:
3450 addCapability(spv::CapabilityGroupNonUniformVote);
3451 op = spv::OpGroupNonUniformAny;
3452 break;
3453 case Builtins::kSubGroupReduceAdd:
3454 case Builtins::kSubGroupScanExclusiveAdd:
3455 case Builtins::kSubGroupScanInclusiveAdd: {
3456 addCapability(spv::CapabilityGroupNonUniformArithmetic);
3457 if (FuncInfo.getParameter(0).type_id == Type::IntegerTyID) {
3458 op = spv::OpGroupNonUniformIAdd;
3459 } else {
3460 op = spv::OpGroupNonUniformFAdd;
3461 }
3462 break;
3463 }
3464 case Builtins::kSubGroupReduceMin:
3465 case Builtins::kSubGroupScanExclusiveMin:
3466 case Builtins::kSubGroupScanInclusiveMin: {
3467 addCapability(spv::CapabilityGroupNonUniformArithmetic);
3468 auto &param = FuncInfo.getParameter(0);
3469 if (param.type_id == Type::IntegerTyID) {
3470 op = param.is_signed ? spv::OpGroupNonUniformSMin
3471 : spv::OpGroupNonUniformUMin;
3472 } else {
3473 op = spv::OpGroupNonUniformFMin;
3474 }
3475 break;
3476 }
3477 case Builtins::kSubGroupReduceMax:
3478 case Builtins::kSubGroupScanExclusiveMax:
3479 case Builtins::kSubGroupScanInclusiveMax: {
3480 addCapability(spv::CapabilityGroupNonUniformArithmetic);
3481 auto &param = FuncInfo.getParameter(0);
3482 if (param.type_id == Type::IntegerTyID) {
3483 op = param.is_signed ? spv::OpGroupNonUniformSMax
3484 : spv::OpGroupNonUniformUMax;
3485 } else {
3486 op = spv::OpGroupNonUniformFMax;
3487 }
3488 break;
3489 }
3490
3491 case Builtins::kGetEnqueuedNumSubGroups:
3492 // TODO(sjw): requires CapabilityKernel (incompatible with Shader)
3493 case Builtins::kGetMaxSubGroupSize:
3494 // TODO(sjw): use SpecConstant, capability Kernel (incompatible with Shader)
3495 case Builtins::kSubGroupBarrier:
3496 case Builtins::kSubGroupReserveReadPipe:
3497 case Builtins::kSubGroupReserveWritePipe:
3498 case Builtins::kSubGroupCommitReadPipe:
3499 case Builtins::kSubGroupCommitWritePipe:
3500 case Builtins::kGetKernelSubGroupCountForNdrange:
3501 case Builtins::kGetKernelMaxSubGroupSizeForNdrange:
3502 default:
3503 Call->print(errs());
3504 llvm_unreachable("Unsupported sub_group operation");
3505 break;
3506 }
3507
3508 assert(op != spv::OpNop);
3509
3510 SPIRVOperandVec Operands;
3511
3512 //
3513 // Generate OpGroupNonUniform*
3514 //
3515 // Ops[0] = Result Type ID
3516 // Ops[1] = ScopeSubgroup
3517 // Ops[2] = Value ID
3518 // Ops[3] = Local ID
3519
3520 // The result type.
3521 Operands << Call->getType();
3522
3523 // Subgroup Scope
3524 Operands << getSPIRVInt32Constant(spv::ScopeSubgroup);
3525
3526 switch (FuncInfo.getType()) {
3527 case Builtins::kSubGroupReduceAdd:
3528 case Builtins::kSubGroupReduceMin:
3529 case Builtins::kSubGroupReduceMax:
3530 Operands << spv::GroupOperationReduce;
3531 break;
3532 case Builtins::kSubGroupScanExclusiveAdd:
3533 case Builtins::kSubGroupScanExclusiveMin:
3534 case Builtins::kSubGroupScanExclusiveMax:
3535 Operands << spv::GroupOperationExclusiveScan;
3536 break;
3537 case Builtins::kSubGroupScanInclusiveAdd:
3538 case Builtins::kSubGroupScanInclusiveMin:
3539 case Builtins::kSubGroupScanInclusiveMax:
3540 Operands << spv::GroupOperationInclusiveScan;
3541 break;
3542 default:
3543 break;
3544 }
3545
3546 for (Use &use : Call->arg_operands()) {
3547 Operands << use.get();
3548 }
3549
3550 return addSPIRVInst(op, Operands);
3551}
3552
3553SPIRVID SPIRVProducerPass::GenerateInstructionFromCall(CallInst *Call) {
3554 LLVMContext &Context = module->getContext();
3555
3556 auto &func_info = Builtins::Lookup(Call->getCalledFunction());
3557 auto func_type = func_info.getType();
3558
3559 if (BUILTIN_IN_GROUP(func_type, Clspv)) {
3560 return GenerateClspvInstruction(Call, func_info);
3561 } else if (BUILTIN_IN_GROUP(func_type, Image)) {
3562 return GenerateImageInstruction(Call, func_info);
3563 } else if (BUILTIN_IN_GROUP(func_type, SubgroupsKHR)) {
3564 return GenerateSubgroupInstruction(Call, func_info);
3565 }
3566
3567 SPIRVID RID;
3568
alan-baker5f2e88e2020-12-07 15:24:04 -05003569 switch (Call->getCalledFunction()->getIntrinsicID()) {
3570 case Intrinsic::ctlz: {
3571 // Implement as 31 - FindUMsb. Ignore the second operand of llvm.ctlz.
3572 SPIRVOperandVec Ops;
3573 Ops << Call->getType() << getOpExtInstImportID()
3574 << glsl::ExtInst::ExtInstFindUMsb << Call->getArgOperand(0);
3575 auto find_msb = addSPIRVInst(spv::OpExtInst, Ops);
3576
3577 Constant *thirty_one = ConstantInt::get(
3578 Call->getType(), Call->getType()->getScalarSizeInBits() - 1);
3579 Ops.clear();
3580 Ops << Call->getType() << thirty_one << find_msb;
3581 return addSPIRVInst(spv::OpISub, Ops);
3582 }
3583 case Intrinsic::cttz: {
3584 // Implement as:
3585 // lsb = FindILsb x
3586 // res = lsb == -1 ? width : lsb
3587 //
3588 // Ignore the second operand of llvm.cttz.
3589 SPIRVOperandVec Ops;
3590 Ops << Call->getType() << getOpExtInstImportID()
3591 << glsl::ExtInst::ExtInstFindILsb << Call->getArgOperand(0);
3592 auto find_lsb = addSPIRVInst(spv::OpExtInst, Ops);
3593
3594 auto neg_one = Constant::getAllOnesValue(Call->getType());
3595 auto i1_ty = Call->getType()->getWithNewBitWidth(1);
3596 auto width = ConstantInt::get(Call->getType(),
3597 Call->getType()->getScalarSizeInBits());
3598
3599 Ops.clear();
3600 Ops << i1_ty << find_lsb << neg_one;
3601 auto cmp = addSPIRVInst(spv::OpIEqual, Ops);
3602
3603 Ops.clear();
3604 Ops << Call->getType() << cmp << width << find_lsb;
3605 return addSPIRVInst(spv::OpSelect, Ops);
3606 }
3607
3608 default:
3609 break;
3610 }
3611
SJW806a5d82020-07-15 12:51:38 -05003612 switch (func_type) {
3613 case Builtins::kPopcount: {
3614 //
3615 // Generate OpBitCount
3616 //
3617 // Ops[0] = Result Type ID
3618 // Ops[1] = Base ID
3619 SPIRVOperandVec Ops;
3620 Ops << Call->getType() << Call->getOperand(0);
3621
3622 RID = addSPIRVInst(spv::OpBitCount, Ops);
3623 break;
3624 }
3625 default: {
3626 glsl::ExtInst EInst = getDirectOrIndirectExtInstEnum(func_info);
3627
alan-baker5f2e88e2020-12-07 15:24:04 -05003628 // Do not replace functions with implementations.
3629 if (EInst && Call->getCalledFunction()->isDeclaration()) {
SJW806a5d82020-07-15 12:51:38 -05003630 SPIRVID ExtInstImportID = getOpExtInstImportID();
3631
3632 //
3633 // Generate OpExtInst.
3634 //
3635
3636 // Ops[0] = Result Type ID
3637 // Ops[1] = Set ID (OpExtInstImport ID)
3638 // Ops[2] = Instruction Number (Literal Number)
3639 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
3640 SPIRVOperandVec Ops;
3641
3642 Ops << Call->getType() << ExtInstImportID << EInst;
3643
3644 for (auto &use : Call->arg_operands()) {
3645 Ops << use.get();
3646 }
3647
3648 RID = addSPIRVInst(spv::OpExtInst, Ops);
3649
3650 const auto IndirectExtInst = getIndirectExtInstEnum(func_info);
3651 if (IndirectExtInst != kGlslExtInstBad) {
SJW806a5d82020-07-15 12:51:38 -05003652 // Generate one more instruction that uses the result of the extended
3653 // instruction. Its result id is one more than the id of the
3654 // extended instruction.
3655 auto generate_extra_inst = [this, &Context, &Call,
3656 &RID](spv::Op opcode, Constant *constant) {
3657 //
3658 // Generate instruction like:
3659 // result = opcode constant <extinst-result>
3660 //
3661 // Ops[0] = Result Type ID
3662 // Ops[1] = Operand 0 ;; the constant, suitably splatted
3663 // Ops[2] = Operand 1 ;; the result of the extended instruction
3664 SPIRVOperandVec Ops;
3665
3666 Type *resultTy = Call->getType();
3667
3668 if (auto *vectorTy = dyn_cast<VectorType>(resultTy)) {
alan-baker931253b2020-08-20 17:15:38 -04003669 constant =
3670 ConstantVector::getSplat(vectorTy->getElementCount(), constant);
SJW806a5d82020-07-15 12:51:38 -05003671 }
3672 Ops << resultTy << constant << RID;
3673
3674 RID = addSPIRVInst(opcode, Ops);
3675 };
3676
SJW806a5d82020-07-15 12:51:38 -05003677 switch (IndirectExtInst) {
SJW806a5d82020-07-15 12:51:38 -05003678 case glsl::ExtInstAcos: // Implementing acospi
3679 case glsl::ExtInstAsin: // Implementing asinpi
3680 case glsl::ExtInstAtan: // Implementing atanpi
3681 case glsl::ExtInstAtan2: // Implementing atan2pi
3682 generate_extra_inst(
3683 spv::OpFMul,
alan-bakercc2bafb2020-11-02 08:30:18 -05003684 ConstantFP::get(Call->getType()->getScalarType(), kOneOverPi));
SJW806a5d82020-07-15 12:51:38 -05003685 break;
3686
3687 default:
3688 assert(false && "internally inconsistent");
3689 }
3690 }
3691 } else {
SJW806a5d82020-07-15 12:51:38 -05003692 // A real function call (not builtin)
3693 // Call instruction is deferred because it needs function's ID.
3694 RID = addSPIRVPlaceholder(Call);
3695 }
3696
3697 break;
3698 }
3699 }
3700
3701 return RID;
3702}
3703
David Neto22f144c2017-06-12 14:26:21 -04003704void SPIRVProducerPass::GenerateInstruction(Instruction &I) {
David Neto22f144c2017-06-12 14:26:21 -04003705 ValueMapType &VMap = getValueMap();
SJW806a5d82020-07-15 12:51:38 -05003706 LLVMContext &Context = module->getContext();
David Neto22f144c2017-06-12 14:26:21 -04003707
SJW806a5d82020-07-15 12:51:38 -05003708 SPIRVID RID;
David Neto22f144c2017-06-12 14:26:21 -04003709
3710 switch (I.getOpcode()) {
3711 default: {
3712 if (Instruction::isCast(I.getOpcode())) {
3713 //
3714 // Generate SPIRV instructions for cast operators.
3715 //
3716
David Netod2de94a2017-08-28 17:27:47 -04003717 auto Ty = I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003718 auto OpTy = I.getOperand(0)->getType();
David Netod2de94a2017-08-28 17:27:47 -04003719 auto toI8 = Ty == Type::getInt8Ty(Context);
3720 auto fromI32 = OpTy == Type::getInt32Ty(Context);
James Price757dea82021-01-11 13:42:39 -05003721 // Handle zext, sext, uitofp, and sitofp with i1 type specially.
David Neto22f144c2017-06-12 14:26:21 -04003722 if ((I.getOpcode() == Instruction::ZExt ||
3723 I.getOpcode() == Instruction::SExt ||
James Price757dea82021-01-11 13:42:39 -05003724 I.getOpcode() == Instruction::UIToFP ||
3725 I.getOpcode() == Instruction::SIToFP) &&
alan-bakerb6b09dc2018-11-08 16:59:28 -05003726 OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003727 //
3728 // Generate OpSelect.
3729 //
3730
3731 // Ops[0] = Result Type ID
3732 // Ops[1] = Condition ID
3733 // Ops[2] = True Constant ID
3734 // Ops[3] = False Constant ID
SJWf93f5f32020-05-05 07:27:56 -05003735 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04003736
SJW01901d92020-05-21 08:58:31 -05003737 Ops << I.getType() << I.getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04003738
David Neto22f144c2017-06-12 14:26:21 -04003739 if (I.getOpcode() == Instruction::ZExt) {
SJW01901d92020-05-21 08:58:31 -05003740 Ops << ConstantInt::get(I.getType(), 1);
David Neto22f144c2017-06-12 14:26:21 -04003741 } else if (I.getOpcode() == Instruction::SExt) {
SJW01901d92020-05-21 08:58:31 -05003742 Ops << ConstantInt::getSigned(I.getType(), -1);
James Price757dea82021-01-11 13:42:39 -05003743 } else if (I.getOpcode() == Instruction::UIToFP) {
James Price96bd3d92020-11-23 09:01:57 -05003744 Ops << ConstantFP::get(I.getType(), 1.0);
James Price757dea82021-01-11 13:42:39 -05003745 } else if (I.getOpcode() == Instruction::SIToFP) {
3746 Ops << ConstantFP::get(I.getType(), -1.0);
David Neto22f144c2017-06-12 14:26:21 -04003747 }
David Neto22f144c2017-06-12 14:26:21 -04003748
David Neto22f144c2017-06-12 14:26:21 -04003749 if (I.getOpcode() == Instruction::ZExt) {
SJW01901d92020-05-21 08:58:31 -05003750 Ops << Constant::getNullValue(I.getType());
David Neto22f144c2017-06-12 14:26:21 -04003751 } else if (I.getOpcode() == Instruction::SExt) {
SJW01901d92020-05-21 08:58:31 -05003752 Ops << Constant::getNullValue(I.getType());
David Neto22f144c2017-06-12 14:26:21 -04003753 } else {
James Price96bd3d92020-11-23 09:01:57 -05003754 Ops << ConstantFP::get(I.getType(), 0.0);
David Neto22f144c2017-06-12 14:26:21 -04003755 }
David Neto22f144c2017-06-12 14:26:21 -04003756
SJWf93f5f32020-05-05 07:27:56 -05003757 RID = addSPIRVInst(spv::OpSelect, Ops);
alan-bakerb39c8262019-03-08 14:03:37 -05003758 } else if (!clspv::Option::Int8Support() &&
3759 I.getOpcode() == Instruction::Trunc && fromI32 && toI8) {
David Netod2de94a2017-08-28 17:27:47 -04003760 // The SPIR-V target type is a 32-bit int. Keep only the bottom
3761 // 8 bits.
3762 // Before:
3763 // %result = trunc i32 %a to i8
3764 // After
3765 // %result = OpBitwiseAnd %uint %a %uint_255
3766
SJWf93f5f32020-05-05 07:27:56 -05003767 SPIRVOperandVec Ops;
David Netod2de94a2017-08-28 17:27:47 -04003768
SJW806a5d82020-07-15 12:51:38 -05003769 Ops << OpTy << I.getOperand(0) << getSPIRVInt32Constant(255);
David Netod2de94a2017-08-28 17:27:47 -04003770
SJWf93f5f32020-05-05 07:27:56 -05003771 RID = addSPIRVInst(spv::OpBitwiseAnd, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003772 } else {
3773 // Ops[0] = Result Type ID
3774 // Ops[1] = Source Value ID
SJWf93f5f32020-05-05 07:27:56 -05003775 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04003776
SJW01901d92020-05-21 08:58:31 -05003777 Ops << I.getType() << I.getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04003778
SJWf93f5f32020-05-05 07:27:56 -05003779 RID = addSPIRVInst(GetSPIRVCastOpcode(I), Ops);
David Neto22f144c2017-06-12 14:26:21 -04003780 }
3781 } else if (isa<BinaryOperator>(I)) {
3782 //
3783 // Generate SPIRV instructions for binary operators.
3784 //
3785
3786 // Handle xor with i1 type specially.
3787 if (I.getOpcode() == Instruction::Xor &&
3788 I.getType() == Type::getInt1Ty(Context) &&
Kévin Petit24272b62018-10-18 19:16:12 +00003789 ((isa<ConstantInt>(I.getOperand(0)) &&
3790 !cast<ConstantInt>(I.getOperand(0))->isZero()) ||
3791 (isa<ConstantInt>(I.getOperand(1)) &&
3792 !cast<ConstantInt>(I.getOperand(1))->isZero()))) {
David Neto22f144c2017-06-12 14:26:21 -04003793 //
3794 // Generate OpLogicalNot.
3795 //
3796 // Ops[0] = Result Type ID
3797 // Ops[1] = Operand
SJWf93f5f32020-05-05 07:27:56 -05003798 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04003799
SJW01901d92020-05-21 08:58:31 -05003800 Ops << I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003801
3802 Value *CondV = I.getOperand(0);
3803 if (isa<Constant>(I.getOperand(0))) {
3804 CondV = I.getOperand(1);
3805 }
SJW01901d92020-05-21 08:58:31 -05003806 Ops << CondV;
David Neto22f144c2017-06-12 14:26:21 -04003807
SJWf93f5f32020-05-05 07:27:56 -05003808 RID = addSPIRVInst(spv::OpLogicalNot, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003809 } else {
3810 // Ops[0] = Result Type ID
3811 // Ops[1] = Operand 0
3812 // Ops[2] = Operand 1
SJWf93f5f32020-05-05 07:27:56 -05003813 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04003814
SJW01901d92020-05-21 08:58:31 -05003815 Ops << I.getType() << I.getOperand(0) << I.getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04003816
SJWf93f5f32020-05-05 07:27:56 -05003817 RID = addSPIRVInst(GetSPIRVBinaryOpcode(I), Ops);
David Neto22f144c2017-06-12 14:26:21 -04003818 }
alan-bakerc9c55ae2019-12-02 16:01:27 -05003819 } else if (I.getOpcode() == Instruction::FNeg) {
3820 // The only unary operator.
3821 //
3822 // Ops[0] = Result Type ID
3823 // Ops[1] = Operand 0
SJW01901d92020-05-21 08:58:31 -05003824 SPIRVOperandVec Ops;
alan-bakerc9c55ae2019-12-02 16:01:27 -05003825
SJW01901d92020-05-21 08:58:31 -05003826 Ops << I.getType() << I.getOperand(0);
3827 RID = addSPIRVInst(spv::OpFNegate, Ops);
Marco Antognini68e5c512020-09-09 16:08:57 +01003828 } else if (I.getOpcode() == Instruction::Unreachable) {
3829 RID = addSPIRVInst(spv::OpUnreachable);
David Neto22f144c2017-06-12 14:26:21 -04003830 } else {
3831 I.print(errs());
3832 llvm_unreachable("Unsupported instruction???");
3833 }
3834 break;
3835 }
3836 case Instruction::GetElementPtr: {
3837 auto &GlobalConstArgSet = getGlobalConstArgSet();
3838
3839 //
3840 // Generate OpAccessChain.
3841 //
3842 GetElementPtrInst *GEP = cast<GetElementPtrInst>(&I);
3843
3844 //
3845 // Generate OpAccessChain.
3846 //
3847
3848 // Ops[0] = Result Type ID
3849 // Ops[1] = Base ID
3850 // Ops[2] ... Ops[n] = Indexes ID
SJWf93f5f32020-05-05 07:27:56 -05003851 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04003852
alan-bakerb6b09dc2018-11-08 16:59:28 -05003853 PointerType *ResultType = cast<PointerType>(GEP->getType());
David Neto22f144c2017-06-12 14:26:21 -04003854 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate ||
3855 GlobalConstArgSet.count(GEP->getPointerOperand())) {
3856 // Use pointer type with private address space for global constant.
3857 Type *EleTy = I.getType()->getPointerElementType();
David Neto1a1a0582017-07-07 12:01:44 -04003858 ResultType = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
David Neto22f144c2017-06-12 14:26:21 -04003859 }
David Neto257c3892018-04-11 13:19:45 -04003860
SJW01901d92020-05-21 08:58:31 -05003861 Ops << ResultType;
David Neto22f144c2017-06-12 14:26:21 -04003862
David Neto862b7d82018-06-14 18:48:37 -04003863 // Generate the base pointer.
SJW01901d92020-05-21 08:58:31 -05003864 Ops << GEP->getPointerOperand();
David Neto22f144c2017-06-12 14:26:21 -04003865
David Neto862b7d82018-06-14 18:48:37 -04003866 // TODO(dneto): Simplify the following?
David Neto22f144c2017-06-12 14:26:21 -04003867
3868 //
3869 // Follows below rules for gep.
3870 //
David Neto862b7d82018-06-14 18:48:37 -04003871 // 1. If gep's first index is 0 generate OpAccessChain and ignore gep's
3872 // first index.
David Neto22f144c2017-06-12 14:26:21 -04003873 // 2. If gep's first index is not 0, generate OpPtrAccessChain and use gep's
3874 // first index.
3875 // 3. If gep's first index is not constant, generate OpPtrAccessChain and
3876 // use gep's first index.
3877 // 4. If it is not above case 1, 2 and 3, generate OpAccessChain and use
3878 // gep's first index.
3879 //
3880 spv::Op Opcode = spv::OpAccessChain;
3881 unsigned offset = 0;
3882 if (ConstantInt *CstInt = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
David Neto862b7d82018-06-14 18:48:37 -04003883 if (CstInt->getZExtValue() == 0) {
David Neto22f144c2017-06-12 14:26:21 -04003884 offset = 1;
David Neto862b7d82018-06-14 18:48:37 -04003885 } else if (CstInt->getZExtValue() != 0) {
David Neto22f144c2017-06-12 14:26:21 -04003886 Opcode = spv::OpPtrAccessChain;
David Neto22f144c2017-06-12 14:26:21 -04003887 }
David Neto862b7d82018-06-14 18:48:37 -04003888 } else {
David Neto22f144c2017-06-12 14:26:21 -04003889 Opcode = spv::OpPtrAccessChain;
David Neto1a1a0582017-07-07 12:01:44 -04003890 }
3891
3892 if (Opcode == spv::OpPtrAccessChain) {
alan-baker7506abb2020-09-10 15:02:55 -04003893 // Shader validation in the SPIR-V spec requires that the base pointer to
3894 // OpPtrAccessChain (in StorageBuffer storage class) be decorated with
3895 // ArrayStride.
alan-baker5b86ed72019-02-15 08:26:50 -05003896 auto address_space = ResultType->getAddressSpace();
3897 setVariablePointersCapabilities(address_space);
3898 switch (GetStorageClass(address_space)) {
Alan Bakerfcda9482018-10-02 17:09:59 -04003899 case spv::StorageClassStorageBuffer:
David Neto1a1a0582017-07-07 12:01:44 -04003900 // Save the need to generate an ArrayStride decoration. But defer
3901 // generation until later, so we only make one decoration.
alan-baker7506abb2020-09-10 15:02:55 -04003902 getTypesNeedingArrayStride().insert(GEP->getPointerOperandType());
3903 break;
3904 case spv::StorageClassWorkgroup:
Alan Bakerfcda9482018-10-02 17:09:59 -04003905 break;
3906 default:
alan-baker7506abb2020-09-10 15:02:55 -04003907 llvm_unreachable(
3908 "OpPtrAccessChain is not supported for this storage class");
Alan Bakerfcda9482018-10-02 17:09:59 -04003909 break;
David Neto1a1a0582017-07-07 12:01:44 -04003910 }
David Neto22f144c2017-06-12 14:26:21 -04003911 }
3912
3913 for (auto II = GEP->idx_begin() + offset; II != GEP->idx_end(); II++) {
SJW01901d92020-05-21 08:58:31 -05003914 Ops << *II;
David Neto22f144c2017-06-12 14:26:21 -04003915 }
3916
SJWf93f5f32020-05-05 07:27:56 -05003917 RID = addSPIRVInst(Opcode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003918 break;
3919 }
3920 case Instruction::ExtractValue: {
3921 ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
3922 // Ops[0] = Result Type ID
3923 // Ops[1] = Composite ID
3924 // Ops[2] ... Ops[n] = Indexes (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05003925 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04003926
SJW01901d92020-05-21 08:58:31 -05003927 Ops << I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003928
SJW01901d92020-05-21 08:58:31 -05003929 Ops << EVI->getAggregateOperand();
David Neto22f144c2017-06-12 14:26:21 -04003930
3931 for (auto &Index : EVI->indices()) {
SJW01901d92020-05-21 08:58:31 -05003932 Ops << Index;
David Neto22f144c2017-06-12 14:26:21 -04003933 }
3934
SJWf93f5f32020-05-05 07:27:56 -05003935 RID = addSPIRVInst(spv::OpCompositeExtract, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003936 break;
3937 }
3938 case Instruction::InsertValue: {
3939 InsertValueInst *IVI = cast<InsertValueInst>(&I);
3940 // Ops[0] = Result Type ID
3941 // Ops[1] = Object ID
3942 // Ops[2] = Composite ID
3943 // Ops[3] ... Ops[n] = Indexes (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05003944 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04003945
SJW01901d92020-05-21 08:58:31 -05003946 Ops << I.getType() << IVI->getInsertedValueOperand()
3947 << IVI->getAggregateOperand();
David Neto22f144c2017-06-12 14:26:21 -04003948
3949 for (auto &Index : IVI->indices()) {
SJW01901d92020-05-21 08:58:31 -05003950 Ops << Index;
David Neto22f144c2017-06-12 14:26:21 -04003951 }
3952
SJWf93f5f32020-05-05 07:27:56 -05003953 RID = addSPIRVInst(spv::OpCompositeInsert, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003954 break;
3955 }
3956 case Instruction::Select: {
3957 //
3958 // Generate OpSelect.
3959 //
3960
3961 // Ops[0] = Result Type ID
3962 // Ops[1] = Condition ID
3963 // Ops[2] = True Constant ID
3964 // Ops[3] = False Constant ID
SJWf93f5f32020-05-05 07:27:56 -05003965 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04003966
3967 // Find SPIRV instruction for parameter type.
3968 auto Ty = I.getType();
3969 if (Ty->isPointerTy()) {
3970 auto PointeeTy = Ty->getPointerElementType();
3971 if (PointeeTy->isStructTy() &&
3972 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
3973 Ty = PointeeTy;
alan-baker5b86ed72019-02-15 08:26:50 -05003974 } else {
3975 // Selecting between pointers requires variable pointers.
3976 setVariablePointersCapabilities(Ty->getPointerAddressSpace());
3977 if (!hasVariablePointers() && !selectFromSameObject(&I)) {
SJW01901d92020-05-21 08:58:31 -05003978 setVariablePointers();
alan-baker5b86ed72019-02-15 08:26:50 -05003979 }
David Neto22f144c2017-06-12 14:26:21 -04003980 }
3981 }
3982
SJW01901d92020-05-21 08:58:31 -05003983 Ops << Ty << I.getOperand(0) << I.getOperand(1) << I.getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04003984
SJWf93f5f32020-05-05 07:27:56 -05003985 RID = addSPIRVInst(spv::OpSelect, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003986 break;
3987 }
3988 case Instruction::ExtractElement: {
3989 // Handle <4 x i8> type manually.
3990 Type *CompositeTy = I.getOperand(0)->getType();
3991 if (is4xi8vec(CompositeTy)) {
3992 //
3993 // Generate OpShiftRightLogical and OpBitwiseAnd for extractelement with
3994 // <4 x i8>.
3995 //
3996
3997 //
3998 // Generate OpShiftRightLogical
3999 //
4000 // Ops[0] = Result Type ID
4001 // Ops[1] = Operand 0
4002 // Ops[2] = Operand 1
4003 //
SJWf93f5f32020-05-05 07:27:56 -05004004 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004005
SJW01901d92020-05-21 08:58:31 -05004006 Ops << CompositeTy << I.getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04004007
SJW01901d92020-05-21 08:58:31 -05004008 SPIRVID Op1ID = 0;
David Neto22f144c2017-06-12 14:26:21 -04004009 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
4010 // Handle constant index.
SJW806a5d82020-07-15 12:51:38 -05004011 uint32_t Idx = static_cast<uint32_t>(CI->getZExtValue());
4012 Op1ID = getSPIRVInt32Constant(Idx * 8);
David Neto22f144c2017-06-12 14:26:21 -04004013 } else {
4014 // Handle variable index.
SJWf93f5f32020-05-05 07:27:56 -05004015 SPIRVOperandVec TmpOps;
David Neto22f144c2017-06-12 14:26:21 -04004016
SJW806a5d82020-07-15 12:51:38 -05004017 TmpOps << Type::getInt32Ty(Context) << I.getOperand(1)
4018 << getSPIRVInt32Constant(8);
David Neto22f144c2017-06-12 14:26:21 -04004019
SJWf93f5f32020-05-05 07:27:56 -05004020 Op1ID = addSPIRVInst(spv::OpIMul, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04004021 }
SJW01901d92020-05-21 08:58:31 -05004022 Ops << Op1ID;
David Neto22f144c2017-06-12 14:26:21 -04004023
SJW01901d92020-05-21 08:58:31 -05004024 SPIRVID ShiftID = addSPIRVInst(spv::OpShiftRightLogical, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004025
4026 //
4027 // Generate OpBitwiseAnd
4028 //
4029 // Ops[0] = Result Type ID
4030 // Ops[1] = Operand 0
4031 // Ops[2] = Operand 1
4032 //
4033 Ops.clear();
4034
SJW806a5d82020-07-15 12:51:38 -05004035 Ops << CompositeTy << ShiftID << getSPIRVInt32Constant(0xFF);
David Neto22f144c2017-06-12 14:26:21 -04004036
SJWf93f5f32020-05-05 07:27:56 -05004037 RID = addSPIRVInst(spv::OpBitwiseAnd, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004038 break;
4039 }
4040
4041 // Ops[0] = Result Type ID
4042 // Ops[1] = Composite ID
4043 // Ops[2] ... Ops[n] = Indexes (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05004044 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004045
SJW01901d92020-05-21 08:58:31 -05004046 Ops << I.getType() << I.getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04004047
4048 spv::Op Opcode = spv::OpCompositeExtract;
4049 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
SJW01901d92020-05-21 08:58:31 -05004050 Ops << static_cast<uint32_t>(CI->getZExtValue());
David Neto22f144c2017-06-12 14:26:21 -04004051 } else {
SJW01901d92020-05-21 08:58:31 -05004052 Ops << I.getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04004053 Opcode = spv::OpVectorExtractDynamic;
4054 }
4055
SJWf93f5f32020-05-05 07:27:56 -05004056 RID = addSPIRVInst(Opcode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004057 break;
4058 }
4059 case Instruction::InsertElement: {
4060 // Handle <4 x i8> type manually.
4061 Type *CompositeTy = I.getOperand(0)->getType();
4062 if (is4xi8vec(CompositeTy)) {
SJW806a5d82020-07-15 12:51:38 -05004063 SPIRVID CstFFID = getSPIRVInt32Constant(0xFF);
David Neto22f144c2017-06-12 14:26:21 -04004064
SJW01901d92020-05-21 08:58:31 -05004065 SPIRVID ShiftAmountID = 0;
David Neto22f144c2017-06-12 14:26:21 -04004066 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
4067 // Handle constant index.
SJW806a5d82020-07-15 12:51:38 -05004068 uint32_t Idx = static_cast<uint32_t>(CI->getZExtValue());
4069 ShiftAmountID = getSPIRVInt32Constant(Idx * 8);
David Neto22f144c2017-06-12 14:26:21 -04004070 } else {
4071 // Handle variable index.
SJWf93f5f32020-05-05 07:27:56 -05004072 SPIRVOperandVec TmpOps;
David Neto22f144c2017-06-12 14:26:21 -04004073
SJW806a5d82020-07-15 12:51:38 -05004074 TmpOps << Type::getInt32Ty(Context) << I.getOperand(2)
4075 << getSPIRVInt32Constant(8);
David Neto22f144c2017-06-12 14:26:21 -04004076
SJWf93f5f32020-05-05 07:27:56 -05004077 ShiftAmountID = addSPIRVInst(spv::OpIMul, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04004078 }
4079
4080 //
4081 // Generate mask operations.
4082 //
4083
4084 // ShiftLeft mask according to index of insertelement.
SJWf93f5f32020-05-05 07:27:56 -05004085 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004086
SJW01901d92020-05-21 08:58:31 -05004087 Ops << CompositeTy << CstFFID << ShiftAmountID;
David Neto22f144c2017-06-12 14:26:21 -04004088
SJW01901d92020-05-21 08:58:31 -05004089 SPIRVID MaskID = addSPIRVInst(spv::OpShiftLeftLogical, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004090
4091 // Inverse mask.
4092 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05004093 Ops << CompositeTy << MaskID;
David Neto22f144c2017-06-12 14:26:21 -04004094
SJW01901d92020-05-21 08:58:31 -05004095 SPIRVID InvMaskID = addSPIRVInst(spv::OpNot, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004096
4097 // Apply mask.
4098 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05004099 Ops << CompositeTy << I.getOperand(0) << InvMaskID;
David Neto22f144c2017-06-12 14:26:21 -04004100
SJW01901d92020-05-21 08:58:31 -05004101 SPIRVID OrgValID = addSPIRVInst(spv::OpBitwiseAnd, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004102
4103 // Create correct value according to index of insertelement.
4104 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05004105 Ops << CompositeTy << I.getOperand(1) << ShiftAmountID;
David Neto22f144c2017-06-12 14:26:21 -04004106
SJW01901d92020-05-21 08:58:31 -05004107 SPIRVID InsertValID = addSPIRVInst(spv::OpShiftLeftLogical, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004108
4109 // Insert value to original value.
4110 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05004111 Ops << CompositeTy << OrgValID << InsertValID;
David Neto22f144c2017-06-12 14:26:21 -04004112
SJWf93f5f32020-05-05 07:27:56 -05004113 RID = addSPIRVInst(spv::OpBitwiseOr, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004114 break;
4115 }
4116
SJWf93f5f32020-05-05 07:27:56 -05004117 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004118
James Priced26efea2018-06-09 23:28:32 +01004119 // Ops[0] = Result Type ID
SJW01901d92020-05-21 08:58:31 -05004120 Ops << I.getType();
David Neto22f144c2017-06-12 14:26:21 -04004121
4122 spv::Op Opcode = spv::OpCompositeInsert;
4123 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
David Neto257c3892018-04-11 13:19:45 -04004124 const auto value = CI->getZExtValue();
4125 assert(value <= UINT32_MAX);
James Priced26efea2018-06-09 23:28:32 +01004126 // Ops[1] = Object ID
4127 // Ops[2] = Composite ID
4128 // Ops[3] ... Ops[n] = Indexes (Literal Number)
SJW01901d92020-05-21 08:58:31 -05004129 Ops << I.getOperand(1) << I.getOperand(0) << static_cast<uint32_t>(value);
David Neto22f144c2017-06-12 14:26:21 -04004130 } else {
James Priced26efea2018-06-09 23:28:32 +01004131 // Ops[1] = Composite ID
4132 // Ops[2] = Object ID
4133 // Ops[3] ... Ops[n] = Indexes (Literal Number)
SJW01901d92020-05-21 08:58:31 -05004134 Ops << I.getOperand(0) << I.getOperand(1) << I.getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04004135 Opcode = spv::OpVectorInsertDynamic;
4136 }
4137
SJWf93f5f32020-05-05 07:27:56 -05004138 RID = addSPIRVInst(Opcode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004139 break;
4140 }
4141 case Instruction::ShuffleVector: {
4142 // Ops[0] = Result Type ID
4143 // Ops[1] = Vector 1 ID
4144 // Ops[2] = Vector 2 ID
4145 // Ops[3] ... Ops[n] = Components (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05004146 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004147
SJW01901d92020-05-21 08:58:31 -05004148 Ops << I.getType() << I.getOperand(0) << I.getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04004149
alan-bakerc9666712020-04-01 16:31:21 -04004150 auto shuffle = cast<ShuffleVectorInst>(&I);
4151 SmallVector<int, 4> mask;
4152 shuffle->getShuffleMask(mask);
4153 for (auto i : mask) {
4154 if (i == UndefMaskElem) {
4155 if (clspv::Option::HackUndef())
4156 // Use 0 instead of undef.
SJW01901d92020-05-21 08:58:31 -05004157 Ops << 0;
alan-bakerc9666712020-04-01 16:31:21 -04004158 else
4159 // Undef for shuffle in SPIR-V.
SJW01901d92020-05-21 08:58:31 -05004160 Ops << 0xffffffff;
David Neto22f144c2017-06-12 14:26:21 -04004161 } else {
SJW01901d92020-05-21 08:58:31 -05004162 Ops << i;
David Neto22f144c2017-06-12 14:26:21 -04004163 }
4164 }
4165
SJWf93f5f32020-05-05 07:27:56 -05004166 RID = addSPIRVInst(spv::OpVectorShuffle, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004167 break;
4168 }
4169 case Instruction::ICmp:
4170 case Instruction::FCmp: {
4171 CmpInst *CmpI = cast<CmpInst>(&I);
4172
David Netod4ca2e62017-07-06 18:47:35 -04004173 // Pointer equality is invalid.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004174 Type *ArgTy = CmpI->getOperand(0)->getType();
David Netod4ca2e62017-07-06 18:47:35 -04004175 if (isa<PointerType>(ArgTy)) {
4176 CmpI->print(errs());
alan-baker21574d32020-01-29 16:00:31 -05004177 std::string name = I.getParent()->getParent()->getName().str();
David Netod4ca2e62017-07-06 18:47:35 -04004178 errs()
4179 << "\nPointer equality test is not supported by SPIR-V for Vulkan, "
4180 << "in function " << name << "\n";
4181 llvm_unreachable("Pointer equality check is invalid");
4182 break;
4183 }
4184
SJWf93f5f32020-05-05 07:27:56 -05004185 SPIRVOperandVec Ops;
alan-baker15106572020-11-06 15:08:10 -05004186 if (CmpI->getPredicate() == CmpInst::FCMP_ORD ||
4187 CmpI->getPredicate() == CmpInst::FCMP_UNO) {
4188 // Implement ordered and unordered comparisons are OpIsNan instructions.
4189 // Optimize the constants to simplify the resulting code.
4190 auto lhs = CmpI->getOperand(0);
4191 auto rhs = CmpI->getOperand(1);
4192 auto const_lhs = dyn_cast_or_null<Constant>(lhs);
4193 auto const_rhs = dyn_cast_or_null<Constant>(rhs);
4194 if ((const_lhs && const_lhs->isNaN()) ||
4195 (const_rhs && const_rhs->isNaN())) {
4196 // Result is a constant, false of ordered, true for unordered.
4197 if (CmpI->getPredicate() == CmpInst::FCMP_ORD) {
4198 RID = getSPIRVConstant(ConstantInt::getFalse(CmpI->getType()));
4199 } else {
4200 RID = getSPIRVConstant(ConstantInt::getTrue(CmpI->getType()));
4201 }
4202 break;
4203 }
4204 SPIRVID lhs_id;
4205 SPIRVID rhs_id;
4206 if (!const_lhs) {
4207 // Generate OpIsNan for the lhs.
4208 Ops.clear();
4209 Ops << CmpI->getType() << lhs;
4210 lhs_id = addSPIRVInst(spv::OpIsNan, Ops);
4211 }
4212 if (!const_rhs) {
4213 // Generate OpIsNan for the rhs.
4214 Ops.clear();
4215 Ops << CmpI->getType() << rhs;
4216 rhs_id = addSPIRVInst(spv::OpIsNan, Ops);
4217 }
4218 if (lhs_id.isValid() && rhs_id.isValid()) {
4219 // Or the results for the lhs and rhs.
4220 Ops.clear();
4221 Ops << CmpI->getType() << lhs_id << rhs_id;
4222 RID = addSPIRVInst(spv::OpLogicalOr, Ops);
4223 } else {
4224 RID = lhs_id.isValid() ? lhs_id : rhs_id;
4225 }
4226 if (CmpI->getPredicate() == CmpInst::FCMP_ORD) {
4227 // For ordered comparisons, invert the intermediate result.
4228 Ops.clear();
4229 Ops << CmpI->getType() << RID;
4230 RID = addSPIRVInst(spv::OpLogicalNot, Ops);
4231 }
4232 break;
4233 } else {
4234 // Remaining comparisons map directly to SPIR-V opcodes.
4235 // Ops[0] = Result Type ID
4236 // Ops[1] = Operand 1 ID
4237 // Ops[2] = Operand 2 ID
4238 Ops << CmpI->getType() << CmpI->getOperand(0) << CmpI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04004239
alan-baker15106572020-11-06 15:08:10 -05004240 spv::Op Opcode = GetSPIRVCmpOpcode(CmpI);
4241 RID = addSPIRVInst(Opcode, Ops);
4242 }
David Neto22f144c2017-06-12 14:26:21 -04004243 break;
4244 }
4245 case Instruction::Br: {
SJW88ed5fe2020-05-11 12:40:57 -05004246 // Branch instruction is deferred because it needs label's ID.
4247 BasicBlock *BrBB = I.getParent();
4248 if (ContinueBlocks.count(BrBB) || MergeBlocks.count(BrBB)) {
4249 // Placeholder for Merge operation
4250 RID = addSPIRVPlaceholder(&I);
4251 }
4252 RID = addSPIRVPlaceholder(&I);
David Neto22f144c2017-06-12 14:26:21 -04004253 break;
4254 }
4255 case Instruction::Switch: {
4256 I.print(errs());
4257 llvm_unreachable("Unsupported instruction???");
4258 break;
4259 }
4260 case Instruction::IndirectBr: {
4261 I.print(errs());
4262 llvm_unreachable("Unsupported instruction???");
4263 break;
4264 }
4265 case Instruction::PHI: {
SJW88ed5fe2020-05-11 12:40:57 -05004266 // PHI instruction is deferred because it needs label's ID.
4267 RID = addSPIRVPlaceholder(&I);
David Neto22f144c2017-06-12 14:26:21 -04004268 break;
4269 }
4270 case Instruction::Alloca: {
4271 //
4272 // Generate OpVariable.
4273 //
4274 // Ops[0] : Result Type ID
4275 // Ops[1] : Storage Class
SJWf93f5f32020-05-05 07:27:56 -05004276 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004277
SJW01901d92020-05-21 08:58:31 -05004278 Ops << I.getType() << spv::StorageClassFunction;
David Neto22f144c2017-06-12 14:26:21 -04004279
SJWf93f5f32020-05-05 07:27:56 -05004280 RID = addSPIRVInst(spv::OpVariable, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004281 break;
4282 }
4283 case Instruction::Load: {
4284 LoadInst *LD = cast<LoadInst>(&I);
4285 //
4286 // Generate OpLoad.
4287 //
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04004288
alan-baker5b86ed72019-02-15 08:26:50 -05004289 if (LD->getType()->isPointerTy()) {
4290 // Loading a pointer requires variable pointers.
4291 setVariablePointersCapabilities(LD->getType()->getPointerAddressSpace());
4292 }
David Neto22f144c2017-06-12 14:26:21 -04004293
SJW01901d92020-05-21 08:58:31 -05004294 SPIRVID PointerID = getSPIRVValue(LD->getPointerOperand());
David Netoa60b00b2017-09-15 16:34:09 -04004295 // This is a hack to work around what looks like a driver bug.
4296 // When we're loading from the special variable holding the WorkgroupSize
David Neto0a2f98d2017-09-15 19:38:40 -04004297 // builtin value, use an OpBitWiseAnd of the value's ID rather than
4298 // generating a load.
David Neto66cfe642018-03-24 06:13:56 -07004299 // TODO(dneto): Remove this awful hack once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -04004300 if (PointerID == WorkgroupSizeVarID) {
David Neto0a2f98d2017-09-15 19:38:40 -04004301 // Generate a bitwise-and of the original value with itself.
4302 // We should have been able to get away with just an OpCopyObject,
4303 // but we need something more complex to get past certain driver bugs.
4304 // This is ridiculous, but necessary.
4305 // TODO(dneto): Revisit this once drivers fix their bugs.
4306
SJWf93f5f32020-05-05 07:27:56 -05004307 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05004308 Ops << LD->getType() << WorkgroupSizeValueID << WorkgroupSizeValueID;
David Neto0a2f98d2017-09-15 19:38:40 -04004309
SJWf93f5f32020-05-05 07:27:56 -05004310 RID = addSPIRVInst(spv::OpBitwiseAnd, Ops);
David Netoa60b00b2017-09-15 16:34:09 -04004311 break;
4312 }
4313
4314 // This is the normal path. Generate a load.
4315
David Neto22f144c2017-06-12 14:26:21 -04004316 // Ops[0] = Result Type ID
4317 // Ops[1] = Pointer ID
4318 // Ops[2] ... Ops[n] = Optional Memory Access
4319 //
4320 // TODO: Do we need to implement Optional Memory Access???
David Neto0a2f98d2017-09-15 19:38:40 -04004321
SJWf93f5f32020-05-05 07:27:56 -05004322 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05004323 Ops << LD->getType() << LD->getPointerOperand();
David Neto22f144c2017-06-12 14:26:21 -04004324
SJWf93f5f32020-05-05 07:27:56 -05004325 RID = addSPIRVInst(spv::OpLoad, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004326 break;
4327 }
4328 case Instruction::Store: {
4329 StoreInst *ST = cast<StoreInst>(&I);
4330 //
4331 // Generate OpStore.
4332 //
4333
alan-baker5b86ed72019-02-15 08:26:50 -05004334 if (ST->getValueOperand()->getType()->isPointerTy()) {
4335 // Storing a pointer requires variable pointers.
4336 setVariablePointersCapabilities(
4337 ST->getValueOperand()->getType()->getPointerAddressSpace());
4338 }
4339
David Neto22f144c2017-06-12 14:26:21 -04004340 // Ops[0] = Pointer ID
4341 // Ops[1] = Object ID
4342 // Ops[2] ... Ops[n] = Optional Memory Access (later???)
4343 //
4344 // TODO: Do we need to implement Optional Memory Access???
SJWf93f5f32020-05-05 07:27:56 -05004345 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05004346 Ops << ST->getPointerOperand() << ST->getValueOperand();
David Neto22f144c2017-06-12 14:26:21 -04004347
SJWf93f5f32020-05-05 07:27:56 -05004348 RID = addSPIRVInst(spv::OpStore, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004349 break;
4350 }
4351 case Instruction::AtomicCmpXchg: {
4352 I.print(errs());
4353 llvm_unreachable("Unsupported instruction???");
4354 break;
4355 }
4356 case Instruction::AtomicRMW: {
Neil Henning39672102017-09-29 14:33:13 +01004357 AtomicRMWInst *AtomicRMW = dyn_cast<AtomicRMWInst>(&I);
4358
4359 spv::Op opcode;
4360
4361 switch (AtomicRMW->getOperation()) {
4362 default:
4363 I.print(errs());
4364 llvm_unreachable("Unsupported instruction???");
4365 case llvm::AtomicRMWInst::Add:
4366 opcode = spv::OpAtomicIAdd;
4367 break;
4368 case llvm::AtomicRMWInst::Sub:
4369 opcode = spv::OpAtomicISub;
4370 break;
4371 case llvm::AtomicRMWInst::Xchg:
4372 opcode = spv::OpAtomicExchange;
4373 break;
4374 case llvm::AtomicRMWInst::Min:
4375 opcode = spv::OpAtomicSMin;
4376 break;
4377 case llvm::AtomicRMWInst::Max:
4378 opcode = spv::OpAtomicSMax;
4379 break;
4380 case llvm::AtomicRMWInst::UMin:
4381 opcode = spv::OpAtomicUMin;
4382 break;
4383 case llvm::AtomicRMWInst::UMax:
4384 opcode = spv::OpAtomicUMax;
4385 break;
4386 case llvm::AtomicRMWInst::And:
4387 opcode = spv::OpAtomicAnd;
4388 break;
4389 case llvm::AtomicRMWInst::Or:
4390 opcode = spv::OpAtomicOr;
4391 break;
4392 case llvm::AtomicRMWInst::Xor:
4393 opcode = spv::OpAtomicXor;
4394 break;
4395 }
4396
4397 //
4398 // Generate OpAtomic*.
4399 //
SJWf93f5f32020-05-05 07:27:56 -05004400 SPIRVOperandVec Ops;
Neil Henning39672102017-09-29 14:33:13 +01004401
SJW01901d92020-05-21 08:58:31 -05004402 Ops << I.getType() << AtomicRMW->getPointerOperand();
Neil Henning39672102017-09-29 14:33:13 +01004403
SJW806a5d82020-07-15 12:51:38 -05004404 const auto ConstantScopeDevice = getSPIRVInt32Constant(spv::ScopeDevice);
SJW01901d92020-05-21 08:58:31 -05004405 Ops << ConstantScopeDevice;
Neil Henning39672102017-09-29 14:33:13 +01004406
SJW806a5d82020-07-15 12:51:38 -05004407 const auto ConstantMemorySemantics =
4408 getSPIRVInt32Constant(spv::MemorySemanticsUniformMemoryMask |
4409 spv::MemorySemanticsSequentiallyConsistentMask);
SJW01901d92020-05-21 08:58:31 -05004410 Ops << ConstantMemorySemantics << AtomicRMW->getValOperand();
Neil Henning39672102017-09-29 14:33:13 +01004411
SJWf93f5f32020-05-05 07:27:56 -05004412 RID = addSPIRVInst(opcode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004413 break;
4414 }
4415 case Instruction::Fence: {
4416 I.print(errs());
4417 llvm_unreachable("Unsupported instruction???");
4418 break;
4419 }
4420 case Instruction::Call: {
4421 CallInst *Call = dyn_cast<CallInst>(&I);
SJW806a5d82020-07-15 12:51:38 -05004422 RID = GenerateInstructionFromCall(Call);
David Neto22f144c2017-06-12 14:26:21 -04004423 break;
4424 }
4425 case Instruction::Ret: {
4426 unsigned NumOps = I.getNumOperands();
4427 if (NumOps == 0) {
4428 //
4429 // Generate OpReturn.
4430 //
SJWf93f5f32020-05-05 07:27:56 -05004431 RID = addSPIRVInst(spv::OpReturn);
David Neto22f144c2017-06-12 14:26:21 -04004432 } else {
4433 //
4434 // Generate OpReturnValue.
4435 //
4436
4437 // Ops[0] = Return Value ID
SJWf93f5f32020-05-05 07:27:56 -05004438 SPIRVOperandVec Ops;
David Neto257c3892018-04-11 13:19:45 -04004439
SJW01901d92020-05-21 08:58:31 -05004440 Ops << I.getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04004441
SJWf93f5f32020-05-05 07:27:56 -05004442 RID = addSPIRVInst(spv::OpReturnValue, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004443 break;
4444 }
4445 break;
4446 }
4447 }
SJWf93f5f32020-05-05 07:27:56 -05004448
4449 // Register Instruction to ValueMap.
SJW01901d92020-05-21 08:58:31 -05004450 if (RID.isValid()) {
SJWf93f5f32020-05-05 07:27:56 -05004451 VMap[&I] = RID;
4452 }
David Neto22f144c2017-06-12 14:26:21 -04004453}
4454
4455void SPIRVProducerPass::GenerateFuncEpilogue() {
David Neto22f144c2017-06-12 14:26:21 -04004456 //
4457 // Generate OpFunctionEnd
4458 //
SJWf93f5f32020-05-05 07:27:56 -05004459 addSPIRVInst(spv::OpFunctionEnd);
David Neto22f144c2017-06-12 14:26:21 -04004460}
4461
4462bool SPIRVProducerPass::is4xi8vec(Type *Ty) const {
alan-bakerb39c8262019-03-08 14:03:37 -05004463 // Don't specialize <4 x i8> if i8 is generally supported.
4464 if (clspv::Option::Int8Support())
4465 return false;
4466
David Neto22f144c2017-06-12 14:26:21 -04004467 LLVMContext &Context = Ty->getContext();
James Pricecf53df42020-04-20 14:41:24 -04004468 if (auto VecTy = dyn_cast<VectorType>(Ty)) {
4469 if (VecTy->getElementType() == Type::getInt8Ty(Context) &&
alan-baker5a8c3be2020-09-09 13:44:26 -04004470 VecTy->getElementCount().getKnownMinValue() == 4) {
David Neto22f144c2017-06-12 14:26:21 -04004471 return true;
4472 }
4473 }
4474
4475 return false;
4476}
4477
4478void SPIRVProducerPass::HandleDeferredInstruction() {
David Neto22f144c2017-06-12 14:26:21 -04004479 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
4480
SJW88ed5fe2020-05-11 12:40:57 -05004481 for (size_t i = 0; i < DeferredInsts.size(); ++i) {
4482 Value *Inst = DeferredInsts[i].first;
4483 SPIRVInstruction *Placeholder = DeferredInsts[i].second;
4484 SPIRVOperandVec Operands;
4485
4486 auto nextDeferred = [&i, &Inst, &DeferredInsts, &Placeholder]() {
4487 ++i;
4488 assert(DeferredInsts.size() > i);
4489 assert(Inst == DeferredInsts[i].first);
4490 Placeholder = DeferredInsts[i].second;
4491 };
David Neto22f144c2017-06-12 14:26:21 -04004492
4493 if (BranchInst *Br = dyn_cast<BranchInst>(Inst)) {
alan-baker06cad652019-12-03 17:56:47 -05004494 // Check whether this branch needs to be preceeded by merge instruction.
David Neto22f144c2017-06-12 14:26:21 -04004495 BasicBlock *BrBB = Br->getParent();
alan-baker06cad652019-12-03 17:56:47 -05004496 if (ContinueBlocks.count(BrBB)) {
David Neto22f144c2017-06-12 14:26:21 -04004497 //
4498 // Generate OpLoopMerge.
4499 //
4500 // Ops[0] = Merge Block ID
4501 // Ops[1] = Continue Target ID
4502 // Ops[2] = Selection Control
SJWf93f5f32020-05-05 07:27:56 -05004503 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004504
SJW01901d92020-05-21 08:58:31 -05004505 Ops << MergeBlocks[BrBB] << ContinueBlocks[BrBB]
4506 << spv::LoopControlMaskNone;
David Neto22f144c2017-06-12 14:26:21 -04004507
SJW88ed5fe2020-05-11 12:40:57 -05004508 replaceSPIRVInst(Placeholder, spv::OpLoopMerge, Ops);
4509
4510 nextDeferred();
4511
alan-baker06cad652019-12-03 17:56:47 -05004512 } else if (MergeBlocks.count(BrBB)) {
4513 //
4514 // Generate OpSelectionMerge.
4515 //
4516 // Ops[0] = Merge Block ID
4517 // Ops[1] = Selection Control
SJWf93f5f32020-05-05 07:27:56 -05004518 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004519
alan-baker06cad652019-12-03 17:56:47 -05004520 auto MergeBB = MergeBlocks[BrBB];
SJW01901d92020-05-21 08:58:31 -05004521 Ops << MergeBB << spv::SelectionControlMaskNone;
David Neto22f144c2017-06-12 14:26:21 -04004522
SJW88ed5fe2020-05-11 12:40:57 -05004523 replaceSPIRVInst(Placeholder, spv::OpSelectionMerge, Ops);
4524
4525 nextDeferred();
David Neto22f144c2017-06-12 14:26:21 -04004526 }
4527
4528 if (Br->isConditional()) {
4529 //
4530 // Generate OpBranchConditional.
4531 //
4532 // Ops[0] = Condition ID
4533 // Ops[1] = True Label ID
4534 // Ops[2] = False Label ID
4535 // Ops[3] ... Ops[n] = Branch weights (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05004536 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004537
SJW01901d92020-05-21 08:58:31 -05004538 Ops << Br->getCondition() << Br->getSuccessor(0) << Br->getSuccessor(1);
David Neto22f144c2017-06-12 14:26:21 -04004539
SJW88ed5fe2020-05-11 12:40:57 -05004540 replaceSPIRVInst(Placeholder, spv::OpBranchConditional, Ops);
4541
David Neto22f144c2017-06-12 14:26:21 -04004542 } else {
4543 //
4544 // Generate OpBranch.
4545 //
4546 // Ops[0] = Target Label ID
SJWf93f5f32020-05-05 07:27:56 -05004547 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004548
SJW01901d92020-05-21 08:58:31 -05004549 Ops << Br->getSuccessor(0);
David Neto22f144c2017-06-12 14:26:21 -04004550
SJW88ed5fe2020-05-11 12:40:57 -05004551 replaceSPIRVInst(Placeholder, spv::OpBranch, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004552 }
4553 } else if (PHINode *PHI = dyn_cast<PHINode>(Inst)) {
alan-baker5ed87542020-03-23 11:05:22 -04004554 if (PHI->getType()->isPointerTy() && !IsSamplerType(PHI->getType()) &&
4555 !IsImageType(PHI->getType())) {
alan-baker5b86ed72019-02-15 08:26:50 -05004556 // OpPhi on pointers requires variable pointers.
4557 setVariablePointersCapabilities(
4558 PHI->getType()->getPointerAddressSpace());
4559 if (!hasVariablePointers() && !selectFromSameObject(PHI)) {
SJW01901d92020-05-21 08:58:31 -05004560 setVariablePointers();
alan-baker5b86ed72019-02-15 08:26:50 -05004561 }
4562 }
4563
David Neto22f144c2017-06-12 14:26:21 -04004564 //
4565 // Generate OpPhi.
4566 //
4567 // Ops[0] = Result Type ID
4568 // Ops[1] ... Ops[n] = (Variable ID, Parent ID) pairs
SJWf93f5f32020-05-05 07:27:56 -05004569 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004570
SJW01901d92020-05-21 08:58:31 -05004571 Ops << PHI->getType();
David Neto22f144c2017-06-12 14:26:21 -04004572
SJW88ed5fe2020-05-11 12:40:57 -05004573 for (unsigned j = 0; j < PHI->getNumIncomingValues(); j++) {
SJW01901d92020-05-21 08:58:31 -05004574 Ops << PHI->getIncomingValue(j) << PHI->getIncomingBlock(j);
David Neto22f144c2017-06-12 14:26:21 -04004575 }
4576
SJW88ed5fe2020-05-11 12:40:57 -05004577 replaceSPIRVInst(Placeholder, spv::OpPhi, Ops);
4578
David Neto22f144c2017-06-12 14:26:21 -04004579 } else if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
4580 Function *Callee = Call->getCalledFunction();
David Neto3fbb4072017-10-16 11:28:14 -04004581 auto callee_name = Callee->getName();
David Neto22f144c2017-06-12 14:26:21 -04004582
SJW61531372020-06-09 07:31:08 -05004583 if (Builtins::Lookup(Callee) == Builtins::kClspvCompositeConstruct) {
David Netoab03f432017-11-03 17:00:44 -04004584 // Generate an OpCompositeConstruct
SJWf93f5f32020-05-05 07:27:56 -05004585 SPIRVOperandVec Ops;
David Netoab03f432017-11-03 17:00:44 -04004586
4587 // The result type.
SJW01901d92020-05-21 08:58:31 -05004588 Ops << Call->getType();
David Netoab03f432017-11-03 17:00:44 -04004589
4590 for (Use &use : Call->arg_operands()) {
SJW01901d92020-05-21 08:58:31 -05004591 Ops << use.get();
David Netoab03f432017-11-03 17:00:44 -04004592 }
4593
SJW88ed5fe2020-05-11 12:40:57 -05004594 replaceSPIRVInst(Placeholder, spv::OpCompositeConstruct, Ops);
David Netoab03f432017-11-03 17:00:44 -04004595
David Neto22f144c2017-06-12 14:26:21 -04004596 } else {
alan-baker5b86ed72019-02-15 08:26:50 -05004597 if (Call->getType()->isPointerTy()) {
4598 // Functions returning pointers require variable pointers.
4599 setVariablePointersCapabilities(
4600 Call->getType()->getPointerAddressSpace());
4601 }
4602
David Neto22f144c2017-06-12 14:26:21 -04004603 //
4604 // Generate OpFunctionCall.
4605 //
4606
4607 // Ops[0] = Result Type ID
4608 // Ops[1] = Callee Function ID
4609 // Ops[2] ... Ops[n] = Argument 0, ... , Argument n
SJWf93f5f32020-05-05 07:27:56 -05004610 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004611
SJW01901d92020-05-21 08:58:31 -05004612 Ops << Call->getType();
David Neto22f144c2017-06-12 14:26:21 -04004613
SJW01901d92020-05-21 08:58:31 -05004614 SPIRVID CalleeID = getSPIRVValue(Callee);
SJW806a5d82020-07-15 12:51:38 -05004615 if (!CalleeID.isValid()) {
David Neto43568eb2017-10-13 18:25:25 -04004616 errs() << "Can't translate function call. Missing builtin? "
David Neto862b7d82018-06-14 18:48:37 -04004617 << callee_name << " in: " << *Call << "\n";
David Neto43568eb2017-10-13 18:25:25 -04004618 // TODO(dneto): Can we error out? Enabling this llvm_unreachable
4619 // causes an infinite loop. Instead, go ahead and generate
4620 // the bad function call. A validator will catch the 0-Id.
4621 // llvm_unreachable("Can't translate function call");
4622 }
David Neto22f144c2017-06-12 14:26:21 -04004623
SJW01901d92020-05-21 08:58:31 -05004624 Ops << CalleeID;
David Neto22f144c2017-06-12 14:26:21 -04004625
David Neto22f144c2017-06-12 14:26:21 -04004626 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
SJW88ed5fe2020-05-11 12:40:57 -05004627 for (unsigned j = 0; j < CalleeFTy->getNumParams(); j++) {
4628 auto *operand = Call->getOperand(j);
alan-bakerd4d50652019-12-03 17:17:15 -05004629 auto *operand_type = operand->getType();
4630 // Images and samplers can be passed as function parameters without
4631 // variable pointers.
4632 if (operand_type->isPointerTy() && !IsImageType(operand_type) &&
4633 !IsSamplerType(operand_type)) {
alan-baker5b86ed72019-02-15 08:26:50 -05004634 auto sc =
4635 GetStorageClass(operand->getType()->getPointerAddressSpace());
4636 if (sc == spv::StorageClassStorageBuffer) {
4637 // Passing SSBO by reference requires variable pointers storage
4638 // buffer.
SJW01901d92020-05-21 08:58:31 -05004639 setVariablePointersStorageBuffer();
alan-baker5b86ed72019-02-15 08:26:50 -05004640 } else if (sc == spv::StorageClassWorkgroup) {
4641 // Workgroup references require variable pointers if they are not
4642 // memory object declarations.
4643 if (auto *operand_call = dyn_cast<CallInst>(operand)) {
4644 // Workgroup accessor represents a variable reference.
SJW61531372020-06-09 07:31:08 -05004645 if (Builtins::Lookup(operand_call->getCalledFunction()) !=
4646 Builtins::kClspvLocal)
SJW01901d92020-05-21 08:58:31 -05004647 setVariablePointers();
alan-baker5b86ed72019-02-15 08:26:50 -05004648 } else {
4649 // Arguments are function parameters.
4650 if (!isa<Argument>(operand))
SJW01901d92020-05-21 08:58:31 -05004651 setVariablePointers();
alan-baker5b86ed72019-02-15 08:26:50 -05004652 }
4653 }
4654 }
SJW01901d92020-05-21 08:58:31 -05004655 Ops << operand;
David Neto22f144c2017-06-12 14:26:21 -04004656 }
4657
SJW88ed5fe2020-05-11 12:40:57 -05004658 replaceSPIRVInst(Placeholder, spv::OpFunctionCall, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004659 }
4660 }
4661 }
4662}
4663
SJW77b87ad2020-04-21 14:37:52 -05004664void SPIRVProducerPass::HandleDeferredDecorations() {
4665 const auto &DL = module->getDataLayout();
alan-baker5a8c3be2020-09-09 13:44:26 -04004666 if (getTypesNeedingArrayStride().empty()) {
David Neto1a1a0582017-07-07 12:01:44 -04004667 return;
David Netoc6f3ab22018-04-06 18:02:31 -04004668 }
David Neto1a1a0582017-07-07 12:01:44 -04004669
David Netoc6f3ab22018-04-06 18:02:31 -04004670 // Insert ArrayStride decorations on pointer types, due to OpPtrAccessChain
4671 // instructions we generated earlier.
alan-bakerc3fd07f2020-10-22 09:48:49 -04004672 DenseSet<uint32_t> seen;
David Neto85082642018-03-24 06:55:20 -07004673 for (auto *type : getTypesNeedingArrayStride()) {
alan-bakerc3fd07f2020-10-22 09:48:49 -04004674 auto id = getSPIRVType(type);
4675 if (!seen.insert(id.get()).second)
4676 continue;
4677
David Neto85082642018-03-24 06:55:20 -07004678 Type *elemTy = nullptr;
4679 if (auto *ptrTy = dyn_cast<PointerType>(type)) {
4680 elemTy = ptrTy->getElementType();
alan-bakerb6b09dc2018-11-08 16:59:28 -05004681 } else if (auto *arrayTy = dyn_cast<ArrayType>(type)) {
alan-baker8eb435a2020-04-08 00:42:06 -04004682 elemTy = arrayTy->getElementType();
4683 } else if (auto *vecTy = dyn_cast<VectorType>(type)) {
4684 elemTy = vecTy->getElementType();
David Neto85082642018-03-24 06:55:20 -07004685 } else {
4686 errs() << "Unhandled strided type " << *type << "\n";
4687 llvm_unreachable("Unhandled strided type");
4688 }
David Neto1a1a0582017-07-07 12:01:44 -04004689
4690 // Ops[0] = Target ID
4691 // Ops[1] = Decoration (ArrayStride)
4692 // Ops[2] = Stride number (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05004693 SPIRVOperandVec Ops;
David Neto1a1a0582017-07-07 12:01:44 -04004694
David Neto85082642018-03-24 06:55:20 -07004695 // Same as DL.getIndexedOffsetInType( elemTy, { 1 } );
Alan Bakerfcda9482018-10-02 17:09:59 -04004696 const uint32_t stride = static_cast<uint32_t>(GetTypeAllocSize(elemTy, DL));
David Neto257c3892018-04-11 13:19:45 -04004697
alan-bakerc3fd07f2020-10-22 09:48:49 -04004698 Ops << id << spv::DecorationArrayStride << stride;
David Neto1a1a0582017-07-07 12:01:44 -04004699
SJWf93f5f32020-05-05 07:27:56 -05004700 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Netoc6f3ab22018-04-06 18:02:31 -04004701 }
David Neto1a1a0582017-07-07 12:01:44 -04004702}
4703
SJW61531372020-06-09 07:31:08 -05004704glsl::ExtInst
4705SPIRVProducerPass::getExtInstEnum(const Builtins::FunctionInfo &func_info) {
SJW61531372020-06-09 07:31:08 -05004706 switch (func_info.getType()) {
SJW2c317da2020-03-23 07:39:13 -05004707 case Builtins::kClamp: {
SJW61531372020-06-09 07:31:08 -05004708 auto param_type = func_info.getParameter(0);
SJW2c317da2020-03-23 07:39:13 -05004709 if (param_type.type_id == Type::FloatTyID) {
alan-bakerecc9c942020-12-07 13:13:32 -05004710 return glsl::ExtInst::ExtInstNClamp;
SJW2c317da2020-03-23 07:39:13 -05004711 }
4712 return param_type.is_signed ? glsl::ExtInst::ExtInstSClamp
4713 : glsl::ExtInst::ExtInstUClamp;
4714 }
4715 case Builtins::kMax: {
SJW61531372020-06-09 07:31:08 -05004716 auto param_type = func_info.getParameter(0);
SJW2c317da2020-03-23 07:39:13 -05004717 if (param_type.type_id == Type::FloatTyID) {
4718 return glsl::ExtInst::ExtInstFMax;
4719 }
4720 return param_type.is_signed ? glsl::ExtInst::ExtInstSMax
4721 : glsl::ExtInst::ExtInstUMax;
4722 }
4723 case Builtins::kMin: {
SJW61531372020-06-09 07:31:08 -05004724 auto param_type = func_info.getParameter(0);
SJW2c317da2020-03-23 07:39:13 -05004725 if (param_type.type_id == Type::FloatTyID) {
4726 return glsl::ExtInst::ExtInstFMin;
4727 }
4728 return param_type.is_signed ? glsl::ExtInst::ExtInstSMin
4729 : glsl::ExtInst::ExtInstUMin;
4730 }
4731 case Builtins::kAbs:
4732 return glsl::ExtInst::ExtInstSAbs;
4733 case Builtins::kFmax:
Marco Antognini55d51862020-07-21 17:50:07 +01004734 return glsl::ExtInst::ExtInstNMax;
SJW2c317da2020-03-23 07:39:13 -05004735 case Builtins::kFmin:
Marco Antognini55d51862020-07-21 17:50:07 +01004736 return glsl::ExtInst::ExtInstNMin;
SJW2c317da2020-03-23 07:39:13 -05004737 case Builtins::kDegrees:
4738 return glsl::ExtInst::ExtInstDegrees;
4739 case Builtins::kRadians:
4740 return glsl::ExtInst::ExtInstRadians;
4741 case Builtins::kMix:
4742 return glsl::ExtInst::ExtInstFMix;
4743 case Builtins::kAcos:
4744 case Builtins::kAcospi:
4745 return glsl::ExtInst::ExtInstAcos;
4746 case Builtins::kAcosh:
4747 return glsl::ExtInst::ExtInstAcosh;
4748 case Builtins::kAsin:
4749 case Builtins::kAsinpi:
4750 return glsl::ExtInst::ExtInstAsin;
4751 case Builtins::kAsinh:
4752 return glsl::ExtInst::ExtInstAsinh;
4753 case Builtins::kAtan:
4754 case Builtins::kAtanpi:
4755 return glsl::ExtInst::ExtInstAtan;
4756 case Builtins::kAtanh:
4757 return glsl::ExtInst::ExtInstAtanh;
4758 case Builtins::kAtan2:
4759 case Builtins::kAtan2pi:
4760 return glsl::ExtInst::ExtInstAtan2;
4761 case Builtins::kCeil:
4762 return glsl::ExtInst::ExtInstCeil;
4763 case Builtins::kSin:
4764 case Builtins::kHalfSin:
4765 case Builtins::kNativeSin:
4766 return glsl::ExtInst::ExtInstSin;
4767 case Builtins::kSinh:
4768 return glsl::ExtInst::ExtInstSinh;
4769 case Builtins::kCos:
4770 case Builtins::kHalfCos:
4771 case Builtins::kNativeCos:
4772 return glsl::ExtInst::ExtInstCos;
4773 case Builtins::kCosh:
4774 return glsl::ExtInst::ExtInstCosh;
4775 case Builtins::kTan:
4776 case Builtins::kHalfTan:
4777 case Builtins::kNativeTan:
4778 return glsl::ExtInst::ExtInstTan;
4779 case Builtins::kTanh:
4780 return glsl::ExtInst::ExtInstTanh;
4781 case Builtins::kExp:
4782 case Builtins::kHalfExp:
4783 case Builtins::kNativeExp:
4784 return glsl::ExtInst::ExtInstExp;
4785 case Builtins::kExp2:
4786 case Builtins::kHalfExp2:
4787 case Builtins::kNativeExp2:
4788 return glsl::ExtInst::ExtInstExp2;
4789 case Builtins::kLog:
4790 case Builtins::kHalfLog:
4791 case Builtins::kNativeLog:
4792 return glsl::ExtInst::ExtInstLog;
4793 case Builtins::kLog2:
4794 case Builtins::kHalfLog2:
4795 case Builtins::kNativeLog2:
4796 return glsl::ExtInst::ExtInstLog2;
4797 case Builtins::kFabs:
4798 return glsl::ExtInst::ExtInstFAbs;
4799 case Builtins::kFma:
4800 return glsl::ExtInst::ExtInstFma;
4801 case Builtins::kFloor:
4802 return glsl::ExtInst::ExtInstFloor;
4803 case Builtins::kLdexp:
4804 return glsl::ExtInst::ExtInstLdexp;
4805 case Builtins::kPow:
4806 case Builtins::kPowr:
4807 case Builtins::kHalfPowr:
4808 case Builtins::kNativePowr:
4809 return glsl::ExtInst::ExtInstPow;
James Price38553362020-09-03 18:30:40 -04004810 case Builtins::kRint:
4811 return glsl::ExtInst::ExtInstRoundEven;
SJW2c317da2020-03-23 07:39:13 -05004812 case Builtins::kRound:
4813 return glsl::ExtInst::ExtInstRound;
4814 case Builtins::kSqrt:
4815 case Builtins::kHalfSqrt:
4816 case Builtins::kNativeSqrt:
4817 return glsl::ExtInst::ExtInstSqrt;
4818 case Builtins::kRsqrt:
4819 case Builtins::kHalfRsqrt:
4820 case Builtins::kNativeRsqrt:
4821 return glsl::ExtInst::ExtInstInverseSqrt;
4822 case Builtins::kTrunc:
4823 return glsl::ExtInst::ExtInstTrunc;
4824 case Builtins::kFrexp:
4825 return glsl::ExtInst::ExtInstFrexp;
SJW61531372020-06-09 07:31:08 -05004826 case Builtins::kClspvFract:
SJW2c317da2020-03-23 07:39:13 -05004827 case Builtins::kFract:
4828 return glsl::ExtInst::ExtInstFract;
4829 case Builtins::kSign:
4830 return glsl::ExtInst::ExtInstFSign;
4831 case Builtins::kLength:
4832 case Builtins::kFastLength:
4833 return glsl::ExtInst::ExtInstLength;
4834 case Builtins::kDistance:
4835 case Builtins::kFastDistance:
4836 return glsl::ExtInst::ExtInstDistance;
4837 case Builtins::kStep:
4838 return glsl::ExtInst::ExtInstStep;
4839 case Builtins::kSmoothstep:
4840 return glsl::ExtInst::ExtInstSmoothStep;
4841 case Builtins::kCross:
4842 return glsl::ExtInst::ExtInstCross;
4843 case Builtins::kNormalize:
4844 case Builtins::kFastNormalize:
4845 return glsl::ExtInst::ExtInstNormalize;
SJW61531372020-06-09 07:31:08 -05004846 case Builtins::kSpirvPack:
4847 return glsl::ExtInst::ExtInstPackHalf2x16;
4848 case Builtins::kSpirvUnpack:
4849 return glsl::ExtInst::ExtInstUnpackHalf2x16;
SJW2c317da2020-03-23 07:39:13 -05004850 default:
4851 break;
4852 }
4853
alan-baker5f2e88e2020-12-07 15:24:04 -05004854 // TODO: improve this by checking the intrinsic id.
SJW61531372020-06-09 07:31:08 -05004855 if (func_info.getName().find("llvm.fmuladd.") == 0) {
4856 return glsl::ExtInst::ExtInstFma;
4857 }
alan-baker5f2e88e2020-12-07 15:24:04 -05004858 if (func_info.getName().find("llvm.sqrt.") == 0) {
4859 return glsl::ExtInst::ExtInstSqrt;
4860 }
4861 if (func_info.getName().find("llvm.trunc.") == 0) {
4862 return glsl::ExtInst::ExtInstTrunc;
4863 }
4864 if (func_info.getName().find("llvm.ctlz.") == 0) {
4865 return glsl::ExtInst::ExtInstFindUMsb;
4866 }
4867 if (func_info.getName().find("llvm.cttz.") == 0) {
4868 return glsl::ExtInst::ExtInstFindILsb;
4869 }
alan-baker3e0de472020-12-08 15:57:17 -05004870 if (func_info.getName().find("llvm.ceil.") == 0) {
4871 return glsl::ExtInst::ExtInstCeil;
4872 }
4873 if (func_info.getName().find("llvm.rint.") == 0) {
4874 return glsl::ExtInst::ExtInstRoundEven;
4875 }
4876 if (func_info.getName().find("llvm.fabs.") == 0) {
4877 return glsl::ExtInst::ExtInstFAbs;
4878 }
4879 if (func_info.getName().find("llvm.floor.") == 0) {
4880 return glsl::ExtInst::ExtInstFloor;
4881 }
4882 if (func_info.getName().find("llvm.sin.") == 0) {
4883 return glsl::ExtInst::ExtInstSin;
4884 }
4885 if (func_info.getName().find("llvm.cos.") == 0) {
4886 return glsl::ExtInst::ExtInstCos;
4887 }
alan-baker8b968112020-12-15 15:53:29 -05004888 if (func_info.getName().find("llvm.exp.") == 0) {
4889 return glsl::ExtInst::ExtInstExp;
4890 }
4891 if (func_info.getName().find("llvm.log.") == 0) {
4892 return glsl::ExtInst::ExtInstLog;
4893 }
4894 if (func_info.getName().find("llvm.pow.") == 0) {
4895 return glsl::ExtInst::ExtInstPow;
4896 }
James Price8cc3bb12021-05-05 10:20:58 -04004897 if (func_info.getName().find("llvm.smax.") == 0) {
4898 return glsl::ExtInst::ExtInstSMax;
4899 }
4900 if (func_info.getName().find("llvm.smin.") == 0) {
4901 return glsl::ExtInst::ExtInstSMin;
4902 }
SJW61531372020-06-09 07:31:08 -05004903 return kGlslExtInstBad;
David Neto3fbb4072017-10-16 11:28:14 -04004904}
4905
SJW61531372020-06-09 07:31:08 -05004906glsl::ExtInst SPIRVProducerPass::getIndirectExtInstEnum(
4907 const Builtins::FunctionInfo &func_info) {
4908 switch (func_info.getType()) {
SJW2c317da2020-03-23 07:39:13 -05004909 case Builtins::kAcospi:
4910 return glsl::ExtInst::ExtInstAcos;
4911 case Builtins::kAsinpi:
4912 return glsl::ExtInst::ExtInstAsin;
4913 case Builtins::kAtanpi:
4914 return glsl::ExtInst::ExtInstAtan;
4915 case Builtins::kAtan2pi:
4916 return glsl::ExtInst::ExtInstAtan2;
4917 default:
4918 break;
4919 }
4920 return kGlslExtInstBad;
David Neto3fbb4072017-10-16 11:28:14 -04004921}
4922
SJW61531372020-06-09 07:31:08 -05004923glsl::ExtInst SPIRVProducerPass::getDirectOrIndirectExtInstEnum(
4924 const Builtins::FunctionInfo &func_info) {
4925 auto direct = getExtInstEnum(func_info);
David Neto3fbb4072017-10-16 11:28:14 -04004926 if (direct != kGlslExtInstBad)
4927 return direct;
SJW61531372020-06-09 07:31:08 -05004928 return getIndirectExtInstEnum(func_info);
David Neto22f144c2017-06-12 14:26:21 -04004929}
4930
David Neto22f144c2017-06-12 14:26:21 -04004931void SPIRVProducerPass::WriteOneWord(uint32_t Word) {
David Neto0676e6f2017-07-11 18:47:44 -04004932 binaryOut->write(reinterpret_cast<const char *>(&Word), sizeof(uint32_t));
David Neto22f144c2017-06-12 14:26:21 -04004933}
4934
SJW88ed5fe2020-05-11 12:40:57 -05004935void SPIRVProducerPass::WriteResultID(const SPIRVInstruction &Inst) {
SJW01901d92020-05-21 08:58:31 -05004936 WriteOneWord(Inst.getResultID().get());
David Neto22f144c2017-06-12 14:26:21 -04004937}
4938
SJW88ed5fe2020-05-11 12:40:57 -05004939void SPIRVProducerPass::WriteWordCountAndOpcode(const SPIRVInstruction &Inst) {
David Neto22f144c2017-06-12 14:26:21 -04004940 // High 16 bit : Word Count
4941 // Low 16 bit : Opcode
SJW88ed5fe2020-05-11 12:40:57 -05004942 uint32_t Word = Inst.getOpcode();
4943 const uint32_t count = Inst.getWordCount();
David Netoee2660d2018-06-28 16:31:29 -04004944 if (count > 65535) {
4945 errs() << "Word count limit of 65535 exceeded: " << count << "\n";
4946 llvm_unreachable("Word count too high");
4947 }
SJW88ed5fe2020-05-11 12:40:57 -05004948 Word |= Inst.getWordCount() << 16;
David Neto22f144c2017-06-12 14:26:21 -04004949 WriteOneWord(Word);
4950}
4951
SJW88ed5fe2020-05-11 12:40:57 -05004952void SPIRVProducerPass::WriteOperand(const SPIRVOperand &Op) {
4953 SPIRVOperandType OpTy = Op.getType();
David Neto22f144c2017-06-12 14:26:21 -04004954 switch (OpTy) {
4955 default: {
4956 llvm_unreachable("Unsupported SPIRV Operand Type???");
4957 break;
4958 }
4959 case SPIRVOperandType::NUMBERID: {
SJW88ed5fe2020-05-11 12:40:57 -05004960 WriteOneWord(Op.getNumID());
David Neto22f144c2017-06-12 14:26:21 -04004961 break;
4962 }
4963 case SPIRVOperandType::LITERAL_STRING: {
SJW88ed5fe2020-05-11 12:40:57 -05004964 std::string Str = Op.getLiteralStr();
David Neto22f144c2017-06-12 14:26:21 -04004965 const char *Data = Str.c_str();
4966 size_t WordSize = Str.size() / 4;
4967 for (unsigned Idx = 0; Idx < WordSize; Idx++) {
4968 WriteOneWord(*reinterpret_cast<const uint32_t *>(&Data[4 * Idx]));
4969 }
4970
4971 uint32_t Remainder = Str.size() % 4;
4972 uint32_t LastWord = 0;
4973 if (Remainder) {
4974 for (unsigned Idx = 0; Idx < Remainder; Idx++) {
4975 LastWord |= Data[4 * WordSize + Idx] << 8 * Idx;
4976 }
4977 }
4978
4979 WriteOneWord(LastWord);
4980 break;
4981 }
SJW88ed5fe2020-05-11 12:40:57 -05004982 case SPIRVOperandType::LITERAL_WORD: {
4983 WriteOneWord(Op.getLiteralNum()[0]);
4984 break;
4985 }
4986 case SPIRVOperandType::LITERAL_DWORD: {
4987 WriteOneWord(Op.getLiteralNum()[0]);
4988 WriteOneWord(Op.getLiteralNum()[1]);
David Neto22f144c2017-06-12 14:26:21 -04004989 break;
4990 }
4991 }
4992}
4993
4994void SPIRVProducerPass::WriteSPIRVBinary() {
SJW69939d52020-04-16 07:29:07 -05004995 for (int i = 0; i < kSectionCount; ++i) {
4996 WriteSPIRVBinary(SPIRVSections[i]);
4997 }
4998}
4999
5000void SPIRVProducerPass::WriteSPIRVBinary(SPIRVInstructionList &SPIRVInstList) {
SJW88ed5fe2020-05-11 12:40:57 -05005001 for (const auto &Inst : SPIRVInstList) {
5002 const auto &Ops = Inst.getOperands();
5003 spv::Op Opcode = static_cast<spv::Op>(Inst.getOpcode());
David Neto22f144c2017-06-12 14:26:21 -04005004
5005 switch (Opcode) {
5006 default: {
David Neto5c22a252018-03-15 16:07:41 -04005007 errs() << "Unsupported SPIR-V instruction opcode " << int(Opcode) << "\n";
David Neto22f144c2017-06-12 14:26:21 -04005008 llvm_unreachable("Unsupported SPIRV instruction");
5009 break;
5010 }
Marco Antognini68e5c512020-09-09 16:08:57 +01005011 case spv::OpUnreachable:
David Neto22f144c2017-06-12 14:26:21 -04005012 case spv::OpCapability:
5013 case spv::OpExtension:
5014 case spv::OpMemoryModel:
5015 case spv::OpEntryPoint:
5016 case spv::OpExecutionMode:
5017 case spv::OpSource:
5018 case spv::OpDecorate:
5019 case spv::OpMemberDecorate:
5020 case spv::OpBranch:
5021 case spv::OpBranchConditional:
5022 case spv::OpSelectionMerge:
5023 case spv::OpLoopMerge:
5024 case spv::OpStore:
5025 case spv::OpImageWrite:
5026 case spv::OpReturnValue:
5027 case spv::OpControlBarrier:
5028 case spv::OpMemoryBarrier:
5029 case spv::OpReturn:
5030 case spv::OpFunctionEnd:
alan-baker4986eff2020-10-29 13:38:00 -04005031 case spv::OpCopyMemory:
5032 case spv::OpAtomicStore: {
David Neto22f144c2017-06-12 14:26:21 -04005033 WriteWordCountAndOpcode(Inst);
5034 for (uint32_t i = 0; i < Ops.size(); i++) {
5035 WriteOperand(Ops[i]);
5036 }
5037 break;
5038 }
5039 case spv::OpTypeBool:
5040 case spv::OpTypeVoid:
5041 case spv::OpTypeSampler:
5042 case spv::OpLabel:
5043 case spv::OpExtInstImport:
5044 case spv::OpTypePointer:
5045 case spv::OpTypeRuntimeArray:
5046 case spv::OpTypeStruct:
5047 case spv::OpTypeImage:
5048 case spv::OpTypeSampledImage:
5049 case spv::OpTypeInt:
5050 case spv::OpTypeFloat:
5051 case spv::OpTypeArray:
5052 case spv::OpTypeVector:
alan-baker86ce19c2020-08-05 13:09:19 -04005053 case spv::OpTypeFunction:
5054 case spv::OpString: {
David Neto22f144c2017-06-12 14:26:21 -04005055 WriteWordCountAndOpcode(Inst);
5056 WriteResultID(Inst);
5057 for (uint32_t i = 0; i < Ops.size(); i++) {
5058 WriteOperand(Ops[i]);
5059 }
5060 break;
5061 }
5062 case spv::OpFunction:
5063 case spv::OpFunctionParameter:
5064 case spv::OpAccessChain:
5065 case spv::OpPtrAccessChain:
5066 case spv::OpInBoundsAccessChain:
5067 case spv::OpUConvert:
5068 case spv::OpSConvert:
5069 case spv::OpConvertFToU:
5070 case spv::OpConvertFToS:
5071 case spv::OpConvertUToF:
5072 case spv::OpConvertSToF:
5073 case spv::OpFConvert:
5074 case spv::OpConvertPtrToU:
5075 case spv::OpConvertUToPtr:
5076 case spv::OpBitcast:
alan-bakerc9c55ae2019-12-02 16:01:27 -05005077 case spv::OpFNegate:
David Neto22f144c2017-06-12 14:26:21 -04005078 case spv::OpIAdd:
alan-bakera52b7312020-10-26 08:58:51 -04005079 case spv::OpIAddCarry:
David Neto22f144c2017-06-12 14:26:21 -04005080 case spv::OpFAdd:
5081 case spv::OpISub:
alan-baker3f1bf492020-11-05 09:07:36 -05005082 case spv::OpISubBorrow:
David Neto22f144c2017-06-12 14:26:21 -04005083 case spv::OpFSub:
5084 case spv::OpIMul:
5085 case spv::OpFMul:
5086 case spv::OpUDiv:
5087 case spv::OpSDiv:
5088 case spv::OpFDiv:
5089 case spv::OpUMod:
5090 case spv::OpSRem:
5091 case spv::OpFRem:
Kévin Petit8a560882019-03-21 15:24:34 +00005092 case spv::OpUMulExtended:
5093 case spv::OpSMulExtended:
David Neto22f144c2017-06-12 14:26:21 -04005094 case spv::OpBitwiseOr:
5095 case spv::OpBitwiseXor:
5096 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04005097 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04005098 case spv::OpShiftLeftLogical:
5099 case spv::OpShiftRightLogical:
5100 case spv::OpShiftRightArithmetic:
5101 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04005102 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04005103 case spv::OpCompositeExtract:
5104 case spv::OpVectorExtractDynamic:
5105 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04005106 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04005107 case spv::OpVectorInsertDynamic:
5108 case spv::OpVectorShuffle:
5109 case spv::OpIEqual:
5110 case spv::OpINotEqual:
5111 case spv::OpUGreaterThan:
5112 case spv::OpUGreaterThanEqual:
5113 case spv::OpULessThan:
5114 case spv::OpULessThanEqual:
5115 case spv::OpSGreaterThan:
5116 case spv::OpSGreaterThanEqual:
5117 case spv::OpSLessThan:
5118 case spv::OpSLessThanEqual:
5119 case spv::OpFOrdEqual:
5120 case spv::OpFOrdGreaterThan:
5121 case spv::OpFOrdGreaterThanEqual:
5122 case spv::OpFOrdLessThan:
5123 case spv::OpFOrdLessThanEqual:
5124 case spv::OpFOrdNotEqual:
5125 case spv::OpFUnordEqual:
5126 case spv::OpFUnordGreaterThan:
5127 case spv::OpFUnordGreaterThanEqual:
5128 case spv::OpFUnordLessThan:
5129 case spv::OpFUnordLessThanEqual:
5130 case spv::OpFUnordNotEqual:
5131 case spv::OpExtInst:
5132 case spv::OpIsInf:
5133 case spv::OpIsNan:
5134 case spv::OpAny:
5135 case spv::OpAll:
5136 case spv::OpUndef:
5137 case spv::OpConstantNull:
5138 case spv::OpLogicalOr:
5139 case spv::OpLogicalAnd:
5140 case spv::OpLogicalNot:
5141 case spv::OpLogicalNotEqual:
5142 case spv::OpConstantComposite:
5143 case spv::OpSpecConstantComposite:
5144 case spv::OpConstantTrue:
5145 case spv::OpConstantFalse:
5146 case spv::OpConstant:
5147 case spv::OpSpecConstant:
5148 case spv::OpVariable:
5149 case spv::OpFunctionCall:
5150 case spv::OpSampledImage:
alan-baker75090e42020-02-20 11:21:04 -05005151 case spv::OpImageFetch:
alan-bakerf6bc8252020-09-23 14:58:55 -04005152 case spv::OpImageRead:
David Neto22f144c2017-06-12 14:26:21 -04005153 case spv::OpImageSampleExplicitLod:
David Neto5c22a252018-03-15 16:07:41 -04005154 case spv::OpImageQuerySize:
alan-bakerce179f12019-12-06 19:02:22 -05005155 case spv::OpImageQuerySizeLod:
David Neto22f144c2017-06-12 14:26:21 -04005156 case spv::OpSelect:
5157 case spv::OpPhi:
5158 case spv::OpLoad:
alan-baker4986eff2020-10-29 13:38:00 -04005159 case spv::OpAtomicLoad:
David Neto22f144c2017-06-12 14:26:21 -04005160 case spv::OpAtomicIAdd:
5161 case spv::OpAtomicISub:
5162 case spv::OpAtomicExchange:
5163 case spv::OpAtomicIIncrement:
5164 case spv::OpAtomicIDecrement:
5165 case spv::OpAtomicCompareExchange:
5166 case spv::OpAtomicUMin:
5167 case spv::OpAtomicSMin:
5168 case spv::OpAtomicUMax:
5169 case spv::OpAtomicSMax:
5170 case spv::OpAtomicAnd:
5171 case spv::OpAtomicOr:
5172 case spv::OpAtomicXor:
SJW806a5d82020-07-15 12:51:38 -05005173 case spv::OpDot:
5174 case spv::OpGroupNonUniformAll:
5175 case spv::OpGroupNonUniformAny:
5176 case spv::OpGroupNonUniformBroadcast:
5177 case spv::OpGroupNonUniformIAdd:
5178 case spv::OpGroupNonUniformFAdd:
5179 case spv::OpGroupNonUniformSMin:
5180 case spv::OpGroupNonUniformUMin:
5181 case spv::OpGroupNonUniformFMin:
5182 case spv::OpGroupNonUniformSMax:
5183 case spv::OpGroupNonUniformUMax:
5184 case spv::OpGroupNonUniformFMax: {
David Neto22f144c2017-06-12 14:26:21 -04005185 WriteWordCountAndOpcode(Inst);
5186 WriteOperand(Ops[0]);
5187 WriteResultID(Inst);
5188 for (uint32_t i = 1; i < Ops.size(); i++) {
5189 WriteOperand(Ops[i]);
5190 }
5191 break;
5192 }
5193 }
5194 }
5195}
Alan Baker9bf93fb2018-08-28 16:59:26 -04005196
alan-bakerb6b09dc2018-11-08 16:59:28 -05005197bool SPIRVProducerPass::IsTypeNullable(const Type *type) const {
Alan Baker9bf93fb2018-08-28 16:59:26 -04005198 switch (type->getTypeID()) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05005199 case Type::HalfTyID:
5200 case Type::FloatTyID:
5201 case Type::DoubleTyID:
5202 case Type::IntegerTyID:
James Price59a1c752020-04-23 23:06:16 -04005203 case Type::FixedVectorTyID:
alan-bakerb6b09dc2018-11-08 16:59:28 -05005204 return true;
5205 case Type::PointerTyID: {
5206 const PointerType *pointer_type = cast<PointerType>(type);
5207 if (pointer_type->getPointerAddressSpace() !=
5208 AddressSpace::UniformConstant) {
5209 auto pointee_type = pointer_type->getPointerElementType();
5210 if (pointee_type->isStructTy() &&
5211 cast<StructType>(pointee_type)->isOpaque()) {
5212 // Images and samplers are not nullable.
5213 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04005214 }
Alan Baker9bf93fb2018-08-28 16:59:26 -04005215 }
alan-bakerb6b09dc2018-11-08 16:59:28 -05005216 return true;
5217 }
5218 case Type::ArrayTyID:
alan-baker8eb435a2020-04-08 00:42:06 -04005219 return IsTypeNullable(type->getArrayElementType());
alan-bakerb6b09dc2018-11-08 16:59:28 -05005220 case Type::StructTyID: {
5221 const StructType *struct_type = cast<StructType>(type);
5222 // Images and samplers are not nullable.
5223 if (struct_type->isOpaque())
Alan Baker9bf93fb2018-08-28 16:59:26 -04005224 return false;
alan-bakerb6b09dc2018-11-08 16:59:28 -05005225 for (const auto element : struct_type->elements()) {
5226 if (!IsTypeNullable(element))
5227 return false;
5228 }
5229 return true;
5230 }
5231 default:
5232 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04005233 }
5234}
Alan Bakerfcda9482018-10-02 17:09:59 -04005235
SJW77b87ad2020-04-21 14:37:52 -05005236void SPIRVProducerPass::PopulateUBOTypeMaps() {
Alan Bakerfcda9482018-10-02 17:09:59 -04005237 if (auto *offsets_md =
SJW77b87ad2020-04-21 14:37:52 -05005238 module->getNamedMetadata(clspv::RemappedTypeOffsetMetadataName())) {
Alan Bakerfcda9482018-10-02 17:09:59 -04005239 // Metdata is stored as key-value pair operands. The first element of each
5240 // operand is the type and the second is a vector of offsets.
5241 for (const auto *operand : offsets_md->operands()) {
5242 const auto *pair = cast<MDTuple>(operand);
5243 auto *type =
5244 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
5245 const auto *offset_vector = cast<MDTuple>(pair->getOperand(1));
5246 std::vector<uint32_t> offsets;
5247 for (const Metadata *offset_md : offset_vector->operands()) {
5248 const auto *constant_md = cast<ConstantAsMetadata>(offset_md);
alan-bakerb6b09dc2018-11-08 16:59:28 -05005249 offsets.push_back(static_cast<uint32_t>(
5250 cast<ConstantInt>(constant_md->getValue())->getZExtValue()));
Alan Bakerfcda9482018-10-02 17:09:59 -04005251 }
5252 RemappedUBOTypeOffsets.insert(std::make_pair(type, offsets));
5253 }
5254 }
5255
5256 if (auto *sizes_md =
SJW77b87ad2020-04-21 14:37:52 -05005257 module->getNamedMetadata(clspv::RemappedTypeSizesMetadataName())) {
Alan Bakerfcda9482018-10-02 17:09:59 -04005258 // Metadata is stored as key-value pair operands. The first element of each
5259 // operand is the type and the second is a triple of sizes: type size in
5260 // bits, store size and alloc size.
5261 for (const auto *operand : sizes_md->operands()) {
5262 const auto *pair = cast<MDTuple>(operand);
5263 auto *type =
5264 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
5265 const auto *size_triple = cast<MDTuple>(pair->getOperand(1));
5266 uint64_t type_size_in_bits =
5267 cast<ConstantInt>(
5268 cast<ConstantAsMetadata>(size_triple->getOperand(0))->getValue())
5269 ->getZExtValue();
5270 uint64_t type_store_size =
5271 cast<ConstantInt>(
5272 cast<ConstantAsMetadata>(size_triple->getOperand(1))->getValue())
5273 ->getZExtValue();
5274 uint64_t type_alloc_size =
5275 cast<ConstantInt>(
5276 cast<ConstantAsMetadata>(size_triple->getOperand(2))->getValue())
5277 ->getZExtValue();
5278 RemappedUBOTypeSizes.insert(std::make_pair(
5279 type, std::make_tuple(type_size_in_bits, type_store_size,
5280 type_alloc_size)));
5281 }
5282 }
5283}
5284
5285uint64_t SPIRVProducerPass::GetTypeSizeInBits(Type *type,
5286 const DataLayout &DL) {
5287 auto iter = RemappedUBOTypeSizes.find(type);
5288 if (iter != RemappedUBOTypeSizes.end()) {
5289 return std::get<0>(iter->second);
5290 }
5291
5292 return DL.getTypeSizeInBits(type);
5293}
5294
Alan Bakerfcda9482018-10-02 17:09:59 -04005295uint64_t SPIRVProducerPass::GetTypeAllocSize(Type *type, const DataLayout &DL) {
5296 auto iter = RemappedUBOTypeSizes.find(type);
5297 if (iter != RemappedUBOTypeSizes.end()) {
5298 return std::get<2>(iter->second);
5299 }
5300
5301 return DL.getTypeAllocSize(type);
5302}
alan-baker5b86ed72019-02-15 08:26:50 -05005303
Kévin Petitbbbda972020-03-03 19:16:31 +00005304uint32_t SPIRVProducerPass::GetExplicitLayoutStructMemberOffset(
5305 StructType *type, unsigned member, const DataLayout &DL) {
5306 const auto StructLayout = DL.getStructLayout(type);
5307 // Search for the correct offsets if this type was remapped.
5308 std::vector<uint32_t> *offsets = nullptr;
5309 auto iter = RemappedUBOTypeOffsets.find(type);
5310 if (iter != RemappedUBOTypeOffsets.end()) {
5311 offsets = &iter->second;
5312 }
5313 auto ByteOffset =
5314 static_cast<uint32_t>(StructLayout->getElementOffset(member));
5315 if (offsets) {
5316 ByteOffset = (*offsets)[member];
5317 }
5318
5319 return ByteOffset;
5320}
5321
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04005322void SPIRVProducerPass::setVariablePointersCapabilities(
5323 unsigned address_space) {
alan-baker5b86ed72019-02-15 08:26:50 -05005324 if (GetStorageClass(address_space) == spv::StorageClassStorageBuffer) {
SJW01901d92020-05-21 08:58:31 -05005325 setVariablePointersStorageBuffer();
alan-baker5b86ed72019-02-15 08:26:50 -05005326 } else {
SJW01901d92020-05-21 08:58:31 -05005327 setVariablePointers();
alan-baker5b86ed72019-02-15 08:26:50 -05005328 }
5329}
5330
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04005331Value *SPIRVProducerPass::GetBasePointer(Value *v) {
alan-baker5b86ed72019-02-15 08:26:50 -05005332 if (auto *gep = dyn_cast<GetElementPtrInst>(v)) {
5333 return GetBasePointer(gep->getPointerOperand());
5334 }
5335
5336 // Conservatively return |v|.
5337 return v;
5338}
5339
5340bool SPIRVProducerPass::sameResource(Value *lhs, Value *rhs) const {
5341 if (auto *lhs_call = dyn_cast<CallInst>(lhs)) {
5342 if (auto *rhs_call = dyn_cast<CallInst>(rhs)) {
alan-baker7506abb2020-09-10 15:02:55 -04005343 const auto &lhs_func_info =
5344 Builtins::Lookup(lhs_call->getCalledFunction());
5345 const auto &rhs_func_info =
5346 Builtins::Lookup(rhs_call->getCalledFunction());
SJW61531372020-06-09 07:31:08 -05005347 if (lhs_func_info.getType() == Builtins::kClspvResource &&
5348 rhs_func_info.getType() == Builtins::kClspvResource) {
alan-baker5b86ed72019-02-15 08:26:50 -05005349 // For resource accessors, match descriptor set and binding.
5350 if (lhs_call->getOperand(0) == rhs_call->getOperand(0) &&
5351 lhs_call->getOperand(1) == rhs_call->getOperand(1))
5352 return true;
SJW61531372020-06-09 07:31:08 -05005353 } else if (lhs_func_info.getType() == Builtins::kClspvLocal &&
5354 rhs_func_info.getType() == Builtins::kClspvLocal) {
alan-baker5b86ed72019-02-15 08:26:50 -05005355 // For workgroup resources, match spec id.
5356 if (lhs_call->getOperand(0) == rhs_call->getOperand(0))
5357 return true;
5358 }
5359 }
5360 }
5361
5362 return false;
5363}
5364
5365bool SPIRVProducerPass::selectFromSameObject(Instruction *inst) {
5366 assert(inst->getType()->isPointerTy());
5367 assert(GetStorageClass(inst->getType()->getPointerAddressSpace()) ==
5368 spv::StorageClassStorageBuffer);
5369 const bool hack_undef = clspv::Option::HackUndef();
5370 if (auto *select = dyn_cast<SelectInst>(inst)) {
5371 auto *true_base = GetBasePointer(select->getTrueValue());
5372 auto *false_base = GetBasePointer(select->getFalseValue());
5373
5374 if (true_base == false_base)
5375 return true;
5376
5377 // If either the true or false operand is a null, then we satisfy the same
5378 // object constraint.
5379 if (auto *true_cst = dyn_cast<Constant>(true_base)) {
5380 if (true_cst->isNullValue() || (hack_undef && isa<UndefValue>(true_base)))
5381 return true;
5382 }
5383
5384 if (auto *false_cst = dyn_cast<Constant>(false_base)) {
5385 if (false_cst->isNullValue() ||
5386 (hack_undef && isa<UndefValue>(false_base)))
5387 return true;
5388 }
5389
5390 if (sameResource(true_base, false_base))
5391 return true;
5392 } else if (auto *phi = dyn_cast<PHINode>(inst)) {
5393 Value *value = nullptr;
5394 bool ok = true;
5395 for (unsigned i = 0; ok && i != phi->getNumIncomingValues(); ++i) {
5396 auto *base = GetBasePointer(phi->getIncomingValue(i));
5397 // Null values satisfy the constraint of selecting of selecting from the
5398 // same object.
5399 if (!value) {
5400 if (auto *cst = dyn_cast<Constant>(base)) {
5401 if (!cst->isNullValue() && !(hack_undef && isa<UndefValue>(base)))
5402 value = base;
5403 } else {
5404 value = base;
5405 }
5406 } else if (base != value) {
5407 if (auto *base_cst = dyn_cast<Constant>(base)) {
5408 if (base_cst->isNullValue() || (hack_undef && isa<UndefValue>(base)))
5409 continue;
5410 }
5411
5412 if (sameResource(value, base))
5413 continue;
5414
5415 // Values don't represent the same base.
5416 ok = false;
5417 }
5418 }
5419
5420 return ok;
5421 }
5422
5423 // Conservatively return false.
5424 return false;
5425}
alan-bakere9308012019-03-15 10:25:13 -04005426
5427bool SPIRVProducerPass::CalledWithCoherentResource(Argument &Arg) {
5428 if (!Arg.getType()->isPointerTy() ||
5429 Arg.getType()->getPointerAddressSpace() != clspv::AddressSpace::Global) {
5430 // Only SSBOs need to be annotated as coherent.
5431 return false;
5432 }
5433
5434 DenseSet<Value *> visited;
5435 std::vector<Value *> stack;
5436 for (auto *U : Arg.getParent()->users()) {
5437 if (auto *call = dyn_cast<CallInst>(U)) {
5438 stack.push_back(call->getOperand(Arg.getArgNo()));
5439 }
5440 }
5441
5442 while (!stack.empty()) {
5443 Value *v = stack.back();
5444 stack.pop_back();
5445
5446 if (!visited.insert(v).second)
5447 continue;
5448
5449 auto *resource_call = dyn_cast<CallInst>(v);
5450 if (resource_call &&
SJW61531372020-06-09 07:31:08 -05005451 Builtins::Lookup(resource_call->getCalledFunction()).getType() ==
5452 Builtins::kClspvResource) {
alan-bakere9308012019-03-15 10:25:13 -04005453 // If this is a resource accessor function, check if the coherent operand
5454 // is set.
5455 const auto coherent =
5456 unsigned(dyn_cast<ConstantInt>(resource_call->getArgOperand(5))
5457 ->getZExtValue());
5458 if (coherent == 1)
5459 return true;
5460 } else if (auto *arg = dyn_cast<Argument>(v)) {
5461 // If this is a function argument, trace through its callers.
alan-bakere98f3f92019-04-08 15:06:36 -04005462 for (auto U : arg->getParent()->users()) {
alan-bakere9308012019-03-15 10:25:13 -04005463 if (auto *call = dyn_cast<CallInst>(U)) {
5464 stack.push_back(call->getOperand(arg->getArgNo()));
5465 }
5466 }
5467 } else if (auto *user = dyn_cast<User>(v)) {
5468 // If this is a user, traverse all operands that could lead to resource
5469 // variables.
5470 for (unsigned i = 0; i != user->getNumOperands(); ++i) {
5471 Value *operand = user->getOperand(i);
5472 if (operand->getType()->isPointerTy() &&
5473 operand->getType()->getPointerAddressSpace() ==
5474 clspv::AddressSpace::Global) {
5475 stack.push_back(operand);
5476 }
5477 }
5478 }
5479 }
5480
5481 // No coherent resource variables encountered.
5482 return false;
5483}
alan-baker06cad652019-12-03 17:56:47 -05005484
SJW77b87ad2020-04-21 14:37:52 -05005485void SPIRVProducerPass::PopulateStructuredCFGMaps() {
alan-baker06cad652019-12-03 17:56:47 -05005486 // First, track loop merges and continues.
5487 DenseSet<BasicBlock *> LoopMergesAndContinues;
SJW77b87ad2020-04-21 14:37:52 -05005488 for (auto &F : *module) {
alan-baker06cad652019-12-03 17:56:47 -05005489 if (F.isDeclaration())
5490 continue;
5491
5492 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
5493 const LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>(F).getLoopInfo();
5494 std::deque<BasicBlock *> order;
5495 DenseSet<BasicBlock *> visited;
5496 clspv::ComputeStructuredOrder(&*F.begin(), &DT, LI, &order, &visited);
5497
5498 for (auto BB : order) {
5499 auto terminator = BB->getTerminator();
5500 auto branch = dyn_cast<BranchInst>(terminator);
5501 if (LI.isLoopHeader(BB)) {
5502 auto L = LI.getLoopFor(BB);
5503 BasicBlock *ContinueBB = nullptr;
5504 BasicBlock *MergeBB = nullptr;
5505
5506 MergeBB = L->getExitBlock();
5507 if (!MergeBB) {
5508 // StructurizeCFG pass converts CFG into triangle shape and the cfg
5509 // has regions with single entry/exit. As a result, loop should not
5510 // have multiple exits.
5511 llvm_unreachable("Loop has multiple exits???");
5512 }
5513
5514 if (L->isLoopLatch(BB)) {
5515 ContinueBB = BB;
5516 } else {
5517 // From SPIR-V spec 2.11, Continue Target must dominate that back-edge
5518 // block.
5519 BasicBlock *Header = L->getHeader();
5520 BasicBlock *Latch = L->getLoopLatch();
5521 for (auto *loop_block : L->blocks()) {
5522 if (loop_block == Header) {
5523 continue;
5524 }
5525
5526 // Check whether block dominates block with back-edge.
5527 // The loop latch is the single block with a back-edge. If it was
5528 // possible, StructurizeCFG made the loop conform to this
5529 // requirement, otherwise |Latch| is a nullptr.
5530 if (DT.dominates(loop_block, Latch)) {
5531 ContinueBB = loop_block;
5532 }
5533 }
5534
5535 if (!ContinueBB) {
5536 llvm_unreachable("Wrong continue block from loop");
5537 }
5538 }
5539
5540 // Record the continue and merge blocks.
5541 MergeBlocks[BB] = MergeBB;
5542 ContinueBlocks[BB] = ContinueBB;
5543 LoopMergesAndContinues.insert(MergeBB);
5544 LoopMergesAndContinues.insert(ContinueBB);
5545 } else if (branch && branch->isConditional()) {
5546 auto L = LI.getLoopFor(BB);
5547 bool HasBackedge = false;
5548 while (L && !HasBackedge) {
5549 if (L->isLoopLatch(BB)) {
5550 HasBackedge = true;
5551 }
5552 L = L->getParentLoop();
5553 }
5554
5555 if (!HasBackedge) {
5556 // Only need a merge if the branch doesn't include a loop break or
5557 // continue.
5558 auto true_bb = branch->getSuccessor(0);
5559 auto false_bb = branch->getSuccessor(1);
5560 if (!LoopMergesAndContinues.count(true_bb) &&
5561 !LoopMergesAndContinues.count(false_bb)) {
5562 // StructurizeCFG pass already manipulated CFG. Just use false block
5563 // of branch instruction as merge block.
5564 MergeBlocks[BB] = false_bb;
5565 }
5566 }
5567 }
5568 }
5569 }
5570}
alan-baker86ce19c2020-08-05 13:09:19 -04005571
5572SPIRVID SPIRVProducerPass::getReflectionImport() {
5573 if (!ReflectionID.isValid()) {
5574 addSPIRVInst<kExtensions>(spv::OpExtension, "SPV_KHR_non_semantic_info");
5575 ReflectionID = addSPIRVInst<kImports>(spv::OpExtInstImport,
5576 "NonSemantic.ClspvReflection.1");
5577 }
5578 return ReflectionID;
5579}
5580
5581void SPIRVProducerPass::GenerateReflection() {
5582 GenerateKernelReflection();
5583 GeneratePushConstantReflection();
5584 GenerateSpecConstantReflection();
5585}
5586
5587void SPIRVProducerPass::GeneratePushConstantReflection() {
5588 if (auto GV = module->getGlobalVariable(clspv::PushConstantsVariableName())) {
5589 auto const &DL = module->getDataLayout();
5590 auto MD = GV->getMetadata(clspv::PushConstantsMetadataName());
5591 auto STy = cast<StructType>(GV->getValueType());
5592
5593 for (unsigned i = 0; i < STy->getNumElements(); i++) {
5594 auto pc = static_cast<clspv::PushConstant>(
5595 mdconst::extract<ConstantInt>(MD->getOperand(i))->getZExtValue());
5596 if (pc == PushConstant::KernelArgument)
5597 continue;
5598
5599 auto memberType = STy->getElementType(i);
5600 auto offset = GetExplicitLayoutStructMemberOffset(STy, i, DL);
Marco Antognini7e338402021-03-15 12:48:37 +00005601#ifndef NDEBUG
alan-baker86ce19c2020-08-05 13:09:19 -04005602 unsigned previousOffset = 0;
5603 if (i > 0) {
5604 previousOffset = GetExplicitLayoutStructMemberOffset(STy, i - 1, DL);
5605 }
alan-baker86ce19c2020-08-05 13:09:19 -04005606 assert(isValidExplicitLayout(*module, STy, i,
5607 spv::StorageClassPushConstant, offset,
5608 previousOffset));
Marco Antognini7e338402021-03-15 12:48:37 +00005609#endif
alan-baker86ce19c2020-08-05 13:09:19 -04005610
5611 reflection::ExtInst pc_inst = reflection::ExtInstMax;
5612 switch (pc) {
5613 case PushConstant::GlobalOffset:
5614 pc_inst = reflection::ExtInstPushConstantGlobalOffset;
5615 break;
5616 case PushConstant::EnqueuedLocalSize:
5617 pc_inst = reflection::ExtInstPushConstantEnqueuedLocalSize;
5618 break;
5619 case PushConstant::GlobalSize:
5620 pc_inst = reflection::ExtInstPushConstantGlobalSize;
5621 break;
5622 case PushConstant::RegionOffset:
5623 pc_inst = reflection::ExtInstPushConstantRegionOffset;
5624 break;
5625 case PushConstant::NumWorkgroups:
5626 pc_inst = reflection::ExtInstPushConstantNumWorkgroups;
5627 break;
5628 case PushConstant::RegionGroupOffset:
5629 pc_inst = reflection::ExtInstPushConstantRegionGroupOffset;
5630 break;
5631 default:
5632 llvm_unreachable("Unhandled push constant");
5633 break;
5634 }
5635
5636 auto import_id = getReflectionImport();
Marco Antognini7e338402021-03-15 12:48:37 +00005637 auto size = static_cast<uint32_t>(GetTypeSizeInBits(memberType, DL)) / 8;
alan-baker86ce19c2020-08-05 13:09:19 -04005638 SPIRVOperandVec Ops;
5639 Ops << getSPIRVType(Type::getVoidTy(module->getContext())) << import_id
5640 << pc_inst << getSPIRVInt32Constant(offset)
5641 << getSPIRVInt32Constant(size);
5642 addSPIRVInst(spv::OpExtInst, Ops);
5643 }
5644 }
5645}
5646
5647void SPIRVProducerPass::GenerateSpecConstantReflection() {
5648 const uint32_t kMax = std::numeric_limits<uint32_t>::max();
5649 uint32_t wgsize_id[3] = {kMax, kMax, kMax};
5650 uint32_t global_offset_id[3] = {kMax, kMax, kMax};
5651 uint32_t work_dim_id = kMax;
5652 for (auto pair : clspv::GetSpecConstants(module)) {
5653 auto kind = pair.first;
5654 auto id = pair.second;
5655
5656 // Local memory size is only used for kernel arguments.
5657 if (kind == SpecConstant::kLocalMemorySize)
5658 continue;
5659
5660 switch (kind) {
5661 case SpecConstant::kWorkgroupSizeX:
5662 wgsize_id[0] = id;
5663 break;
5664 case SpecConstant::kWorkgroupSizeY:
5665 wgsize_id[1] = id;
5666 break;
5667 case SpecConstant::kWorkgroupSizeZ:
5668 wgsize_id[2] = id;
5669 break;
5670 case SpecConstant::kGlobalOffsetX:
5671 global_offset_id[0] = id;
5672 break;
5673 case SpecConstant::kGlobalOffsetY:
5674 global_offset_id[1] = id;
5675 break;
5676 case SpecConstant::kGlobalOffsetZ:
5677 global_offset_id[2] = id;
5678 break;
5679 case SpecConstant::kWorkDim:
5680 work_dim_id = id;
5681 break;
5682 default:
5683 llvm_unreachable("Unhandled spec constant");
5684 }
5685 }
5686
5687 auto import_id = getReflectionImport();
5688 auto void_id = getSPIRVType(Type::getVoidTy(module->getContext()));
5689 SPIRVOperandVec Ops;
5690 if (wgsize_id[0] != kMax) {
5691 assert(wgsize_id[1] != kMax);
5692 assert(wgsize_id[2] != kMax);
5693 Ops.clear();
5694 Ops << void_id << import_id << reflection::ExtInstSpecConstantWorkgroupSize
5695 << getSPIRVInt32Constant(wgsize_id[0])
5696 << getSPIRVInt32Constant(wgsize_id[1])
5697 << getSPIRVInt32Constant(wgsize_id[2]);
5698 addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
5699 }
5700 if (global_offset_id[0] != kMax) {
5701 assert(global_offset_id[1] != kMax);
5702 assert(global_offset_id[2] != kMax);
5703 Ops.clear();
5704 Ops << void_id << import_id << reflection::ExtInstSpecConstantGlobalOffset
5705 << getSPIRVInt32Constant(global_offset_id[0])
5706 << getSPIRVInt32Constant(global_offset_id[1])
5707 << getSPIRVInt32Constant(global_offset_id[2]);
5708 addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
5709 }
5710 if (work_dim_id != kMax) {
5711 Ops.clear();
5712 Ops << void_id << import_id << reflection::ExtInstSpecConstantWorkDim
5713 << getSPIRVInt32Constant(work_dim_id);
5714 addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
5715 }
5716}
5717
5718void SPIRVProducerPass::GenerateKernelReflection() {
5719 const auto &DL = module->getDataLayout();
5720 auto import_id = getReflectionImport();
5721 auto void_id = getSPIRVType(Type::getVoidTy(module->getContext()));
5722
5723 for (auto &F : *module) {
5724 if (F.isDeclaration() || F.getCallingConv() != CallingConv::SPIR_KERNEL) {
5725 continue;
5726 }
5727
5728 // OpString for the kernel name.
5729 auto kernel_name =
5730 addSPIRVInst<kDebug>(spv::OpString, F.getName().str().c_str());
5731
5732 // Kernel declaration
5733 // Ops[0] = void type
5734 // Ops[1] = reflection ext import
5735 // Ops[2] = function id
5736 // Ops[3] = kernel name
5737 SPIRVOperandVec Ops;
5738 Ops << void_id << import_id << reflection::ExtInstKernel << ValueMap[&F]
5739 << kernel_name;
5740 auto kernel_decl = addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
5741
5742 // Generate the required workgroup size property if it was specified.
5743 if (const MDNode *MD = F.getMetadata("reqd_work_group_size")) {
5744 uint32_t CurXDimCst = static_cast<uint32_t>(
5745 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
5746 uint32_t CurYDimCst = static_cast<uint32_t>(
5747 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
5748 uint32_t CurZDimCst = static_cast<uint32_t>(
5749 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
5750
5751 Ops.clear();
5752 Ops << void_id << import_id
5753 << reflection::ExtInstPropertyRequiredWorkgroupSize << kernel_decl
5754 << getSPIRVInt32Constant(CurXDimCst)
5755 << getSPIRVInt32Constant(CurYDimCst)
5756 << getSPIRVInt32Constant(CurZDimCst);
5757 addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
5758 }
5759
5760 auto &resource_var_at_index = FunctionToResourceVarsMap[&F];
5761 auto *func_ty = F.getFunctionType();
5762
5763 // If we've clustered POD arguments, then argument details are in metadata.
5764 // If an argument maps to a resource variable, then get descriptor set and
5765 // binding from the resource variable. Other info comes from the metadata.
5766 const auto *arg_map = F.getMetadata(clspv::KernelArgMapMetadataName());
5767 auto local_spec_id_md =
5768 module->getNamedMetadata(clspv::LocalSpecIdMetadataName());
5769 if (arg_map) {
5770 for (const auto &arg : arg_map->operands()) {
5771 const MDNode *arg_node = dyn_cast<MDNode>(arg.get());
5772 assert(arg_node->getNumOperands() == 6);
5773 const auto name =
5774 dyn_cast<MDString>(arg_node->getOperand(0))->getString();
5775 const auto old_index =
5776 dyn_extract<ConstantInt>(arg_node->getOperand(1))->getZExtValue();
5777 // Remapped argument index
5778 const int new_index = static_cast<int>(
5779 dyn_extract<ConstantInt>(arg_node->getOperand(2))->getSExtValue());
5780 const auto offset =
5781 dyn_extract<ConstantInt>(arg_node->getOperand(3))->getZExtValue();
5782 const auto size =
5783 dyn_extract<ConstantInt>(arg_node->getOperand(4))->getZExtValue();
5784 const auto argKind = clspv::GetArgKindFromName(
5785 dyn_cast<MDString>(arg_node->getOperand(5))->getString().str());
5786
5787 // If this is a local memory argument, find the right spec id for this
5788 // argument.
5789 int64_t spec_id = -1;
5790 if (argKind == clspv::ArgKind::Local) {
5791 for (auto spec_id_arg : local_spec_id_md->operands()) {
5792 if ((&F == dyn_cast<Function>(
5793 dyn_cast<ValueAsMetadata>(spec_id_arg->getOperand(0))
5794 ->getValue())) &&
5795 (static_cast<uint64_t>(new_index) ==
5796 mdconst::extract<ConstantInt>(spec_id_arg->getOperand(1))
5797 ->getZExtValue())) {
5798 spec_id =
5799 mdconst::extract<ConstantInt>(spec_id_arg->getOperand(2))
5800 ->getSExtValue();
5801 break;
5802 }
5803 }
5804 }
5805
5806 // Generate the specific argument instruction.
5807 const uint32_t ordinal = static_cast<uint32_t>(old_index);
5808 const uint32_t arg_offset = static_cast<uint32_t>(offset);
5809 const uint32_t arg_size = static_cast<uint32_t>(size);
5810 uint32_t elem_size = 0;
5811 uint32_t descriptor_set = 0;
5812 uint32_t binding = 0;
5813 if (spec_id > 0) {
5814 elem_size = static_cast<uint32_t>(
5815 GetTypeAllocSize(func_ty->getParamType(unsigned(new_index))
5816 ->getPointerElementType(),
5817 DL));
5818 } else if (new_index >= 0) {
5819 auto *info = resource_var_at_index[new_index];
5820 assert(info);
5821 descriptor_set = info->descriptor_set;
5822 binding = info->binding;
5823 }
5824 AddArgumentReflection(kernel_decl, name.str(), argKind, ordinal,
5825 descriptor_set, binding, arg_offset, arg_size,
5826 static_cast<uint32_t>(spec_id), elem_size);
5827 }
5828 } else {
5829 // There is no argument map.
5830 // Take descriptor info from the resource variable calls.
5831 // Take argument name and size from the arguments list.
5832
5833 SmallVector<Argument *, 4> arguments;
5834 for (auto &arg : F.args()) {
5835 arguments.push_back(&arg);
5836 }
5837
5838 unsigned arg_index = 0;
5839 for (auto *info : resource_var_at_index) {
5840 if (info) {
5841 auto arg = arguments[arg_index];
5842 unsigned arg_size = 0;
5843 if (info->arg_kind == clspv::ArgKind::Pod ||
5844 info->arg_kind == clspv::ArgKind::PodUBO ||
5845 info->arg_kind == clspv::ArgKind::PodPushConstant) {
5846 arg_size =
5847 static_cast<uint32_t>(DL.getTypeStoreSize(arg->getType()));
5848 }
5849
5850 // Local pointer arguments are unused in this case.
5851 // offset, spec_id and elem_size always 0.
5852 AddArgumentReflection(kernel_decl, arg->getName().str(),
5853 info->arg_kind, arg_index, info->descriptor_set,
5854 info->binding, 0, arg_size, 0, 0);
5855 }
5856 arg_index++;
5857 }
5858 // Generate mappings for pointer-to-local arguments.
5859 for (arg_index = 0; arg_index < arguments.size(); ++arg_index) {
5860 Argument *arg = arguments[arg_index];
5861 auto where = LocalArgSpecIds.find(arg);
5862 if (where != LocalArgSpecIds.end()) {
5863 auto &local_arg_info = LocalSpecIdInfoMap[where->second];
5864
5865 // descriptor_set, binding, offset and size are always 0.
5866 AddArgumentReflection(kernel_decl, arg->getName().str(),
5867 ArgKind::Local, arg_index, 0, 0, 0, 0,
5868 static_cast<uint32_t>(local_arg_info.spec_id),
5869 static_cast<uint32_t>(GetTypeAllocSize(
5870 local_arg_info.elem_type, DL)));
5871 }
5872 }
5873 }
5874 }
5875}
5876
5877void SPIRVProducerPass::AddArgumentReflection(
5878 SPIRVID kernel_decl, const std::string &name, clspv::ArgKind arg_kind,
5879 uint32_t ordinal, uint32_t descriptor_set, uint32_t binding,
5880 uint32_t offset, uint32_t size, uint32_t spec_id, uint32_t elem_size) {
5881 // Generate ArgumentInfo for this argument.
5882 // TODO: generate remaining optional operands.
5883 auto import_id = getReflectionImport();
5884 auto arg_name = addSPIRVInst<kDebug>(spv::OpString, name.c_str());
5885 auto void_id = getSPIRVType(Type::getVoidTy(module->getContext()));
5886 SPIRVOperandVec Ops;
5887 Ops << void_id << import_id << reflection::ExtInstArgumentInfo << arg_name;
5888 auto arg_info = addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
5889
5890 Ops.clear();
5891 Ops << void_id << import_id;
5892 reflection::ExtInst ext_inst = reflection::ExtInstMax;
5893 // Determine the extended instruction.
5894 switch (arg_kind) {
5895 case clspv::ArgKind::Buffer:
5896 ext_inst = reflection::ExtInstArgumentStorageBuffer;
5897 break;
5898 case clspv::ArgKind::BufferUBO:
5899 ext_inst = reflection::ExtInstArgumentUniform;
5900 break;
5901 case clspv::ArgKind::Local:
5902 ext_inst = reflection::ExtInstArgumentWorkgroup;
5903 break;
5904 case clspv::ArgKind::Pod:
5905 ext_inst = reflection::ExtInstArgumentPodStorageBuffer;
5906 break;
5907 case clspv::ArgKind::PodUBO:
5908 ext_inst = reflection::ExtInstArgumentPodUniform;
5909 break;
5910 case clspv::ArgKind::PodPushConstant:
5911 ext_inst = reflection::ExtInstArgumentPodPushConstant;
5912 break;
alan-bakerf6bc8252020-09-23 14:58:55 -04005913 case clspv::ArgKind::SampledImage:
alan-baker86ce19c2020-08-05 13:09:19 -04005914 ext_inst = reflection::ExtInstArgumentSampledImage;
5915 break;
alan-bakerf6bc8252020-09-23 14:58:55 -04005916 case clspv::ArgKind::StorageImage:
alan-baker86ce19c2020-08-05 13:09:19 -04005917 ext_inst = reflection::ExtInstArgumentStorageImage;
5918 break;
5919 case clspv::ArgKind::Sampler:
5920 ext_inst = reflection::ExtInstArgumentSampler;
5921 break;
5922 default:
5923 llvm_unreachable("Unhandled argument reflection");
5924 break;
5925 }
5926 Ops << ext_inst << kernel_decl << getSPIRVInt32Constant(ordinal);
5927
5928 // Add descriptor set and binding for applicable arguments.
5929 switch (arg_kind) {
5930 case clspv::ArgKind::Buffer:
5931 case clspv::ArgKind::BufferUBO:
5932 case clspv::ArgKind::Pod:
5933 case clspv::ArgKind::PodUBO:
alan-bakerf6bc8252020-09-23 14:58:55 -04005934 case clspv::ArgKind::SampledImage:
5935 case clspv::ArgKind::StorageImage:
alan-baker86ce19c2020-08-05 13:09:19 -04005936 case clspv::ArgKind::Sampler:
5937 Ops << getSPIRVInt32Constant(descriptor_set)
5938 << getSPIRVInt32Constant(binding);
5939 break;
5940 default:
5941 break;
5942 }
5943
5944 // Add remaining operands for arguments.
5945 switch (arg_kind) {
5946 case clspv::ArgKind::Local:
5947 Ops << getSPIRVInt32Constant(spec_id) << getSPIRVInt32Constant(elem_size);
5948 break;
5949 case clspv::ArgKind::Pod:
5950 case clspv::ArgKind::PodUBO:
5951 case clspv::ArgKind::PodPushConstant:
5952 Ops << getSPIRVInt32Constant(offset) << getSPIRVInt32Constant(size);
5953 break;
5954 default:
5955 break;
5956 }
5957 Ops << arg_info;
5958 addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
5959}