blob: df0a6e898a94121a79663292316d73ed99cde315 [file] [log] [blame]
David Neto22f144c2017-06-12 14:26:21 -04001// Copyright 2017 The Clspv Authors. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#ifdef _MSC_VER
16#pragma warning(push, 0)
17#endif
18
David Neto156783e2017-07-05 15:39:41 -040019#include <cassert>
David Neto257c3892018-04-11 13:19:45 -040020#include <cstring>
David Neto118188e2018-08-24 11:27:54 -040021#include <iomanip>
22#include <list>
David Neto862b7d82018-06-14 18:48:37 -040023#include <memory>
David Neto118188e2018-08-24 11:27:54 -040024#include <set>
25#include <sstream>
26#include <string>
27#include <tuple>
28#include <unordered_set>
29#include <utility>
David Neto862b7d82018-06-14 18:48:37 -040030
David Neto118188e2018-08-24 11:27:54 -040031#include "llvm/ADT/StringSwitch.h"
32#include "llvm/ADT/UniqueVector.h"
33#include "llvm/Analysis/LoopInfo.h"
34#include "llvm/IR/Constants.h"
35#include "llvm/IR/Dominators.h"
36#include "llvm/IR/Instructions.h"
37#include "llvm/IR/Metadata.h"
38#include "llvm/IR/Module.h"
alan-bakerf67468c2019-11-25 15:51:49 -050039#include "llvm/IR/ValueSymbolTable.h"
David Neto118188e2018-08-24 11:27:54 -040040#include "llvm/Pass.h"
41#include "llvm/Support/CommandLine.h"
Kévin Petitbbbda972020-03-03 19:16:31 +000042#include "llvm/Support/MathExtras.h"
David Neto118188e2018-08-24 11:27:54 -040043#include "llvm/Support/raw_ostream.h"
44#include "llvm/Transforms/Utils/Cloning.h"
David Neto22f144c2017-06-12 14:26:21 -040045
SJWf93f5f32020-05-05 07:27:56 -050046// enable spv::HasResultAndType
47#define SPV_ENABLE_UTILITY_CODE
alan-bakere0902602020-03-23 08:43:40 -040048#include "spirv/unified1/spirv.hpp"
David Neto118188e2018-08-24 11:27:54 -040049
David Neto85082642018-03-24 06:55:20 -070050#include "clspv/AddressSpace.h"
David Neto118188e2018-08-24 11:27:54 -040051#include "clspv/Option.h"
alan-baker86ce19c2020-08-05 13:09:19 -040052#include "clspv/PushConstant.h"
53#include "clspv/SpecConstant.h"
David Neto85082642018-03-24 06:55:20 -070054#include "clspv/spirv_c_strings.hpp"
55#include "clspv/spirv_glsl.hpp"
alan-baker86ce19c2020-08-05 13:09:19 -040056#include "clspv/spirv_reflection.hpp"
David Neto22f144c2017-06-12 14:26:21 -040057
David Neto4feb7a42017-10-06 17:29:42 -040058#include "ArgKind.h"
alan-bakerf67468c2019-11-25 15:51:49 -050059#include "Builtins.h"
alan-baker06cad652019-12-03 17:56:47 -050060#include "ComputeStructuredOrder.h"
David Neto85082642018-03-24 06:55:20 -070061#include "ConstantEmitter.h"
Alan Baker202c8c72018-08-13 13:47:44 -040062#include "Constants.h"
David Neto78383442018-06-15 20:31:56 -040063#include "DescriptorCounter.h"
alan-bakerc4579bb2020-04-29 14:15:50 -040064#include "Layout.h"
alan-baker56f7aff2019-05-22 08:06:42 -040065#include "NormalizeGlobalVariable.h"
Diego Novilloa4c44fa2019-04-11 10:56:15 -040066#include "Passes.h"
alan-bakera1be3322020-04-20 12:48:18 -040067#include "SpecConstant.h"
alan-bakerce179f12019-12-06 19:02:22 -050068#include "Types.h"
David Neto48f56a42017-10-06 16:44:25 -040069
David Neto22f144c2017-06-12 14:26:21 -040070#if defined(_MSC_VER)
71#pragma warning(pop)
72#endif
73
74using namespace llvm;
75using namespace clspv;
SJW173c7e92020-03-16 08:44:47 -050076using namespace clspv::Builtins;
SJW806a5d82020-07-15 12:51:38 -050077using namespace clspv::Option;
David Neto156783e2017-07-05 15:39:41 -040078using namespace mdconst;
David Neto22f144c2017-06-12 14:26:21 -040079
80namespace {
David Netocd8ca5f2017-10-02 23:34:11 -040081
David Neto862b7d82018-06-14 18:48:37 -040082cl::opt<bool> ShowResourceVars("show-rv", cl::init(false), cl::Hidden,
83 cl::desc("Show resource variable creation"));
84
alan-baker5ed87542020-03-23 11:05:22 -040085cl::opt<bool>
86 ShowProducerIR("show-producer-ir", cl::init(false), cl::ReallyHidden,
87 cl::desc("Dump the IR at the start of SPIRVProducer"));
88
David Neto862b7d82018-06-14 18:48:37 -040089// These hacks exist to help transition code generation algorithms
90// without making huge noise in detailed test output.
91const bool Hack_generate_runtime_array_stride_early = true;
92
David Neto3fbb4072017-10-16 11:28:14 -040093// The value of 1/pi. This value is from MSDN
94// https://msdn.microsoft.com/en-us/library/4hwaceh6.aspx
95const double kOneOverPi = 0.318309886183790671538;
96const glsl::ExtInst kGlslExtInstBad = static_cast<glsl::ExtInst>(0);
97
alan-baker86ce19c2020-08-05 13:09:19 -040098// SPIRV Module Sections (per 2.4 of the SPIR-V spec)
SJW69939d52020-04-16 07:29:07 -050099// These are used to collect SPIRVInstructions by type on-the-fly.
100enum SPIRVSection {
101 kCapabilities,
102 kExtensions,
103 kImports,
104 kMemoryModel,
105 kEntryPoints,
106 kExecutionModes,
107
108 kDebug,
109 kAnnotations,
110
111 kTypes,
112 kConstants = kTypes,
113 kGlobalVariables,
114
115 kFunctions,
116
alan-baker86ce19c2020-08-05 13:09:19 -0400117 // This is not a section of the SPIR-V spec and should always immediately
118 // precede kSectionCount. It is a convenient place for the embedded
119 // reflection data.
120 kReflection,
SJW69939d52020-04-16 07:29:07 -0500121 kSectionCount
122};
123
SJW01901d92020-05-21 08:58:31 -0500124class SPIRVID {
125 uint32_t id;
126
127public:
128 SPIRVID(uint32_t _id = 0) : id(_id) {}
129 uint32_t get() const { return id; }
130 bool isValid() const { return id != 0; }
131 bool operator==(const SPIRVID &that) const { return id == that.id; }
SJW806a5d82020-07-15 12:51:38 -0500132 bool operator<(const SPIRVID &that) const { return id < that.id; }
SJW01901d92020-05-21 08:58:31 -0500133};
SJWf93f5f32020-05-05 07:27:56 -0500134
SJW88ed5fe2020-05-11 12:40:57 -0500135enum SPIRVOperandType { NUMBERID, LITERAL_WORD, LITERAL_DWORD, LITERAL_STRING };
David Neto22f144c2017-06-12 14:26:21 -0400136
137struct SPIRVOperand {
SJW88ed5fe2020-05-11 12:40:57 -0500138 explicit SPIRVOperand(SPIRVOperandType Ty, uint32_t Num) : Type(Ty) {
139 LiteralNum[0] = Num;
140 }
David Neto22f144c2017-06-12 14:26:21 -0400141 explicit SPIRVOperand(SPIRVOperandType Ty, const char *Str)
142 : Type(Ty), LiteralStr(Str) {}
143 explicit SPIRVOperand(SPIRVOperandType Ty, StringRef Str)
144 : Type(Ty), LiteralStr(Str) {}
SJW88ed5fe2020-05-11 12:40:57 -0500145 explicit SPIRVOperand(ArrayRef<uint32_t> NumVec) {
146 auto sz = NumVec.size();
147 assert(sz >= 1 && sz <= 2);
148 Type = sz == 1 ? LITERAL_WORD : LITERAL_DWORD;
149 LiteralNum[0] = NumVec[0];
150 if (sz == 2) {
151 LiteralNum[1] = NumVec[1];
152 }
153 }
David Neto22f144c2017-06-12 14:26:21 -0400154
alan-baker7506abb2020-09-10 15:02:55 -0400155 SPIRVOperandType getType() const { return Type; }
156 uint32_t getNumID() const { return LiteralNum[0]; }
157 std::string getLiteralStr() const { return LiteralStr; }
158 const uint32_t *getLiteralNum() const { return LiteralNum; }
David Neto22f144c2017-06-12 14:26:21 -0400159
David Neto87846742018-04-11 17:36:22 -0400160 uint32_t GetNumWords() const {
161 switch (Type) {
162 case NUMBERID:
SJW88ed5fe2020-05-11 12:40:57 -0500163 case LITERAL_WORD:
David Neto87846742018-04-11 17:36:22 -0400164 return 1;
SJW88ed5fe2020-05-11 12:40:57 -0500165 case LITERAL_DWORD:
166 return 2;
David Neto87846742018-04-11 17:36:22 -0400167 case LITERAL_STRING:
168 // Account for the terminating null character.
David Netoee2660d2018-06-28 16:31:29 -0400169 return uint32_t((LiteralStr.size() + 4) / 4);
David Neto87846742018-04-11 17:36:22 -0400170 }
171 llvm_unreachable("Unhandled case in SPIRVOperand::GetNumWords()");
172 }
173
David Neto22f144c2017-06-12 14:26:21 -0400174private:
175 SPIRVOperandType Type;
176 std::string LiteralStr;
SJW88ed5fe2020-05-11 12:40:57 -0500177 uint32_t LiteralNum[2];
David Neto22f144c2017-06-12 14:26:21 -0400178};
179
SJW88ed5fe2020-05-11 12:40:57 -0500180typedef SmallVector<SPIRVOperand, 4> SPIRVOperandVec;
David Netoc6f3ab22018-04-06 18:02:31 -0400181
David Neto22f144c2017-06-12 14:26:21 -0400182struct SPIRVInstruction {
SJWf93f5f32020-05-05 07:27:56 -0500183 // Primary constructor must have Opcode, initializes WordCount based on ResID.
184 SPIRVInstruction(spv::Op Opc, SPIRVID ResID = 0)
185 : Opcode(static_cast<uint16_t>(Opc)) {
186 setResult(ResID);
David Neto87846742018-04-11 17:36:22 -0400187 }
David Neto22f144c2017-06-12 14:26:21 -0400188
SJWf93f5f32020-05-05 07:27:56 -0500189 // Creates an instruction with an opcode and no result ID, and with the given
190 // operands. This calls primary constructor to initialize Opcode, WordCount.
191 // Takes ownership of the operands and clears |Ops|.
192 SPIRVInstruction(spv::Op Opc, SPIRVOperandVec &Ops) : SPIRVInstruction(Opc) {
193 setOperands(Ops);
David Netoef5ba2b2019-12-20 08:35:54 -0500194 }
SJWf93f5f32020-05-05 07:27:56 -0500195 // Creates an instruction with an opcode and no result ID, and with the given
196 // operands. This calls primary constructor to initialize Opcode, WordCount.
197 // Takes ownership of the operands and clears |Ops|.
198 SPIRVInstruction(spv::Op Opc, SPIRVID ResID, SPIRVOperandVec &Ops)
199 : SPIRVInstruction(Opc, ResID) {
200 setOperands(Ops);
David Netoef5ba2b2019-12-20 08:35:54 -0500201 }
David Netoef5ba2b2019-12-20 08:35:54 -0500202
David Netoee2660d2018-06-28 16:31:29 -0400203 uint32_t getWordCount() const { return WordCount; }
David Neto22f144c2017-06-12 14:26:21 -0400204 uint16_t getOpcode() const { return Opcode; }
SJW88ed5fe2020-05-11 12:40:57 -0500205 SPIRVID getResultID() const { return ResultID; }
206 const SPIRVOperandVec &getOperands() const { return Operands; }
David Neto22f144c2017-06-12 14:26:21 -0400207
208private:
SJW01901d92020-05-21 08:58:31 -0500209 void setResult(SPIRVID ResID = 0) {
210 WordCount = 1 + (ResID.isValid() ? 1 : 0);
SJWf93f5f32020-05-05 07:27:56 -0500211 ResultID = ResID;
212 }
213
214 void setOperands(SPIRVOperandVec &Ops) {
215 assert(Operands.empty());
216 Operands = std::move(Ops);
217 for (auto &opd : Operands) {
SJW88ed5fe2020-05-11 12:40:57 -0500218 WordCount += uint16_t(opd.GetNumWords());
SJWf93f5f32020-05-05 07:27:56 -0500219 }
220 }
221
222private:
David Netoee2660d2018-06-28 16:31:29 -0400223 uint32_t WordCount; // Check the 16-bit bound at code generation time.
David Neto22f144c2017-06-12 14:26:21 -0400224 uint16_t Opcode;
SJW88ed5fe2020-05-11 12:40:57 -0500225 SPIRVID ResultID;
SJWf93f5f32020-05-05 07:27:56 -0500226 SPIRVOperandVec Operands;
David Neto22f144c2017-06-12 14:26:21 -0400227};
228
229struct SPIRVProducerPass final : public ModulePass {
SJW01901d92020-05-21 08:58:31 -0500230 typedef DenseMap<Type *, SPIRVID> TypeMapType;
David Neto22f144c2017-06-12 14:26:21 -0400231 typedef UniqueVector<Type *> TypeList;
SJW88ed5fe2020-05-11 12:40:57 -0500232 typedef DenseMap<Value *, SPIRVID> ValueMapType;
SJW806a5d82020-07-15 12:51:38 -0500233 typedef std::list<SPIRVID> SPIRVIDListType;
SJW01901d92020-05-21 08:58:31 -0500234 typedef std::vector<std::pair<Value *, SPIRVID>> EntryPointVecType;
235 typedef std::set<uint32_t> CapabilitySetType;
SJW88ed5fe2020-05-11 12:40:57 -0500236 typedef std::list<SPIRVInstruction> SPIRVInstructionList;
SJW806a5d82020-07-15 12:51:38 -0500237 typedef std::map<spv::BuiltIn, SPIRVID> BuiltinConstantMapType;
SJW88ed5fe2020-05-11 12:40:57 -0500238 // A vector of pairs, each of which is:
David Neto87846742018-04-11 17:36:22 -0400239 // - the LLVM instruction that we will later generate SPIR-V code for
SJW88ed5fe2020-05-11 12:40:57 -0500240 // - the SPIR-V instruction placeholder that will be replaced
241 typedef std::vector<std::pair<Value *, SPIRVInstruction *>>
David Neto22f144c2017-06-12 14:26:21 -0400242 DeferredInstVecType;
243 typedef DenseMap<FunctionType *, std::pair<FunctionType *, uint32_t>>
244 GlobalConstFuncMapType;
245
David Neto44795152017-07-13 15:45:28 -0400246 explicit SPIRVProducerPass(
alan-bakerf5e5f692018-11-27 08:33:24 -0500247 raw_pwrite_stream &out,
alan-baker00e7a582019-06-07 12:54:21 -0400248 ArrayRef<std::pair<unsigned, std::string>> samplerMap,
David Neto44795152017-07-13 15:45:28 -0400249 bool outputCInitList)
SJW01901d92020-05-21 08:58:31 -0500250 : ModulePass(ID), module(nullptr), samplerMap(samplerMap), out(out),
David Neto0676e6f2017-07-11 18:47:44 -0400251 binaryTempOut(binaryTempUnderlyingVector), binaryOut(&out),
David Neto0676e6f2017-07-11 18:47:44 -0400252 outputCInitList(outputCInitList), patchBoundOffset(0), nextID(1),
alan-baker5b86ed72019-02-15 08:26:50 -0500253 OpExtInstImportID(0), HasVariablePointersStorageBuffer(false),
254 HasVariablePointers(false), SamplerTy(nullptr), WorkgroupSizeValueID(0),
SJW01901d92020-05-21 08:58:31 -0500255 WorkgroupSizeVarID(0) {
256 addCapability(spv::CapabilityShader);
257 Ptr = this;
258 }
David Neto22f144c2017-06-12 14:26:21 -0400259
James Price11010dc2019-12-19 13:53:09 -0500260 virtual ~SPIRVProducerPass() {
James Price11010dc2019-12-19 13:53:09 -0500261 }
262
David Neto22f144c2017-06-12 14:26:21 -0400263 void getAnalysisUsage(AnalysisUsage &AU) const override {
264 AU.addRequired<DominatorTreeWrapperPass>();
265 AU.addRequired<LoopInfoWrapperPass>();
266 }
267
268 virtual bool runOnModule(Module &module) override;
269
270 // output the SPIR-V header block
271 void outputHeader();
272
273 // patch the SPIR-V header block
274 void patchHeader();
275
SJW01901d92020-05-21 08:58:31 -0500276 CapabilitySetType &getCapabilitySet() { return CapabilitySet; }
David Neto22f144c2017-06-12 14:26:21 -0400277 TypeMapType &getImageTypeMap() { return ImageTypeMap; }
alan-baker7506abb2020-09-10 15:02:55 -0400278 TypeList &getTypeList() { return Types; }
David Neto22f144c2017-06-12 14:26:21 -0400279 ValueMapType &getValueMap() { return ValueMap; }
SJW69939d52020-04-16 07:29:07 -0500280 SPIRVInstructionList &getSPIRVInstList(SPIRVSection Section) {
281 return SPIRVSections[Section];
282 };
alan-baker7506abb2020-09-10 15:02:55 -0400283 EntryPointVecType &getEntryPointVec() { return EntryPointVec; }
284 DeferredInstVecType &getDeferredInstVec() { return DeferredInstVec; }
SJW806a5d82020-07-15 12:51:38 -0500285 SPIRVIDListType &getEntryPointInterfacesList() {
286 return EntryPointInterfacesList;
alan-baker7506abb2020-09-10 15:02:55 -0400287 }
SJW01901d92020-05-21 08:58:31 -0500288 SPIRVID getOpExtInstImportID();
alan-baker7506abb2020-09-10 15:02:55 -0400289 std::vector<SPIRVID> &getBuiltinDimVec() { return BuiltinDimensionVec; }
SJW2c317da2020-03-23 07:39:13 -0500290
alan-baker5b86ed72019-02-15 08:26:50 -0500291 bool hasVariablePointersStorageBuffer() {
292 return HasVariablePointersStorageBuffer;
293 }
SJW01901d92020-05-21 08:58:31 -0500294 void setVariablePointersStorageBuffer() {
295 if (!HasVariablePointersStorageBuffer) {
296 addCapability(spv::CapabilityVariablePointersStorageBuffer);
297 HasVariablePointersStorageBuffer = true;
298 }
alan-baker5b86ed72019-02-15 08:26:50 -0500299 }
alan-baker7506abb2020-09-10 15:02:55 -0400300 bool hasVariablePointers() { return HasVariablePointers; }
SJW01901d92020-05-21 08:58:31 -0500301 void setVariablePointers() {
302 if (!HasVariablePointers) {
303 addCapability(spv::CapabilityVariablePointers);
304 HasVariablePointers = true;
305 }
alan-baker7506abb2020-09-10 15:02:55 -0400306 }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500307 ArrayRef<std::pair<unsigned, std::string>> &getSamplerMap() {
308 return samplerMap;
309 }
David Neto22f144c2017-06-12 14:26:21 -0400310 GlobalConstFuncMapType &getGlobalConstFuncTypeMap() {
311 return GlobalConstFuncTypeMap;
312 }
313 SmallPtrSet<Value *, 16> &getGlobalConstArgSet() {
314 return GlobalConstArgumentSet;
315 }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500316 TypeList &getTypesNeedingArrayStride() { return TypesNeedingArrayStride; }
David Neto22f144c2017-06-12 14:26:21 -0400317
SJW77b87ad2020-04-21 14:37:52 -0500318 void GenerateLLVMIRInfo();
alan-bakerb6b09dc2018-11-08 16:59:28 -0500319 // Populate GlobalConstFuncTypeMap. Also, if module-scope __constant will
320 // *not* be converted to a storage buffer, replace each such global variable
321 // with one in the storage class expecgted by SPIR-V.
SJW77b87ad2020-04-21 14:37:52 -0500322 void FindGlobalConstVars();
David Neto862b7d82018-06-14 18:48:37 -0400323 // Populate ResourceVarInfoList, FunctionToResourceVarsMap, and
324 // ModuleOrderedResourceVars.
SJW77b87ad2020-04-21 14:37:52 -0500325 void FindResourceVars();
David Neto22f144c2017-06-12 14:26:21 -0400326 void FindTypePerGlobalVar(GlobalVariable &GV);
327 void FindTypePerFunc(Function &F);
SJW77b87ad2020-04-21 14:37:52 -0500328 void FindTypesForSamplerMap();
329 void FindTypesForResourceVars();
alan-bakerb6b09dc2018-11-08 16:59:28 -0500330 // Inserts |Ty| and relevant sub-types into the |Types| member, indicating
331 // that |Ty| and its subtypes will need a corresponding SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400332 void FindType(Type *Ty);
SJWf93f5f32020-05-05 07:27:56 -0500333
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);
417 uint64_t GetTypeStoreSize(Type *type, const DataLayout &DL);
418 uint64_t GetTypeAllocSize(Type *type, const DataLayout &DL);
Kévin Petitbbbda972020-03-03 19:16:31 +0000419 uint32_t GetExplicitLayoutStructMemberOffset(StructType *type,
420 unsigned member,
421 const DataLayout &DL);
Alan Bakerfcda9482018-10-02 17:09:59 -0400422
alan-baker5b86ed72019-02-15 08:26:50 -0500423 // Returns the base pointer of |v|.
424 Value *GetBasePointer(Value *v);
425
SJW01901d92020-05-21 08:58:31 -0500426 // Add Capability if not already (e.g. CapabilityGroupNonUniformBroadcast)
427 void addCapability(uint32_t c) { CapabilitySet.emplace(c); }
428
alan-baker5b86ed72019-02-15 08:26:50 -0500429 // Sets |HasVariablePointersStorageBuffer| or |HasVariablePointers| base on
430 // |address_space|.
431 void setVariablePointersCapabilities(unsigned address_space);
432
433 // Returns true if |lhs| and |rhs| represent the same resource or workgroup
434 // variable.
435 bool sameResource(Value *lhs, Value *rhs) const;
436
437 // Returns true if |inst| is phi or select that selects from the same
438 // structure (or null).
439 bool selectFromSameObject(Instruction *inst);
440
alan-bakere9308012019-03-15 10:25:13 -0400441 // Returns true if |Arg| is called with a coherent resource.
442 bool CalledWithCoherentResource(Argument &Arg);
443
SJWf93f5f32020-05-05 07:27:56 -0500444 //
445 // Primary interface for adding SPIRVInstructions to a SPIRVSection.
446 template <enum SPIRVSection TSection = kFunctions>
447 SPIRVID addSPIRVInst(spv::Op Opcode, SPIRVOperandVec &Operands) {
448 bool has_result, has_result_type;
449 spv::HasResultAndType(Opcode, &has_result, &has_result_type);
450 SPIRVID RID = has_result ? incrNextID() : 0;
SJW88ed5fe2020-05-11 12:40:57 -0500451 SPIRVSections[TSection].emplace_back(Opcode, RID, Operands);
SJWf93f5f32020-05-05 07:27:56 -0500452 return RID;
453 }
454 template <enum SPIRVSection TSection = kFunctions>
455 SPIRVID addSPIRVInst(spv::Op Op) {
456 SPIRVOperandVec Ops;
457 return addSPIRVInst<TSection>(Op, Ops);
458 }
459 template <enum SPIRVSection TSection = kFunctions>
460 SPIRVID addSPIRVInst(spv::Op Op, uint32_t V) {
461 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -0500462 Ops.emplace_back(LITERAL_WORD, V);
SJWf93f5f32020-05-05 07:27:56 -0500463 return addSPIRVInst<TSection>(Op, Ops);
464 }
465 template <enum SPIRVSection TSection = kFunctions>
466 SPIRVID addSPIRVInst(spv::Op Op, const char *V) {
467 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -0500468 Ops.emplace_back(LITERAL_STRING, V);
SJWf93f5f32020-05-05 07:27:56 -0500469 return addSPIRVInst<TSection>(Op, Ops);
470 }
471
SJW88ed5fe2020-05-11 12:40:57 -0500472 //
473 // Add placeholder for llvm::Value that references future values.
474 // Must have result ID just in case final SPIRVInstruction requires.
475 SPIRVID addSPIRVPlaceholder(Value *I) {
476 SPIRVID RID = incrNextID();
477 SPIRVOperandVec Ops;
478 SPIRVSections[kFunctions].emplace_back(spv::OpExtInst, RID, Ops);
479 DeferredInstVec.push_back({I, &SPIRVSections[kFunctions].back()});
480 return RID;
481 }
482 // Replace placeholder with actual SPIRVInstruction on the final pass
483 // (HandleDeferredInstruction).
484 SPIRVID replaceSPIRVInst(SPIRVInstruction *I, spv::Op Opcode,
485 SPIRVOperandVec &Operands) {
486 bool has_result, has_result_type;
487 spv::HasResultAndType(Opcode, &has_result, &has_result_type);
488 SPIRVID RID = has_result ? I->getResultID() : 0;
489 *I = SPIRVInstruction(Opcode, RID, Operands);
490 return RID;
491 }
492
SJW806a5d82020-07-15 12:51:38 -0500493 //
494 // Add global variable and capture entry point interface
495 SPIRVID addSPIRVGlobalVariable(const SPIRVID &TypeID, spv::StorageClass SC,
496 const SPIRVID &InitID = SPIRVID());
497
alan-baker86ce19c2020-08-05 13:09:19 -0400498 SPIRVID getReflectionImport();
499 void GenerateReflection();
500 void GenerateKernelReflection();
501 void GeneratePushConstantReflection();
502 void GenerateSpecConstantReflection();
503 void AddArgumentReflection(SPIRVID kernel_decl, const std::string &name,
504 clspv::ArgKind arg_kind, uint32_t ordinal,
505 uint32_t descriptor_set, uint32_t binding,
506 uint32_t offset, uint32_t size, uint32_t spec_id,
507 uint32_t elem_size);
508
David Neto22f144c2017-06-12 14:26:21 -0400509private:
510 static char ID;
SJW77b87ad2020-04-21 14:37:52 -0500511
512 Module *module;
513
SJW01901d92020-05-21 08:58:31 -0500514 // Set of Capabilities required
515 CapabilitySetType CapabilitySet;
516
SJW806a5d82020-07-15 12:51:38 -0500517 // Map from clspv::BuiltinType to SPIRV Global Variable
518 BuiltinConstantMapType BuiltinConstantMap;
519
David Neto44795152017-07-13 15:45:28 -0400520 ArrayRef<std::pair<unsigned, std::string>> samplerMap;
David Neto22f144c2017-06-12 14:26:21 -0400521 raw_pwrite_stream &out;
David Neto0676e6f2017-07-11 18:47:44 -0400522
523 // TODO(dneto): Wouldn't it be better to always just emit a binary, and then
524 // convert to other formats on demand?
525
526 // When emitting a C initialization list, the WriteSPIRVBinary method
527 // will actually write its words to this vector via binaryTempOut.
528 SmallVector<char, 100> binaryTempUnderlyingVector;
529 raw_svector_ostream binaryTempOut;
530
531 // Binary output writes to this stream, which might be |out| or
532 // |binaryTempOut|. It's the latter when we really want to write a C
533 // initializer list.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400534 raw_pwrite_stream *binaryOut;
David Neto0676e6f2017-07-11 18:47:44 -0400535 const bool outputCInitList; // If true, output look like {0x7023, ... , 5}
David Neto22f144c2017-06-12 14:26:21 -0400536 uint64_t patchBoundOffset;
537 uint32_t nextID;
538
SJWf93f5f32020-05-05 07:27:56 -0500539 SPIRVID incrNextID() { return nextID++; }
540
alan-bakerf67468c2019-11-25 15:51:49 -0500541 // ID for OpTypeInt 32 1.
SJW01901d92020-05-21 08:58:31 -0500542 SPIRVID int32ID;
alan-bakerf67468c2019-11-25 15:51:49 -0500543 // ID for OpTypeVector %int 4.
SJW01901d92020-05-21 08:58:31 -0500544 SPIRVID v4int32ID;
alan-bakerf67468c2019-11-25 15:51:49 -0500545
David Neto19a1bad2017-08-25 15:01:41 -0400546 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400547 TypeMapType TypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400548 // Maps an LLVM image type to its SPIR-V ID.
David Neto22f144c2017-06-12 14:26:21 -0400549 TypeMapType ImageTypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400550 // A unique-vector of LLVM types that map to a SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400551 TypeList Types;
David Neto19a1bad2017-08-25 15:01:41 -0400552 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400553 ValueMapType ValueMap;
SJW69939d52020-04-16 07:29:07 -0500554 SPIRVInstructionList SPIRVSections[kSectionCount];
David Neto862b7d82018-06-14 18:48:37 -0400555
David Neto22f144c2017-06-12 14:26:21 -0400556 EntryPointVecType EntryPointVec;
557 DeferredInstVecType DeferredInstVec;
SJW806a5d82020-07-15 12:51:38 -0500558 SPIRVIDListType EntryPointInterfacesList;
SJW01901d92020-05-21 08:58:31 -0500559 SPIRVID OpExtInstImportID;
560 std::vector<SPIRVID> BuiltinDimensionVec;
alan-baker5b86ed72019-02-15 08:26:50 -0500561 bool HasVariablePointersStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -0400562 bool HasVariablePointers;
563 Type *SamplerTy;
SJW01901d92020-05-21 08:58:31 -0500564 DenseMap<unsigned, SPIRVID> SamplerLiteralToIDMap;
David Netoc77d9e22018-03-24 06:30:28 -0700565
566 // If a function F has a pointer-to-__constant parameter, then this variable
David Neto9ed8e2f2018-03-24 06:47:24 -0700567 // will map F's type to (G, index of the parameter), where in a first phase
568 // G is F's type. During FindTypePerFunc, G will be changed to F's type
569 // but replacing the pointer-to-constant parameter with
570 // pointer-to-ModuleScopePrivate.
David Netoc77d9e22018-03-24 06:30:28 -0700571 // TODO(dneto): This doesn't seem general enough? A function might have
572 // more than one such parameter.
David Neto22f144c2017-06-12 14:26:21 -0400573 GlobalConstFuncMapType GlobalConstFuncTypeMap;
574 SmallPtrSet<Value *, 16> GlobalConstArgumentSet;
David Neto1a1a0582017-07-07 12:01:44 -0400575 // An ordered set of pointer types of Base arguments to OpPtrAccessChain,
David Neto85082642018-03-24 06:55:20 -0700576 // or array types, and which point into transparent memory (StorageBuffer
577 // storage class). These will require an ArrayStride decoration.
David Neto1a1a0582017-07-07 12:01:44 -0400578 // See SPV_KHR_variable_pointers rev 13.
David Neto85082642018-03-24 06:55:20 -0700579 TypeList TypesNeedingArrayStride;
David Netoa60b00b2017-09-15 16:34:09 -0400580
581 // This is truly ugly, but works around what look like driver bugs.
582 // For get_local_size, an earlier part of the flow has created a module-scope
583 // variable in Private address space to hold the value for the workgroup
584 // size. Its intializer is a uint3 value marked as builtin WorkgroupSize.
585 // When this is present, save the IDs of the initializer value and variable
586 // in these two variables. We only ever do a vector load from it, and
587 // when we see one of those, substitute just the value of the intializer.
588 // This mimics what Glslang does, and that's what drivers are used to.
David Neto66cfe642018-03-24 06:13:56 -0700589 // TODO(dneto): Remove this once drivers are fixed.
SJW01901d92020-05-21 08:58:31 -0500590 SPIRVID WorkgroupSizeValueID;
591 SPIRVID WorkgroupSizeVarID;
David Neto26aaf622017-10-23 18:11:53 -0400592
David Neto862b7d82018-06-14 18:48:37 -0400593 // Bookkeeping for mapping kernel arguments to resource variables.
594 struct ResourceVarInfo {
595 ResourceVarInfo(int index_arg, unsigned set_arg, unsigned binding_arg,
alan-bakere9308012019-03-15 10:25:13 -0400596 Function *fn, clspv::ArgKind arg_kind_arg, int coherent_arg)
David Neto862b7d82018-06-14 18:48:37 -0400597 : index(index_arg), descriptor_set(set_arg), binding(binding_arg),
alan-bakere9308012019-03-15 10:25:13 -0400598 var_fn(fn), arg_kind(arg_kind_arg), coherent(coherent_arg),
David Neto862b7d82018-06-14 18:48:37 -0400599 addr_space(fn->getReturnType()->getPointerAddressSpace()) {}
600 const int index; // Index into ResourceVarInfoList
601 const unsigned descriptor_set;
602 const unsigned binding;
603 Function *const var_fn; // The @clspv.resource.var.* function.
604 const clspv::ArgKind arg_kind;
alan-bakere9308012019-03-15 10:25:13 -0400605 const int coherent;
David Neto862b7d82018-06-14 18:48:37 -0400606 const unsigned addr_space; // The LLVM address space
607 // The SPIR-V ID of the OpVariable. Not populated at construction time.
SJW01901d92020-05-21 08:58:31 -0500608 SPIRVID var_id;
David Neto862b7d82018-06-14 18:48:37 -0400609 };
610 // A list of resource var info. Each one correponds to a module-scope
611 // resource variable we will have to create. Resource var indices are
612 // indices into this vector.
613 SmallVector<std::unique_ptr<ResourceVarInfo>, 8> ResourceVarInfoList;
614 // This is a vector of pointers of all the resource vars, but ordered by
615 // kernel function, and then by argument.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500616 UniqueVector<ResourceVarInfo *> ModuleOrderedResourceVars;
David Neto862b7d82018-06-14 18:48:37 -0400617 // Map a function to the ordered list of resource variables it uses, one for
618 // each argument. If an argument does not use a resource variable, it
619 // will have a null pointer entry.
620 using FunctionToResourceVarsMapType =
621 DenseMap<Function *, SmallVector<ResourceVarInfo *, 8>>;
622 FunctionToResourceVarsMapType FunctionToResourceVarsMap;
623
624 // What LLVM types map to SPIR-V types needing layout? These are the
625 // arrays and structures supporting storage buffers and uniform buffers.
626 TypeList TypesNeedingLayout;
627 // What LLVM struct types map to a SPIR-V struct type with Block decoration?
628 UniqueVector<StructType *> StructTypesNeedingBlock;
629 // For a call that represents a load from an opaque type (samplers, images),
630 // map it to the variable id it should load from.
SJW01901d92020-05-21 08:58:31 -0500631 DenseMap<CallInst *, SPIRVID> ResourceVarDeferredLoadCalls;
David Neto85082642018-03-24 06:55:20 -0700632
David Netoc6f3ab22018-04-06 18:02:31 -0400633 // An ordered list of the kernel arguments of type pointer-to-local.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500634 using LocalArgList = SmallVector<Argument *, 8>;
David Netoc6f3ab22018-04-06 18:02:31 -0400635 LocalArgList LocalArgs;
636 // Information about a pointer-to-local argument.
637 struct LocalArgInfo {
638 // The SPIR-V ID of the array variable.
SJW01901d92020-05-21 08:58:31 -0500639 SPIRVID variable_id;
David Netoc6f3ab22018-04-06 18:02:31 -0400640 // The element type of the
alan-bakerb6b09dc2018-11-08 16:59:28 -0500641 Type *elem_type;
David Netoc6f3ab22018-04-06 18:02:31 -0400642 // The ID of the array type.
SJW01901d92020-05-21 08:58:31 -0500643 SPIRVID array_size_id;
David Netoc6f3ab22018-04-06 18:02:31 -0400644 // The ID of the array type.
SJW01901d92020-05-21 08:58:31 -0500645 SPIRVID array_type_id;
David Netoc6f3ab22018-04-06 18:02:31 -0400646 // The ID of the pointer to the array type.
SJW01901d92020-05-21 08:58:31 -0500647 SPIRVID ptr_array_type_id;
David Netoc6f3ab22018-04-06 18:02:31 -0400648 // The specialization constant ID of the array size.
649 int spec_id;
650 };
Alan Baker202c8c72018-08-13 13:47:44 -0400651 // A mapping from Argument to its assigned SpecId.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500652 DenseMap<const Argument *, int> LocalArgSpecIds;
Alan Baker202c8c72018-08-13 13:47:44 -0400653 // A mapping from SpecId to its LocalArgInfo.
654 DenseMap<int, LocalArgInfo> LocalSpecIdInfoMap;
Alan Bakerfcda9482018-10-02 17:09:59 -0400655 // A mapping from a remapped type to its real offsets.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500656 DenseMap<Type *, std::vector<uint32_t>> RemappedUBOTypeOffsets;
Alan Bakerfcda9482018-10-02 17:09:59 -0400657 // A mapping from a remapped type to its real sizes.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500658 DenseMap<Type *, std::tuple<uint64_t, uint64_t, uint64_t>>
659 RemappedUBOTypeSizes;
alan-baker06cad652019-12-03 17:56:47 -0500660
661 // Maps basic block to its merge block.
662 DenseMap<BasicBlock *, BasicBlock *> MergeBlocks;
663 // Maps basic block to its continue block.
664 DenseMap<BasicBlock *, BasicBlock *> ContinueBlocks;
SJW01901d92020-05-21 08:58:31 -0500665
alan-baker86ce19c2020-08-05 13:09:19 -0400666 SPIRVID ReflectionID;
667 DenseMap<Function *, SPIRVID> KernelDeclarations;
668
SJW01901d92020-05-21 08:58:31 -0500669public:
670 static SPIRVProducerPass *Ptr;
David Neto22f144c2017-06-12 14:26:21 -0400671};
672
673char SPIRVProducerPass::ID;
SJW01901d92020-05-21 08:58:31 -0500674SPIRVProducerPass *SPIRVProducerPass::Ptr = nullptr;
David Netoc6f3ab22018-04-06 18:02:31 -0400675
alan-bakerb6b09dc2018-11-08 16:59:28 -0500676} // namespace
David Neto22f144c2017-06-12 14:26:21 -0400677
678namespace clspv {
alan-baker86ce19c2020-08-05 13:09:19 -0400679ModulePass *
680createSPIRVProducerPass(raw_pwrite_stream &out,
681 ArrayRef<std::pair<unsigned, std::string>> samplerMap,
682 bool outputCInitList) {
683 return new SPIRVProducerPass(out, samplerMap, outputCInitList);
David Neto22f144c2017-06-12 14:26:21 -0400684}
David Netoc2c368d2017-06-30 16:50:17 -0400685} // namespace clspv
David Neto22f144c2017-06-12 14:26:21 -0400686
SJW01901d92020-05-21 08:58:31 -0500687namespace {
688SPIRVOperandVec &operator<<(SPIRVOperandVec &list, uint32_t num) {
689 list.emplace_back(LITERAL_WORD, num);
690 return list;
691}
692
693SPIRVOperandVec &operator<<(SPIRVOperandVec &list, int32_t num) {
694 list.emplace_back(LITERAL_WORD, static_cast<uint32_t>(num));
695 return list;
696}
697
698SPIRVOperandVec &operator<<(SPIRVOperandVec &list, ArrayRef<uint32_t> num_vec) {
699 list.emplace_back(num_vec);
700 return list;
701}
702
703SPIRVOperandVec &operator<<(SPIRVOperandVec &list, StringRef str) {
704 list.emplace_back(LITERAL_STRING, str);
705 return list;
706}
707
708SPIRVOperandVec &operator<<(SPIRVOperandVec &list, Type *t) {
709 list.emplace_back(NUMBERID, SPIRVProducerPass::Ptr->getSPIRVType(t).get());
710 return list;
711}
712
713SPIRVOperandVec &operator<<(SPIRVOperandVec &list, Value *v) {
714 list.emplace_back(NUMBERID, SPIRVProducerPass::Ptr->getSPIRVValue(v).get());
715 return list;
716}
717
SJW806a5d82020-07-15 12:51:38 -0500718SPIRVOperandVec &operator<<(SPIRVOperandVec &list, const SPIRVID &v) {
SJW01901d92020-05-21 08:58:31 -0500719 list.emplace_back(NUMBERID, v.get());
720 return list;
721}
722} // namespace
723
SJW77b87ad2020-04-21 14:37:52 -0500724bool SPIRVProducerPass::runOnModule(Module &M) {
SJW01901d92020-05-21 08:58:31 -0500725 // TODO(sjw): Need to reset all data members for each Module, or better
726 // yet create a new SPIRVProducer for every module.. For now only
727 // allow 1 call.
728 assert(module == nullptr);
SJW77b87ad2020-04-21 14:37:52 -0500729 module = &M;
alan-baker5ed87542020-03-23 11:05:22 -0400730 if (ShowProducerIR) {
SJW77b87ad2020-04-21 14:37:52 -0500731 llvm::outs() << *module << "\n";
alan-baker5ed87542020-03-23 11:05:22 -0400732 }
David Neto0676e6f2017-07-11 18:47:44 -0400733 binaryOut = outputCInitList ? &binaryTempOut : &out;
734
SJW77b87ad2020-04-21 14:37:52 -0500735 PopulateUBOTypeMaps();
736 PopulateStructuredCFGMaps();
Alan Bakerfcda9482018-10-02 17:09:59 -0400737
David Neto22f144c2017-06-12 14:26:21 -0400738 // SPIR-V always begins with its header information
739 outputHeader();
740
741 // Gather information from the LLVM IR that we require.
SJW77b87ad2020-04-21 14:37:52 -0500742 GenerateLLVMIRInfo();
David Neto22f144c2017-06-12 14:26:21 -0400743
David Neto22f144c2017-06-12 14:26:21 -0400744 // Collect information on global variables too.
SJW77b87ad2020-04-21 14:37:52 -0500745 for (GlobalVariable &GV : module->globals()) {
David Neto22f144c2017-06-12 14:26:21 -0400746 // If the GV is one of our special __spirv_* variables, remove the
747 // initializer as it was only placed there to force LLVM to not throw the
748 // value away.
Kévin Petitbbbda972020-03-03 19:16:31 +0000749 if (GV.getName().startswith("__spirv_") ||
750 GV.getAddressSpace() == clspv::AddressSpace::PushConstant) {
David Neto22f144c2017-06-12 14:26:21 -0400751 GV.setInitializer(nullptr);
752 }
753
754 // Collect types' information from global variable.
755 FindTypePerGlobalVar(GV);
David Neto22f144c2017-06-12 14:26:21 -0400756 }
757
David Neto22f144c2017-06-12 14:26:21 -0400758 // Generate SPIRV instructions for types.
SJW77b87ad2020-04-21 14:37:52 -0500759 GenerateSPIRVTypes();
David Neto22f144c2017-06-12 14:26:21 -0400760
alan-baker09cb9802019-12-10 13:16:27 -0500761 // Generate literal samplers if necessary.
SJW77b87ad2020-04-21 14:37:52 -0500762 GenerateSamplers();
David Neto22f144c2017-06-12 14:26:21 -0400763
764 // Generate SPIRV variables.
SJW77b87ad2020-04-21 14:37:52 -0500765 for (GlobalVariable &GV : module->globals()) {
David Neto22f144c2017-06-12 14:26:21 -0400766 GenerateGlobalVar(GV);
767 }
SJW77b87ad2020-04-21 14:37:52 -0500768 GenerateResourceVars();
769 GenerateWorkgroupVars();
David Neto22f144c2017-06-12 14:26:21 -0400770
771 // Generate SPIRV instructions for each function.
SJW77b87ad2020-04-21 14:37:52 -0500772 for (Function &F : *module) {
David Neto22f144c2017-06-12 14:26:21 -0400773 if (F.isDeclaration()) {
774 continue;
775 }
776
777 // Generate Function Prologue.
778 GenerateFuncPrologue(F);
779
780 // Generate SPIRV instructions for function body.
781 GenerateFuncBody(F);
782
783 // Generate Function Epilogue.
784 GenerateFuncEpilogue();
785 }
786
787 HandleDeferredInstruction();
SJW77b87ad2020-04-21 14:37:52 -0500788 HandleDeferredDecorations();
alan-bakera1be3322020-04-20 12:48:18 -0400789
David Neto22f144c2017-06-12 14:26:21 -0400790 // Generate SPIRV module information.
SJW77b87ad2020-04-21 14:37:52 -0500791 GenerateModuleInfo();
David Neto22f144c2017-06-12 14:26:21 -0400792
alan-baker86ce19c2020-08-05 13:09:19 -0400793 // Generate embedded reflection information.
794 GenerateReflection();
795
alan-baker00e7a582019-06-07 12:54:21 -0400796 WriteSPIRVBinary();
David Neto22f144c2017-06-12 14:26:21 -0400797
798 // We need to patch the SPIR-V header to set bound correctly.
799 patchHeader();
David Neto0676e6f2017-07-11 18:47:44 -0400800
801 if (outputCInitList) {
802 bool first = true;
David Neto0676e6f2017-07-11 18:47:44 -0400803 std::ostringstream os;
804
David Neto57fb0b92017-08-04 15:35:09 -0400805 auto emit_word = [&os, &first](uint32_t word) {
David Neto0676e6f2017-07-11 18:47:44 -0400806 if (!first)
David Neto57fb0b92017-08-04 15:35:09 -0400807 os << ",\n";
808 os << word;
David Neto0676e6f2017-07-11 18:47:44 -0400809 first = false;
810 };
811
812 os << "{";
David Neto57fb0b92017-08-04 15:35:09 -0400813 const std::string str(binaryTempOut.str());
814 for (unsigned i = 0; i < str.size(); i += 4) {
815 const uint32_t a = static_cast<unsigned char>(str[i]);
816 const uint32_t b = static_cast<unsigned char>(str[i + 1]);
817 const uint32_t c = static_cast<unsigned char>(str[i + 2]);
818 const uint32_t d = static_cast<unsigned char>(str[i + 3]);
819 emit_word(a | (b << 8) | (c << 16) | (d << 24));
David Neto0676e6f2017-07-11 18:47:44 -0400820 }
821 os << "}\n";
822 out << os.str();
823 }
824
David Neto22f144c2017-06-12 14:26:21 -0400825 return false;
826}
827
828void SPIRVProducerPass::outputHeader() {
alan-baker00e7a582019-06-07 12:54:21 -0400829 binaryOut->write(reinterpret_cast<const char *>(&spv::MagicNumber),
830 sizeof(spv::MagicNumber));
SJW806a5d82020-07-15 12:51:38 -0500831 uint32_t minor = 0;
832 if (SpvVersion() == SPIRVVersion::SPIRV_1_3) {
833 minor = 3;
834 }
835 uint32_t version = (1 << 16) | (minor << 8);
836 binaryOut->write(reinterpret_cast<const char *>(&version), sizeof(version));
David Neto22f144c2017-06-12 14:26:21 -0400837
alan-baker0c18ab02019-06-12 10:23:21 -0400838 // use Google's vendor ID
839 const uint32_t vendor = 21 << 16;
alan-baker00e7a582019-06-07 12:54:21 -0400840 binaryOut->write(reinterpret_cast<const char *>(&vendor), sizeof(vendor));
David Neto22f144c2017-06-12 14:26:21 -0400841
alan-baker00e7a582019-06-07 12:54:21 -0400842 // we record where we need to come back to and patch in the bound value
843 patchBoundOffset = binaryOut->tell();
David Neto22f144c2017-06-12 14:26:21 -0400844
alan-baker00e7a582019-06-07 12:54:21 -0400845 // output a bad bound for now
846 binaryOut->write(reinterpret_cast<const char *>(&nextID), sizeof(nextID));
David Neto22f144c2017-06-12 14:26:21 -0400847
alan-baker00e7a582019-06-07 12:54:21 -0400848 // output the schema (reserved for use and must be 0)
849 const uint32_t schema = 0;
850 binaryOut->write(reinterpret_cast<const char *>(&schema), sizeof(schema));
David Neto22f144c2017-06-12 14:26:21 -0400851}
852
853void SPIRVProducerPass::patchHeader() {
alan-baker00e7a582019-06-07 12:54:21 -0400854 // for a binary we just write the value of nextID over bound
855 binaryOut->pwrite(reinterpret_cast<char *>(&nextID), sizeof(nextID),
856 patchBoundOffset);
David Neto22f144c2017-06-12 14:26:21 -0400857}
858
SJW77b87ad2020-04-21 14:37:52 -0500859void SPIRVProducerPass::GenerateLLVMIRInfo() {
David Neto22f144c2017-06-12 14:26:21 -0400860 // This function generates LLVM IR for function such as global variable for
861 // argument, constant and pointer type for argument access. These information
862 // is artificial one because we need Vulkan SPIR-V output. This function is
863 // executed ahead of FindType and FindConstant.
David Neto22f144c2017-06-12 14:26:21 -0400864
SJW77b87ad2020-04-21 14:37:52 -0500865 FindGlobalConstVars();
David Neto5c22a252018-03-15 16:07:41 -0400866
SJW77b87ad2020-04-21 14:37:52 -0500867 FindResourceVars();
David Neto22f144c2017-06-12 14:26:21 -0400868
869 bool HasWorkGroupBuiltin = false;
SJW77b87ad2020-04-21 14:37:52 -0500870 for (GlobalVariable &GV : module->globals()) {
David Neto22f144c2017-06-12 14:26:21 -0400871 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
872 if (spv::BuiltInWorkgroupSize == BuiltinType) {
873 HasWorkGroupBuiltin = true;
874 }
875 }
876
SJW77b87ad2020-04-21 14:37:52 -0500877 FindTypesForSamplerMap();
878 FindTypesForResourceVars();
David Neto22f144c2017-06-12 14:26:21 -0400879}
880
SJW77b87ad2020-04-21 14:37:52 -0500881void SPIRVProducerPass::FindGlobalConstVars() {
882 clspv::NormalizeGlobalVariables(*module);
883 const DataLayout &DL = module->getDataLayout();
alan-baker56f7aff2019-05-22 08:06:42 -0400884
David Neto862b7d82018-06-14 18:48:37 -0400885 SmallVector<GlobalVariable *, 8> GVList;
886 SmallVector<GlobalVariable *, 8> DeadGVList;
SJW77b87ad2020-04-21 14:37:52 -0500887 for (GlobalVariable &GV : module->globals()) {
David Neto862b7d82018-06-14 18:48:37 -0400888 if (GV.getType()->getAddressSpace() == AddressSpace::Constant) {
889 if (GV.use_empty()) {
890 DeadGVList.push_back(&GV);
891 } else {
892 GVList.push_back(&GV);
893 }
894 }
895 }
896
897 // Remove dead global __constant variables.
898 for (auto GV : DeadGVList) {
899 GV->eraseFromParent();
900 }
901 DeadGVList.clear();
902
903 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
904 // For now, we only support a single storage buffer.
alan-baker7506abb2020-09-10 15:02:55 -0400905 if (!GVList.empty()) {
David Neto862b7d82018-06-14 18:48:37 -0400906 assert(GVList.size() == 1);
907 const auto *GV = GVList[0];
908 const auto constants_byte_size =
Alan Bakerfcda9482018-10-02 17:09:59 -0400909 (GetTypeSizeInBits(GV->getInitializer()->getType(), DL)) / 8;
David Neto862b7d82018-06-14 18:48:37 -0400910 const size_t kConstantMaxSize = 65536;
911 if (constants_byte_size > kConstantMaxSize) {
912 outs() << "Max __constant capacity of " << kConstantMaxSize
913 << " bytes exceeded: " << constants_byte_size << " bytes used\n";
914 llvm_unreachable("Max __constant capacity exceeded");
915 }
916 }
917 } else {
918 // Change global constant variable's address space to ModuleScopePrivate.
919 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
920 for (auto GV : GVList) {
921 // Create new gv with ModuleScopePrivate address space.
922 Type *NewGVTy = GV->getType()->getPointerElementType();
923 GlobalVariable *NewGV = new GlobalVariable(
SJW77b87ad2020-04-21 14:37:52 -0500924 *module, NewGVTy, false, GV->getLinkage(), GV->getInitializer(), "",
David Neto862b7d82018-06-14 18:48:37 -0400925 nullptr, GV->getThreadLocalMode(), AddressSpace::ModuleScopePrivate);
926 NewGV->takeName(GV);
927
928 const SmallVector<User *, 8> GVUsers(GV->user_begin(), GV->user_end());
929 SmallVector<User *, 8> CandidateUsers;
930
931 auto record_called_function_type_as_user =
932 [&GlobalConstFuncTyMap](Value *gv, CallInst *call) {
933 // Find argument index.
934 unsigned index = 0;
935 for (unsigned i = 0; i < call->getNumArgOperands(); i++) {
936 if (gv == call->getOperand(i)) {
937 // TODO(dneto): Should we break here?
938 index = i;
939 }
940 }
941
942 // Record function type with global constant.
943 GlobalConstFuncTyMap[call->getFunctionType()] =
944 std::make_pair(call->getFunctionType(), index);
945 };
946
947 for (User *GVU : GVUsers) {
948 if (CallInst *Call = dyn_cast<CallInst>(GVU)) {
949 record_called_function_type_as_user(GV, Call);
950 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(GVU)) {
951 // Check GEP users.
952 for (User *GEPU : GEP->users()) {
953 if (CallInst *GEPCall = dyn_cast<CallInst>(GEPU)) {
954 record_called_function_type_as_user(GEP, GEPCall);
955 }
956 }
957 }
958
959 CandidateUsers.push_back(GVU);
960 }
961
962 for (User *U : CandidateUsers) {
963 // Update users of gv with new gv.
alan-bakered80f572019-02-11 17:28:26 -0500964 if (!isa<Constant>(U)) {
965 // #254: Can't change operands of a constant, but this shouldn't be
966 // something that sticks around in the module.
967 U->replaceUsesOfWith(GV, NewGV);
968 }
David Neto862b7d82018-06-14 18:48:37 -0400969 }
970
971 // Delete original gv.
972 GV->eraseFromParent();
973 }
974 }
975}
976
SJW77b87ad2020-04-21 14:37:52 -0500977void SPIRVProducerPass::FindResourceVars() {
David Neto862b7d82018-06-14 18:48:37 -0400978 ResourceVarInfoList.clear();
979 FunctionToResourceVarsMap.clear();
980 ModuleOrderedResourceVars.reset();
981 // Normally, there is one resource variable per clspv.resource.var.*
982 // function, since that is unique'd by arg type and index. By design,
983 // we can share these resource variables across kernels because all
984 // kernels use the same descriptor set.
985 //
986 // But if the user requested distinct descriptor sets per kernel, then
987 // the descriptor allocator has made different (set,binding) pairs for
988 // the same (type,arg_index) pair. Since we can decorate a resource
989 // variable with only exactly one DescriptorSet and Binding, we are
990 // forced in this case to make distinct resource variables whenever
Kévin Petitbbbda972020-03-03 19:16:31 +0000991 // the same clspv.resource.var.X function is seen with disintct
David Neto862b7d82018-06-14 18:48:37 -0400992 // (set,binding) values.
993 const bool always_distinct_sets =
994 clspv::Option::DistinctKernelDescriptorSets();
SJW77b87ad2020-04-21 14:37:52 -0500995 for (Function &F : *module) {
David Neto862b7d82018-06-14 18:48:37 -0400996 // Rely on the fact the resource var functions have a stable ordering
997 // in the module.
SJW61531372020-06-09 07:31:08 -0500998 if (Builtins::Lookup(&F) == Builtins::kClspvResource) {
David Neto862b7d82018-06-14 18:48:37 -0400999 // Find all calls to this function with distinct set and binding pairs.
1000 // Save them in ResourceVarInfoList.
1001
1002 // Determine uniqueness of the (set,binding) pairs only withing this
1003 // one resource-var builtin function.
1004 using SetAndBinding = std::pair<unsigned, unsigned>;
1005 // Maps set and binding to the resource var info.
1006 DenseMap<SetAndBinding, ResourceVarInfo *> set_and_binding_map;
1007 bool first_use = true;
1008 for (auto &U : F.uses()) {
1009 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
1010 const auto set = unsigned(
1011 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
1012 const auto binding = unsigned(
1013 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
1014 const auto arg_kind = clspv::ArgKind(
1015 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
1016 const auto arg_index = unsigned(
1017 dyn_cast<ConstantInt>(call->getArgOperand(3))->getZExtValue());
alan-bakere9308012019-03-15 10:25:13 -04001018 const auto coherent = unsigned(
1019 dyn_cast<ConstantInt>(call->getArgOperand(5))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04001020
1021 // Find or make the resource var info for this combination.
1022 ResourceVarInfo *rv = nullptr;
1023 if (always_distinct_sets) {
1024 // Make a new resource var any time we see a different
1025 // (set,binding) pair.
1026 SetAndBinding key{set, binding};
1027 auto where = set_and_binding_map.find(key);
1028 if (where == set_and_binding_map.end()) {
alan-baker7506abb2020-09-10 15:02:55 -04001029 rv = new ResourceVarInfo(
1030 static_cast<int>(ResourceVarInfoList.size()), set, binding,
1031 &F, arg_kind, coherent);
David Neto862b7d82018-06-14 18:48:37 -04001032 ResourceVarInfoList.emplace_back(rv);
1033 set_and_binding_map[key] = rv;
1034 } else {
1035 rv = where->second;
1036 }
1037 } else {
1038 // The default is to make exactly one resource for each
1039 // clspv.resource.var.* function.
1040 if (first_use) {
1041 first_use = false;
alan-baker7506abb2020-09-10 15:02:55 -04001042 rv = new ResourceVarInfo(
1043 static_cast<int>(ResourceVarInfoList.size()), set, binding,
1044 &F, arg_kind, coherent);
David Neto862b7d82018-06-14 18:48:37 -04001045 ResourceVarInfoList.emplace_back(rv);
1046 } else {
1047 rv = ResourceVarInfoList.back().get();
1048 }
1049 }
1050
1051 // Now populate FunctionToResourceVarsMap.
1052 auto &mapping =
1053 FunctionToResourceVarsMap[call->getParent()->getParent()];
1054 while (mapping.size() <= arg_index) {
1055 mapping.push_back(nullptr);
1056 }
1057 mapping[arg_index] = rv;
1058 }
1059 }
1060 }
1061 }
1062
1063 // Populate ModuleOrderedResourceVars.
SJW77b87ad2020-04-21 14:37:52 -05001064 for (Function &F : *module) {
David Neto862b7d82018-06-14 18:48:37 -04001065 auto where = FunctionToResourceVarsMap.find(&F);
1066 if (where != FunctionToResourceVarsMap.end()) {
1067 for (auto &rv : where->second) {
1068 if (rv != nullptr) {
1069 ModuleOrderedResourceVars.insert(rv);
1070 }
1071 }
1072 }
1073 }
1074 if (ShowResourceVars) {
1075 for (auto *info : ModuleOrderedResourceVars) {
1076 outs() << "MORV index " << info->index << " (" << info->descriptor_set
1077 << "," << info->binding << ") " << *(info->var_fn->getReturnType())
1078 << "\n";
1079 }
1080 }
1081}
1082
David Neto22f144c2017-06-12 14:26:21 -04001083void SPIRVProducerPass::FindTypePerGlobalVar(GlobalVariable &GV) {
1084 // Investigate global variable's type.
1085 FindType(GV.getType());
1086}
1087
1088void SPIRVProducerPass::FindTypePerFunc(Function &F) {
1089 // Investigate function's type.
1090 FunctionType *FTy = F.getFunctionType();
1091
1092 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
1093 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
David Neto9ed8e2f2018-03-24 06:47:24 -07001094 // Handle a regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04001095 if (GlobalConstFuncTyMap.count(FTy)) {
1096 uint32_t GVCstArgIdx = GlobalConstFuncTypeMap[FTy].second;
1097 SmallVector<Type *, 4> NewFuncParamTys;
1098 for (unsigned i = 0; i < FTy->getNumParams(); i++) {
1099 Type *ParamTy = FTy->getParamType(i);
1100 if (i == GVCstArgIdx) {
1101 Type *EleTy = ParamTy->getPointerElementType();
1102 ParamTy = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1103 }
1104
1105 NewFuncParamTys.push_back(ParamTy);
1106 }
1107
1108 FunctionType *NewFTy =
1109 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1110 GlobalConstFuncTyMap[FTy] = std::make_pair(NewFTy, GVCstArgIdx);
1111 FTy = NewFTy;
1112 }
1113
1114 FindType(FTy);
1115 } else {
1116 // As kernel functions do not have parameters, create new function type and
1117 // add it to type map.
1118 SmallVector<Type *, 4> NewFuncParamTys;
1119 FunctionType *NewFTy =
1120 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1121 FindType(NewFTy);
1122 }
1123
1124 // Investigate instructions' type in function body.
1125 for (BasicBlock &BB : F) {
1126 for (Instruction &I : BB) {
1127 if (isa<ShuffleVectorInst>(I)) {
1128 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1129 // Ignore type for mask of shuffle vector instruction.
1130 if (i == 2) {
1131 continue;
1132 }
1133
1134 Value *Op = I.getOperand(i);
1135 if (!isa<MetadataAsValue>(Op)) {
1136 FindType(Op->getType());
1137 }
1138 }
1139
1140 FindType(I.getType());
1141 continue;
1142 }
1143
David Neto862b7d82018-06-14 18:48:37 -04001144 CallInst *Call = dyn_cast<CallInst>(&I);
1145
SJW61531372020-06-09 07:31:08 -05001146 if (Call) {
1147 auto &func_info = Builtins::Lookup(Call->getCalledFunction());
1148 if (func_info.getType() == Builtins::kClspvResource ||
1149 func_info.getType() == Builtins::kClspvLocal) {
1150 // This is a fake call representing access to a resource/workgroup
1151 // variable. We handle that elsewhere.
1152 continue;
1153 }
Alan Baker202c8c72018-08-13 13:47:44 -04001154 }
1155
alan-bakerf083bed2020-01-29 08:15:42 -05001156 // #497: InsertValue and ExtractValue map to OpCompositeInsert and
1157 // OpCompositeExtract which takes literal values for indices. As a result
1158 // don't map the type of indices.
1159 if (I.getOpcode() == Instruction::ExtractValue) {
1160 FindType(I.getOperand(0)->getType());
1161 continue;
1162 }
1163 if (I.getOpcode() == Instruction::InsertValue) {
1164 FindType(I.getOperand(0)->getType());
1165 FindType(I.getOperand(1)->getType());
1166 continue;
1167 }
1168
1169 // #497: InsertElement and ExtractElement map to OpCompositeExtract if
1170 // the index is a constant. In such a case don't map the index type.
1171 if (I.getOpcode() == Instruction::ExtractElement) {
1172 FindType(I.getOperand(0)->getType());
1173 Value *op1 = I.getOperand(1);
1174 if (!isa<Constant>(op1) || isa<GlobalValue>(op1)) {
1175 FindType(op1->getType());
1176 }
1177 continue;
1178 }
1179 if (I.getOpcode() == Instruction::InsertElement) {
1180 FindType(I.getOperand(0)->getType());
1181 FindType(I.getOperand(1)->getType());
1182 Value *op2 = I.getOperand(2);
1183 if (!isa<Constant>(op2) || isa<GlobalValue>(op2)) {
1184 FindType(op2->getType());
1185 }
1186 continue;
1187 }
1188
David Neto22f144c2017-06-12 14:26:21 -04001189 // Work through the operands of the instruction.
1190 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1191 Value *const Op = I.getOperand(i);
1192 // If any of the operands is a constant, find the type!
1193 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1194 FindType(Op->getType());
1195 }
1196 }
1197
1198 for (Use &Op : I.operands()) {
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001199 if (isa<CallInst>(&I)) {
David Neto22f144c2017-06-12 14:26:21 -04001200 // Avoid to check call instruction's type.
1201 break;
1202 }
Alan Baker202c8c72018-08-13 13:47:44 -04001203 if (CallInst *OpCall = dyn_cast<CallInst>(Op)) {
SJW61531372020-06-09 07:31:08 -05001204 if (Builtins::Lookup(OpCall->getCalledFunction()) ==
1205 Builtins::kClspvLocal) {
Alan Baker202c8c72018-08-13 13:47:44 -04001206 // This is a fake call representing access to a workgroup variable.
1207 // We handle that elsewhere.
1208 continue;
1209 }
1210 }
David Neto22f144c2017-06-12 14:26:21 -04001211 if (!isa<MetadataAsValue>(&Op)) {
1212 FindType(Op->getType());
1213 continue;
1214 }
1215 }
1216
David Neto22f144c2017-06-12 14:26:21 -04001217 // We don't want to track the type of this call as we are going to replace
1218 // it.
SJW61531372020-06-09 07:31:08 -05001219 if (Call && Builtins::Lookup(Call->getCalledFunction()) ==
1220 Builtins::kClspvSamplerVarLiteral) {
David Neto22f144c2017-06-12 14:26:21 -04001221 continue;
1222 }
1223
1224 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
1225 // If gep's base operand has ModuleScopePrivate address space, make gep
1226 // return ModuleScopePrivate address space.
1227 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate) {
1228 // Add pointer type with private address space for global constant to
1229 // type list.
1230 Type *EleTy = I.getType()->getPointerElementType();
1231 Type *NewPTy =
1232 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1233
1234 FindType(NewPTy);
1235 continue;
1236 }
1237 }
1238
1239 FindType(I.getType());
1240 }
1241 }
1242}
1243
SJW77b87ad2020-04-21 14:37:52 -05001244void SPIRVProducerPass::FindTypesForSamplerMap() {
David Neto862b7d82018-06-14 18:48:37 -04001245 // If we are using a sampler map, find the type of the sampler.
SJW77b87ad2020-04-21 14:37:52 -05001246 if (module->getFunction(clspv::LiteralSamplerFunction()) ||
alan-baker7506abb2020-09-10 15:02:55 -04001247 !getSamplerMap().empty()) {
SJW77b87ad2020-04-21 14:37:52 -05001248 auto SamplerStructTy = module->getTypeByName("opencl.sampler_t");
David Neto862b7d82018-06-14 18:48:37 -04001249 if (!SamplerStructTy) {
SJW77b87ad2020-04-21 14:37:52 -05001250 SamplerStructTy =
1251 StructType::create(module->getContext(), "opencl.sampler_t");
David Neto862b7d82018-06-14 18:48:37 -04001252 }
1253
1254 SamplerTy = SamplerStructTy->getPointerTo(AddressSpace::UniformConstant);
1255
1256 FindType(SamplerTy);
1257 }
1258}
1259
SJW77b87ad2020-04-21 14:37:52 -05001260void SPIRVProducerPass::FindTypesForResourceVars() {
David Neto862b7d82018-06-14 18:48:37 -04001261 // Record types so they are generated.
1262 TypesNeedingLayout.reset();
1263 StructTypesNeedingBlock.reset();
1264
1265 // To match older clspv codegen, generate the float type first if required
1266 // for images.
1267 for (const auto *info : ModuleOrderedResourceVars) {
alan-bakerf6bc8252020-09-23 14:58:55 -04001268 if (info->arg_kind == clspv::ArgKind::SampledImage ||
1269 info->arg_kind == clspv::ArgKind::StorageImage) {
alan-bakerf67468c2019-11-25 15:51:49 -05001270 if (IsIntImageType(info->var_fn->getReturnType())) {
1271 // Nothing for now...
1272 } else if (IsUintImageType(info->var_fn->getReturnType())) {
SJW77b87ad2020-04-21 14:37:52 -05001273 FindType(Type::getInt32Ty(module->getContext()));
alan-bakerf67468c2019-11-25 15:51:49 -05001274 }
1275
1276 // We need "float" either for the sampled type or for the Lod operand.
SJW77b87ad2020-04-21 14:37:52 -05001277 FindType(Type::getFloatTy(module->getContext()));
David Neto862b7d82018-06-14 18:48:37 -04001278 }
1279 }
1280
1281 for (const auto *info : ModuleOrderedResourceVars) {
1282 Type *type = info->var_fn->getReturnType();
1283
1284 switch (info->arg_kind) {
1285 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04001286 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04001287 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1288 StructTypesNeedingBlock.insert(sty);
1289 } else {
1290 errs() << *type << "\n";
1291 llvm_unreachable("Buffer arguments must map to structures!");
1292 }
1293 break;
1294 case clspv::ArgKind::Pod:
alan-baker9b0ec3c2020-04-06 14:45:34 -04001295 case clspv::ArgKind::PodUBO:
1296 case clspv::ArgKind::PodPushConstant:
David Neto862b7d82018-06-14 18:48:37 -04001297 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1298 StructTypesNeedingBlock.insert(sty);
1299 } else {
1300 errs() << *type << "\n";
1301 llvm_unreachable("POD arguments must map to structures!");
1302 }
1303 break;
alan-bakerf6bc8252020-09-23 14:58:55 -04001304 case clspv::ArgKind::SampledImage:
1305 case clspv::ArgKind::StorageImage:
David Neto862b7d82018-06-14 18:48:37 -04001306 case clspv::ArgKind::Sampler:
1307 // Sampler and image types map to the pointee type but
1308 // in the uniform constant address space.
1309 type = PointerType::get(type->getPointerElementType(),
1310 clspv::AddressSpace::UniformConstant);
1311 break;
1312 default:
1313 break;
1314 }
1315
1316 // The converted type is the type of the OpVariable we will generate.
1317 // If the pointee type is an array of size zero, FindType will convert it
1318 // to a runtime array.
1319 FindType(type);
1320 }
1321
alan-bakerdcd97412019-09-16 15:32:30 -04001322 // If module constants are clustered in a storage buffer then that struct
1323 // needs layout decorations.
1324 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
SJW77b87ad2020-04-21 14:37:52 -05001325 for (GlobalVariable &GV : module->globals()) {
alan-bakerdcd97412019-09-16 15:32:30 -04001326 PointerType *PTy = cast<PointerType>(GV.getType());
1327 const auto AS = PTy->getAddressSpace();
1328 const bool module_scope_constant_external_init =
1329 (AS == AddressSpace::Constant) && GV.hasInitializer();
1330 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
1331 if (module_scope_constant_external_init &&
1332 spv::BuiltInMax == BuiltinType) {
1333 StructTypesNeedingBlock.insert(
1334 cast<StructType>(PTy->getPointerElementType()));
1335 }
1336 }
1337 }
1338
SJW77b87ad2020-04-21 14:37:52 -05001339 for (const GlobalVariable &GV : module->globals()) {
Kévin Petitbbbda972020-03-03 19:16:31 +00001340 if (GV.getAddressSpace() == clspv::AddressSpace::PushConstant) {
1341 auto Ty = cast<PointerType>(GV.getType())->getPointerElementType();
1342 assert(Ty->isStructTy() && "Push constants have to be structures.");
1343 auto STy = cast<StructType>(Ty);
1344 StructTypesNeedingBlock.insert(STy);
1345 }
1346 }
1347
David Neto862b7d82018-06-14 18:48:37 -04001348 // Traverse the arrays and structures underneath each Block, and
1349 // mark them as needing layout.
1350 std::vector<Type *> work_list(StructTypesNeedingBlock.begin(),
1351 StructTypesNeedingBlock.end());
1352 while (!work_list.empty()) {
1353 Type *type = work_list.back();
1354 work_list.pop_back();
1355 TypesNeedingLayout.insert(type);
1356 switch (type->getTypeID()) {
1357 case Type::ArrayTyID:
1358 work_list.push_back(type->getArrayElementType());
1359 if (!Hack_generate_runtime_array_stride_early) {
1360 // Remember this array type for deferred decoration.
1361 TypesNeedingArrayStride.insert(type);
1362 }
1363 break;
1364 case Type::StructTyID:
1365 for (auto *elem_ty : cast<StructType>(type)->elements()) {
1366 work_list.push_back(elem_ty);
1367 }
1368 default:
1369 // This type and its contained types don't get layout.
1370 break;
1371 }
1372 }
1373}
1374
SJWf93f5f32020-05-05 07:27:56 -05001375void SPIRVProducerPass::GenerateWorkgroupVars() {
Alan Baker202c8c72018-08-13 13:47:44 -04001376 // The SpecId assignment for pointer-to-local arguments is recorded in
1377 // module-level metadata. Translate that information into local argument
1378 // information.
SJWf93f5f32020-05-05 07:27:56 -05001379 LLVMContext &Context = module->getContext();
SJW77b87ad2020-04-21 14:37:52 -05001380 NamedMDNode *nmd = module->getNamedMetadata(clspv::LocalSpecIdMetadataName());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001381 if (!nmd)
1382 return;
Alan Baker202c8c72018-08-13 13:47:44 -04001383 for (auto operand : nmd->operands()) {
1384 MDTuple *tuple = cast<MDTuple>(operand);
1385 ValueAsMetadata *fn_md = cast<ValueAsMetadata>(tuple->getOperand(0));
1386 Function *func = cast<Function>(fn_md->getValue());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001387 ConstantAsMetadata *arg_index_md =
1388 cast<ConstantAsMetadata>(tuple->getOperand(1));
1389 int arg_index = static_cast<int>(
1390 cast<ConstantInt>(arg_index_md->getValue())->getSExtValue());
1391 Argument *arg = &*(func->arg_begin() + arg_index);
Alan Baker202c8c72018-08-13 13:47:44 -04001392
1393 ConstantAsMetadata *spec_id_md =
1394 cast<ConstantAsMetadata>(tuple->getOperand(2));
alan-bakerb6b09dc2018-11-08 16:59:28 -05001395 int spec_id = static_cast<int>(
1396 cast<ConstantInt>(spec_id_md->getValue())->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04001397
Alan Baker202c8c72018-08-13 13:47:44 -04001398 LocalArgSpecIds[arg] = spec_id;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001399 if (LocalSpecIdInfoMap.count(spec_id))
1400 continue;
Alan Baker202c8c72018-08-13 13:47:44 -04001401
SJWf93f5f32020-05-05 07:27:56 -05001402 // Generate the spec constant.
1403 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05001404 Ops << Type::getInt32Ty(Context) << 1;
SJWf93f5f32020-05-05 07:27:56 -05001405 SPIRVID ArraySizeID = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
Alan Baker202c8c72018-08-13 13:47:44 -04001406
SJWf93f5f32020-05-05 07:27:56 -05001407 // Generate the array type.
1408 Type *ElemTy = arg->getType()->getPointerElementType();
1409 Ops.clear();
1410 // The element type must have been created.
SJW01901d92020-05-21 08:58:31 -05001411 Ops << ElemTy << ArraySizeID;
SJWf93f5f32020-05-05 07:27:56 -05001412
1413 SPIRVID ArrayTypeID = addSPIRVInst<kTypes>(spv::OpTypeArray, Ops);
1414
1415 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05001416 Ops << spv::StorageClassWorkgroup << ArrayTypeID;
SJWf93f5f32020-05-05 07:27:56 -05001417 SPIRVID PtrArrayTypeID = addSPIRVInst<kTypes>(spv::OpTypePointer, Ops);
1418
1419 // Generate OpVariable.
1420 //
1421 // Ops[0] : Result Type ID
1422 // Ops[1] : Storage Class
SJW806a5d82020-07-15 12:51:38 -05001423 SPIRVID VariableID =
1424 addSPIRVGlobalVariable(PtrArrayTypeID, spv::StorageClassWorkgroup);
SJWf93f5f32020-05-05 07:27:56 -05001425
1426 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05001427 Ops << ArraySizeID << spv::DecorationSpecId << spec_id;
SJWf93f5f32020-05-05 07:27:56 -05001428 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
1429
1430 LocalArgInfo info{VariableID, ElemTy, ArraySizeID,
1431 ArrayTypeID, PtrArrayTypeID, spec_id};
1432 LocalSpecIdInfoMap[spec_id] = info;
Alan Baker202c8c72018-08-13 13:47:44 -04001433 }
1434}
1435
David Neto22f144c2017-06-12 14:26:21 -04001436void SPIRVProducerPass::FindType(Type *Ty) {
1437 TypeList &TyList = getTypeList();
1438
1439 if (0 != TyList.idFor(Ty)) {
1440 return;
1441 }
1442
1443 if (Ty->isPointerTy()) {
1444 auto AddrSpace = Ty->getPointerAddressSpace();
1445 if ((AddressSpace::Constant == AddrSpace) ||
1446 (AddressSpace::Global == AddrSpace)) {
1447 auto PointeeTy = Ty->getPointerElementType();
1448
1449 if (PointeeTy->isStructTy() &&
1450 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1451 FindType(PointeeTy);
1452 auto ActualPointerTy =
1453 PointeeTy->getPointerTo(AddressSpace::UniformConstant);
1454 FindType(ActualPointerTy);
1455 return;
1456 }
1457 }
1458 }
1459
David Neto862b7d82018-06-14 18:48:37 -04001460 // By convention, LLVM array type with 0 elements will map to
1461 // OpTypeRuntimeArray. Otherwise, it will map to OpTypeArray, which
1462 // has a constant number of elements. We need to support type of the
1463 // constant.
1464 if (auto *arrayTy = dyn_cast<ArrayType>(Ty)) {
1465 if (arrayTy->getNumElements() > 0) {
1466 LLVMContext &Context = Ty->getContext();
1467 FindType(Type::getInt32Ty(Context));
1468 }
David Neto22f144c2017-06-12 14:26:21 -04001469 }
1470
1471 for (Type *SubTy : Ty->subtypes()) {
1472 FindType(SubTy);
1473 }
1474
1475 TyList.insert(Ty);
1476}
1477
David Neto22f144c2017-06-12 14:26:21 -04001478spv::StorageClass SPIRVProducerPass::GetStorageClass(unsigned AddrSpace) const {
1479 switch (AddrSpace) {
1480 default:
1481 llvm_unreachable("Unsupported OpenCL address space");
1482 case AddressSpace::Private:
1483 return spv::StorageClassFunction;
1484 case AddressSpace::Global:
David Neto22f144c2017-06-12 14:26:21 -04001485 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001486 case AddressSpace::Constant:
1487 return clspv::Option::ConstantArgsInUniformBuffer()
1488 ? spv::StorageClassUniform
1489 : spv::StorageClassStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -04001490 case AddressSpace::Input:
1491 return spv::StorageClassInput;
1492 case AddressSpace::Local:
1493 return spv::StorageClassWorkgroup;
1494 case AddressSpace::UniformConstant:
1495 return spv::StorageClassUniformConstant;
David Neto9ed8e2f2018-03-24 06:47:24 -07001496 case AddressSpace::Uniform:
David Netoe439d702018-03-23 13:14:08 -07001497 return spv::StorageClassUniform;
David Neto22f144c2017-06-12 14:26:21 -04001498 case AddressSpace::ModuleScopePrivate:
1499 return spv::StorageClassPrivate;
Kévin Petitbbbda972020-03-03 19:16:31 +00001500 case AddressSpace::PushConstant:
1501 return spv::StorageClassPushConstant;
David Neto22f144c2017-06-12 14:26:21 -04001502 }
1503}
1504
David Neto862b7d82018-06-14 18:48:37 -04001505spv::StorageClass
1506SPIRVProducerPass::GetStorageClassForArgKind(clspv::ArgKind arg_kind) const {
1507 switch (arg_kind) {
1508 case clspv::ArgKind::Buffer:
1509 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001510 case clspv::ArgKind::BufferUBO:
1511 return spv::StorageClassUniform;
David Neto862b7d82018-06-14 18:48:37 -04001512 case clspv::ArgKind::Pod:
alan-baker9b0ec3c2020-04-06 14:45:34 -04001513 return spv::StorageClassStorageBuffer;
1514 case clspv::ArgKind::PodUBO:
1515 return spv::StorageClassUniform;
1516 case clspv::ArgKind::PodPushConstant:
1517 return spv::StorageClassPushConstant;
David Neto862b7d82018-06-14 18:48:37 -04001518 case clspv::ArgKind::Local:
1519 return spv::StorageClassWorkgroup;
alan-bakerf6bc8252020-09-23 14:58:55 -04001520 case clspv::ArgKind::SampledImage:
1521 case clspv::ArgKind::StorageImage:
David Neto862b7d82018-06-14 18:48:37 -04001522 case clspv::ArgKind::Sampler:
1523 return spv::StorageClassUniformConstant;
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001524 default:
1525 llvm_unreachable("Unsupported storage class for argument kind");
David Neto862b7d82018-06-14 18:48:37 -04001526 }
1527}
1528
David Neto22f144c2017-06-12 14:26:21 -04001529spv::BuiltIn SPIRVProducerPass::GetBuiltin(StringRef Name) const {
1530 return StringSwitch<spv::BuiltIn>(Name)
1531 .Case("__spirv_GlobalInvocationId", spv::BuiltInGlobalInvocationId)
1532 .Case("__spirv_LocalInvocationId", spv::BuiltInLocalInvocationId)
1533 .Case("__spirv_WorkgroupSize", spv::BuiltInWorkgroupSize)
1534 .Case("__spirv_NumWorkgroups", spv::BuiltInNumWorkgroups)
1535 .Case("__spirv_WorkgroupId", spv::BuiltInWorkgroupId)
alan-bakerbed3a882020-04-21 14:42:41 -04001536 .Case("__spirv_WorkDim", spv::BuiltInWorkDim)
alan-bakere1996972020-05-04 08:38:12 -04001537 .Case("__spirv_GlobalOffset", spv::BuiltInGlobalOffset)
David Neto22f144c2017-06-12 14:26:21 -04001538 .Default(spv::BuiltInMax);
1539}
1540
SJW01901d92020-05-21 08:58:31 -05001541SPIRVID SPIRVProducerPass::getOpExtInstImportID() {
1542 if (OpExtInstImportID == 0) {
1543 //
1544 // Generate OpExtInstImport.
1545 //
1546 // Ops[0] ... Ops[n] = Name (Literal String)
David Neto22f144c2017-06-12 14:26:21 -04001547
SJW01901d92020-05-21 08:58:31 -05001548 OpExtInstImportID =
1549 addSPIRVInst<kImports>(spv::OpExtInstImport, "GLSL.std.450");
1550 }
1551 return OpExtInstImportID;
SJWf93f5f32020-05-05 07:27:56 -05001552}
1553
SJW806a5d82020-07-15 12:51:38 -05001554SPIRVID SPIRVProducerPass::addSPIRVGlobalVariable(const SPIRVID &TypeID,
1555 spv::StorageClass SC,
1556 const SPIRVID &InitID) {
1557 // Generate OpVariable.
1558 //
1559 // Ops[0] : Result Type ID
1560 // Ops[1] : Storage Class
1561 // Ops[2] : Initialization Value ID (optional)
1562
1563 SPIRVOperandVec Ops;
1564 Ops << TypeID << SC;
1565 if (InitID.isValid()) {
1566 Ops << InitID;
1567 }
1568
1569 SPIRVID VID = addSPIRVInst<kGlobalVariables>(spv::OpVariable, Ops);
1570
1571 if (SC == spv::StorageClassInput) {
1572 getEntryPointInterfacesList().push_back(VID);
1573 }
1574
1575 return VID;
1576}
1577
alan-bakerc3fd07f2020-10-22 09:48:49 -04001578Type *SPIRVProducerPass::CanonicalType(Type *type) {
1579 if (type->getNumContainedTypes() != 0) {
1580 switch (type->getTypeID()) {
1581 case Type::PointerTyID: {
1582 // For the purposes of our Vulkan SPIR-V type system, constant and global
1583 // are conflated.
1584 auto *ptr_ty = cast<PointerType>(type);
1585 unsigned AddrSpace = ptr_ty->getAddressSpace();
1586 if (AddressSpace::Constant == AddrSpace) {
1587 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1588 AddrSpace = AddressSpace::Global;
1589 // The canonical type of __constant is __global unless constants are
1590 // passed in uniform buffers.
1591 auto *GlobalTy =
1592 ptr_ty->getPointerElementType()->getPointerTo(AddrSpace);
1593 return GlobalTy;
1594 }
1595 }
1596 break;
1597 }
1598 case Type::StructTyID: {
1599 SmallVector<Type *, 8> subtypes;
1600 bool changed = false;
1601 for (auto *subtype : type->subtypes()) {
1602 auto canonical = CanonicalType(subtype);
1603 subtypes.push_back(canonical);
1604 if (canonical != subtype) {
1605 changed = true;
1606 }
1607 }
1608 if (changed) {
1609 return StructType::get(type->getContext(), subtypes,
1610 cast<StructType>(type)->isPacked());
1611 }
1612 break;
1613 }
1614 case Type::ArrayTyID: {
1615 auto *elem_ty = type->getArrayElementType();
1616 auto *equiv_elem_ty = CanonicalType(elem_ty);
1617 if (equiv_elem_ty != elem_ty) {
1618 return ArrayType::get(equiv_elem_ty,
1619 cast<ArrayType>(type)->getNumElements());
1620 }
1621 break;
1622 }
1623 case Type::FunctionTyID: {
1624 auto *func_ty = cast<FunctionType>(type);
1625 auto *return_ty = CanonicalType(func_ty->getReturnType());
1626 SmallVector<Type *, 8> params;
1627 for (unsigned i = 0; i < func_ty->getNumParams(); ++i) {
1628 params.push_back(CanonicalType(func_ty->getParamType(i)));
1629 }
1630 return FunctionType::get(return_ty, params, func_ty->isVarArg());
1631 }
1632 default:
1633 break;
1634 }
1635 }
1636
1637 return type;
1638}
1639
SJW01901d92020-05-21 08:58:31 -05001640SPIRVID SPIRVProducerPass::getSPIRVType(Type *Ty) {
SJWf93f5f32020-05-05 07:27:56 -05001641 auto TI = TypeMap.find(Ty);
1642 if (TI != TypeMap.end()) {
SJW01901d92020-05-21 08:58:31 -05001643 assert(TI->second.isValid());
SJWf93f5f32020-05-05 07:27:56 -05001644 return TI->second;
1645 }
1646
alan-bakerc3fd07f2020-10-22 09:48:49 -04001647 auto Canonical = CanonicalType(Ty);
1648 if (Canonical != Ty) {
1649 auto CanonicalTI = TypeMap.find(Canonical);
1650 if (CanonicalTI != TypeMap.end()) {
1651 assert(CanonicalTI->second.isValid());
1652 return CanonicalTI->second;
1653 }
1654 }
1655
1656 // Perform the mapping with the canonical type.
1657
SJWf93f5f32020-05-05 07:27:56 -05001658 const auto &DL = module->getDataLayout();
1659
SJW01901d92020-05-21 08:58:31 -05001660 SPIRVID RID;
SJWf93f5f32020-05-05 07:27:56 -05001661
alan-bakerc3fd07f2020-10-22 09:48:49 -04001662 switch (Canonical->getTypeID()) {
SJWf93f5f32020-05-05 07:27:56 -05001663 default: {
alan-bakerc3fd07f2020-10-22 09:48:49 -04001664 Canonical->print(errs());
SJWf93f5f32020-05-05 07:27:56 -05001665 llvm_unreachable("Unsupported type???");
1666 break;
1667 }
1668 case Type::MetadataTyID:
1669 case Type::LabelTyID: {
1670 // Ignore these types.
1671 break;
1672 }
1673 case Type::PointerTyID: {
alan-bakerc3fd07f2020-10-22 09:48:49 -04001674 PointerType *PTy = cast<PointerType>(Canonical);
SJWf93f5f32020-05-05 07:27:56 -05001675 unsigned AddrSpace = PTy->getAddressSpace();
1676
1677 if (AddrSpace != AddressSpace::UniformConstant) {
1678 auto PointeeTy = PTy->getElementType();
1679 if (PointeeTy->isStructTy() &&
1680 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1681 // TODO(sjw): assert always an image?
1682 RID = getSPIRVType(PointeeTy);
1683 break;
1684 }
1685 }
1686
SJWf93f5f32020-05-05 07:27:56 -05001687 //
1688 // Generate OpTypePointer.
1689 //
1690
1691 // OpTypePointer
1692 // Ops[0] = Storage Class
1693 // Ops[1] = Element Type ID
1694 SPIRVOperandVec Ops;
1695
SJW01901d92020-05-21 08:58:31 -05001696 Ops << GetStorageClass(AddrSpace) << PTy->getElementType();
SJWf93f5f32020-05-05 07:27:56 -05001697
1698 RID = addSPIRVInst<kTypes>(spv::OpTypePointer, Ops);
1699 break;
1700 }
1701 case Type::StructTyID: {
alan-bakerc3fd07f2020-10-22 09:48:49 -04001702 StructType *STy = cast<StructType>(Canonical);
SJWf93f5f32020-05-05 07:27:56 -05001703
1704 // Handle sampler type.
1705 if (STy->isOpaque()) {
1706 if (STy->getName().equals("opencl.sampler_t")) {
1707 //
1708 // Generate OpTypeSampler
1709 //
1710 // Empty Ops.
1711
1712 RID = addSPIRVInst<kTypes>(spv::OpTypeSampler);
1713 break;
1714 } else if (STy->getName().startswith("opencl.image1d_ro_t") ||
alan-bakerf6bc8252020-09-23 14:58:55 -04001715 STy->getName().startswith("opencl.image1d_rw_t") ||
SJWf93f5f32020-05-05 07:27:56 -05001716 STy->getName().startswith("opencl.image1d_wo_t") ||
1717 STy->getName().startswith("opencl.image1d_array_ro_t") ||
alan-bakerf6bc8252020-09-23 14:58:55 -04001718 STy->getName().startswith("opencl.image1d_array_rw_t") ||
SJWf93f5f32020-05-05 07:27:56 -05001719 STy->getName().startswith("opencl.image1d_array_wo_t") ||
1720 STy->getName().startswith("opencl.image2d_ro_t") ||
alan-bakerf6bc8252020-09-23 14:58:55 -04001721 STy->getName().startswith("opencl.image2d_rw_t") ||
SJWf93f5f32020-05-05 07:27:56 -05001722 STy->getName().startswith("opencl.image2d_wo_t") ||
1723 STy->getName().startswith("opencl.image2d_array_ro_t") ||
alan-bakerf6bc8252020-09-23 14:58:55 -04001724 STy->getName().startswith("opencl.image2d_array_rw_t") ||
SJWf93f5f32020-05-05 07:27:56 -05001725 STy->getName().startswith("opencl.image2d_array_wo_t") ||
1726 STy->getName().startswith("opencl.image3d_ro_t") ||
alan-bakerf6bc8252020-09-23 14:58:55 -04001727 STy->getName().startswith("opencl.image3d_rw_t") ||
SJWf93f5f32020-05-05 07:27:56 -05001728 STy->getName().startswith("opencl.image3d_wo_t")) {
SJW01901d92020-05-21 08:58:31 -05001729 if (STy->getName().startswith("opencl.image1d_")) {
1730 if (STy->getName().contains(".sampled"))
1731 addCapability(spv::CapabilitySampled1D);
1732 else
1733 addCapability(spv::CapabilityImage1D);
1734 }
1735
SJWf93f5f32020-05-05 07:27:56 -05001736 //
1737 // Generate OpTypeImage
1738 //
1739 // Ops[0] = Sampled Type ID
1740 // Ops[1] = Dim ID
1741 // Ops[2] = Depth (Literal Number)
1742 // Ops[3] = Arrayed (Literal Number)
1743 // Ops[4] = MS (Literal Number)
1744 // Ops[5] = Sampled (Literal Number)
1745 // Ops[6] = Image Format ID
1746 //
1747 SPIRVOperandVec Ops;
1748
SJW01901d92020-05-21 08:58:31 -05001749 SPIRVID SampledTyID;
SJWf93f5f32020-05-05 07:27:56 -05001750 if (STy->getName().contains(".float")) {
alan-bakerc3fd07f2020-10-22 09:48:49 -04001751 SampledTyID = getSPIRVType(Type::getFloatTy(Canonical->getContext()));
SJWf93f5f32020-05-05 07:27:56 -05001752 } else if (STy->getName().contains(".uint")) {
alan-bakerc3fd07f2020-10-22 09:48:49 -04001753 SampledTyID = getSPIRVType(Type::getInt32Ty(Canonical->getContext()));
SJWf93f5f32020-05-05 07:27:56 -05001754 } else if (STy->getName().contains(".int")) {
1755 // Generate a signed 32-bit integer if necessary.
1756 if (int32ID == 0) {
1757 SPIRVOperandVec intOps;
SJW01901d92020-05-21 08:58:31 -05001758 intOps << 32 << 1;
SJWf93f5f32020-05-05 07:27:56 -05001759 int32ID = addSPIRVInst<kTypes>(spv::OpTypeInt, intOps);
1760 }
1761 SampledTyID = int32ID;
1762
1763 // Generate a vec4 of the signed int if necessary.
1764 if (v4int32ID == 0) {
1765 SPIRVOperandVec vecOps;
SJW01901d92020-05-21 08:58:31 -05001766 vecOps << int32ID << 4;
SJWf93f5f32020-05-05 07:27:56 -05001767 v4int32ID = addSPIRVInst<kTypes>(spv::OpTypeVector, vecOps);
1768 }
1769 } else {
1770 // This was likely an UndefValue.
alan-bakerc3fd07f2020-10-22 09:48:49 -04001771 SampledTyID = getSPIRVType(Type::getFloatTy(Canonical->getContext()));
SJWf93f5f32020-05-05 07:27:56 -05001772 }
SJW01901d92020-05-21 08:58:31 -05001773 Ops << SampledTyID;
SJWf93f5f32020-05-05 07:27:56 -05001774
1775 spv::Dim DimID = spv::Dim2D;
1776 if (STy->getName().startswith("opencl.image1d_ro_t") ||
alan-bakerf6bc8252020-09-23 14:58:55 -04001777 STy->getName().startswith("opencl.image1d_rw_t") ||
SJWf93f5f32020-05-05 07:27:56 -05001778 STy->getName().startswith("opencl.image1d_wo_t") ||
1779 STy->getName().startswith("opencl.image1d_array_ro_t") ||
alan-bakerf6bc8252020-09-23 14:58:55 -04001780 STy->getName().startswith("opencl.image1d_array_rw_t") ||
SJWf93f5f32020-05-05 07:27:56 -05001781 STy->getName().startswith("opencl.image1d_array_wo_t")) {
1782 DimID = spv::Dim1D;
1783 } else if (STy->getName().startswith("opencl.image3d_ro_t") ||
alan-bakerf6bc8252020-09-23 14:58:55 -04001784 STy->getName().startswith("opencl.image3d_rw_t") ||
SJWf93f5f32020-05-05 07:27:56 -05001785 STy->getName().startswith("opencl.image3d_wo_t")) {
1786 DimID = spv::Dim3D;
1787 }
SJW01901d92020-05-21 08:58:31 -05001788 Ops << DimID;
SJWf93f5f32020-05-05 07:27:56 -05001789
1790 // TODO: Set up Depth.
SJW01901d92020-05-21 08:58:31 -05001791 Ops << 0;
SJWf93f5f32020-05-05 07:27:56 -05001792
1793 uint32_t arrayed = STy->getName().contains("_array_") ? 1 : 0;
SJW01901d92020-05-21 08:58:31 -05001794 Ops << arrayed;
SJWf93f5f32020-05-05 07:27:56 -05001795
1796 // TODO: Set up MS.
SJW01901d92020-05-21 08:58:31 -05001797 Ops << 0;
SJWf93f5f32020-05-05 07:27:56 -05001798
1799 // Set up Sampled.
1800 //
1801 // From Spec
1802 //
1803 // 0 indicates this is only known at run time, not at compile time
1804 // 1 indicates will be used with sampler
1805 // 2 indicates will be used without a sampler (a storage image)
1806 uint32_t Sampled = 1;
1807 if (!STy->getName().contains(".sampled")) {
1808 Sampled = 2;
1809 }
SJW01901d92020-05-21 08:58:31 -05001810 Ops << Sampled;
SJWf93f5f32020-05-05 07:27:56 -05001811
1812 // TODO: Set up Image Format.
SJW01901d92020-05-21 08:58:31 -05001813 Ops << spv::ImageFormatUnknown;
SJWf93f5f32020-05-05 07:27:56 -05001814 RID = addSPIRVInst<kTypes>(spv::OpTypeImage, Ops);
1815
alan-bakerf6bc8252020-09-23 14:58:55 -04001816 // Only need a sampled version of the type if it is used with a sampler.
1817 if (Sampled == 1) {
1818 Ops.clear();
1819 Ops << RID;
alan-bakerc3fd07f2020-10-22 09:48:49 -04001820 getImageTypeMap()[Canonical] =
alan-bakerf6bc8252020-09-23 14:58:55 -04001821 addSPIRVInst<kTypes>(spv::OpTypeSampledImage, Ops);
1822 }
SJWf93f5f32020-05-05 07:27:56 -05001823 break;
1824 }
1825 }
1826
1827 //
1828 // Generate OpTypeStruct
1829 //
1830 // Ops[0] ... Ops[n] = Member IDs
1831 SPIRVOperandVec Ops;
1832
1833 for (auto *EleTy : STy->elements()) {
SJW01901d92020-05-21 08:58:31 -05001834 Ops << EleTy;
SJWf93f5f32020-05-05 07:27:56 -05001835 }
1836
1837 RID = addSPIRVInst<kTypes>(spv::OpTypeStruct, Ops);
1838
alan-bakerc3fd07f2020-10-22 09:48:49 -04001839 // Generate OpMemberDecorate unless we are generating it for the canonical
1840 // type.
1841 StructType *canonical = cast<StructType>(CanonicalType(STy));
1842 if (TypesNeedingLayout.idFor(STy) &&
1843 (canonical == STy || !TypesNeedingLayout.idFor(canonical))) {
SJWf93f5f32020-05-05 07:27:56 -05001844 for (unsigned MemberIdx = 0; MemberIdx < STy->getNumElements();
1845 MemberIdx++) {
1846 // Ops[0] = Structure Type ID
1847 // Ops[1] = Member Index(Literal Number)
1848 // Ops[2] = Decoration (Offset)
1849 // Ops[3] = Byte Offset (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05001850 const auto ByteOffset =
1851 GetExplicitLayoutStructMemberOffset(STy, MemberIdx, DL);
1852
SJW01901d92020-05-21 08:58:31 -05001853 Ops.clear();
1854 Ops << RID << MemberIdx << spv::DecorationOffset << ByteOffset;
SJWf93f5f32020-05-05 07:27:56 -05001855
1856 addSPIRVInst<kAnnotations>(spv::OpMemberDecorate, Ops);
1857 }
1858 }
1859
alan-bakerc3fd07f2020-10-22 09:48:49 -04001860 // Generate OpDecorate unless we are generating it for the canonical type.
1861 if (StructTypesNeedingBlock.idFor(STy) &&
1862 (canonical == STy || !StructTypesNeedingBlock.idFor(canonical))) {
SJWf93f5f32020-05-05 07:27:56 -05001863 Ops.clear();
1864 // Use Block decorations with StorageBuffer storage class.
SJW01901d92020-05-21 08:58:31 -05001865 Ops << RID << spv::DecorationBlock;
SJWf93f5f32020-05-05 07:27:56 -05001866
1867 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
1868 }
1869 break;
1870 }
1871 case Type::IntegerTyID: {
alan-bakerc3fd07f2020-10-22 09:48:49 -04001872 uint32_t bit_width =
1873 static_cast<uint32_t>(Canonical->getPrimitiveSizeInBits());
SJWf93f5f32020-05-05 07:27:56 -05001874
alan-bakere2a62752020-07-09 22:53:23 -04001875 if (clspv::Option::Int8Support() && bit_width == 8) {
SJW01901d92020-05-21 08:58:31 -05001876 addCapability(spv::CapabilityInt8);
alan-bakere2a62752020-07-09 22:53:23 -04001877 } else if (bit_width == 16) {
SJW01901d92020-05-21 08:58:31 -05001878 addCapability(spv::CapabilityInt16);
alan-bakere2a62752020-07-09 22:53:23 -04001879 } else if (bit_width == 64) {
SJW01901d92020-05-21 08:58:31 -05001880 addCapability(spv::CapabilityInt64);
1881 }
1882
alan-bakere2a62752020-07-09 22:53:23 -04001883 if (bit_width == 1) {
SJWf93f5f32020-05-05 07:27:56 -05001884 RID = addSPIRVInst<kTypes>(spv::OpTypeBool);
1885 } else {
alan-bakere2a62752020-07-09 22:53:23 -04001886 if (!clspv::Option::Int8Support() && bit_width == 8) {
SJWf93f5f32020-05-05 07:27:56 -05001887 // i8 is added to TypeMap as i32.
alan-bakerc3fd07f2020-10-22 09:48:49 -04001888 RID = getSPIRVType(Type::getIntNTy(Canonical->getContext(), 32));
SJWf93f5f32020-05-05 07:27:56 -05001889 } else {
1890 SPIRVOperandVec Ops;
alan-bakere2a62752020-07-09 22:53:23 -04001891 Ops << bit_width << 0 /* not signed */;
SJWf93f5f32020-05-05 07:27:56 -05001892 RID = addSPIRVInst<kTypes>(spv::OpTypeInt, Ops);
1893 }
1894 }
1895 break;
1896 }
1897 case Type::HalfTyID:
1898 case Type::FloatTyID:
1899 case Type::DoubleTyID: {
alan-bakerc3fd07f2020-10-22 09:48:49 -04001900 uint32_t bit_width =
1901 static_cast<uint32_t>(Canonical->getPrimitiveSizeInBits());
alan-bakere2a62752020-07-09 22:53:23 -04001902 if (bit_width == 16) {
SJW01901d92020-05-21 08:58:31 -05001903 addCapability(spv::CapabilityFloat16);
alan-bakere2a62752020-07-09 22:53:23 -04001904 } else if (bit_width == 64) {
SJW01901d92020-05-21 08:58:31 -05001905 addCapability(spv::CapabilityFloat64);
1906 }
1907
SJWf93f5f32020-05-05 07:27:56 -05001908 SPIRVOperandVec Ops;
alan-bakere2a62752020-07-09 22:53:23 -04001909 Ops << bit_width;
SJWf93f5f32020-05-05 07:27:56 -05001910
1911 RID = addSPIRVInst<kTypes>(spv::OpTypeFloat, Ops);
1912 break;
1913 }
1914 case Type::ArrayTyID: {
alan-bakerc3fd07f2020-10-22 09:48:49 -04001915 ArrayType *ArrTy = cast<ArrayType>(Canonical);
SJWf93f5f32020-05-05 07:27:56 -05001916 const uint64_t Length = ArrTy->getArrayNumElements();
1917 if (Length == 0) {
1918 // By convention, map it to a RuntimeArray.
1919
1920 Type *EleTy = ArrTy->getArrayElementType();
1921
1922 //
1923 // Generate OpTypeRuntimeArray.
1924 //
1925 // OpTypeRuntimeArray
1926 // Ops[0] = Element Type ID
1927 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05001928 Ops << EleTy;
SJWf93f5f32020-05-05 07:27:56 -05001929
1930 RID = addSPIRVInst<kTypes>(spv::OpTypeRuntimeArray, Ops);
1931
1932 if (Hack_generate_runtime_array_stride_early) {
1933 // Generate OpDecorate.
1934
1935 // Ops[0] = Target ID
1936 // Ops[1] = Decoration (ArrayStride)
1937 // Ops[2] = Stride Number(Literal Number)
1938 Ops.clear();
1939
SJW01901d92020-05-21 08:58:31 -05001940 Ops << RID << spv::DecorationArrayStride
1941 << static_cast<uint32_t>(GetTypeAllocSize(EleTy, DL));
SJWf93f5f32020-05-05 07:27:56 -05001942
1943 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
1944 }
1945
1946 } else {
1947
1948 //
1949 // Generate OpConstant and OpTypeArray.
1950 //
1951
1952 //
1953 // Generate OpConstant for array length.
1954 //
1955 // Add constant for length to constant list.
1956 Constant *CstLength =
1957 ConstantInt::get(Type::getInt32Ty(module->getContext()), Length);
SJWf93f5f32020-05-05 07:27:56 -05001958
1959 // Remember to generate ArrayStride later
alan-bakerc3fd07f2020-10-22 09:48:49 -04001960 getTypesNeedingArrayStride().insert(Canonical);
SJWf93f5f32020-05-05 07:27:56 -05001961
1962 //
1963 // Generate OpTypeArray.
1964 //
1965 // Ops[0] = Element Type ID
1966 // Ops[1] = Array Length Constant ID
1967 SPIRVOperandVec Ops;
1968
SJW01901d92020-05-21 08:58:31 -05001969 Ops << ArrTy->getElementType() << CstLength;
SJWf93f5f32020-05-05 07:27:56 -05001970
1971 RID = addSPIRVInst<kTypes>(spv::OpTypeArray, Ops);
1972 }
1973 break;
1974 }
1975 case Type::FixedVectorTyID: {
alan-bakerc3fd07f2020-10-22 09:48:49 -04001976 auto VecTy = cast<VectorType>(Canonical);
SJWf93f5f32020-05-05 07:27:56 -05001977 // <4 x i8> is changed to i32 if i8 is not generally supported.
1978 if (!clspv::Option::Int8Support() &&
1979 VecTy->getElementType() == Type::getInt8Ty(module->getContext())) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001980 if (VecTy->getElementCount().getKnownMinValue() == 4) {
SJWf93f5f32020-05-05 07:27:56 -05001981 RID = getSPIRVType(VecTy->getElementType());
1982 break;
1983 } else {
alan-bakerc3fd07f2020-10-22 09:48:49 -04001984 Canonical->print(errs());
SJWf93f5f32020-05-05 07:27:56 -05001985 llvm_unreachable("Support above i8 vector type");
1986 }
1987 }
1988
1989 // Ops[0] = Component Type ID
1990 // Ops[1] = Component Count (Literal Number)
1991 SPIRVOperandVec Ops;
alan-baker5a8c3be2020-09-09 13:44:26 -04001992 Ops << VecTy->getElementType()
1993 << VecTy->getElementCount().getKnownMinValue();
SJWf93f5f32020-05-05 07:27:56 -05001994
1995 RID = addSPIRVInst<kTypes>(spv::OpTypeVector, Ops);
1996 break;
1997 }
1998 case Type::VoidTyID: {
1999 RID = addSPIRVInst<kTypes>(spv::OpTypeVoid);
2000 break;
2001 }
2002 case Type::FunctionTyID: {
2003 // Generate SPIRV instruction for function type.
alan-bakerc3fd07f2020-10-22 09:48:49 -04002004 FunctionType *FTy = cast<FunctionType>(Canonical);
SJWf93f5f32020-05-05 07:27:56 -05002005
2006 // Ops[0] = Return Type ID
2007 // Ops[1] ... Ops[n] = Parameter Type IDs
2008 SPIRVOperandVec Ops;
2009
2010 // Find SPIRV instruction for return type
SJW01901d92020-05-21 08:58:31 -05002011 Ops << FTy->getReturnType();
SJWf93f5f32020-05-05 07:27:56 -05002012
2013 // Find SPIRV instructions for parameter types
2014 for (unsigned k = 0; k < FTy->getNumParams(); k++) {
2015 // Find SPIRV instruction for parameter type.
2016 auto ParamTy = FTy->getParamType(k);
2017 if (ParamTy->isPointerTy()) {
2018 auto PointeeTy = ParamTy->getPointerElementType();
2019 if (PointeeTy->isStructTy() &&
2020 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
2021 ParamTy = PointeeTy;
2022 }
2023 }
2024
SJW01901d92020-05-21 08:58:31 -05002025 Ops << ParamTy;
SJWf93f5f32020-05-05 07:27:56 -05002026 }
2027
2028 RID = addSPIRVInst<kTypes>(spv::OpTypeFunction, Ops);
2029 break;
2030 }
2031 }
2032
SJW01901d92020-05-21 08:58:31 -05002033 if (RID.isValid()) {
alan-bakerc3fd07f2020-10-22 09:48:49 -04002034 TypeMap[Canonical] = RID;
2035 if (Ty != Canonical) {
2036 // Speed up future lookups of this type by also caching the non-canonical
2037 // type.
2038 TypeMap[Ty] = RID;
2039 }
SJWf93f5f32020-05-05 07:27:56 -05002040 }
2041 return RID;
David Neto22f144c2017-06-12 14:26:21 -04002042}
2043
SJW77b87ad2020-04-21 14:37:52 -05002044void SPIRVProducerPass::GenerateSPIRVTypes() {
David Neto22f144c2017-06-12 14:26:21 -04002045 for (Type *Ty : getTypeList()) {
SJWf93f5f32020-05-05 07:27:56 -05002046 getSPIRVType(Ty);
David Netoc6f3ab22018-04-06 18:02:31 -04002047 }
David Neto22f144c2017-06-12 14:26:21 -04002048}
2049
SJW806a5d82020-07-15 12:51:38 -05002050SPIRVID SPIRVProducerPass::getSPIRVInt32Constant(uint32_t CstVal) {
2051 Type *i32 = Type::getInt32Ty(module->getContext());
2052 Constant *Cst = ConstantInt::get(i32, CstVal);
2053 return getSPIRVValue(Cst);
2054}
2055
SJWf93f5f32020-05-05 07:27:56 -05002056SPIRVID SPIRVProducerPass::getSPIRVConstant(Constant *Cst) {
David Neto22f144c2017-06-12 14:26:21 -04002057 ValueMapType &VMap = getValueMap();
David Neto482550a2018-03-24 05:21:07 -07002058 const bool hack_undef = clspv::Option::HackUndef();
David Neto22f144c2017-06-12 14:26:21 -04002059
SJW01901d92020-05-21 08:58:31 -05002060 SPIRVID RID;
David Neto22f144c2017-06-12 14:26:21 -04002061
SJWf93f5f32020-05-05 07:27:56 -05002062 //
2063 // Generate OpConstant.
2064 //
2065 // Ops[0] = Result Type ID
2066 // Ops[1] .. Ops[n] = Values LiteralNumber
2067 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04002068
SJW01901d92020-05-21 08:58:31 -05002069 Ops << Cst->getType();
David Neto22f144c2017-06-12 14:26:21 -04002070
SJWf93f5f32020-05-05 07:27:56 -05002071 std::vector<uint32_t> LiteralNum;
2072 spv::Op Opcode = spv::OpNop;
David Neto22f144c2017-06-12 14:26:21 -04002073
SJWf93f5f32020-05-05 07:27:56 -05002074 if (isa<UndefValue>(Cst)) {
David Neto22f144c2017-06-12 14:26:21 -04002075 // Ops[0] = Result Type ID
SJWf93f5f32020-05-05 07:27:56 -05002076 Opcode = spv::OpUndef;
2077 if (hack_undef && IsTypeNullable(Cst->getType())) {
2078 Opcode = spv::OpConstantNull;
2079 }
2080 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(Cst)) {
alan-bakere2a62752020-07-09 22:53:23 -04002081 unsigned bit_width = CI->getBitWidth();
2082 if (bit_width == 1) {
SJWf93f5f32020-05-05 07:27:56 -05002083 // If the bitwidth of constant is 1, generate OpConstantTrue or
2084 // OpConstantFalse.
2085 if (CI->getZExtValue()) {
2086 // Ops[0] = Result Type ID
2087 Opcode = spv::OpConstantTrue;
David Neto22f144c2017-06-12 14:26:21 -04002088 } else {
SJWf93f5f32020-05-05 07:27:56 -05002089 // Ops[0] = Result Type ID
2090 Opcode = spv::OpConstantFalse;
David Neto22f144c2017-06-12 14:26:21 -04002091 }
SJWf93f5f32020-05-05 07:27:56 -05002092 } else {
2093 auto V = CI->getZExtValue();
2094 LiteralNum.push_back(V & 0xFFFFFFFF);
2095
alan-bakere2a62752020-07-09 22:53:23 -04002096 if (bit_width > 32) {
SJWf93f5f32020-05-05 07:27:56 -05002097 LiteralNum.push_back(V >> 32);
David Neto22f144c2017-06-12 14:26:21 -04002098 }
2099
2100 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002101
SJW01901d92020-05-21 08:58:31 -05002102 Ops << LiteralNum;
SJWf93f5f32020-05-05 07:27:56 -05002103 }
2104 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Cst)) {
2105 uint64_t FPVal = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
2106 Type *CFPTy = CFP->getType();
2107 if (CFPTy->isFloatTy()) {
2108 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
2109 } else if (CFPTy->isDoubleTy()) {
2110 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
2111 LiteralNum.push_back(FPVal >> 32);
2112 } else if (CFPTy->isHalfTy()) {
2113 LiteralNum.push_back(FPVal & 0xFFFF);
2114 } else {
2115 CFPTy->print(errs());
2116 llvm_unreachable("Implement this ConstantFP Type");
2117 }
David Neto22f144c2017-06-12 14:26:21 -04002118
SJWf93f5f32020-05-05 07:27:56 -05002119 Opcode = spv::OpConstant;
David Neto49351ac2017-08-26 17:32:20 -04002120
SJW01901d92020-05-21 08:58:31 -05002121 Ops << LiteralNum;
SJWf93f5f32020-05-05 07:27:56 -05002122 } else if (isa<ConstantDataSequential>(Cst) &&
2123 cast<ConstantDataSequential>(Cst)->isString()) {
2124 Cst->print(errs());
2125 llvm_unreachable("Implement this Constant");
David Neto49351ac2017-08-26 17:32:20 -04002126
SJWf93f5f32020-05-05 07:27:56 -05002127 } else if (const ConstantDataSequential *CDS =
2128 dyn_cast<ConstantDataSequential>(Cst)) {
2129 // Let's convert <4 x i8> constant to int constant specially.
2130 // This case occurs when all the values are specified as constant
2131 // ints.
2132 Type *CstTy = Cst->getType();
2133 if (is4xi8vec(CstTy)) {
SJWf93f5f32020-05-05 07:27:56 -05002134 //
2135 // Generate OpConstant with OpTypeInt 32 0.
2136 //
2137 uint32_t IntValue = 0;
2138 for (unsigned k = 0; k < 4; k++) {
2139 const uint64_t Val = CDS->getElementAsInteger(k);
2140 IntValue = (IntValue << 8) | (Val & 0xffu);
David Neto49351ac2017-08-26 17:32:20 -04002141 }
2142
SJW806a5d82020-07-15 12:51:38 -05002143 RID = getSPIRVInt32Constant(IntValue);
SJWf93f5f32020-05-05 07:27:56 -05002144 } else {
2145
David Neto49351ac2017-08-26 17:32:20 -04002146 // A normal constant-data-sequential case.
David Neto22f144c2017-06-12 14:26:21 -04002147 for (unsigned k = 0; k < CDS->getNumElements(); k++) {
SJW01901d92020-05-21 08:58:31 -05002148 Ops << CDS->getElementAsConstant(k);
David Neto22f144c2017-06-12 14:26:21 -04002149 }
2150
2151 Opcode = spv::OpConstantComposite;
SJWf93f5f32020-05-05 07:27:56 -05002152 }
2153 } else if (const ConstantAggregate *CA = dyn_cast<ConstantAggregate>(Cst)) {
2154 // Let's convert <4 x i8> constant to int constant specially.
2155 // This case occurs when at least one of the values is an undef.
2156 Type *CstTy = Cst->getType();
2157 if (is4xi8vec(CstTy)) {
SJWf93f5f32020-05-05 07:27:56 -05002158 //
2159 // Generate OpConstant with OpTypeInt 32 0.
2160 //
2161 uint32_t IntValue = 0;
2162 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end();
2163 I != E; ++I) {
2164 uint64_t Val = 0;
2165 const Value *CV = *I;
2166 if (auto *CI2 = dyn_cast<ConstantInt>(CV)) {
2167 Val = CI2->getZExtValue();
David Neto22f144c2017-06-12 14:26:21 -04002168 }
SJWf93f5f32020-05-05 07:27:56 -05002169 IntValue = (IntValue << 8) | (Val & 0xffu);
David Neto22f144c2017-06-12 14:26:21 -04002170 }
2171
SJW806a5d82020-07-15 12:51:38 -05002172 RID = getSPIRVInt32Constant(IntValue);
SJWf93f5f32020-05-05 07:27:56 -05002173 } else {
2174
David Neto22f144c2017-06-12 14:26:21 -04002175 // We use a constant composite in SPIR-V for our constant aggregate in
2176 // LLVM.
2177 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002178
2179 for (unsigned k = 0; k < CA->getNumOperands(); k++) {
David Neto22f144c2017-06-12 14:26:21 -04002180 // And add an operand to the composite we are constructing
SJW01901d92020-05-21 08:58:31 -05002181 Ops << CA->getAggregateElement(k);
David Neto22f144c2017-06-12 14:26:21 -04002182 }
David Neto22f144c2017-06-12 14:26:21 -04002183 }
SJWf93f5f32020-05-05 07:27:56 -05002184 } else if (Cst->isNullValue()) {
2185 Opcode = spv::OpConstantNull;
2186 } else {
2187 Cst->print(errs());
2188 llvm_unreachable("Unsupported Constant???");
2189 }
David Neto22f144c2017-06-12 14:26:21 -04002190
SJWf93f5f32020-05-05 07:27:56 -05002191 if (Opcode == spv::OpConstantNull && Cst->getType()->isPointerTy()) {
2192 // Null pointer requires variable pointers.
2193 setVariablePointersCapabilities(Cst->getType()->getPointerAddressSpace());
2194 }
alan-baker5b86ed72019-02-15 08:26:50 -05002195
SJWf93f5f32020-05-05 07:27:56 -05002196 if (RID == 0) {
2197 RID = addSPIRVInst<kConstants>(Opcode, Ops);
2198 }
2199
2200 VMap[Cst] = RID;
2201
2202 return RID;
2203}
2204
2205SPIRVID SPIRVProducerPass::getSPIRVValue(Value *V) {
2206 auto II = ValueMap.find(V);
2207 if (II != ValueMap.end()) {
SJW01901d92020-05-21 08:58:31 -05002208 assert(II->second.isValid());
SJWf93f5f32020-05-05 07:27:56 -05002209 return II->second;
2210 }
2211 if (Constant *Cst = dyn_cast<Constant>(V)) {
2212 return getSPIRVConstant(Cst);
2213 } else {
2214 llvm_unreachable("Variable not found");
2215 }
2216}
2217
SJW77b87ad2020-04-21 14:37:52 -05002218void SPIRVProducerPass::GenerateSamplers() {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002219 auto &sampler_map = getSamplerMap();
alan-baker09cb9802019-12-10 13:16:27 -05002220 SamplerLiteralToIDMap.clear();
David Neto862b7d82018-06-14 18:48:37 -04002221 DenseMap<unsigned, unsigned> SamplerLiteralToDescriptorSetMap;
2222 DenseMap<unsigned, unsigned> SamplerLiteralToBindingMap;
David Neto22f144c2017-06-12 14:26:21 -04002223
David Neto862b7d82018-06-14 18:48:37 -04002224 // We might have samplers in the sampler map that are not used
2225 // in the translation unit. We need to allocate variables
2226 // for them and bindings too.
2227 DenseSet<unsigned> used_bindings;
David Neto22f144c2017-06-12 14:26:21 -04002228
SJW77b87ad2020-04-21 14:37:52 -05002229 auto *var_fn = module->getFunction(clspv::LiteralSamplerFunction());
alan-baker09cb9802019-12-10 13:16:27 -05002230 // Return if there are no literal samplers.
alan-bakerb6b09dc2018-11-08 16:59:28 -05002231 if (!var_fn)
2232 return;
alan-baker09cb9802019-12-10 13:16:27 -05002233
David Neto862b7d82018-06-14 18:48:37 -04002234 for (auto user : var_fn->users()) {
2235 // Populate SamplerLiteralToDescriptorSetMap and
2236 // SamplerLiteralToBindingMap.
2237 //
2238 // Look for calls like
2239 // call %opencl.sampler_t addrspace(2)*
2240 // @clspv.sampler.var.literal(
2241 // i32 descriptor,
2242 // i32 binding,
alan-baker09cb9802019-12-10 13:16:27 -05002243 // i32 (index-into-sampler-map|sampler_mask))
alan-bakerb6b09dc2018-11-08 16:59:28 -05002244 if (auto *call = dyn_cast<CallInst>(user)) {
alan-baker09cb9802019-12-10 13:16:27 -05002245 const auto third_param = static_cast<unsigned>(
alan-bakerb6b09dc2018-11-08 16:59:28 -05002246 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
alan-baker09cb9802019-12-10 13:16:27 -05002247 auto sampler_value = third_param;
2248 if (clspv::Option::UseSamplerMap()) {
2249 if (third_param >= sampler_map.size()) {
2250 errs() << "Out of bounds index to sampler map: " << third_param;
2251 llvm_unreachable("bad sampler init: out of bounds");
2252 }
2253 sampler_value = sampler_map[third_param].first;
David Neto862b7d82018-06-14 18:48:37 -04002254 }
2255
David Neto862b7d82018-06-14 18:48:37 -04002256 const auto descriptor_set = static_cast<unsigned>(
2257 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
2258 const auto binding = static_cast<unsigned>(
2259 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
2260
2261 SamplerLiteralToDescriptorSetMap[sampler_value] = descriptor_set;
2262 SamplerLiteralToBindingMap[sampler_value] = binding;
2263 used_bindings.insert(binding);
2264 }
2265 }
2266
alan-baker09cb9802019-12-10 13:16:27 -05002267 DenseSet<size_t> seen;
2268 for (auto user : var_fn->users()) {
2269 if (!isa<CallInst>(user))
2270 continue;
2271
2272 auto call = cast<CallInst>(user);
2273 const unsigned third_param = static_cast<unsigned>(
2274 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
2275
2276 // Already allocated a variable for this value.
2277 if (!seen.insert(third_param).second)
2278 continue;
2279
2280 auto sampler_value = third_param;
2281 if (clspv::Option::UseSamplerMap()) {
2282 sampler_value = sampler_map[third_param].first;
2283 }
2284
SJW806a5d82020-07-15 12:51:38 -05002285 auto sampler_var_id = addSPIRVGlobalVariable(
2286 getSPIRVType(SamplerTy), spv::StorageClassUniformConstant);
David Neto22f144c2017-06-12 14:26:21 -04002287
alan-baker09cb9802019-12-10 13:16:27 -05002288 SamplerLiteralToIDMap[sampler_value] = sampler_var_id;
David Neto22f144c2017-06-12 14:26:21 -04002289
David Neto862b7d82018-06-14 18:48:37 -04002290 unsigned descriptor_set;
2291 unsigned binding;
alan-baker09cb9802019-12-10 13:16:27 -05002292 if (SamplerLiteralToBindingMap.find(sampler_value) ==
alan-bakerb6b09dc2018-11-08 16:59:28 -05002293 SamplerLiteralToBindingMap.end()) {
David Neto862b7d82018-06-14 18:48:37 -04002294 // This sampler is not actually used. Find the next one.
alan-baker7506abb2020-09-10 15:02:55 -04002295 for (binding = 0; used_bindings.count(binding); binding++) {
2296 }
David Neto862b7d82018-06-14 18:48:37 -04002297 descriptor_set = 0; // Literal samplers always use descriptor set 0.
2298 used_bindings.insert(binding);
2299 } else {
alan-baker09cb9802019-12-10 13:16:27 -05002300 descriptor_set = SamplerLiteralToDescriptorSetMap[sampler_value];
2301 binding = SamplerLiteralToBindingMap[sampler_value];
alan-bakercff80152019-06-15 00:38:00 -04002302
alan-baker86ce19c2020-08-05 13:09:19 -04002303 auto import_id = getReflectionImport();
2304 SPIRVOperandVec Ops;
2305 Ops << getSPIRVType(Type::getVoidTy(module->getContext())) << import_id
2306 << reflection::ExtInstLiteralSampler
2307 << getSPIRVInt32Constant(descriptor_set)
2308 << getSPIRVInt32Constant(binding)
2309 << getSPIRVInt32Constant(sampler_value);
2310 addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
David Neto862b7d82018-06-14 18:48:37 -04002311 }
2312
SJW69939d52020-04-16 07:29:07 -05002313 // Ops[0] = Target ID
2314 // Ops[1] = Decoration (DescriptorSet)
2315 // Ops[2] = LiteralNumber according to Decoration
SJW806a5d82020-07-15 12:51:38 -05002316 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05002317 Ops << sampler_var_id << spv::DecorationDescriptorSet << descriptor_set;
David Neto22f144c2017-06-12 14:26:21 -04002318
SJWf93f5f32020-05-05 07:27:56 -05002319 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002320
2321 // Ops[0] = Target ID
2322 // Ops[1] = Decoration (Binding)
2323 // Ops[2] = LiteralNumber according to Decoration
2324 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002325 Ops << sampler_var_id << spv::DecorationBinding << binding;
David Neto22f144c2017-06-12 14:26:21 -04002326
SJWf93f5f32020-05-05 07:27:56 -05002327 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002328 }
David Neto862b7d82018-06-14 18:48:37 -04002329}
David Neto22f144c2017-06-12 14:26:21 -04002330
SJW77b87ad2020-04-21 14:37:52 -05002331void SPIRVProducerPass::GenerateResourceVars() {
David Neto862b7d82018-06-14 18:48:37 -04002332 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04002333
David Neto862b7d82018-06-14 18:48:37 -04002334 // Generate variables. Make one for each of resource var info object.
2335 for (auto *info : ModuleOrderedResourceVars) {
2336 Type *type = info->var_fn->getReturnType();
2337 // Remap the address space for opaque types.
2338 switch (info->arg_kind) {
2339 case clspv::ArgKind::Sampler:
alan-bakerf6bc8252020-09-23 14:58:55 -04002340 case clspv::ArgKind::SampledImage:
2341 case clspv::ArgKind::StorageImage:
David Neto862b7d82018-06-14 18:48:37 -04002342 type = PointerType::get(type->getPointerElementType(),
2343 clspv::AddressSpace::UniformConstant);
2344 break;
2345 default:
2346 break;
2347 }
David Neto22f144c2017-06-12 14:26:21 -04002348
David Neto862b7d82018-06-14 18:48:37 -04002349 const auto sc = GetStorageClassForArgKind(info->arg_kind);
David Neto22f144c2017-06-12 14:26:21 -04002350
SJW806a5d82020-07-15 12:51:38 -05002351 info->var_id = addSPIRVGlobalVariable(getSPIRVType(type), sc);
David Neto862b7d82018-06-14 18:48:37 -04002352
2353 // Map calls to the variable-builtin-function.
2354 for (auto &U : info->var_fn->uses()) {
2355 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
2356 const auto set = unsigned(
2357 dyn_cast<ConstantInt>(call->getOperand(0))->getZExtValue());
2358 const auto binding = unsigned(
2359 dyn_cast<ConstantInt>(call->getOperand(1))->getZExtValue());
2360 if (set == info->descriptor_set && binding == info->binding) {
2361 switch (info->arg_kind) {
2362 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002363 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002364 case clspv::ArgKind::Pod:
alan-baker9b0ec3c2020-04-06 14:45:34 -04002365 case clspv::ArgKind::PodUBO:
2366 case clspv::ArgKind::PodPushConstant:
David Neto862b7d82018-06-14 18:48:37 -04002367 // The call maps to the variable directly.
2368 VMap[call] = info->var_id;
2369 break;
2370 case clspv::ArgKind::Sampler:
alan-bakerf6bc8252020-09-23 14:58:55 -04002371 case clspv::ArgKind::SampledImage:
2372 case clspv::ArgKind::StorageImage:
David Neto862b7d82018-06-14 18:48:37 -04002373 // The call maps to a load we generate later.
2374 ResourceVarDeferredLoadCalls[call] = info->var_id;
2375 break;
2376 default:
2377 llvm_unreachable("Unhandled arg kind");
2378 }
2379 }
David Neto22f144c2017-06-12 14:26:21 -04002380 }
David Neto862b7d82018-06-14 18:48:37 -04002381 }
2382 }
David Neto22f144c2017-06-12 14:26:21 -04002383
David Neto862b7d82018-06-14 18:48:37 -04002384 // Generate associated decorations.
SJWf93f5f32020-05-05 07:27:56 -05002385 SPIRVOperandVec Ops;
David Neto862b7d82018-06-14 18:48:37 -04002386 for (auto *info : ModuleOrderedResourceVars) {
alan-baker9b0ec3c2020-04-06 14:45:34 -04002387 // Push constants don't need descriptor set or binding decorations.
2388 if (info->arg_kind == clspv::ArgKind::PodPushConstant)
2389 continue;
2390
David Neto862b7d82018-06-14 18:48:37 -04002391 // Decorate with DescriptorSet and Binding.
2392 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002393 Ops << info->var_id << spv::DecorationDescriptorSet << info->descriptor_set;
SJWf93f5f32020-05-05 07:27:56 -05002394 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto862b7d82018-06-14 18:48:37 -04002395
2396 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002397 Ops << info->var_id << spv::DecorationBinding << info->binding;
SJWf93f5f32020-05-05 07:27:56 -05002398 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto862b7d82018-06-14 18:48:37 -04002399
alan-bakere9308012019-03-15 10:25:13 -04002400 if (info->coherent) {
2401 // Decorate with Coherent if required for the variable.
2402 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002403 Ops << info->var_id << spv::DecorationCoherent;
SJWf93f5f32020-05-05 07:27:56 -05002404 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
alan-bakere9308012019-03-15 10:25:13 -04002405 }
2406
David Neto862b7d82018-06-14 18:48:37 -04002407 // Generate NonWritable and NonReadable
2408 switch (info->arg_kind) {
2409 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002410 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002411 if (info->var_fn->getReturnType()->getPointerAddressSpace() ==
2412 clspv::AddressSpace::Constant) {
2413 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002414 Ops << info->var_id << spv::DecorationNonWritable;
SJWf93f5f32020-05-05 07:27:56 -05002415 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002416 }
David Neto862b7d82018-06-14 18:48:37 -04002417 break;
alan-bakerf6bc8252020-09-23 14:58:55 -04002418 case clspv::ArgKind::StorageImage: {
2419 auto *type = info->var_fn->getReturnType();
2420 auto *struct_ty = cast<StructType>(type->getPointerElementType());
2421 // TODO(alan-baker): This is conservative. If compiling for OpenCL 2.0 or
2422 // above, the compiler treats all write_only images as read_write images.
2423 if (struct_ty->getName().contains("_wo_t")) {
2424 Ops.clear();
2425 Ops << info->var_id << spv::DecorationNonReadable;
2426 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
2427 }
David Neto862b7d82018-06-14 18:48:37 -04002428 break;
alan-bakerf6bc8252020-09-23 14:58:55 -04002429 }
David Neto862b7d82018-06-14 18:48:37 -04002430 default:
2431 break;
David Neto22f144c2017-06-12 14:26:21 -04002432 }
2433 }
2434}
2435
2436void SPIRVProducerPass::GenerateGlobalVar(GlobalVariable &GV) {
David Neto22f144c2017-06-12 14:26:21 -04002437 ValueMapType &VMap = getValueMap();
SJW01901d92020-05-21 08:58:31 -05002438 std::vector<SPIRVID> &BuiltinDimVec = getBuiltinDimVec();
David Neto85082642018-03-24 06:55:20 -07002439 const DataLayout &DL = GV.getParent()->getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04002440
2441 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
2442 Type *Ty = GV.getType();
2443 PointerType *PTy = cast<PointerType>(Ty);
2444
SJW01901d92020-05-21 08:58:31 -05002445 SPIRVID InitializerID;
David Neto22f144c2017-06-12 14:26:21 -04002446
2447 // Workgroup size is handled differently (it goes into a constant)
2448 if (spv::BuiltInWorkgroupSize == BuiltinType) {
David Neto22f144c2017-06-12 14:26:21 -04002449 uint32_t PrevXDimCst = 0xFFFFFFFF;
2450 uint32_t PrevYDimCst = 0xFFFFFFFF;
2451 uint32_t PrevZDimCst = 0xFFFFFFFF;
alan-baker3b609772020-09-03 19:10:17 -04002452 bool HasMD = true;
David Neto22f144c2017-06-12 14:26:21 -04002453 for (Function &Func : *GV.getParent()) {
2454 if (Func.isDeclaration()) {
2455 continue;
2456 }
2457
2458 // We only need to check kernels.
2459 if (Func.getCallingConv() != CallingConv::SPIR_KERNEL) {
2460 continue;
2461 }
2462
2463 if (const MDNode *MD =
2464 dyn_cast<Function>(&Func)->getMetadata("reqd_work_group_size")) {
2465 uint32_t CurXDimCst = static_cast<uint32_t>(
2466 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
2467 uint32_t CurYDimCst = static_cast<uint32_t>(
2468 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
2469 uint32_t CurZDimCst = static_cast<uint32_t>(
2470 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
2471
2472 if (PrevXDimCst == 0xFFFFFFFF && PrevYDimCst == 0xFFFFFFFF &&
2473 PrevZDimCst == 0xFFFFFFFF) {
2474 PrevXDimCst = CurXDimCst;
2475 PrevYDimCst = CurYDimCst;
2476 PrevZDimCst = CurZDimCst;
2477 } else if (CurXDimCst != PrevXDimCst || CurYDimCst != PrevYDimCst ||
2478 CurZDimCst != PrevZDimCst) {
alan-baker3b609772020-09-03 19:10:17 -04002479 HasMD = false;
2480 continue;
David Neto22f144c2017-06-12 14:26:21 -04002481 } else {
2482 continue;
2483 }
2484
2485 //
2486 // Generate OpConstantComposite.
2487 //
2488 // Ops[0] : Result Type ID
2489 // Ops[1] : Constant size for x dimension.
2490 // Ops[2] : Constant size for y dimension.
2491 // Ops[3] : Constant size for z dimension.
SJWf93f5f32020-05-05 07:27:56 -05002492 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04002493
SJW01901d92020-05-21 08:58:31 -05002494 SPIRVID XDimCstID =
SJWf93f5f32020-05-05 07:27:56 -05002495 getSPIRVValue(mdconst::extract<ConstantInt>(MD->getOperand(0)));
SJW01901d92020-05-21 08:58:31 -05002496 SPIRVID YDimCstID =
SJWf93f5f32020-05-05 07:27:56 -05002497 getSPIRVValue(mdconst::extract<ConstantInt>(MD->getOperand(1)));
SJW01901d92020-05-21 08:58:31 -05002498 SPIRVID ZDimCstID =
SJWf93f5f32020-05-05 07:27:56 -05002499 getSPIRVValue(mdconst::extract<ConstantInt>(MD->getOperand(2)));
David Neto22f144c2017-06-12 14:26:21 -04002500
SJW01901d92020-05-21 08:58:31 -05002501 Ops << Ty->getPointerElementType() << XDimCstID << YDimCstID
2502 << ZDimCstID;
David Neto22f144c2017-06-12 14:26:21 -04002503
SJWf93f5f32020-05-05 07:27:56 -05002504 InitializerID =
2505 addSPIRVInst<kGlobalVariables>(spv::OpConstantComposite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002506 } else {
alan-baker3b609772020-09-03 19:10:17 -04002507 HasMD = false;
David Neto22f144c2017-06-12 14:26:21 -04002508 }
2509 }
2510
2511 // If all kernels do not have metadata for reqd_work_group_size, generate
2512 // OpSpecConstants for x/y/z dimension.
Kévin Petit21c23c62020-04-29 01:38:28 +01002513 if (!HasMD || clspv::Option::NonUniformNDRangeSupported()) {
David Neto22f144c2017-06-12 14:26:21 -04002514 //
2515 // Generate OpSpecConstants for x/y/z dimension.
2516 //
2517 // Ops[0] : Result Type ID
2518 // Ops[1] : Constant size for x/y/z dimension (Literal Number).
David Neto22f144c2017-06-12 14:26:21 -04002519
alan-bakera1be3322020-04-20 12:48:18 -04002520 // Allocate spec constants for workgroup size.
SJW77b87ad2020-04-21 14:37:52 -05002521 clspv::AddWorkgroupSpecConstants(module);
alan-bakera1be3322020-04-20 12:48:18 -04002522
SJWf93f5f32020-05-05 07:27:56 -05002523 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05002524 SPIRVID result_type_id = getSPIRVType(
SJWf93f5f32020-05-05 07:27:56 -05002525 dyn_cast<VectorType>(Ty->getPointerElementType())->getElementType());
David Neto22f144c2017-06-12 14:26:21 -04002526
David Neto257c3892018-04-11 13:19:45 -04002527 // X Dimension
SJW01901d92020-05-21 08:58:31 -05002528 Ops << result_type_id << 1;
2529 SPIRVID XDimCstID = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002530
2531 // Y Dimension
2532 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002533 Ops << result_type_id << 1;
2534 SPIRVID YDimCstID = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002535
2536 // Z Dimension
2537 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002538 Ops << result_type_id << 1;
2539 SPIRVID ZDimCstID = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002540
David Neto257c3892018-04-11 13:19:45 -04002541 BuiltinDimVec.push_back(XDimCstID);
2542 BuiltinDimVec.push_back(YDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002543 BuiltinDimVec.push_back(ZDimCstID);
2544
David Neto22f144c2017-06-12 14:26:21 -04002545 //
2546 // Generate OpSpecConstantComposite.
2547 //
2548 // Ops[0] : Result Type ID
2549 // Ops[1] : Constant size for x dimension.
2550 // Ops[2] : Constant size for y dimension.
2551 // Ops[3] : Constant size for z dimension.
David Neto22f144c2017-06-12 14:26:21 -04002552 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002553 Ops << Ty->getPointerElementType() << XDimCstID << YDimCstID << ZDimCstID;
David Neto22f144c2017-06-12 14:26:21 -04002554
SJWf93f5f32020-05-05 07:27:56 -05002555 InitializerID =
2556 addSPIRVInst<kConstants>(spv::OpSpecConstantComposite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002557 }
alan-bakerbed3a882020-04-21 14:42:41 -04002558 } else if (BuiltinType == spv::BuiltInWorkDim) {
2559 // 1. Generate a specialization constant with a default of 3.
2560 // 2. Allocate and annotate a SpecId for the constant.
2561 // 3. Use the spec constant as the initializer for the variable.
SJWf93f5f32020-05-05 07:27:56 -05002562 SPIRVOperandVec Ops;
alan-bakerbed3a882020-04-21 14:42:41 -04002563
2564 //
2565 // Generate OpSpecConstant.
2566 //
2567 // Ops[0] : Result Type ID
2568 // Ops[1] : Default literal value
alan-bakerbed3a882020-04-21 14:42:41 -04002569
SJW01901d92020-05-21 08:58:31 -05002570 Ops << IntegerType::get(GV.getContext(), 32) << 3;
alan-bakerbed3a882020-04-21 14:42:41 -04002571
SJWf93f5f32020-05-05 07:27:56 -05002572 InitializerID = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
alan-bakerbed3a882020-04-21 14:42:41 -04002573
2574 //
2575 // Generate SpecId decoration.
2576 //
2577 // Ops[0] : target
2578 // Ops[1] : decoration
2579 // Ops[2] : SpecId
Alan Baker75ccc252020-04-21 17:11:52 -04002580 auto spec_id = AllocateSpecConstant(module, SpecConstant::kWorkDim);
alan-bakerbed3a882020-04-21 14:42:41 -04002581 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002582 Ops << InitializerID << spv::DecorationSpecId << spec_id;
alan-bakerbed3a882020-04-21 14:42:41 -04002583
SJWf93f5f32020-05-05 07:27:56 -05002584 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002585 } else if (BuiltinType == spv::BuiltInGlobalOffset) {
2586 // 1. Generate a spec constant with a default of {0, 0, 0}.
2587 // 2. Allocate and annotate SpecIds for the constants.
2588 // 3. Use the spec constant as the initializer for the variable.
SJWf93f5f32020-05-05 07:27:56 -05002589 SPIRVOperandVec Ops;
alan-bakere1996972020-05-04 08:38:12 -04002590
2591 //
2592 // Generate OpSpecConstant for each dimension.
2593 //
2594 // Ops[0] : Result Type ID
2595 // Ops[1] : Default literal value
2596 //
SJW01901d92020-05-21 08:58:31 -05002597 Ops << IntegerType::get(GV.getContext(), 32) << 0;
2598 SPIRVID x_id = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002599
alan-bakere1996972020-05-04 08:38:12 -04002600 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002601 Ops << IntegerType::get(GV.getContext(), 32) << 0;
2602 SPIRVID y_id = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002603
alan-bakere1996972020-05-04 08:38:12 -04002604 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002605 Ops << IntegerType::get(GV.getContext(), 32) << 0;
2606 SPIRVID z_id = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002607
2608 //
2609 // Generate SpecId decoration for each dimension.
2610 //
2611 // Ops[0] : target
2612 // Ops[1] : decoration
2613 // Ops[2] : SpecId
2614 //
2615 auto spec_id = AllocateSpecConstant(module, SpecConstant::kGlobalOffsetX);
2616 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002617 Ops << x_id << spv::DecorationSpecId << spec_id;
SJWf93f5f32020-05-05 07:27:56 -05002618 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002619
2620 spec_id = AllocateSpecConstant(module, SpecConstant::kGlobalOffsetY);
2621 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002622 Ops << y_id << spv::DecorationSpecId << spec_id;
SJWf93f5f32020-05-05 07:27:56 -05002623 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002624
2625 spec_id = AllocateSpecConstant(module, SpecConstant::kGlobalOffsetZ);
2626 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002627 Ops << z_id << spv::DecorationSpecId << spec_id;
SJWf93f5f32020-05-05 07:27:56 -05002628 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002629
2630 //
2631 // Generate OpSpecConstantComposite.
2632 //
2633 // Ops[0] : type id
2634 // Ops[1..n-1] : elements
2635 //
alan-bakere1996972020-05-04 08:38:12 -04002636 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002637 Ops << GV.getType()->getPointerElementType() << x_id << y_id << z_id;
SJWf93f5f32020-05-05 07:27:56 -05002638 InitializerID = addSPIRVInst<kConstants>(spv::OpSpecConstantComposite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002639 }
2640
David Neto85082642018-03-24 06:55:20 -07002641 const auto AS = PTy->getAddressSpace();
SJW806a5d82020-07-15 12:51:38 -05002642 const auto spvSC = GetStorageClass(AS);
David Neto22f144c2017-06-12 14:26:21 -04002643
David Neto85082642018-03-24 06:55:20 -07002644 const bool module_scope_constant_external_init =
David Neto862b7d82018-06-14 18:48:37 -04002645 (AS == AddressSpace::Constant) && GV.hasInitializer() &&
David Neto85082642018-03-24 06:55:20 -07002646 clspv::Option::ModuleConstantsInStorageBuffer();
2647
Kévin Petit23d5f182019-08-13 16:21:29 +01002648 if (GV.hasInitializer()) {
2649 auto GVInit = GV.getInitializer();
2650 if (!isa<UndefValue>(GVInit) && !module_scope_constant_external_init) {
SJWf93f5f32020-05-05 07:27:56 -05002651 InitializerID = getSPIRVValue(GVInit);
David Neto85082642018-03-24 06:55:20 -07002652 }
2653 }
Kévin Petit23d5f182019-08-13 16:21:29 +01002654
SJW806a5d82020-07-15 12:51:38 -05002655 SPIRVID var_id =
2656 addSPIRVGlobalVariable(getSPIRVType(Ty), spvSC, InitializerID);
David Neto85082642018-03-24 06:55:20 -07002657
SJWf93f5f32020-05-05 07:27:56 -05002658 VMap[&GV] = var_id;
David Neto22f144c2017-06-12 14:26:21 -04002659
alan-bakere1996972020-05-04 08:38:12 -04002660 auto IsOpenCLBuiltin = [](spv::BuiltIn builtin) {
2661 return builtin == spv::BuiltInWorkDim ||
2662 builtin == spv::BuiltInGlobalOffset;
2663 };
2664
alan-bakere1996972020-05-04 08:38:12 -04002665 // If we have a builtin (not an OpenCL builtin).
2666 if (spv::BuiltInMax != BuiltinType && !IsOpenCLBuiltin(BuiltinType)) {
David Neto22f144c2017-06-12 14:26:21 -04002667 //
2668 // Generate OpDecorate.
2669 //
2670 // DOps[0] = Target ID
2671 // DOps[1] = Decoration (Builtin)
2672 // DOps[2] = BuiltIn ID
SJW01901d92020-05-21 08:58:31 -05002673 SPIRVID ResultID;
David Neto22f144c2017-06-12 14:26:21 -04002674
2675 // WorkgroupSize is different, we decorate the constant composite that has
2676 // its value, rather than the variable that we use to access the value.
2677 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2678 ResultID = InitializerID;
David Netoa60b00b2017-09-15 16:34:09 -04002679 // Save both the value and variable IDs for later.
2680 WorkgroupSizeValueID = InitializerID;
SJWf93f5f32020-05-05 07:27:56 -05002681 WorkgroupSizeVarID = getSPIRVValue(&GV);
David Neto22f144c2017-06-12 14:26:21 -04002682 } else {
SJWf93f5f32020-05-05 07:27:56 -05002683 ResultID = getSPIRVValue(&GV);
David Neto22f144c2017-06-12 14:26:21 -04002684 }
2685
SJW806a5d82020-07-15 12:51:38 -05002686 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05002687 Ops << ResultID << spv::DecorationBuiltIn << BuiltinType;
David Neto22f144c2017-06-12 14:26:21 -04002688
SJW01901d92020-05-21 08:58:31 -05002689 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto85082642018-03-24 06:55:20 -07002690 } else if (module_scope_constant_external_init) {
2691 // This module scope constant is initialized from a storage buffer with data
2692 // provided by the host at binding 0 of the next descriptor set.
SJW77b87ad2020-04-21 14:37:52 -05002693 const uint32_t descriptor_set = TakeDescriptorIndex(module);
David Neto85082642018-03-24 06:55:20 -07002694
alan-baker86ce19c2020-08-05 13:09:19 -04002695 // Emit the intializer as a reflection instruction.
David Neto85082642018-03-24 06:55:20 -07002696 // Use "kind,buffer" to indicate storage buffer. We might want to expand
2697 // that later to other types, like uniform buffer.
alan-bakerf5e5f692018-11-27 08:33:24 -05002698 std::string hexbytes;
2699 llvm::raw_string_ostream str(hexbytes);
2700 clspv::ConstantEmitter(DL, str).Emit(GV.getInitializer());
alan-baker86ce19c2020-08-05 13:09:19 -04002701
2702 // Reflection instruction for constant data.
2703 SPIRVOperandVec Ops;
2704 auto data_id = addSPIRVInst<kDebug>(spv::OpString, str.str().c_str());
2705 Ops << getSPIRVType(Type::getVoidTy(module->getContext()))
2706 << getReflectionImport() << reflection::ExtInstConstantDataStorageBuffer
2707 << getSPIRVInt32Constant(descriptor_set) << getSPIRVInt32Constant(0)
2708 << data_id;
2709 addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
David Neto85082642018-03-24 06:55:20 -07002710
David Neto85082642018-03-24 06:55:20 -07002711 // OpDecorate %var DescriptorSet <descriptor_set>
alan-baker86ce19c2020-08-05 13:09:19 -04002712 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002713 Ops << var_id << spv::DecorationDescriptorSet << descriptor_set;
2714 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
SJW69939d52020-04-16 07:29:07 -05002715
2716 // OpDecorate %var Binding <binding>
SJW01901d92020-05-21 08:58:31 -05002717 Ops.clear();
2718 Ops << var_id << spv::DecorationBinding << 0;
2719 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Netoc6f3ab22018-04-06 18:02:31 -04002720 }
2721}
2722
David Neto22f144c2017-06-12 14:26:21 -04002723void SPIRVProducerPass::GenerateFuncPrologue(Function &F) {
David Neto22f144c2017-06-12 14:26:21 -04002724 ValueMapType &VMap = getValueMap();
2725 EntryPointVecType &EntryPoints = getEntryPointVec();
David Neto22f144c2017-06-12 14:26:21 -04002726 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
2727 auto &GlobalConstArgSet = getGlobalConstArgSet();
2728
2729 FunctionType *FTy = F.getFunctionType();
2730
2731 //
David Neto22f144c2017-06-12 14:26:21 -04002732 // Generate OPFunction.
2733 //
2734
2735 // FOps[0] : Result Type ID
2736 // FOps[1] : Function Control
2737 // FOps[2] : Function Type ID
SJWf93f5f32020-05-05 07:27:56 -05002738 SPIRVOperandVec FOps;
David Neto22f144c2017-06-12 14:26:21 -04002739
2740 // Find SPIRV instruction for return type.
SJW01901d92020-05-21 08:58:31 -05002741 FOps << FTy->getReturnType();
David Neto22f144c2017-06-12 14:26:21 -04002742
2743 // Check function attributes for SPIRV Function Control.
2744 uint32_t FuncControl = spv::FunctionControlMaskNone;
2745 if (F.hasFnAttribute(Attribute::AlwaysInline)) {
2746 FuncControl |= spv::FunctionControlInlineMask;
2747 }
2748 if (F.hasFnAttribute(Attribute::NoInline)) {
2749 FuncControl |= spv::FunctionControlDontInlineMask;
2750 }
2751 // TODO: Check llvm attribute for Function Control Pure.
2752 if (F.hasFnAttribute(Attribute::ReadOnly)) {
2753 FuncControl |= spv::FunctionControlPureMask;
2754 }
2755 // TODO: Check llvm attribute for Function Control Const.
2756 if (F.hasFnAttribute(Attribute::ReadNone)) {
2757 FuncControl |= spv::FunctionControlConstMask;
2758 }
2759
SJW01901d92020-05-21 08:58:31 -05002760 FOps << FuncControl;
David Neto22f144c2017-06-12 14:26:21 -04002761
SJW01901d92020-05-21 08:58:31 -05002762 SPIRVID FTyID;
David Neto22f144c2017-06-12 14:26:21 -04002763 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
2764 SmallVector<Type *, 4> NewFuncParamTys;
2765 FunctionType *NewFTy =
2766 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
SJWf93f5f32020-05-05 07:27:56 -05002767 FTyID = getSPIRVType(NewFTy);
David Neto22f144c2017-06-12 14:26:21 -04002768 } else {
David Neto9ed8e2f2018-03-24 06:47:24 -07002769 // Handle regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04002770 if (GlobalConstFuncTyMap.count(FTy)) {
SJWf93f5f32020-05-05 07:27:56 -05002771 FTyID = getSPIRVType(GlobalConstFuncTyMap[FTy].first);
David Neto22f144c2017-06-12 14:26:21 -04002772 } else {
SJWf93f5f32020-05-05 07:27:56 -05002773 FTyID = getSPIRVType(FTy);
David Neto22f144c2017-06-12 14:26:21 -04002774 }
2775 }
2776
SJW01901d92020-05-21 08:58:31 -05002777 FOps << FTyID;
David Neto22f144c2017-06-12 14:26:21 -04002778
SJWf93f5f32020-05-05 07:27:56 -05002779 // Generate SPIRV instruction for function.
2780 SPIRVID FID = addSPIRVInst(spv::OpFunction, FOps);
2781 VMap[&F] = FID;
David Neto22f144c2017-06-12 14:26:21 -04002782
SJWf93f5f32020-05-05 07:27:56 -05002783 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
2784 EntryPoints.push_back(std::make_pair(&F, FID));
2785 }
David Neto22f144c2017-06-12 14:26:21 -04002786
David Neto482550a2018-03-24 05:21:07 -07002787 if (clspv::Option::ShowIDs()) {
SJW01901d92020-05-21 08:58:31 -05002788 errs() << "Function " << F.getName() << " is " << FID.get() << "\n";
David Netob05675d2018-02-16 12:37:49 -05002789 }
David Neto22f144c2017-06-12 14:26:21 -04002790
2791 //
2792 // Generate OpFunctionParameter for Normal function.
2793 //
David Neto22f144c2017-06-12 14:26:21 -04002794 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
alan-bakere9308012019-03-15 10:25:13 -04002795
David Neto22f144c2017-06-12 14:26:21 -04002796 // Iterate Argument for name instead of param type from function type.
2797 unsigned ArgIdx = 0;
2798 for (Argument &Arg : F.args()) {
David Neto22f144c2017-06-12 14:26:21 -04002799 // ParamOps[0] : Result Type ID
SJW01901d92020-05-21 08:58:31 -05002800 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04002801
2802 // Find SPIRV instruction for parameter type.
SJW01901d92020-05-21 08:58:31 -05002803 SPIRVID ParamTyID = getSPIRVType(Arg.getType());
David Neto22f144c2017-06-12 14:26:21 -04002804 if (PointerType *PTy = dyn_cast<PointerType>(Arg.getType())) {
2805 if (GlobalConstFuncTyMap.count(FTy)) {
2806 if (ArgIdx == GlobalConstFuncTyMap[FTy].second) {
2807 Type *EleTy = PTy->getPointerElementType();
2808 Type *ArgTy =
2809 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
SJWf93f5f32020-05-05 07:27:56 -05002810 ParamTyID = getSPIRVType(ArgTy);
David Neto22f144c2017-06-12 14:26:21 -04002811 GlobalConstArgSet.insert(&Arg);
2812 }
2813 }
2814 }
SJW01901d92020-05-21 08:58:31 -05002815 Ops << ParamTyID;
David Neto22f144c2017-06-12 14:26:21 -04002816
2817 // Generate SPIRV instruction for parameter.
SJW01901d92020-05-21 08:58:31 -05002818 SPIRVID param_id = addSPIRVInst(spv::OpFunctionParameter, Ops);
SJWf93f5f32020-05-05 07:27:56 -05002819 VMap[&Arg] = param_id;
2820
2821 if (CalledWithCoherentResource(Arg)) {
2822 // If the arg is passed a coherent resource ever, then decorate this
2823 // parameter with Coherent too.
SJW01901d92020-05-21 08:58:31 -05002824 Ops.clear();
2825 Ops << param_id << spv::DecorationCoherent;
2826 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
SJWf93f5f32020-05-05 07:27:56 -05002827 }
David Neto22f144c2017-06-12 14:26:21 -04002828
2829 ArgIdx++;
2830 }
2831 }
2832}
2833
SJW77b87ad2020-04-21 14:37:52 -05002834void SPIRVProducerPass::GenerateModuleInfo() {
David Neto22f144c2017-06-12 14:26:21 -04002835 EntryPointVecType &EntryPoints = getEntryPointVec();
SJW806a5d82020-07-15 12:51:38 -05002836 auto &EntryPointInterfaces = getEntryPointInterfacesList();
SJW01901d92020-05-21 08:58:31 -05002837 std::vector<SPIRVID> &BuiltinDimVec = getBuiltinDimVec();
David Neto22f144c2017-06-12 14:26:21 -04002838
SJWf93f5f32020-05-05 07:27:56 -05002839 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04002840
SJW01901d92020-05-21 08:58:31 -05002841 for (auto Capability : CapabilitySet) {
David Neto22f144c2017-06-12 14:26:21 -04002842 //
SJW01901d92020-05-21 08:58:31 -05002843 // Generate OpCapability
David Neto22f144c2017-06-12 14:26:21 -04002844 //
2845 // Ops[0] = Capability
SJW01901d92020-05-21 08:58:31 -05002846 addSPIRVInst<kCapabilities>(spv::OpCapability, Capability);
alan-baker5b86ed72019-02-15 08:26:50 -05002847 }
2848
2849 // Always add the storage buffer extension
2850 {
David Neto22f144c2017-06-12 14:26:21 -04002851 //
2852 // Generate OpExtension.
2853 //
2854 // Ops[0] = Name (Literal String)
2855 //
SJWf93f5f32020-05-05 07:27:56 -05002856 addSPIRVInst<kExtensions>(spv::OpExtension,
2857 "SPV_KHR_storage_buffer_storage_class");
alan-baker5b86ed72019-02-15 08:26:50 -05002858 }
David Neto22f144c2017-06-12 14:26:21 -04002859
alan-baker5b86ed72019-02-15 08:26:50 -05002860 if (hasVariablePointers() || hasVariablePointersStorageBuffer()) {
2861 //
2862 // Generate OpExtension.
2863 //
2864 // Ops[0] = Name (Literal String)
2865 //
SJWf93f5f32020-05-05 07:27:56 -05002866 addSPIRVInst<kExtensions>(spv::OpExtension, "SPV_KHR_variable_pointers");
David Neto22f144c2017-06-12 14:26:21 -04002867 }
2868
2869 //
2870 // Generate OpMemoryModel
2871 //
2872 // Memory model for Vulkan will always be GLSL450.
2873
2874 // Ops[0] = Addressing Model
2875 // Ops[1] = Memory Model
2876 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002877 Ops << spv::AddressingModelLogical << spv::MemoryModelGLSL450;
David Neto22f144c2017-06-12 14:26:21 -04002878
SJWf93f5f32020-05-05 07:27:56 -05002879 addSPIRVInst<kMemoryModel>(spv::OpMemoryModel, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002880
2881 //
2882 // Generate OpEntryPoint
2883 //
2884 for (auto EntryPoint : EntryPoints) {
2885 // Ops[0] = Execution Model
2886 // Ops[1] = EntryPoint ID
2887 // Ops[2] = Name (Literal String)
2888 // ...
2889 //
2890 // TODO: Do we need to consider Interface ID for forward references???
2891 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05002892 const StringRef &name = EntryPoint.first->getName();
SJW01901d92020-05-21 08:58:31 -05002893 Ops << spv::ExecutionModelGLCompute << EntryPoint.second << name;
David Neto22f144c2017-06-12 14:26:21 -04002894
SJW806a5d82020-07-15 12:51:38 -05002895 for (auto &Interface : EntryPointInterfaces) {
SJW01901d92020-05-21 08:58:31 -05002896 Ops << Interface;
David Neto22f144c2017-06-12 14:26:21 -04002897 }
2898
SJWf93f5f32020-05-05 07:27:56 -05002899 addSPIRVInst<kEntryPoints>(spv::OpEntryPoint, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002900 }
2901
alan-baker3b609772020-09-03 19:10:17 -04002902 if (BuiltinDimVec.empty()) {
2903 for (auto EntryPoint : EntryPoints) {
2904 const MDNode *MD = dyn_cast<Function>(EntryPoint.first)
2905 ->getMetadata("reqd_work_group_size");
2906 if ((MD != nullptr) && !clspv::Option::NonUniformNDRangeSupported()) {
2907 //
2908 // Generate OpExecutionMode
2909 //
David Neto22f144c2017-06-12 14:26:21 -04002910
alan-baker3b609772020-09-03 19:10:17 -04002911 // Ops[0] = Entry Point ID
2912 // Ops[1] = Execution Mode
2913 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
2914 Ops.clear();
2915 Ops << EntryPoint.second << spv::ExecutionModeLocalSize;
2916
2917 uint32_t XDim = static_cast<uint32_t>(
2918 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
2919 uint32_t YDim = static_cast<uint32_t>(
2920 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
2921 uint32_t ZDim = static_cast<uint32_t>(
2922 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
2923
2924 Ops << XDim << YDim << ZDim;
2925
2926 addSPIRVInst<kExecutionModes>(spv::OpExecutionMode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002927 }
David Neto22f144c2017-06-12 14:26:21 -04002928 }
2929 }
2930
2931 //
2932 // Generate OpSource.
2933 //
2934 // Ops[0] = SourceLanguage ID
2935 // Ops[1] = Version (LiteralNum)
2936 //
SJW01901d92020-05-21 08:58:31 -05002937 uint32_t LangID = spv::SourceLanguageUnknown;
2938 uint32_t LangVer = 0;
Kévin Petitf0515712020-01-07 18:29:20 +00002939 switch (clspv::Option::Language()) {
2940 case clspv::Option::SourceLanguage::OpenCL_C_10:
SJW01901d92020-05-21 08:58:31 -05002941 LangID = spv::SourceLanguageOpenCL_C;
2942 LangVer = 100;
Kévin Petitf0515712020-01-07 18:29:20 +00002943 break;
2944 case clspv::Option::SourceLanguage::OpenCL_C_11:
SJW01901d92020-05-21 08:58:31 -05002945 LangID = spv::SourceLanguageOpenCL_C;
2946 LangVer = 110;
Kévin Petitf0515712020-01-07 18:29:20 +00002947 break;
2948 case clspv::Option::SourceLanguage::OpenCL_C_12:
SJW01901d92020-05-21 08:58:31 -05002949 LangID = spv::SourceLanguageOpenCL_C;
2950 LangVer = 120;
Kévin Petitf0515712020-01-07 18:29:20 +00002951 break;
2952 case clspv::Option::SourceLanguage::OpenCL_C_20:
SJW01901d92020-05-21 08:58:31 -05002953 LangID = spv::SourceLanguageOpenCL_C;
2954 LangVer = 200;
Kévin Petitf0515712020-01-07 18:29:20 +00002955 break;
Kévin Petit77838ff2020-10-19 18:54:51 +01002956 case clspv::Option::SourceLanguage::OpenCL_C_30:
2957 LangID = spv::SourceLanguageOpenCL_C;
2958 LangVer = 300;
2959 break;
Kévin Petitf0515712020-01-07 18:29:20 +00002960 case clspv::Option::SourceLanguage::OpenCL_CPP:
SJW01901d92020-05-21 08:58:31 -05002961 LangID = spv::SourceLanguageOpenCL_CPP;
2962 LangVer = 100;
Kévin Petitf0515712020-01-07 18:29:20 +00002963 break;
2964 default:
Kévin Petitf0515712020-01-07 18:29:20 +00002965 break;
Kévin Petit0fc88042019-04-09 23:25:02 +01002966 }
David Neto22f144c2017-06-12 14:26:21 -04002967
SJW01901d92020-05-21 08:58:31 -05002968 Ops.clear();
2969 Ops << LangID << LangVer;
SJWf93f5f32020-05-05 07:27:56 -05002970 addSPIRVInst<kDebug>(spv::OpSource, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002971
2972 if (!BuiltinDimVec.empty()) {
2973 //
2974 // Generate OpDecorates for x/y/z dimension.
2975 //
2976 // Ops[0] = Target ID
2977 // Ops[1] = Decoration (SpecId)
David Neto257c3892018-04-11 13:19:45 -04002978 // Ops[2] = Specialization Constant ID (Literal Number)
David Neto22f144c2017-06-12 14:26:21 -04002979
2980 // X Dimension
2981 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002982 Ops << BuiltinDimVec[0] << spv::DecorationSpecId << 0;
SJWf93f5f32020-05-05 07:27:56 -05002983 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002984
2985 // Y Dimension
2986 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002987 Ops << BuiltinDimVec[1] << spv::DecorationSpecId << 1;
SJWf93f5f32020-05-05 07:27:56 -05002988 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002989
2990 // Z Dimension
2991 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002992 Ops << BuiltinDimVec[2] << spv::DecorationSpecId << 2;
SJWf93f5f32020-05-05 07:27:56 -05002993 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002994 }
2995}
2996
David Netob6e2e062018-04-25 10:32:06 -04002997void SPIRVProducerPass::GenerateEntryPointInitialStores() {
2998 // Work around a driver bug. Initializers on Private variables might not
2999 // work. So the start of the kernel should store the initializer value to the
3000 // variables. Yes, *every* entry point pays this cost if *any* entry point
3001 // uses this builtin. At this point I judge this to be an acceptable tradeoff
3002 // of complexity vs. runtime, for a broken driver.
alan-bakerb6b09dc2018-11-08 16:59:28 -05003003 // TODO(dneto): Remove this at some point once fixed drivers are widely
3004 // available.
SJW01901d92020-05-21 08:58:31 -05003005 if (WorkgroupSizeVarID.isValid()) {
3006 assert(WorkgroupSizeValueID.isValid());
David Netob6e2e062018-04-25 10:32:06 -04003007
SJWf93f5f32020-05-05 07:27:56 -05003008 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05003009 Ops << WorkgroupSizeVarID << WorkgroupSizeValueID;
David Netob6e2e062018-04-25 10:32:06 -04003010
SJWf93f5f32020-05-05 07:27:56 -05003011 addSPIRVInst(spv::OpStore, Ops);
David Netob6e2e062018-04-25 10:32:06 -04003012 }
3013}
3014
David Neto22f144c2017-06-12 14:26:21 -04003015void SPIRVProducerPass::GenerateFuncBody(Function &F) {
David Neto22f144c2017-06-12 14:26:21 -04003016 ValueMapType &VMap = getValueMap();
3017
David Netob6e2e062018-04-25 10:32:06 -04003018 const bool IsKernel = F.getCallingConv() == CallingConv::SPIR_KERNEL;
David Neto22f144c2017-06-12 14:26:21 -04003019
3020 for (BasicBlock &BB : F) {
3021 // Register BasicBlock to ValueMap.
David Neto22f144c2017-06-12 14:26:21 -04003022
3023 //
3024 // Generate OpLabel for Basic Block.
3025 //
SJWf93f5f32020-05-05 07:27:56 -05003026 VMap[&BB] = addSPIRVInst(spv::OpLabel);
David Neto22f144c2017-06-12 14:26:21 -04003027
David Neto6dcd4712017-06-23 11:06:47 -04003028 // OpVariable instructions must come first.
3029 for (Instruction &I : BB) {
alan-baker5b86ed72019-02-15 08:26:50 -05003030 if (auto *alloca = dyn_cast<AllocaInst>(&I)) {
3031 // Allocating a pointer requires variable pointers.
3032 if (alloca->getAllocatedType()->isPointerTy()) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003033 setVariablePointersCapabilities(
3034 alloca->getAllocatedType()->getPointerAddressSpace());
alan-baker5b86ed72019-02-15 08:26:50 -05003035 }
David Neto6dcd4712017-06-23 11:06:47 -04003036 GenerateInstruction(I);
3037 }
3038 }
3039
David Neto22f144c2017-06-12 14:26:21 -04003040 if (&BB == &F.getEntryBlock() && IsKernel) {
David Netob6e2e062018-04-25 10:32:06 -04003041 if (clspv::Option::HackInitializers()) {
3042 GenerateEntryPointInitialStores();
3043 }
David Neto22f144c2017-06-12 14:26:21 -04003044 }
3045
3046 for (Instruction &I : BB) {
David Neto6dcd4712017-06-23 11:06:47 -04003047 if (!isa<AllocaInst>(I)) {
3048 GenerateInstruction(I);
3049 }
David Neto22f144c2017-06-12 14:26:21 -04003050 }
3051 }
3052}
3053
3054spv::Op SPIRVProducerPass::GetSPIRVCmpOpcode(CmpInst *I) {
3055 const std::map<CmpInst::Predicate, spv::Op> Map = {
3056 {CmpInst::ICMP_EQ, spv::OpIEqual},
3057 {CmpInst::ICMP_NE, spv::OpINotEqual},
3058 {CmpInst::ICMP_UGT, spv::OpUGreaterThan},
3059 {CmpInst::ICMP_UGE, spv::OpUGreaterThanEqual},
3060 {CmpInst::ICMP_ULT, spv::OpULessThan},
3061 {CmpInst::ICMP_ULE, spv::OpULessThanEqual},
3062 {CmpInst::ICMP_SGT, spv::OpSGreaterThan},
3063 {CmpInst::ICMP_SGE, spv::OpSGreaterThanEqual},
3064 {CmpInst::ICMP_SLT, spv::OpSLessThan},
3065 {CmpInst::ICMP_SLE, spv::OpSLessThanEqual},
3066 {CmpInst::FCMP_OEQ, spv::OpFOrdEqual},
3067 {CmpInst::FCMP_OGT, spv::OpFOrdGreaterThan},
3068 {CmpInst::FCMP_OGE, spv::OpFOrdGreaterThanEqual},
3069 {CmpInst::FCMP_OLT, spv::OpFOrdLessThan},
3070 {CmpInst::FCMP_OLE, spv::OpFOrdLessThanEqual},
3071 {CmpInst::FCMP_ONE, spv::OpFOrdNotEqual},
3072 {CmpInst::FCMP_UEQ, spv::OpFUnordEqual},
3073 {CmpInst::FCMP_UGT, spv::OpFUnordGreaterThan},
3074 {CmpInst::FCMP_UGE, spv::OpFUnordGreaterThanEqual},
3075 {CmpInst::FCMP_ULT, spv::OpFUnordLessThan},
3076 {CmpInst::FCMP_ULE, spv::OpFUnordLessThanEqual},
3077 {CmpInst::FCMP_UNE, spv::OpFUnordNotEqual}};
3078
3079 assert(0 != Map.count(I->getPredicate()));
3080
3081 return Map.at(I->getPredicate());
3082}
3083
3084spv::Op SPIRVProducerPass::GetSPIRVCastOpcode(Instruction &I) {
3085 const std::map<unsigned, spv::Op> Map{
3086 {Instruction::Trunc, spv::OpUConvert},
3087 {Instruction::ZExt, spv::OpUConvert},
3088 {Instruction::SExt, spv::OpSConvert},
3089 {Instruction::FPToUI, spv::OpConvertFToU},
3090 {Instruction::FPToSI, spv::OpConvertFToS},
3091 {Instruction::UIToFP, spv::OpConvertUToF},
3092 {Instruction::SIToFP, spv::OpConvertSToF},
3093 {Instruction::FPTrunc, spv::OpFConvert},
3094 {Instruction::FPExt, spv::OpFConvert},
3095 {Instruction::BitCast, spv::OpBitcast}};
3096
3097 assert(0 != Map.count(I.getOpcode()));
3098
3099 return Map.at(I.getOpcode());
3100}
3101
3102spv::Op SPIRVProducerPass::GetSPIRVBinaryOpcode(Instruction &I) {
Kévin Petit24272b62018-10-18 19:16:12 +00003103 if (I.getType()->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003104 switch (I.getOpcode()) {
3105 default:
3106 break;
3107 case Instruction::Or:
3108 return spv::OpLogicalOr;
3109 case Instruction::And:
3110 return spv::OpLogicalAnd;
3111 case Instruction::Xor:
3112 return spv::OpLogicalNotEqual;
3113 }
3114 }
3115
alan-bakerb6b09dc2018-11-08 16:59:28 -05003116 const std::map<unsigned, spv::Op> Map{
David Neto22f144c2017-06-12 14:26:21 -04003117 {Instruction::Add, spv::OpIAdd},
3118 {Instruction::FAdd, spv::OpFAdd},
3119 {Instruction::Sub, spv::OpISub},
3120 {Instruction::FSub, spv::OpFSub},
3121 {Instruction::Mul, spv::OpIMul},
3122 {Instruction::FMul, spv::OpFMul},
3123 {Instruction::UDiv, spv::OpUDiv},
3124 {Instruction::SDiv, spv::OpSDiv},
3125 {Instruction::FDiv, spv::OpFDiv},
3126 {Instruction::URem, spv::OpUMod},
3127 {Instruction::SRem, spv::OpSRem},
3128 {Instruction::FRem, spv::OpFRem},
3129 {Instruction::Or, spv::OpBitwiseOr},
3130 {Instruction::Xor, spv::OpBitwiseXor},
3131 {Instruction::And, spv::OpBitwiseAnd},
3132 {Instruction::Shl, spv::OpShiftLeftLogical},
3133 {Instruction::LShr, spv::OpShiftRightLogical},
3134 {Instruction::AShr, spv::OpShiftRightArithmetic}};
3135
3136 assert(0 != Map.count(I.getOpcode()));
3137
3138 return Map.at(I.getOpcode());
3139}
3140
SJW806a5d82020-07-15 12:51:38 -05003141SPIRVID SPIRVProducerPass::getSPIRVBuiltin(spv::BuiltIn BID,
3142 spv::Capability Cap) {
3143 SPIRVID RID;
3144
3145 auto ii = BuiltinConstantMap.find(BID);
3146
3147 if (ii != BuiltinConstantMap.end()) {
3148 return ii->second;
3149 } else {
SJW806a5d82020-07-15 12:51:38 -05003150 addCapability(Cap);
3151
3152 Type *type = PointerType::get(IntegerType::get(module->getContext(), 32),
3153 AddressSpace::Input);
3154
3155 RID = addSPIRVGlobalVariable(getSPIRVType(type), spv::StorageClassInput);
3156
3157 BuiltinConstantMap[BID] = RID;
3158
3159 //
3160 // Generate OpDecorate.
3161 //
3162 // Ops[0] : target
3163 // Ops[1] : decoration
3164 // Ops[2] : SpecId
3165 SPIRVOperandVec Ops;
3166 Ops << RID << spv::DecorationBuiltIn << static_cast<int>(BID);
3167
3168 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
3169 }
3170
3171 return RID;
3172}
3173
3174SPIRVID
3175SPIRVProducerPass::GenerateClspvInstruction(CallInst *Call,
3176 const FunctionInfo &FuncInfo) {
3177 SPIRVID RID;
3178
3179 switch (FuncInfo.getType()) {
3180 case Builtins::kClspvCompositeConstruct:
3181 RID = addSPIRVPlaceholder(Call);
3182 break;
3183 case Builtins::kClspvResource: {
3184 if (ResourceVarDeferredLoadCalls.count(Call) && Call->hasNUsesOrMore(1)) {
3185 // Generate an OpLoad
3186 SPIRVOperandVec Ops;
3187
3188 Ops << Call->getType()->getPointerElementType()
3189 << ResourceVarDeferredLoadCalls[Call];
3190
3191 RID = addSPIRVInst(spv::OpLoad, Ops);
3192
3193 } else {
3194 // This maps to an OpVariable we've already generated.
3195 // No code is generated for the call.
3196 }
3197 break;
3198 }
3199 case Builtins::kClspvLocal: {
3200 // Don't codegen an instruction here, but instead map this call directly
3201 // to the workgroup variable id.
3202 int spec_id = static_cast<int>(
3203 cast<ConstantInt>(Call->getOperand(0))->getSExtValue());
3204 const auto &info = LocalSpecIdInfoMap[spec_id];
3205 RID = info.variable_id;
3206 break;
3207 }
3208 case Builtins::kClspvSamplerVarLiteral: {
3209 // Sampler initializers become a load of the corresponding sampler.
3210 // Map this to a load from the variable.
3211 const auto third_param = static_cast<unsigned>(
3212 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue());
3213 auto sampler_value = third_param;
3214 if (clspv::Option::UseSamplerMap()) {
3215 sampler_value = getSamplerMap()[third_param].first;
3216 }
3217
3218 // Generate an OpLoad
3219 SPIRVOperandVec Ops;
3220
3221 Ops << SamplerTy->getPointerElementType()
3222 << SamplerLiteralToIDMap[sampler_value];
3223
3224 RID = addSPIRVInst(spv::OpLoad, Ops);
3225 break;
3226 }
3227 case Builtins::kSpirvAtomicXor: {
3228 // Handle SPIR-V intrinsics
3229 SPIRVOperandVec Ops;
3230
3231 if (!Call->getType()->isVoidTy()) {
3232 Ops << Call->getType();
3233 }
3234
3235 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
3236 Ops << Call->getArgOperand(i);
3237 }
3238
3239 RID = addSPIRVInst(spv::OpAtomicXor, Ops);
3240 break;
3241 }
3242 case Builtins::kSpirvOp: {
3243 // Handle SPIR-V intrinsics
3244 auto *arg0 = dyn_cast<ConstantInt>(Call->getArgOperand(0));
3245 spv::Op opcode = static_cast<spv::Op>(arg0->getZExtValue());
3246 if (opcode != spv::OpNop) {
3247 SPIRVOperandVec Ops;
3248
3249 if (!Call->getType()->isVoidTy()) {
3250 Ops << Call->getType();
3251 }
3252
3253 for (unsigned i = 1; i < Call->getNumArgOperands(); i++) {
3254 Ops << Call->getArgOperand(i);
3255 }
3256
3257 RID = addSPIRVInst(opcode, Ops);
3258 }
3259 break;
3260 }
3261 case Builtins::kSpirvCopyMemory: {
3262 //
3263 // Generate OpCopyMemory.
3264 //
3265
3266 // Ops[0] = Dst ID
3267 // Ops[1] = Src ID
3268 // Ops[2] = Memory Access
3269 // Ops[3] = Alignment
3270
3271 auto IsVolatile =
3272 dyn_cast<ConstantInt>(Call->getArgOperand(3))->getZExtValue() != 0;
3273
3274 auto VolatileMemoryAccess = (IsVolatile) ? spv::MemoryAccessVolatileMask
3275 : spv::MemoryAccessMaskNone;
3276
3277 auto MemoryAccess = VolatileMemoryAccess | spv::MemoryAccessAlignedMask;
3278
3279 auto Alignment =
3280 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
3281
3282 SPIRVOperandVec Ops;
3283 Ops << Call->getArgOperand(0) << Call->getArgOperand(1) << MemoryAccess
3284 << static_cast<uint32_t>(Alignment);
3285
3286 RID = addSPIRVInst(spv::OpCopyMemory, Ops);
3287 break;
3288 }
3289 default:
3290 llvm_unreachable("Unknown CLSPV Instruction");
3291 break;
3292 }
3293 return RID;
3294}
3295
3296SPIRVID
3297SPIRVProducerPass::GenerateImageInstruction(CallInst *Call,
3298 const FunctionInfo &FuncInfo) {
3299 SPIRVID RID;
3300
3301 LLVMContext &Context = module->getContext();
3302 switch (FuncInfo.getType()) {
3303 case Builtins::kReadImagef:
3304 case Builtins::kReadImageh:
3305 case Builtins::kReadImagei:
3306 case Builtins::kReadImageui: {
3307 // read_image is converted to OpSampledImage and OpImageSampleExplicitLod.
3308 // Additionally, OpTypeSampledImage is generated.
alan-bakerf6bc8252020-09-23 14:58:55 -04003309 const auto image_ty = Call->getArgOperand(0)->getType();
SJW806a5d82020-07-15 12:51:38 -05003310 const auto &pi = FuncInfo.getParameter(1);
3311 if (pi.isSampler()) {
3312 //
3313 // Generate OpSampledImage.
3314 //
3315 // Ops[0] = Result Type ID
3316 // Ops[1] = Image ID
3317 // Ops[2] = Sampler ID
3318 //
3319 SPIRVOperandVec Ops;
3320
3321 Value *Image = Call->getArgOperand(0);
3322 Value *Sampler = Call->getArgOperand(1);
3323 Value *Coordinate = Call->getArgOperand(2);
3324
3325 TypeMapType &OpImageTypeMap = getImageTypeMap();
3326 Type *ImageTy = Image->getType()->getPointerElementType();
3327 SPIRVID ImageTyID = OpImageTypeMap[ImageTy];
3328
3329 Ops << ImageTyID << Image << Sampler;
3330
3331 SPIRVID SampledImageID = addSPIRVInst(spv::OpSampledImage, Ops);
3332
3333 //
3334 // Generate OpImageSampleExplicitLod.
3335 //
3336 // Ops[0] = Result Type ID
3337 // Ops[1] = Sampled Image ID
3338 // Ops[2] = Coordinate ID
3339 // Ops[3] = Image Operands Type ID
3340 // Ops[4] ... Ops[n] = Operands ID
3341 //
3342 Ops.clear();
3343
3344 const bool is_int_image = IsIntImageType(Image->getType());
3345 SPIRVID result_type;
3346 if (is_int_image) {
3347 result_type = v4int32ID;
3348 } else {
3349 result_type = getSPIRVType(Call->getType());
3350 }
3351
3352 Constant *CstFP0 = ConstantFP::get(Context, APFloat(0.0f));
3353 Ops << result_type << SampledImageID << Coordinate
3354 << spv::ImageOperandsLodMask << CstFP0;
3355
3356 RID = addSPIRVInst(spv::OpImageSampleExplicitLod, Ops);
3357
3358 if (is_int_image) {
3359 // Generate the bitcast.
3360 Ops.clear();
3361 Ops << Call->getType() << RID;
3362 RID = addSPIRVInst(spv::OpBitcast, Ops);
3363 }
alan-bakerf6bc8252020-09-23 14:58:55 -04003364 } else if (IsStorageImageType(image_ty)) {
3365 // read_image on a storage image is mapped to OpImageRead.
3366 Value *Image = Call->getArgOperand(0);
3367 Value *Coordinate = Call->getArgOperand(1);
3368
3369 //
3370 // Generate OpImageRead
3371 //
3372 // Ops[0] = Result Type ID
3373 // Ops[1] = Image ID
3374 // Ops[2] = Coordinate
3375 // No optional image operands.
3376 //
3377 SPIRVOperandVec Ops;
3378
3379 const bool is_int_image = IsIntImageType(Image->getType());
3380 SPIRVID result_type;
3381 if (is_int_image) {
3382 result_type = v4int32ID;
3383 } else {
3384 result_type = getSPIRVType(Call->getType());
3385 }
3386
3387 Ops << result_type << Image << Coordinate;
3388 RID = addSPIRVInst(spv::OpImageRead, Ops);
3389
3390 if (is_int_image) {
3391 // Generate the bitcast.
3392 Ops.clear();
3393 Ops << Call->getType() << RID;
3394 RID = addSPIRVInst(spv::OpBitcast, Ops);
3395 }
3396
3397 // OpImageRead requires StorageImageReadWithoutFormat.
3398 addCapability(spv::CapabilityStorageImageReadWithoutFormat);
SJW806a5d82020-07-15 12:51:38 -05003399 } else {
alan-bakerf6bc8252020-09-23 14:58:55 -04003400 // read_image on a sampled image (without a sampler) is mapped to
3401 // OpImageFetch.
SJW806a5d82020-07-15 12:51:38 -05003402 Value *Image = Call->getArgOperand(0);
3403 Value *Coordinate = Call->getArgOperand(1);
3404
3405 //
3406 // Generate OpImageFetch
3407 //
3408 // Ops[0] = Result Type ID
3409 // Ops[1] = Image ID
3410 // Ops[2] = Coordinate ID
3411 // Ops[3] = Lod
3412 // Ops[4] = 0
3413 //
3414 SPIRVOperandVec Ops;
3415
3416 const bool is_int_image = IsIntImageType(Image->getType());
3417 SPIRVID result_type;
3418 if (is_int_image) {
3419 result_type = v4int32ID;
3420 } else {
3421 result_type = getSPIRVType(Call->getType());
3422 }
3423
3424 Ops << result_type << Image << Coordinate << spv::ImageOperandsLodMask
3425 << getSPIRVInt32Constant(0);
3426
3427 RID = addSPIRVInst(spv::OpImageFetch, Ops);
3428
3429 if (is_int_image) {
3430 // Generate the bitcast.
3431 Ops.clear();
3432 Ops << Call->getType() << RID;
3433 RID = addSPIRVInst(spv::OpBitcast, Ops);
3434 }
3435 }
3436 break;
3437 }
3438
3439 case Builtins::kWriteImagef:
3440 case Builtins::kWriteImageh:
3441 case Builtins::kWriteImagei:
3442 case Builtins::kWriteImageui: {
3443 // write_image is mapped to OpImageWrite.
3444 //
3445 // Generate OpImageWrite.
3446 //
3447 // Ops[0] = Image ID
3448 // Ops[1] = Coordinate ID
3449 // Ops[2] = Texel ID
3450 // Ops[3] = (Optional) Image Operands Type (Literal Number)
3451 // Ops[4] ... Ops[n] = (Optional) Operands ID
3452 //
3453 SPIRVOperandVec Ops;
3454
3455 Value *Image = Call->getArgOperand(0);
3456 Value *Coordinate = Call->getArgOperand(1);
3457 Value *Texel = Call->getArgOperand(2);
3458
3459 SPIRVID TexelID = getSPIRVValue(Texel);
3460
3461 const bool is_int_image = IsIntImageType(Image->getType());
3462 if (is_int_image) {
3463 // Generate a bitcast to v4int and use it as the texel value.
3464 Ops << v4int32ID << TexelID;
3465 TexelID = addSPIRVInst(spv::OpBitcast, Ops);
3466 Ops.clear();
3467 }
3468 Ops << Image << Coordinate << TexelID;
SJW806a5d82020-07-15 12:51:38 -05003469 RID = addSPIRVInst(spv::OpImageWrite, Ops);
alan-bakerf6bc8252020-09-23 14:58:55 -04003470
3471 // Image writes require StorageImageWriteWithoutFormat.
3472 addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
SJW806a5d82020-07-15 12:51:38 -05003473 break;
3474 }
3475
3476 case Builtins::kGetImageHeight:
3477 case Builtins::kGetImageWidth:
3478 case Builtins::kGetImageDepth:
3479 case Builtins::kGetImageDim: {
3480 // get_image_* is mapped to OpImageQuerySize or OpImageQuerySizeLod
3481 addCapability(spv::CapabilityImageQuery);
3482
3483 //
3484 // Generate OpImageQuerySize[Lod]
3485 //
3486 // Ops[0] = Image ID
3487 //
3488 // Result type has components equal to the dimensionality of the image,
3489 // plus 1 if the image is arrayed.
3490 //
3491 // %sizes = OpImageQuerySize[Lod] %uint[2|3|4] %im [%uint_0]
3492 SPIRVOperandVec Ops;
3493
3494 // Implement:
3495 // %sizes = OpImageQuerySize[Lod] %uint[2|3|4] %im [%uint_0]
3496 SPIRVID SizesTypeID;
3497
3498 Value *Image = Call->getArgOperand(0);
3499 const uint32_t dim = ImageDimensionality(Image->getType());
3500 const uint32_t components =
3501 dim + (IsArrayImageType(Image->getType()) ? 1 : 0);
3502 if (components == 1) {
3503 SizesTypeID = getSPIRVType(Type::getInt32Ty(Context));
3504 } else {
3505 SizesTypeID = getSPIRVType(
3506 FixedVectorType::get(Type::getInt32Ty(Context), components));
3507 }
3508 Ops << SizesTypeID << Image;
3509 spv::Op query_opcode = spv::OpImageQuerySize;
3510 if (IsSampledImageType(Image->getType())) {
3511 query_opcode = spv::OpImageQuerySizeLod;
3512 // Need explicit 0 for Lod operand.
3513 Ops << getSPIRVInt32Constant(0);
3514 }
3515
3516 RID = addSPIRVInst(query_opcode, Ops);
3517
3518 // May require an extra instruction to create the appropriate result of
3519 // the builtin function.
3520 if (FuncInfo.getType() == Builtins::kGetImageDim) {
3521 if (dim == 3) {
3522 // get_image_dim returns an int4 for 3D images.
3523 //
3524
3525 // Implement:
3526 // %result = OpCompositeConstruct %uint4 %sizes %uint_0
3527 Ops.clear();
3528 Ops << FixedVectorType::get(Type::getInt32Ty(Context), 4) << RID
3529 << getSPIRVInt32Constant(0);
3530
3531 RID = addSPIRVInst(spv::OpCompositeConstruct, Ops);
3532 } else if (dim != components) {
3533 // get_image_dim return an int2 regardless of the arrayedness of the
3534 // image. If the image is arrayed an element must be dropped from the
3535 // query result.
3536 //
3537
3538 // Implement:
3539 // %result = OpVectorShuffle %uint2 %sizes %sizes 0 1
3540 Ops.clear();
3541 Ops << FixedVectorType::get(Type::getInt32Ty(Context), 2) << RID << RID
3542 << 0 << 1;
3543
3544 RID = addSPIRVInst(spv::OpVectorShuffle, Ops);
3545 }
3546 } else if (components > 1) {
3547 // Implement:
3548 // %result = OpCompositeExtract %uint %sizes <component number>
3549 Ops.clear();
3550 Ops << Call->getType() << RID;
3551
3552 uint32_t component = 0;
3553 if (FuncInfo.getType() == Builtins::kGetImageHeight)
3554 component = 1;
3555 else if (FuncInfo.getType() == Builtins::kGetImageDepth)
3556 component = 2;
3557 Ops << component;
3558
3559 RID = addSPIRVInst(spv::OpCompositeExtract, Ops);
3560 }
3561 break;
3562 }
3563 default:
3564 llvm_unreachable("Unsupported Image builtin");
3565 }
3566
3567 return RID;
3568}
3569
3570SPIRVID
3571SPIRVProducerPass::GenerateSubgroupInstruction(CallInst *Call,
3572 const FunctionInfo &FuncInfo) {
3573 SPIRVID RID;
3574
3575 // requires SPIRV version 1.3 or greater
3576 if (SpvVersion() != SPIRVVersion::SPIRV_1_3) {
3577 // llvm_unreachable("SubGroups extension requires SPIRV 1.3 or greater");
3578 // TODO(sjw): error out gracefully
3579 }
3580
3581 auto loadBuiltin = [this, Call](spv::BuiltIn spvBI,
3582 spv::Capability spvCap =
3583 spv::CapabilityGroupNonUniform) {
3584 SPIRVOperandVec Ops;
3585 Ops << Call->getType() << this->getSPIRVBuiltin(spvBI, spvCap);
3586
3587 return addSPIRVInst(spv::OpLoad, Ops);
3588 };
3589
3590 spv::Op op = spv::OpNop;
3591 switch (FuncInfo.getType()) {
3592 case Builtins::kGetSubGroupSize:
3593 return loadBuiltin(spv::BuiltInSubgroupSize);
3594 case Builtins::kGetNumSubGroups:
3595 return loadBuiltin(spv::BuiltInNumSubgroups);
3596 case Builtins::kGetSubGroupId:
3597 return loadBuiltin(spv::BuiltInSubgroupId);
3598 case Builtins::kGetSubGroupLocalId:
3599 return loadBuiltin(spv::BuiltInSubgroupLocalInvocationId);
3600
3601 case Builtins::kSubGroupBroadcast:
3602 if (SpvVersion() < SPIRVVersion::SPIRV_1_5 &&
3603 !dyn_cast<ConstantInt>(Call->getOperand(1))) {
3604 llvm_unreachable("sub_group_broadcast requires constant lane Id for "
3605 "SPIRV version < 1.5");
3606 }
3607 addCapability(spv::CapabilityGroupNonUniformBallot);
3608 op = spv::OpGroupNonUniformBroadcast;
3609 break;
3610
3611 case Builtins::kSubGroupAll:
3612 addCapability(spv::CapabilityGroupNonUniformVote);
3613 op = spv::OpGroupNonUniformAll;
3614 break;
3615 case Builtins::kSubGroupAny:
3616 addCapability(spv::CapabilityGroupNonUniformVote);
3617 op = spv::OpGroupNonUniformAny;
3618 break;
3619 case Builtins::kSubGroupReduceAdd:
3620 case Builtins::kSubGroupScanExclusiveAdd:
3621 case Builtins::kSubGroupScanInclusiveAdd: {
3622 addCapability(spv::CapabilityGroupNonUniformArithmetic);
3623 if (FuncInfo.getParameter(0).type_id == Type::IntegerTyID) {
3624 op = spv::OpGroupNonUniformIAdd;
3625 } else {
3626 op = spv::OpGroupNonUniformFAdd;
3627 }
3628 break;
3629 }
3630 case Builtins::kSubGroupReduceMin:
3631 case Builtins::kSubGroupScanExclusiveMin:
3632 case Builtins::kSubGroupScanInclusiveMin: {
3633 addCapability(spv::CapabilityGroupNonUniformArithmetic);
3634 auto &param = FuncInfo.getParameter(0);
3635 if (param.type_id == Type::IntegerTyID) {
3636 op = param.is_signed ? spv::OpGroupNonUniformSMin
3637 : spv::OpGroupNonUniformUMin;
3638 } else {
3639 op = spv::OpGroupNonUniformFMin;
3640 }
3641 break;
3642 }
3643 case Builtins::kSubGroupReduceMax:
3644 case Builtins::kSubGroupScanExclusiveMax:
3645 case Builtins::kSubGroupScanInclusiveMax: {
3646 addCapability(spv::CapabilityGroupNonUniformArithmetic);
3647 auto &param = FuncInfo.getParameter(0);
3648 if (param.type_id == Type::IntegerTyID) {
3649 op = param.is_signed ? spv::OpGroupNonUniformSMax
3650 : spv::OpGroupNonUniformUMax;
3651 } else {
3652 op = spv::OpGroupNonUniformFMax;
3653 }
3654 break;
3655 }
3656
3657 case Builtins::kGetEnqueuedNumSubGroups:
3658 // TODO(sjw): requires CapabilityKernel (incompatible with Shader)
3659 case Builtins::kGetMaxSubGroupSize:
3660 // TODO(sjw): use SpecConstant, capability Kernel (incompatible with Shader)
3661 case Builtins::kSubGroupBarrier:
3662 case Builtins::kSubGroupReserveReadPipe:
3663 case Builtins::kSubGroupReserveWritePipe:
3664 case Builtins::kSubGroupCommitReadPipe:
3665 case Builtins::kSubGroupCommitWritePipe:
3666 case Builtins::kGetKernelSubGroupCountForNdrange:
3667 case Builtins::kGetKernelMaxSubGroupSizeForNdrange:
3668 default:
3669 Call->print(errs());
3670 llvm_unreachable("Unsupported sub_group operation");
3671 break;
3672 }
3673
3674 assert(op != spv::OpNop);
3675
3676 SPIRVOperandVec Operands;
3677
3678 //
3679 // Generate OpGroupNonUniform*
3680 //
3681 // Ops[0] = Result Type ID
3682 // Ops[1] = ScopeSubgroup
3683 // Ops[2] = Value ID
3684 // Ops[3] = Local ID
3685
3686 // The result type.
3687 Operands << Call->getType();
3688
3689 // Subgroup Scope
3690 Operands << getSPIRVInt32Constant(spv::ScopeSubgroup);
3691
3692 switch (FuncInfo.getType()) {
3693 case Builtins::kSubGroupReduceAdd:
3694 case Builtins::kSubGroupReduceMin:
3695 case Builtins::kSubGroupReduceMax:
3696 Operands << spv::GroupOperationReduce;
3697 break;
3698 case Builtins::kSubGroupScanExclusiveAdd:
3699 case Builtins::kSubGroupScanExclusiveMin:
3700 case Builtins::kSubGroupScanExclusiveMax:
3701 Operands << spv::GroupOperationExclusiveScan;
3702 break;
3703 case Builtins::kSubGroupScanInclusiveAdd:
3704 case Builtins::kSubGroupScanInclusiveMin:
3705 case Builtins::kSubGroupScanInclusiveMax:
3706 Operands << spv::GroupOperationInclusiveScan;
3707 break;
3708 default:
3709 break;
3710 }
3711
3712 for (Use &use : Call->arg_operands()) {
3713 Operands << use.get();
3714 }
3715
3716 return addSPIRVInst(op, Operands);
3717}
3718
3719SPIRVID SPIRVProducerPass::GenerateInstructionFromCall(CallInst *Call) {
3720 LLVMContext &Context = module->getContext();
3721
3722 auto &func_info = Builtins::Lookup(Call->getCalledFunction());
3723 auto func_type = func_info.getType();
3724
3725 if (BUILTIN_IN_GROUP(func_type, Clspv)) {
3726 return GenerateClspvInstruction(Call, func_info);
3727 } else if (BUILTIN_IN_GROUP(func_type, Image)) {
3728 return GenerateImageInstruction(Call, func_info);
3729 } else if (BUILTIN_IN_GROUP(func_type, SubgroupsKHR)) {
3730 return GenerateSubgroupInstruction(Call, func_info);
3731 }
3732
3733 SPIRVID RID;
3734
3735 switch (func_type) {
3736 case Builtins::kPopcount: {
3737 //
3738 // Generate OpBitCount
3739 //
3740 // Ops[0] = Result Type ID
3741 // Ops[1] = Base ID
3742 SPIRVOperandVec Ops;
3743 Ops << Call->getType() << Call->getOperand(0);
3744
3745 RID = addSPIRVInst(spv::OpBitCount, Ops);
3746 break;
3747 }
3748 default: {
3749 glsl::ExtInst EInst = getDirectOrIndirectExtInstEnum(func_info);
3750
3751 if (EInst) {
3752 SPIRVID ExtInstImportID = getOpExtInstImportID();
3753
3754 //
3755 // Generate OpExtInst.
3756 //
3757
3758 // Ops[0] = Result Type ID
3759 // Ops[1] = Set ID (OpExtInstImport ID)
3760 // Ops[2] = Instruction Number (Literal Number)
3761 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
3762 SPIRVOperandVec Ops;
3763
3764 Ops << Call->getType() << ExtInstImportID << EInst;
3765
3766 for (auto &use : Call->arg_operands()) {
3767 Ops << use.get();
3768 }
3769
3770 RID = addSPIRVInst(spv::OpExtInst, Ops);
3771
3772 const auto IndirectExtInst = getIndirectExtInstEnum(func_info);
3773 if (IndirectExtInst != kGlslExtInstBad) {
SJW806a5d82020-07-15 12:51:38 -05003774 // Generate one more instruction that uses the result of the extended
3775 // instruction. Its result id is one more than the id of the
3776 // extended instruction.
3777 auto generate_extra_inst = [this, &Context, &Call,
3778 &RID](spv::Op opcode, Constant *constant) {
3779 //
3780 // Generate instruction like:
3781 // result = opcode constant <extinst-result>
3782 //
3783 // Ops[0] = Result Type ID
3784 // Ops[1] = Operand 0 ;; the constant, suitably splatted
3785 // Ops[2] = Operand 1 ;; the result of the extended instruction
3786 SPIRVOperandVec Ops;
3787
3788 Type *resultTy = Call->getType();
3789
3790 if (auto *vectorTy = dyn_cast<VectorType>(resultTy)) {
alan-baker931253b2020-08-20 17:15:38 -04003791 constant =
3792 ConstantVector::getSplat(vectorTy->getElementCount(), constant);
SJW806a5d82020-07-15 12:51:38 -05003793 }
3794 Ops << resultTy << constant << RID;
3795
3796 RID = addSPIRVInst(opcode, Ops);
3797 };
3798
alan-bakercc2bafb2020-11-02 08:30:18 -05003799 auto bitwidth = Call->getType()->getScalarSizeInBits();
SJW806a5d82020-07-15 12:51:38 -05003800 switch (IndirectExtInst) {
3801 case glsl::ExtInstFindUMsb: // Implementing clz
alan-bakercc2bafb2020-11-02 08:30:18 -05003802 generate_extra_inst(
3803 spv::OpISub,
3804 ConstantInt::get(Call->getType()->getScalarType(), bitwidth - 1));
SJW806a5d82020-07-15 12:51:38 -05003805 break;
3806 case glsl::ExtInstAcos: // Implementing acospi
3807 case glsl::ExtInstAsin: // Implementing asinpi
3808 case glsl::ExtInstAtan: // Implementing atanpi
3809 case glsl::ExtInstAtan2: // Implementing atan2pi
3810 generate_extra_inst(
3811 spv::OpFMul,
alan-bakercc2bafb2020-11-02 08:30:18 -05003812 ConstantFP::get(Call->getType()->getScalarType(), kOneOverPi));
SJW806a5d82020-07-15 12:51:38 -05003813 break;
3814
3815 default:
3816 assert(false && "internally inconsistent");
3817 }
3818 }
3819 } else {
SJW806a5d82020-07-15 12:51:38 -05003820 // A real function call (not builtin)
3821 // Call instruction is deferred because it needs function's ID.
3822 RID = addSPIRVPlaceholder(Call);
3823 }
3824
3825 break;
3826 }
3827 }
3828
3829 return RID;
3830}
3831
David Neto22f144c2017-06-12 14:26:21 -04003832void SPIRVProducerPass::GenerateInstruction(Instruction &I) {
David Neto22f144c2017-06-12 14:26:21 -04003833 ValueMapType &VMap = getValueMap();
SJW806a5d82020-07-15 12:51:38 -05003834 LLVMContext &Context = module->getContext();
David Neto22f144c2017-06-12 14:26:21 -04003835
SJW806a5d82020-07-15 12:51:38 -05003836 SPIRVID RID;
David Neto22f144c2017-06-12 14:26:21 -04003837
3838 switch (I.getOpcode()) {
3839 default: {
3840 if (Instruction::isCast(I.getOpcode())) {
3841 //
3842 // Generate SPIRV instructions for cast operators.
3843 //
3844
David Netod2de94a2017-08-28 17:27:47 -04003845 auto Ty = I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003846 auto OpTy = I.getOperand(0)->getType();
David Netod2de94a2017-08-28 17:27:47 -04003847 auto toI8 = Ty == Type::getInt8Ty(Context);
3848 auto fromI32 = OpTy == Type::getInt32Ty(Context);
David Neto22f144c2017-06-12 14:26:21 -04003849 // Handle zext, sext and uitofp with i1 type specially.
3850 if ((I.getOpcode() == Instruction::ZExt ||
3851 I.getOpcode() == Instruction::SExt ||
3852 I.getOpcode() == Instruction::UIToFP) &&
alan-bakerb6b09dc2018-11-08 16:59:28 -05003853 OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003854 //
3855 // Generate OpSelect.
3856 //
3857
3858 // Ops[0] = Result Type ID
3859 // Ops[1] = Condition ID
3860 // Ops[2] = True Constant ID
3861 // Ops[3] = False Constant ID
SJWf93f5f32020-05-05 07:27:56 -05003862 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04003863
SJW01901d92020-05-21 08:58:31 -05003864 Ops << I.getType() << I.getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04003865
David Neto22f144c2017-06-12 14:26:21 -04003866 if (I.getOpcode() == Instruction::ZExt) {
SJW01901d92020-05-21 08:58:31 -05003867 Ops << ConstantInt::get(I.getType(), 1);
David Neto22f144c2017-06-12 14:26:21 -04003868 } else if (I.getOpcode() == Instruction::SExt) {
SJW01901d92020-05-21 08:58:31 -05003869 Ops << ConstantInt::getSigned(I.getType(), -1);
David Neto22f144c2017-06-12 14:26:21 -04003870 } else {
SJW01901d92020-05-21 08:58:31 -05003871 Ops << ConstantFP::get(Context, APFloat(1.0f));
David Neto22f144c2017-06-12 14:26:21 -04003872 }
David Neto22f144c2017-06-12 14:26:21 -04003873
David Neto22f144c2017-06-12 14:26:21 -04003874 if (I.getOpcode() == Instruction::ZExt) {
SJW01901d92020-05-21 08:58:31 -05003875 Ops << Constant::getNullValue(I.getType());
David Neto22f144c2017-06-12 14:26:21 -04003876 } else if (I.getOpcode() == Instruction::SExt) {
SJW01901d92020-05-21 08:58:31 -05003877 Ops << Constant::getNullValue(I.getType());
David Neto22f144c2017-06-12 14:26:21 -04003878 } else {
SJW01901d92020-05-21 08:58:31 -05003879 Ops << ConstantFP::get(Context, APFloat(0.0f));
David Neto22f144c2017-06-12 14:26:21 -04003880 }
David Neto22f144c2017-06-12 14:26:21 -04003881
SJWf93f5f32020-05-05 07:27:56 -05003882 RID = addSPIRVInst(spv::OpSelect, Ops);
alan-bakerb39c8262019-03-08 14:03:37 -05003883 } else if (!clspv::Option::Int8Support() &&
3884 I.getOpcode() == Instruction::Trunc && fromI32 && toI8) {
David Netod2de94a2017-08-28 17:27:47 -04003885 // The SPIR-V target type is a 32-bit int. Keep only the bottom
3886 // 8 bits.
3887 // Before:
3888 // %result = trunc i32 %a to i8
3889 // After
3890 // %result = OpBitwiseAnd %uint %a %uint_255
3891
SJWf93f5f32020-05-05 07:27:56 -05003892 SPIRVOperandVec Ops;
David Netod2de94a2017-08-28 17:27:47 -04003893
SJW806a5d82020-07-15 12:51:38 -05003894 Ops << OpTy << I.getOperand(0) << getSPIRVInt32Constant(255);
David Netod2de94a2017-08-28 17:27:47 -04003895
SJWf93f5f32020-05-05 07:27:56 -05003896 RID = addSPIRVInst(spv::OpBitwiseAnd, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003897 } else {
3898 // Ops[0] = Result Type ID
3899 // Ops[1] = Source Value ID
SJWf93f5f32020-05-05 07:27:56 -05003900 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04003901
SJW01901d92020-05-21 08:58:31 -05003902 Ops << I.getType() << I.getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04003903
SJWf93f5f32020-05-05 07:27:56 -05003904 RID = addSPIRVInst(GetSPIRVCastOpcode(I), Ops);
David Neto22f144c2017-06-12 14:26:21 -04003905 }
3906 } else if (isa<BinaryOperator>(I)) {
3907 //
3908 // Generate SPIRV instructions for binary operators.
3909 //
3910
3911 // Handle xor with i1 type specially.
3912 if (I.getOpcode() == Instruction::Xor &&
3913 I.getType() == Type::getInt1Ty(Context) &&
Kévin Petit24272b62018-10-18 19:16:12 +00003914 ((isa<ConstantInt>(I.getOperand(0)) &&
3915 !cast<ConstantInt>(I.getOperand(0))->isZero()) ||
3916 (isa<ConstantInt>(I.getOperand(1)) &&
3917 !cast<ConstantInt>(I.getOperand(1))->isZero()))) {
David Neto22f144c2017-06-12 14:26:21 -04003918 //
3919 // Generate OpLogicalNot.
3920 //
3921 // Ops[0] = Result Type ID
3922 // Ops[1] = Operand
SJWf93f5f32020-05-05 07:27:56 -05003923 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04003924
SJW01901d92020-05-21 08:58:31 -05003925 Ops << I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003926
3927 Value *CondV = I.getOperand(0);
3928 if (isa<Constant>(I.getOperand(0))) {
3929 CondV = I.getOperand(1);
3930 }
SJW01901d92020-05-21 08:58:31 -05003931 Ops << CondV;
David Neto22f144c2017-06-12 14:26:21 -04003932
SJWf93f5f32020-05-05 07:27:56 -05003933 RID = addSPIRVInst(spv::OpLogicalNot, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003934 } else {
3935 // Ops[0] = Result Type ID
3936 // Ops[1] = Operand 0
3937 // Ops[2] = Operand 1
SJWf93f5f32020-05-05 07:27:56 -05003938 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04003939
SJW01901d92020-05-21 08:58:31 -05003940 Ops << I.getType() << I.getOperand(0) << I.getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04003941
SJWf93f5f32020-05-05 07:27:56 -05003942 RID = addSPIRVInst(GetSPIRVBinaryOpcode(I), Ops);
David Neto22f144c2017-06-12 14:26:21 -04003943 }
alan-bakerc9c55ae2019-12-02 16:01:27 -05003944 } else if (I.getOpcode() == Instruction::FNeg) {
3945 // The only unary operator.
3946 //
3947 // Ops[0] = Result Type ID
3948 // Ops[1] = Operand 0
SJW01901d92020-05-21 08:58:31 -05003949 SPIRVOperandVec Ops;
alan-bakerc9c55ae2019-12-02 16:01:27 -05003950
SJW01901d92020-05-21 08:58:31 -05003951 Ops << I.getType() << I.getOperand(0);
3952 RID = addSPIRVInst(spv::OpFNegate, Ops);
Marco Antognini68e5c512020-09-09 16:08:57 +01003953 } else if (I.getOpcode() == Instruction::Unreachable) {
3954 RID = addSPIRVInst(spv::OpUnreachable);
David Neto22f144c2017-06-12 14:26:21 -04003955 } else {
3956 I.print(errs());
3957 llvm_unreachable("Unsupported instruction???");
3958 }
3959 break;
3960 }
3961 case Instruction::GetElementPtr: {
3962 auto &GlobalConstArgSet = getGlobalConstArgSet();
3963
3964 //
3965 // Generate OpAccessChain.
3966 //
3967 GetElementPtrInst *GEP = cast<GetElementPtrInst>(&I);
3968
3969 //
3970 // Generate OpAccessChain.
3971 //
3972
3973 // Ops[0] = Result Type ID
3974 // Ops[1] = Base ID
3975 // Ops[2] ... Ops[n] = Indexes ID
SJWf93f5f32020-05-05 07:27:56 -05003976 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04003977
alan-bakerb6b09dc2018-11-08 16:59:28 -05003978 PointerType *ResultType = cast<PointerType>(GEP->getType());
David Neto22f144c2017-06-12 14:26:21 -04003979 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate ||
3980 GlobalConstArgSet.count(GEP->getPointerOperand())) {
3981 // Use pointer type with private address space for global constant.
3982 Type *EleTy = I.getType()->getPointerElementType();
David Neto1a1a0582017-07-07 12:01:44 -04003983 ResultType = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
David Neto22f144c2017-06-12 14:26:21 -04003984 }
David Neto257c3892018-04-11 13:19:45 -04003985
SJW01901d92020-05-21 08:58:31 -05003986 Ops << ResultType;
David Neto22f144c2017-06-12 14:26:21 -04003987
David Neto862b7d82018-06-14 18:48:37 -04003988 // Generate the base pointer.
SJW01901d92020-05-21 08:58:31 -05003989 Ops << GEP->getPointerOperand();
David Neto22f144c2017-06-12 14:26:21 -04003990
David Neto862b7d82018-06-14 18:48:37 -04003991 // TODO(dneto): Simplify the following?
David Neto22f144c2017-06-12 14:26:21 -04003992
3993 //
3994 // Follows below rules for gep.
3995 //
David Neto862b7d82018-06-14 18:48:37 -04003996 // 1. If gep's first index is 0 generate OpAccessChain and ignore gep's
3997 // first index.
David Neto22f144c2017-06-12 14:26:21 -04003998 // 2. If gep's first index is not 0, generate OpPtrAccessChain and use gep's
3999 // first index.
4000 // 3. If gep's first index is not constant, generate OpPtrAccessChain and
4001 // use gep's first index.
4002 // 4. If it is not above case 1, 2 and 3, generate OpAccessChain and use
4003 // gep's first index.
4004 //
4005 spv::Op Opcode = spv::OpAccessChain;
4006 unsigned offset = 0;
4007 if (ConstantInt *CstInt = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
David Neto862b7d82018-06-14 18:48:37 -04004008 if (CstInt->getZExtValue() == 0) {
David Neto22f144c2017-06-12 14:26:21 -04004009 offset = 1;
David Neto862b7d82018-06-14 18:48:37 -04004010 } else if (CstInt->getZExtValue() != 0) {
David Neto22f144c2017-06-12 14:26:21 -04004011 Opcode = spv::OpPtrAccessChain;
David Neto22f144c2017-06-12 14:26:21 -04004012 }
David Neto862b7d82018-06-14 18:48:37 -04004013 } else {
David Neto22f144c2017-06-12 14:26:21 -04004014 Opcode = spv::OpPtrAccessChain;
David Neto1a1a0582017-07-07 12:01:44 -04004015 }
4016
4017 if (Opcode == spv::OpPtrAccessChain) {
alan-baker7506abb2020-09-10 15:02:55 -04004018 // Shader validation in the SPIR-V spec requires that the base pointer to
4019 // OpPtrAccessChain (in StorageBuffer storage class) be decorated with
4020 // ArrayStride.
alan-baker5b86ed72019-02-15 08:26:50 -05004021 auto address_space = ResultType->getAddressSpace();
4022 setVariablePointersCapabilities(address_space);
4023 switch (GetStorageClass(address_space)) {
Alan Bakerfcda9482018-10-02 17:09:59 -04004024 case spv::StorageClassStorageBuffer:
David Neto1a1a0582017-07-07 12:01:44 -04004025 // Save the need to generate an ArrayStride decoration. But defer
4026 // generation until later, so we only make one decoration.
alan-baker7506abb2020-09-10 15:02:55 -04004027 getTypesNeedingArrayStride().insert(GEP->getPointerOperandType());
4028 break;
4029 case spv::StorageClassWorkgroup:
Alan Bakerfcda9482018-10-02 17:09:59 -04004030 break;
4031 default:
alan-baker7506abb2020-09-10 15:02:55 -04004032 llvm_unreachable(
4033 "OpPtrAccessChain is not supported for this storage class");
Alan Bakerfcda9482018-10-02 17:09:59 -04004034 break;
David Neto1a1a0582017-07-07 12:01:44 -04004035 }
David Neto22f144c2017-06-12 14:26:21 -04004036 }
4037
4038 for (auto II = GEP->idx_begin() + offset; II != GEP->idx_end(); II++) {
SJW01901d92020-05-21 08:58:31 -05004039 Ops << *II;
David Neto22f144c2017-06-12 14:26:21 -04004040 }
4041
SJWf93f5f32020-05-05 07:27:56 -05004042 RID = addSPIRVInst(Opcode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004043 break;
4044 }
4045 case Instruction::ExtractValue: {
4046 ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
4047 // Ops[0] = Result Type ID
4048 // Ops[1] = Composite ID
4049 // Ops[2] ... Ops[n] = Indexes (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05004050 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004051
SJW01901d92020-05-21 08:58:31 -05004052 Ops << I.getType();
David Neto22f144c2017-06-12 14:26:21 -04004053
SJW01901d92020-05-21 08:58:31 -05004054 Ops << EVI->getAggregateOperand();
David Neto22f144c2017-06-12 14:26:21 -04004055
4056 for (auto &Index : EVI->indices()) {
SJW01901d92020-05-21 08:58:31 -05004057 Ops << Index;
David Neto22f144c2017-06-12 14:26:21 -04004058 }
4059
SJWf93f5f32020-05-05 07:27:56 -05004060 RID = addSPIRVInst(spv::OpCompositeExtract, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004061 break;
4062 }
4063 case Instruction::InsertValue: {
4064 InsertValueInst *IVI = cast<InsertValueInst>(&I);
4065 // Ops[0] = Result Type ID
4066 // Ops[1] = Object ID
4067 // Ops[2] = Composite ID
4068 // Ops[3] ... Ops[n] = Indexes (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05004069 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004070
SJW01901d92020-05-21 08:58:31 -05004071 Ops << I.getType() << IVI->getInsertedValueOperand()
4072 << IVI->getAggregateOperand();
David Neto22f144c2017-06-12 14:26:21 -04004073
4074 for (auto &Index : IVI->indices()) {
SJW01901d92020-05-21 08:58:31 -05004075 Ops << Index;
David Neto22f144c2017-06-12 14:26:21 -04004076 }
4077
SJWf93f5f32020-05-05 07:27:56 -05004078 RID = addSPIRVInst(spv::OpCompositeInsert, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004079 break;
4080 }
4081 case Instruction::Select: {
4082 //
4083 // Generate OpSelect.
4084 //
4085
4086 // Ops[0] = Result Type ID
4087 // Ops[1] = Condition ID
4088 // Ops[2] = True Constant ID
4089 // Ops[3] = False Constant ID
SJWf93f5f32020-05-05 07:27:56 -05004090 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004091
4092 // Find SPIRV instruction for parameter type.
4093 auto Ty = I.getType();
4094 if (Ty->isPointerTy()) {
4095 auto PointeeTy = Ty->getPointerElementType();
4096 if (PointeeTy->isStructTy() &&
4097 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
4098 Ty = PointeeTy;
alan-baker5b86ed72019-02-15 08:26:50 -05004099 } else {
4100 // Selecting between pointers requires variable pointers.
4101 setVariablePointersCapabilities(Ty->getPointerAddressSpace());
4102 if (!hasVariablePointers() && !selectFromSameObject(&I)) {
SJW01901d92020-05-21 08:58:31 -05004103 setVariablePointers();
alan-baker5b86ed72019-02-15 08:26:50 -05004104 }
David Neto22f144c2017-06-12 14:26:21 -04004105 }
4106 }
4107
SJW01901d92020-05-21 08:58:31 -05004108 Ops << Ty << I.getOperand(0) << I.getOperand(1) << I.getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04004109
SJWf93f5f32020-05-05 07:27:56 -05004110 RID = addSPIRVInst(spv::OpSelect, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004111 break;
4112 }
4113 case Instruction::ExtractElement: {
4114 // Handle <4 x i8> type manually.
4115 Type *CompositeTy = I.getOperand(0)->getType();
4116 if (is4xi8vec(CompositeTy)) {
4117 //
4118 // Generate OpShiftRightLogical and OpBitwiseAnd for extractelement with
4119 // <4 x i8>.
4120 //
4121
4122 //
4123 // Generate OpShiftRightLogical
4124 //
4125 // Ops[0] = Result Type ID
4126 // Ops[1] = Operand 0
4127 // Ops[2] = Operand 1
4128 //
SJWf93f5f32020-05-05 07:27:56 -05004129 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004130
SJW01901d92020-05-21 08:58:31 -05004131 Ops << CompositeTy << I.getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04004132
SJW01901d92020-05-21 08:58:31 -05004133 SPIRVID Op1ID = 0;
David Neto22f144c2017-06-12 14:26:21 -04004134 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
4135 // Handle constant index.
SJW806a5d82020-07-15 12:51:38 -05004136 uint32_t Idx = static_cast<uint32_t>(CI->getZExtValue());
4137 Op1ID = getSPIRVInt32Constant(Idx * 8);
David Neto22f144c2017-06-12 14:26:21 -04004138 } else {
4139 // Handle variable index.
SJWf93f5f32020-05-05 07:27:56 -05004140 SPIRVOperandVec TmpOps;
David Neto22f144c2017-06-12 14:26:21 -04004141
SJW806a5d82020-07-15 12:51:38 -05004142 TmpOps << Type::getInt32Ty(Context) << I.getOperand(1)
4143 << getSPIRVInt32Constant(8);
David Neto22f144c2017-06-12 14:26:21 -04004144
SJWf93f5f32020-05-05 07:27:56 -05004145 Op1ID = addSPIRVInst(spv::OpIMul, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04004146 }
SJW01901d92020-05-21 08:58:31 -05004147 Ops << Op1ID;
David Neto22f144c2017-06-12 14:26:21 -04004148
SJW01901d92020-05-21 08:58:31 -05004149 SPIRVID ShiftID = addSPIRVInst(spv::OpShiftRightLogical, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004150
4151 //
4152 // Generate OpBitwiseAnd
4153 //
4154 // Ops[0] = Result Type ID
4155 // Ops[1] = Operand 0
4156 // Ops[2] = Operand 1
4157 //
4158 Ops.clear();
4159
SJW806a5d82020-07-15 12:51:38 -05004160 Ops << CompositeTy << ShiftID << getSPIRVInt32Constant(0xFF);
David Neto22f144c2017-06-12 14:26:21 -04004161
SJWf93f5f32020-05-05 07:27:56 -05004162 RID = addSPIRVInst(spv::OpBitwiseAnd, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004163 break;
4164 }
4165
4166 // Ops[0] = Result Type ID
4167 // Ops[1] = Composite ID
4168 // Ops[2] ... Ops[n] = Indexes (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05004169 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004170
SJW01901d92020-05-21 08:58:31 -05004171 Ops << I.getType() << I.getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04004172
4173 spv::Op Opcode = spv::OpCompositeExtract;
4174 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
SJW01901d92020-05-21 08:58:31 -05004175 Ops << static_cast<uint32_t>(CI->getZExtValue());
David Neto22f144c2017-06-12 14:26:21 -04004176 } else {
SJW01901d92020-05-21 08:58:31 -05004177 Ops << I.getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04004178 Opcode = spv::OpVectorExtractDynamic;
4179 }
4180
SJWf93f5f32020-05-05 07:27:56 -05004181 RID = addSPIRVInst(Opcode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004182 break;
4183 }
4184 case Instruction::InsertElement: {
4185 // Handle <4 x i8> type manually.
4186 Type *CompositeTy = I.getOperand(0)->getType();
4187 if (is4xi8vec(CompositeTy)) {
SJW806a5d82020-07-15 12:51:38 -05004188 SPIRVID CstFFID = getSPIRVInt32Constant(0xFF);
David Neto22f144c2017-06-12 14:26:21 -04004189
SJW01901d92020-05-21 08:58:31 -05004190 SPIRVID ShiftAmountID = 0;
David Neto22f144c2017-06-12 14:26:21 -04004191 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
4192 // Handle constant index.
SJW806a5d82020-07-15 12:51:38 -05004193 uint32_t Idx = static_cast<uint32_t>(CI->getZExtValue());
4194 ShiftAmountID = getSPIRVInt32Constant(Idx * 8);
David Neto22f144c2017-06-12 14:26:21 -04004195 } else {
4196 // Handle variable index.
SJWf93f5f32020-05-05 07:27:56 -05004197 SPIRVOperandVec TmpOps;
David Neto22f144c2017-06-12 14:26:21 -04004198
SJW806a5d82020-07-15 12:51:38 -05004199 TmpOps << Type::getInt32Ty(Context) << I.getOperand(2)
4200 << getSPIRVInt32Constant(8);
David Neto22f144c2017-06-12 14:26:21 -04004201
SJWf93f5f32020-05-05 07:27:56 -05004202 ShiftAmountID = addSPIRVInst(spv::OpIMul, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04004203 }
4204
4205 //
4206 // Generate mask operations.
4207 //
4208
4209 // ShiftLeft mask according to index of insertelement.
SJWf93f5f32020-05-05 07:27:56 -05004210 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004211
SJW01901d92020-05-21 08:58:31 -05004212 Ops << CompositeTy << CstFFID << ShiftAmountID;
David Neto22f144c2017-06-12 14:26:21 -04004213
SJW01901d92020-05-21 08:58:31 -05004214 SPIRVID MaskID = addSPIRVInst(spv::OpShiftLeftLogical, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004215
4216 // Inverse mask.
4217 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05004218 Ops << CompositeTy << MaskID;
David Neto22f144c2017-06-12 14:26:21 -04004219
SJW01901d92020-05-21 08:58:31 -05004220 SPIRVID InvMaskID = addSPIRVInst(spv::OpNot, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004221
4222 // Apply mask.
4223 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05004224 Ops << CompositeTy << I.getOperand(0) << InvMaskID;
David Neto22f144c2017-06-12 14:26:21 -04004225
SJW01901d92020-05-21 08:58:31 -05004226 SPIRVID OrgValID = addSPIRVInst(spv::OpBitwiseAnd, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004227
4228 // Create correct value according to index of insertelement.
4229 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05004230 Ops << CompositeTy << I.getOperand(1) << ShiftAmountID;
David Neto22f144c2017-06-12 14:26:21 -04004231
SJW01901d92020-05-21 08:58:31 -05004232 SPIRVID InsertValID = addSPIRVInst(spv::OpShiftLeftLogical, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004233
4234 // Insert value to original value.
4235 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05004236 Ops << CompositeTy << OrgValID << InsertValID;
David Neto22f144c2017-06-12 14:26:21 -04004237
SJWf93f5f32020-05-05 07:27:56 -05004238 RID = addSPIRVInst(spv::OpBitwiseOr, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004239 break;
4240 }
4241
SJWf93f5f32020-05-05 07:27:56 -05004242 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004243
James Priced26efea2018-06-09 23:28:32 +01004244 // Ops[0] = Result Type ID
SJW01901d92020-05-21 08:58:31 -05004245 Ops << I.getType();
David Neto22f144c2017-06-12 14:26:21 -04004246
4247 spv::Op Opcode = spv::OpCompositeInsert;
4248 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
David Neto257c3892018-04-11 13:19:45 -04004249 const auto value = CI->getZExtValue();
4250 assert(value <= UINT32_MAX);
James Priced26efea2018-06-09 23:28:32 +01004251 // Ops[1] = Object ID
4252 // Ops[2] = Composite ID
4253 // Ops[3] ... Ops[n] = Indexes (Literal Number)
SJW01901d92020-05-21 08:58:31 -05004254 Ops << I.getOperand(1) << I.getOperand(0) << static_cast<uint32_t>(value);
David Neto22f144c2017-06-12 14:26:21 -04004255 } else {
James Priced26efea2018-06-09 23:28:32 +01004256 // Ops[1] = Composite ID
4257 // Ops[2] = Object ID
4258 // Ops[3] ... Ops[n] = Indexes (Literal Number)
SJW01901d92020-05-21 08:58:31 -05004259 Ops << I.getOperand(0) << I.getOperand(1) << I.getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04004260 Opcode = spv::OpVectorInsertDynamic;
4261 }
4262
SJWf93f5f32020-05-05 07:27:56 -05004263 RID = addSPIRVInst(Opcode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004264 break;
4265 }
4266 case Instruction::ShuffleVector: {
4267 // Ops[0] = Result Type ID
4268 // Ops[1] = Vector 1 ID
4269 // Ops[2] = Vector 2 ID
4270 // Ops[3] ... Ops[n] = Components (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05004271 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004272
SJW01901d92020-05-21 08:58:31 -05004273 Ops << I.getType() << I.getOperand(0) << I.getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04004274
alan-bakerc9666712020-04-01 16:31:21 -04004275 auto shuffle = cast<ShuffleVectorInst>(&I);
4276 SmallVector<int, 4> mask;
4277 shuffle->getShuffleMask(mask);
4278 for (auto i : mask) {
4279 if (i == UndefMaskElem) {
4280 if (clspv::Option::HackUndef())
4281 // Use 0 instead of undef.
SJW01901d92020-05-21 08:58:31 -05004282 Ops << 0;
alan-bakerc9666712020-04-01 16:31:21 -04004283 else
4284 // Undef for shuffle in SPIR-V.
SJW01901d92020-05-21 08:58:31 -05004285 Ops << 0xffffffff;
David Neto22f144c2017-06-12 14:26:21 -04004286 } else {
SJW01901d92020-05-21 08:58:31 -05004287 Ops << i;
David Neto22f144c2017-06-12 14:26:21 -04004288 }
4289 }
4290
SJWf93f5f32020-05-05 07:27:56 -05004291 RID = addSPIRVInst(spv::OpVectorShuffle, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004292 break;
4293 }
4294 case Instruction::ICmp:
4295 case Instruction::FCmp: {
4296 CmpInst *CmpI = cast<CmpInst>(&I);
4297
David Netod4ca2e62017-07-06 18:47:35 -04004298 // Pointer equality is invalid.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004299 Type *ArgTy = CmpI->getOperand(0)->getType();
David Netod4ca2e62017-07-06 18:47:35 -04004300 if (isa<PointerType>(ArgTy)) {
4301 CmpI->print(errs());
alan-baker21574d32020-01-29 16:00:31 -05004302 std::string name = I.getParent()->getParent()->getName().str();
David Netod4ca2e62017-07-06 18:47:35 -04004303 errs()
4304 << "\nPointer equality test is not supported by SPIR-V for Vulkan, "
4305 << "in function " << name << "\n";
4306 llvm_unreachable("Pointer equality check is invalid");
4307 break;
4308 }
4309
David Neto257c3892018-04-11 13:19:45 -04004310 // Ops[0] = Result Type ID
4311 // Ops[1] = Operand 1 ID
4312 // Ops[2] = Operand 2 ID
SJWf93f5f32020-05-05 07:27:56 -05004313 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004314
SJW01901d92020-05-21 08:58:31 -05004315 Ops << CmpI->getType() << CmpI->getOperand(0) << CmpI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04004316
4317 spv::Op Opcode = GetSPIRVCmpOpcode(CmpI);
SJWf93f5f32020-05-05 07:27:56 -05004318 RID = addSPIRVInst(Opcode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004319 break;
4320 }
4321 case Instruction::Br: {
SJW88ed5fe2020-05-11 12:40:57 -05004322 // Branch instruction is deferred because it needs label's ID.
4323 BasicBlock *BrBB = I.getParent();
4324 if (ContinueBlocks.count(BrBB) || MergeBlocks.count(BrBB)) {
4325 // Placeholder for Merge operation
4326 RID = addSPIRVPlaceholder(&I);
4327 }
4328 RID = addSPIRVPlaceholder(&I);
David Neto22f144c2017-06-12 14:26:21 -04004329 break;
4330 }
4331 case Instruction::Switch: {
4332 I.print(errs());
4333 llvm_unreachable("Unsupported instruction???");
4334 break;
4335 }
4336 case Instruction::IndirectBr: {
4337 I.print(errs());
4338 llvm_unreachable("Unsupported instruction???");
4339 break;
4340 }
4341 case Instruction::PHI: {
SJW88ed5fe2020-05-11 12:40:57 -05004342 // PHI instruction is deferred because it needs label's ID.
4343 RID = addSPIRVPlaceholder(&I);
David Neto22f144c2017-06-12 14:26:21 -04004344 break;
4345 }
4346 case Instruction::Alloca: {
4347 //
4348 // Generate OpVariable.
4349 //
4350 // Ops[0] : Result Type ID
4351 // Ops[1] : Storage Class
SJWf93f5f32020-05-05 07:27:56 -05004352 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004353
SJW01901d92020-05-21 08:58:31 -05004354 Ops << I.getType() << spv::StorageClassFunction;
David Neto22f144c2017-06-12 14:26:21 -04004355
SJWf93f5f32020-05-05 07:27:56 -05004356 RID = addSPIRVInst(spv::OpVariable, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004357 break;
4358 }
4359 case Instruction::Load: {
4360 LoadInst *LD = cast<LoadInst>(&I);
4361 //
4362 // Generate OpLoad.
4363 //
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04004364
alan-baker5b86ed72019-02-15 08:26:50 -05004365 if (LD->getType()->isPointerTy()) {
4366 // Loading a pointer requires variable pointers.
4367 setVariablePointersCapabilities(LD->getType()->getPointerAddressSpace());
4368 }
David Neto22f144c2017-06-12 14:26:21 -04004369
SJW01901d92020-05-21 08:58:31 -05004370 SPIRVID PointerID = getSPIRVValue(LD->getPointerOperand());
David Netoa60b00b2017-09-15 16:34:09 -04004371 // This is a hack to work around what looks like a driver bug.
4372 // When we're loading from the special variable holding the WorkgroupSize
David Neto0a2f98d2017-09-15 19:38:40 -04004373 // builtin value, use an OpBitWiseAnd of the value's ID rather than
4374 // generating a load.
David Neto66cfe642018-03-24 06:13:56 -07004375 // TODO(dneto): Remove this awful hack once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -04004376 if (PointerID == WorkgroupSizeVarID) {
David Neto0a2f98d2017-09-15 19:38:40 -04004377 // Generate a bitwise-and of the original value with itself.
4378 // We should have been able to get away with just an OpCopyObject,
4379 // but we need something more complex to get past certain driver bugs.
4380 // This is ridiculous, but necessary.
4381 // TODO(dneto): Revisit this once drivers fix their bugs.
4382
SJWf93f5f32020-05-05 07:27:56 -05004383 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05004384 Ops << LD->getType() << WorkgroupSizeValueID << WorkgroupSizeValueID;
David Neto0a2f98d2017-09-15 19:38:40 -04004385
SJWf93f5f32020-05-05 07:27:56 -05004386 RID = addSPIRVInst(spv::OpBitwiseAnd, Ops);
David Netoa60b00b2017-09-15 16:34:09 -04004387 break;
4388 }
4389
4390 // This is the normal path. Generate a load.
4391
David Neto22f144c2017-06-12 14:26:21 -04004392 // Ops[0] = Result Type ID
4393 // Ops[1] = Pointer ID
4394 // Ops[2] ... Ops[n] = Optional Memory Access
4395 //
4396 // TODO: Do we need to implement Optional Memory Access???
David Neto0a2f98d2017-09-15 19:38:40 -04004397
SJWf93f5f32020-05-05 07:27:56 -05004398 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05004399 Ops << LD->getType() << LD->getPointerOperand();
David Neto22f144c2017-06-12 14:26:21 -04004400
SJWf93f5f32020-05-05 07:27:56 -05004401 RID = addSPIRVInst(spv::OpLoad, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004402 break;
4403 }
4404 case Instruction::Store: {
4405 StoreInst *ST = cast<StoreInst>(&I);
4406 //
4407 // Generate OpStore.
4408 //
4409
alan-baker5b86ed72019-02-15 08:26:50 -05004410 if (ST->getValueOperand()->getType()->isPointerTy()) {
4411 // Storing a pointer requires variable pointers.
4412 setVariablePointersCapabilities(
4413 ST->getValueOperand()->getType()->getPointerAddressSpace());
4414 }
4415
David Neto22f144c2017-06-12 14:26:21 -04004416 // Ops[0] = Pointer ID
4417 // Ops[1] = Object ID
4418 // Ops[2] ... Ops[n] = Optional Memory Access (later???)
4419 //
4420 // TODO: Do we need to implement Optional Memory Access???
SJWf93f5f32020-05-05 07:27:56 -05004421 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05004422 Ops << ST->getPointerOperand() << ST->getValueOperand();
David Neto22f144c2017-06-12 14:26:21 -04004423
SJWf93f5f32020-05-05 07:27:56 -05004424 RID = addSPIRVInst(spv::OpStore, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004425 break;
4426 }
4427 case Instruction::AtomicCmpXchg: {
4428 I.print(errs());
4429 llvm_unreachable("Unsupported instruction???");
4430 break;
4431 }
4432 case Instruction::AtomicRMW: {
Neil Henning39672102017-09-29 14:33:13 +01004433 AtomicRMWInst *AtomicRMW = dyn_cast<AtomicRMWInst>(&I);
4434
4435 spv::Op opcode;
4436
4437 switch (AtomicRMW->getOperation()) {
4438 default:
4439 I.print(errs());
4440 llvm_unreachable("Unsupported instruction???");
4441 case llvm::AtomicRMWInst::Add:
4442 opcode = spv::OpAtomicIAdd;
4443 break;
4444 case llvm::AtomicRMWInst::Sub:
4445 opcode = spv::OpAtomicISub;
4446 break;
4447 case llvm::AtomicRMWInst::Xchg:
4448 opcode = spv::OpAtomicExchange;
4449 break;
4450 case llvm::AtomicRMWInst::Min:
4451 opcode = spv::OpAtomicSMin;
4452 break;
4453 case llvm::AtomicRMWInst::Max:
4454 opcode = spv::OpAtomicSMax;
4455 break;
4456 case llvm::AtomicRMWInst::UMin:
4457 opcode = spv::OpAtomicUMin;
4458 break;
4459 case llvm::AtomicRMWInst::UMax:
4460 opcode = spv::OpAtomicUMax;
4461 break;
4462 case llvm::AtomicRMWInst::And:
4463 opcode = spv::OpAtomicAnd;
4464 break;
4465 case llvm::AtomicRMWInst::Or:
4466 opcode = spv::OpAtomicOr;
4467 break;
4468 case llvm::AtomicRMWInst::Xor:
4469 opcode = spv::OpAtomicXor;
4470 break;
4471 }
4472
4473 //
4474 // Generate OpAtomic*.
4475 //
SJWf93f5f32020-05-05 07:27:56 -05004476 SPIRVOperandVec Ops;
Neil Henning39672102017-09-29 14:33:13 +01004477
SJW01901d92020-05-21 08:58:31 -05004478 Ops << I.getType() << AtomicRMW->getPointerOperand();
Neil Henning39672102017-09-29 14:33:13 +01004479
SJW806a5d82020-07-15 12:51:38 -05004480 const auto ConstantScopeDevice = getSPIRVInt32Constant(spv::ScopeDevice);
SJW01901d92020-05-21 08:58:31 -05004481 Ops << ConstantScopeDevice;
Neil Henning39672102017-09-29 14:33:13 +01004482
SJW806a5d82020-07-15 12:51:38 -05004483 const auto ConstantMemorySemantics =
4484 getSPIRVInt32Constant(spv::MemorySemanticsUniformMemoryMask |
4485 spv::MemorySemanticsSequentiallyConsistentMask);
SJW01901d92020-05-21 08:58:31 -05004486 Ops << ConstantMemorySemantics << AtomicRMW->getValOperand();
Neil Henning39672102017-09-29 14:33:13 +01004487
SJWf93f5f32020-05-05 07:27:56 -05004488 RID = addSPIRVInst(opcode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004489 break;
4490 }
4491 case Instruction::Fence: {
4492 I.print(errs());
4493 llvm_unreachable("Unsupported instruction???");
4494 break;
4495 }
4496 case Instruction::Call: {
4497 CallInst *Call = dyn_cast<CallInst>(&I);
SJW806a5d82020-07-15 12:51:38 -05004498 RID = GenerateInstructionFromCall(Call);
David Neto22f144c2017-06-12 14:26:21 -04004499 break;
4500 }
4501 case Instruction::Ret: {
4502 unsigned NumOps = I.getNumOperands();
4503 if (NumOps == 0) {
4504 //
4505 // Generate OpReturn.
4506 //
SJWf93f5f32020-05-05 07:27:56 -05004507 RID = addSPIRVInst(spv::OpReturn);
David Neto22f144c2017-06-12 14:26:21 -04004508 } else {
4509 //
4510 // Generate OpReturnValue.
4511 //
4512
4513 // Ops[0] = Return Value ID
SJWf93f5f32020-05-05 07:27:56 -05004514 SPIRVOperandVec Ops;
David Neto257c3892018-04-11 13:19:45 -04004515
SJW01901d92020-05-21 08:58:31 -05004516 Ops << I.getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04004517
SJWf93f5f32020-05-05 07:27:56 -05004518 RID = addSPIRVInst(spv::OpReturnValue, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004519 break;
4520 }
4521 break;
4522 }
4523 }
SJWf93f5f32020-05-05 07:27:56 -05004524
4525 // Register Instruction to ValueMap.
SJW01901d92020-05-21 08:58:31 -05004526 if (RID.isValid()) {
SJWf93f5f32020-05-05 07:27:56 -05004527 VMap[&I] = RID;
4528 }
David Neto22f144c2017-06-12 14:26:21 -04004529}
4530
4531void SPIRVProducerPass::GenerateFuncEpilogue() {
David Neto22f144c2017-06-12 14:26:21 -04004532 //
4533 // Generate OpFunctionEnd
4534 //
SJWf93f5f32020-05-05 07:27:56 -05004535 addSPIRVInst(spv::OpFunctionEnd);
David Neto22f144c2017-06-12 14:26:21 -04004536}
4537
4538bool SPIRVProducerPass::is4xi8vec(Type *Ty) const {
alan-bakerb39c8262019-03-08 14:03:37 -05004539 // Don't specialize <4 x i8> if i8 is generally supported.
4540 if (clspv::Option::Int8Support())
4541 return false;
4542
David Neto22f144c2017-06-12 14:26:21 -04004543 LLVMContext &Context = Ty->getContext();
James Pricecf53df42020-04-20 14:41:24 -04004544 if (auto VecTy = dyn_cast<VectorType>(Ty)) {
4545 if (VecTy->getElementType() == Type::getInt8Ty(Context) &&
alan-baker5a8c3be2020-09-09 13:44:26 -04004546 VecTy->getElementCount().getKnownMinValue() == 4) {
David Neto22f144c2017-06-12 14:26:21 -04004547 return true;
4548 }
4549 }
4550
4551 return false;
4552}
4553
4554void SPIRVProducerPass::HandleDeferredInstruction() {
David Neto22f144c2017-06-12 14:26:21 -04004555 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
4556
SJW88ed5fe2020-05-11 12:40:57 -05004557 for (size_t i = 0; i < DeferredInsts.size(); ++i) {
4558 Value *Inst = DeferredInsts[i].first;
4559 SPIRVInstruction *Placeholder = DeferredInsts[i].second;
4560 SPIRVOperandVec Operands;
4561
4562 auto nextDeferred = [&i, &Inst, &DeferredInsts, &Placeholder]() {
4563 ++i;
4564 assert(DeferredInsts.size() > i);
4565 assert(Inst == DeferredInsts[i].first);
4566 Placeholder = DeferredInsts[i].second;
4567 };
David Neto22f144c2017-06-12 14:26:21 -04004568
4569 if (BranchInst *Br = dyn_cast<BranchInst>(Inst)) {
alan-baker06cad652019-12-03 17:56:47 -05004570 // Check whether this branch needs to be preceeded by merge instruction.
David Neto22f144c2017-06-12 14:26:21 -04004571 BasicBlock *BrBB = Br->getParent();
alan-baker06cad652019-12-03 17:56:47 -05004572 if (ContinueBlocks.count(BrBB)) {
David Neto22f144c2017-06-12 14:26:21 -04004573 //
4574 // Generate OpLoopMerge.
4575 //
4576 // Ops[0] = Merge Block ID
4577 // Ops[1] = Continue Target ID
4578 // Ops[2] = Selection Control
SJWf93f5f32020-05-05 07:27:56 -05004579 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004580
SJW01901d92020-05-21 08:58:31 -05004581 Ops << MergeBlocks[BrBB] << ContinueBlocks[BrBB]
4582 << spv::LoopControlMaskNone;
David Neto22f144c2017-06-12 14:26:21 -04004583
SJW88ed5fe2020-05-11 12:40:57 -05004584 replaceSPIRVInst(Placeholder, spv::OpLoopMerge, Ops);
4585
4586 nextDeferred();
4587
alan-baker06cad652019-12-03 17:56:47 -05004588 } else if (MergeBlocks.count(BrBB)) {
4589 //
4590 // Generate OpSelectionMerge.
4591 //
4592 // Ops[0] = Merge Block ID
4593 // Ops[1] = Selection Control
SJWf93f5f32020-05-05 07:27:56 -05004594 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004595
alan-baker06cad652019-12-03 17:56:47 -05004596 auto MergeBB = MergeBlocks[BrBB];
SJW01901d92020-05-21 08:58:31 -05004597 Ops << MergeBB << spv::SelectionControlMaskNone;
David Neto22f144c2017-06-12 14:26:21 -04004598
SJW88ed5fe2020-05-11 12:40:57 -05004599 replaceSPIRVInst(Placeholder, spv::OpSelectionMerge, Ops);
4600
4601 nextDeferred();
David Neto22f144c2017-06-12 14:26:21 -04004602 }
4603
4604 if (Br->isConditional()) {
4605 //
4606 // Generate OpBranchConditional.
4607 //
4608 // Ops[0] = Condition ID
4609 // Ops[1] = True Label ID
4610 // Ops[2] = False Label ID
4611 // Ops[3] ... Ops[n] = Branch weights (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05004612 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004613
SJW01901d92020-05-21 08:58:31 -05004614 Ops << Br->getCondition() << Br->getSuccessor(0) << Br->getSuccessor(1);
David Neto22f144c2017-06-12 14:26:21 -04004615
SJW88ed5fe2020-05-11 12:40:57 -05004616 replaceSPIRVInst(Placeholder, spv::OpBranchConditional, Ops);
4617
David Neto22f144c2017-06-12 14:26:21 -04004618 } else {
4619 //
4620 // Generate OpBranch.
4621 //
4622 // Ops[0] = Target Label ID
SJWf93f5f32020-05-05 07:27:56 -05004623 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004624
SJW01901d92020-05-21 08:58:31 -05004625 Ops << Br->getSuccessor(0);
David Neto22f144c2017-06-12 14:26:21 -04004626
SJW88ed5fe2020-05-11 12:40:57 -05004627 replaceSPIRVInst(Placeholder, spv::OpBranch, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004628 }
4629 } else if (PHINode *PHI = dyn_cast<PHINode>(Inst)) {
alan-baker5ed87542020-03-23 11:05:22 -04004630 if (PHI->getType()->isPointerTy() && !IsSamplerType(PHI->getType()) &&
4631 !IsImageType(PHI->getType())) {
alan-baker5b86ed72019-02-15 08:26:50 -05004632 // OpPhi on pointers requires variable pointers.
4633 setVariablePointersCapabilities(
4634 PHI->getType()->getPointerAddressSpace());
4635 if (!hasVariablePointers() && !selectFromSameObject(PHI)) {
SJW01901d92020-05-21 08:58:31 -05004636 setVariablePointers();
alan-baker5b86ed72019-02-15 08:26:50 -05004637 }
4638 }
4639
David Neto22f144c2017-06-12 14:26:21 -04004640 //
4641 // Generate OpPhi.
4642 //
4643 // Ops[0] = Result Type ID
4644 // Ops[1] ... Ops[n] = (Variable ID, Parent ID) pairs
SJWf93f5f32020-05-05 07:27:56 -05004645 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004646
SJW01901d92020-05-21 08:58:31 -05004647 Ops << PHI->getType();
David Neto22f144c2017-06-12 14:26:21 -04004648
SJW88ed5fe2020-05-11 12:40:57 -05004649 for (unsigned j = 0; j < PHI->getNumIncomingValues(); j++) {
SJW01901d92020-05-21 08:58:31 -05004650 Ops << PHI->getIncomingValue(j) << PHI->getIncomingBlock(j);
David Neto22f144c2017-06-12 14:26:21 -04004651 }
4652
SJW88ed5fe2020-05-11 12:40:57 -05004653 replaceSPIRVInst(Placeholder, spv::OpPhi, Ops);
4654
David Neto22f144c2017-06-12 14:26:21 -04004655 } else if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
4656 Function *Callee = Call->getCalledFunction();
David Neto3fbb4072017-10-16 11:28:14 -04004657 auto callee_name = Callee->getName();
David Neto22f144c2017-06-12 14:26:21 -04004658
SJW61531372020-06-09 07:31:08 -05004659 if (Builtins::Lookup(Callee) == Builtins::kClspvCompositeConstruct) {
David Netoab03f432017-11-03 17:00:44 -04004660 // Generate an OpCompositeConstruct
SJWf93f5f32020-05-05 07:27:56 -05004661 SPIRVOperandVec Ops;
David Netoab03f432017-11-03 17:00:44 -04004662
4663 // The result type.
SJW01901d92020-05-21 08:58:31 -05004664 Ops << Call->getType();
David Netoab03f432017-11-03 17:00:44 -04004665
4666 for (Use &use : Call->arg_operands()) {
SJW01901d92020-05-21 08:58:31 -05004667 Ops << use.get();
David Netoab03f432017-11-03 17:00:44 -04004668 }
4669
SJW88ed5fe2020-05-11 12:40:57 -05004670 replaceSPIRVInst(Placeholder, spv::OpCompositeConstruct, Ops);
David Netoab03f432017-11-03 17:00:44 -04004671
David Neto22f144c2017-06-12 14:26:21 -04004672 } else {
alan-baker5b86ed72019-02-15 08:26:50 -05004673 if (Call->getType()->isPointerTy()) {
4674 // Functions returning pointers require variable pointers.
4675 setVariablePointersCapabilities(
4676 Call->getType()->getPointerAddressSpace());
4677 }
4678
David Neto22f144c2017-06-12 14:26:21 -04004679 //
4680 // Generate OpFunctionCall.
4681 //
4682
4683 // Ops[0] = Result Type ID
4684 // Ops[1] = Callee Function ID
4685 // Ops[2] ... Ops[n] = Argument 0, ... , Argument n
SJWf93f5f32020-05-05 07:27:56 -05004686 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004687
SJW01901d92020-05-21 08:58:31 -05004688 Ops << Call->getType();
David Neto22f144c2017-06-12 14:26:21 -04004689
SJW01901d92020-05-21 08:58:31 -05004690 SPIRVID CalleeID = getSPIRVValue(Callee);
SJW806a5d82020-07-15 12:51:38 -05004691 if (!CalleeID.isValid()) {
David Neto43568eb2017-10-13 18:25:25 -04004692 errs() << "Can't translate function call. Missing builtin? "
David Neto862b7d82018-06-14 18:48:37 -04004693 << callee_name << " in: " << *Call << "\n";
David Neto43568eb2017-10-13 18:25:25 -04004694 // TODO(dneto): Can we error out? Enabling this llvm_unreachable
4695 // causes an infinite loop. Instead, go ahead and generate
4696 // the bad function call. A validator will catch the 0-Id.
4697 // llvm_unreachable("Can't translate function call");
4698 }
David Neto22f144c2017-06-12 14:26:21 -04004699
SJW01901d92020-05-21 08:58:31 -05004700 Ops << CalleeID;
David Neto22f144c2017-06-12 14:26:21 -04004701
David Neto22f144c2017-06-12 14:26:21 -04004702 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
SJW88ed5fe2020-05-11 12:40:57 -05004703 for (unsigned j = 0; j < CalleeFTy->getNumParams(); j++) {
4704 auto *operand = Call->getOperand(j);
alan-bakerd4d50652019-12-03 17:17:15 -05004705 auto *operand_type = operand->getType();
4706 // Images and samplers can be passed as function parameters without
4707 // variable pointers.
4708 if (operand_type->isPointerTy() && !IsImageType(operand_type) &&
4709 !IsSamplerType(operand_type)) {
alan-baker5b86ed72019-02-15 08:26:50 -05004710 auto sc =
4711 GetStorageClass(operand->getType()->getPointerAddressSpace());
4712 if (sc == spv::StorageClassStorageBuffer) {
4713 // Passing SSBO by reference requires variable pointers storage
4714 // buffer.
SJW01901d92020-05-21 08:58:31 -05004715 setVariablePointersStorageBuffer();
alan-baker5b86ed72019-02-15 08:26:50 -05004716 } else if (sc == spv::StorageClassWorkgroup) {
4717 // Workgroup references require variable pointers if they are not
4718 // memory object declarations.
4719 if (auto *operand_call = dyn_cast<CallInst>(operand)) {
4720 // Workgroup accessor represents a variable reference.
SJW61531372020-06-09 07:31:08 -05004721 if (Builtins::Lookup(operand_call->getCalledFunction()) !=
4722 Builtins::kClspvLocal)
SJW01901d92020-05-21 08:58:31 -05004723 setVariablePointers();
alan-baker5b86ed72019-02-15 08:26:50 -05004724 } else {
4725 // Arguments are function parameters.
4726 if (!isa<Argument>(operand))
SJW01901d92020-05-21 08:58:31 -05004727 setVariablePointers();
alan-baker5b86ed72019-02-15 08:26:50 -05004728 }
4729 }
4730 }
SJW01901d92020-05-21 08:58:31 -05004731 Ops << operand;
David Neto22f144c2017-06-12 14:26:21 -04004732 }
4733
SJW88ed5fe2020-05-11 12:40:57 -05004734 replaceSPIRVInst(Placeholder, spv::OpFunctionCall, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004735 }
4736 }
4737 }
4738}
4739
SJW77b87ad2020-04-21 14:37:52 -05004740void SPIRVProducerPass::HandleDeferredDecorations() {
4741 const auto &DL = module->getDataLayout();
alan-baker5a8c3be2020-09-09 13:44:26 -04004742 if (getTypesNeedingArrayStride().empty()) {
David Neto1a1a0582017-07-07 12:01:44 -04004743 return;
David Netoc6f3ab22018-04-06 18:02:31 -04004744 }
David Neto1a1a0582017-07-07 12:01:44 -04004745
David Netoc6f3ab22018-04-06 18:02:31 -04004746 // Insert ArrayStride decorations on pointer types, due to OpPtrAccessChain
4747 // instructions we generated earlier.
alan-bakerc3fd07f2020-10-22 09:48:49 -04004748 DenseSet<uint32_t> seen;
David Neto85082642018-03-24 06:55:20 -07004749 for (auto *type : getTypesNeedingArrayStride()) {
alan-bakerc3fd07f2020-10-22 09:48:49 -04004750 auto id = getSPIRVType(type);
4751 if (!seen.insert(id.get()).second)
4752 continue;
4753
David Neto85082642018-03-24 06:55:20 -07004754 Type *elemTy = nullptr;
4755 if (auto *ptrTy = dyn_cast<PointerType>(type)) {
4756 elemTy = ptrTy->getElementType();
alan-bakerb6b09dc2018-11-08 16:59:28 -05004757 } else if (auto *arrayTy = dyn_cast<ArrayType>(type)) {
alan-baker8eb435a2020-04-08 00:42:06 -04004758 elemTy = arrayTy->getElementType();
4759 } else if (auto *vecTy = dyn_cast<VectorType>(type)) {
4760 elemTy = vecTy->getElementType();
David Neto85082642018-03-24 06:55:20 -07004761 } else {
4762 errs() << "Unhandled strided type " << *type << "\n";
4763 llvm_unreachable("Unhandled strided type");
4764 }
David Neto1a1a0582017-07-07 12:01:44 -04004765
4766 // Ops[0] = Target ID
4767 // Ops[1] = Decoration (ArrayStride)
4768 // Ops[2] = Stride number (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05004769 SPIRVOperandVec Ops;
David Neto1a1a0582017-07-07 12:01:44 -04004770
David Neto85082642018-03-24 06:55:20 -07004771 // Same as DL.getIndexedOffsetInType( elemTy, { 1 } );
Alan Bakerfcda9482018-10-02 17:09:59 -04004772 const uint32_t stride = static_cast<uint32_t>(GetTypeAllocSize(elemTy, DL));
David Neto257c3892018-04-11 13:19:45 -04004773
alan-bakerc3fd07f2020-10-22 09:48:49 -04004774 Ops << id << spv::DecorationArrayStride << stride;
David Neto1a1a0582017-07-07 12:01:44 -04004775
SJWf93f5f32020-05-05 07:27:56 -05004776 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Netoc6f3ab22018-04-06 18:02:31 -04004777 }
David Neto1a1a0582017-07-07 12:01:44 -04004778}
4779
SJW61531372020-06-09 07:31:08 -05004780glsl::ExtInst
4781SPIRVProducerPass::getExtInstEnum(const Builtins::FunctionInfo &func_info) {
SJW61531372020-06-09 07:31:08 -05004782 switch (func_info.getType()) {
SJW2c317da2020-03-23 07:39:13 -05004783 case Builtins::kClamp: {
SJW61531372020-06-09 07:31:08 -05004784 auto param_type = func_info.getParameter(0);
SJW2c317da2020-03-23 07:39:13 -05004785 if (param_type.type_id == Type::FloatTyID) {
4786 return glsl::ExtInst::ExtInstFClamp;
4787 }
4788 return param_type.is_signed ? glsl::ExtInst::ExtInstSClamp
4789 : glsl::ExtInst::ExtInstUClamp;
4790 }
4791 case Builtins::kMax: {
SJW61531372020-06-09 07:31:08 -05004792 auto param_type = func_info.getParameter(0);
SJW2c317da2020-03-23 07:39:13 -05004793 if (param_type.type_id == Type::FloatTyID) {
4794 return glsl::ExtInst::ExtInstFMax;
4795 }
4796 return param_type.is_signed ? glsl::ExtInst::ExtInstSMax
4797 : glsl::ExtInst::ExtInstUMax;
4798 }
4799 case Builtins::kMin: {
SJW61531372020-06-09 07:31:08 -05004800 auto param_type = func_info.getParameter(0);
SJW2c317da2020-03-23 07:39:13 -05004801 if (param_type.type_id == Type::FloatTyID) {
4802 return glsl::ExtInst::ExtInstFMin;
4803 }
4804 return param_type.is_signed ? glsl::ExtInst::ExtInstSMin
4805 : glsl::ExtInst::ExtInstUMin;
4806 }
4807 case Builtins::kAbs:
4808 return glsl::ExtInst::ExtInstSAbs;
4809 case Builtins::kFmax:
Marco Antognini55d51862020-07-21 17:50:07 +01004810 return glsl::ExtInst::ExtInstNMax;
SJW2c317da2020-03-23 07:39:13 -05004811 case Builtins::kFmin:
Marco Antognini55d51862020-07-21 17:50:07 +01004812 return glsl::ExtInst::ExtInstNMin;
SJW2c317da2020-03-23 07:39:13 -05004813 case Builtins::kDegrees:
4814 return glsl::ExtInst::ExtInstDegrees;
4815 case Builtins::kRadians:
4816 return glsl::ExtInst::ExtInstRadians;
4817 case Builtins::kMix:
4818 return glsl::ExtInst::ExtInstFMix;
4819 case Builtins::kAcos:
4820 case Builtins::kAcospi:
4821 return glsl::ExtInst::ExtInstAcos;
4822 case Builtins::kAcosh:
4823 return glsl::ExtInst::ExtInstAcosh;
4824 case Builtins::kAsin:
4825 case Builtins::kAsinpi:
4826 return glsl::ExtInst::ExtInstAsin;
4827 case Builtins::kAsinh:
4828 return glsl::ExtInst::ExtInstAsinh;
4829 case Builtins::kAtan:
4830 case Builtins::kAtanpi:
4831 return glsl::ExtInst::ExtInstAtan;
4832 case Builtins::kAtanh:
4833 return glsl::ExtInst::ExtInstAtanh;
4834 case Builtins::kAtan2:
4835 case Builtins::kAtan2pi:
4836 return glsl::ExtInst::ExtInstAtan2;
4837 case Builtins::kCeil:
4838 return glsl::ExtInst::ExtInstCeil;
4839 case Builtins::kSin:
4840 case Builtins::kHalfSin:
4841 case Builtins::kNativeSin:
4842 return glsl::ExtInst::ExtInstSin;
4843 case Builtins::kSinh:
4844 return glsl::ExtInst::ExtInstSinh;
4845 case Builtins::kCos:
4846 case Builtins::kHalfCos:
4847 case Builtins::kNativeCos:
4848 return glsl::ExtInst::ExtInstCos;
4849 case Builtins::kCosh:
4850 return glsl::ExtInst::ExtInstCosh;
4851 case Builtins::kTan:
4852 case Builtins::kHalfTan:
4853 case Builtins::kNativeTan:
4854 return glsl::ExtInst::ExtInstTan;
4855 case Builtins::kTanh:
4856 return glsl::ExtInst::ExtInstTanh;
4857 case Builtins::kExp:
4858 case Builtins::kHalfExp:
4859 case Builtins::kNativeExp:
4860 return glsl::ExtInst::ExtInstExp;
4861 case Builtins::kExp2:
4862 case Builtins::kHalfExp2:
4863 case Builtins::kNativeExp2:
4864 return glsl::ExtInst::ExtInstExp2;
4865 case Builtins::kLog:
4866 case Builtins::kHalfLog:
4867 case Builtins::kNativeLog:
4868 return glsl::ExtInst::ExtInstLog;
4869 case Builtins::kLog2:
4870 case Builtins::kHalfLog2:
4871 case Builtins::kNativeLog2:
4872 return glsl::ExtInst::ExtInstLog2;
4873 case Builtins::kFabs:
4874 return glsl::ExtInst::ExtInstFAbs;
4875 case Builtins::kFma:
4876 return glsl::ExtInst::ExtInstFma;
4877 case Builtins::kFloor:
4878 return glsl::ExtInst::ExtInstFloor;
4879 case Builtins::kLdexp:
4880 return glsl::ExtInst::ExtInstLdexp;
4881 case Builtins::kPow:
4882 case Builtins::kPowr:
4883 case Builtins::kHalfPowr:
4884 case Builtins::kNativePowr:
4885 return glsl::ExtInst::ExtInstPow;
James Price38553362020-09-03 18:30:40 -04004886 case Builtins::kRint:
4887 return glsl::ExtInst::ExtInstRoundEven;
SJW2c317da2020-03-23 07:39:13 -05004888 case Builtins::kRound:
4889 return glsl::ExtInst::ExtInstRound;
4890 case Builtins::kSqrt:
4891 case Builtins::kHalfSqrt:
4892 case Builtins::kNativeSqrt:
4893 return glsl::ExtInst::ExtInstSqrt;
4894 case Builtins::kRsqrt:
4895 case Builtins::kHalfRsqrt:
4896 case Builtins::kNativeRsqrt:
4897 return glsl::ExtInst::ExtInstInverseSqrt;
4898 case Builtins::kTrunc:
4899 return glsl::ExtInst::ExtInstTrunc;
4900 case Builtins::kFrexp:
4901 return glsl::ExtInst::ExtInstFrexp;
SJW61531372020-06-09 07:31:08 -05004902 case Builtins::kClspvFract:
SJW2c317da2020-03-23 07:39:13 -05004903 case Builtins::kFract:
4904 return glsl::ExtInst::ExtInstFract;
4905 case Builtins::kSign:
4906 return glsl::ExtInst::ExtInstFSign;
4907 case Builtins::kLength:
4908 case Builtins::kFastLength:
4909 return glsl::ExtInst::ExtInstLength;
4910 case Builtins::kDistance:
4911 case Builtins::kFastDistance:
4912 return glsl::ExtInst::ExtInstDistance;
4913 case Builtins::kStep:
4914 return glsl::ExtInst::ExtInstStep;
4915 case Builtins::kSmoothstep:
4916 return glsl::ExtInst::ExtInstSmoothStep;
4917 case Builtins::kCross:
4918 return glsl::ExtInst::ExtInstCross;
4919 case Builtins::kNormalize:
4920 case Builtins::kFastNormalize:
4921 return glsl::ExtInst::ExtInstNormalize;
SJW61531372020-06-09 07:31:08 -05004922 case Builtins::kSpirvPack:
4923 return glsl::ExtInst::ExtInstPackHalf2x16;
4924 case Builtins::kSpirvUnpack:
4925 return glsl::ExtInst::ExtInstUnpackHalf2x16;
SJW2c317da2020-03-23 07:39:13 -05004926 default:
4927 break;
4928 }
4929
SJW61531372020-06-09 07:31:08 -05004930 if (func_info.getName().find("llvm.fmuladd.") == 0) {
4931 return glsl::ExtInst::ExtInstFma;
4932 }
4933 return kGlslExtInstBad;
David Neto3fbb4072017-10-16 11:28:14 -04004934}
4935
SJW61531372020-06-09 07:31:08 -05004936glsl::ExtInst SPIRVProducerPass::getIndirectExtInstEnum(
4937 const Builtins::FunctionInfo &func_info) {
4938 switch (func_info.getType()) {
SJW2c317da2020-03-23 07:39:13 -05004939 case Builtins::kClz:
4940 return glsl::ExtInst::ExtInstFindUMsb;
4941 case Builtins::kAcospi:
4942 return glsl::ExtInst::ExtInstAcos;
4943 case Builtins::kAsinpi:
4944 return glsl::ExtInst::ExtInstAsin;
4945 case Builtins::kAtanpi:
4946 return glsl::ExtInst::ExtInstAtan;
4947 case Builtins::kAtan2pi:
4948 return glsl::ExtInst::ExtInstAtan2;
4949 default:
4950 break;
4951 }
4952 return kGlslExtInstBad;
David Neto3fbb4072017-10-16 11:28:14 -04004953}
4954
SJW61531372020-06-09 07:31:08 -05004955glsl::ExtInst SPIRVProducerPass::getDirectOrIndirectExtInstEnum(
4956 const Builtins::FunctionInfo &func_info) {
4957 auto direct = getExtInstEnum(func_info);
David Neto3fbb4072017-10-16 11:28:14 -04004958 if (direct != kGlslExtInstBad)
4959 return direct;
SJW61531372020-06-09 07:31:08 -05004960 return getIndirectExtInstEnum(func_info);
David Neto22f144c2017-06-12 14:26:21 -04004961}
4962
David Neto22f144c2017-06-12 14:26:21 -04004963void SPIRVProducerPass::WriteOneWord(uint32_t Word) {
David Neto0676e6f2017-07-11 18:47:44 -04004964 binaryOut->write(reinterpret_cast<const char *>(&Word), sizeof(uint32_t));
David Neto22f144c2017-06-12 14:26:21 -04004965}
4966
SJW88ed5fe2020-05-11 12:40:57 -05004967void SPIRVProducerPass::WriteResultID(const SPIRVInstruction &Inst) {
SJW01901d92020-05-21 08:58:31 -05004968 WriteOneWord(Inst.getResultID().get());
David Neto22f144c2017-06-12 14:26:21 -04004969}
4970
SJW88ed5fe2020-05-11 12:40:57 -05004971void SPIRVProducerPass::WriteWordCountAndOpcode(const SPIRVInstruction &Inst) {
David Neto22f144c2017-06-12 14:26:21 -04004972 // High 16 bit : Word Count
4973 // Low 16 bit : Opcode
SJW88ed5fe2020-05-11 12:40:57 -05004974 uint32_t Word = Inst.getOpcode();
4975 const uint32_t count = Inst.getWordCount();
David Netoee2660d2018-06-28 16:31:29 -04004976 if (count > 65535) {
4977 errs() << "Word count limit of 65535 exceeded: " << count << "\n";
4978 llvm_unreachable("Word count too high");
4979 }
SJW88ed5fe2020-05-11 12:40:57 -05004980 Word |= Inst.getWordCount() << 16;
David Neto22f144c2017-06-12 14:26:21 -04004981 WriteOneWord(Word);
4982}
4983
SJW88ed5fe2020-05-11 12:40:57 -05004984void SPIRVProducerPass::WriteOperand(const SPIRVOperand &Op) {
4985 SPIRVOperandType OpTy = Op.getType();
David Neto22f144c2017-06-12 14:26:21 -04004986 switch (OpTy) {
4987 default: {
4988 llvm_unreachable("Unsupported SPIRV Operand Type???");
4989 break;
4990 }
4991 case SPIRVOperandType::NUMBERID: {
SJW88ed5fe2020-05-11 12:40:57 -05004992 WriteOneWord(Op.getNumID());
David Neto22f144c2017-06-12 14:26:21 -04004993 break;
4994 }
4995 case SPIRVOperandType::LITERAL_STRING: {
SJW88ed5fe2020-05-11 12:40:57 -05004996 std::string Str = Op.getLiteralStr();
David Neto22f144c2017-06-12 14:26:21 -04004997 const char *Data = Str.c_str();
4998 size_t WordSize = Str.size() / 4;
4999 for (unsigned Idx = 0; Idx < WordSize; Idx++) {
5000 WriteOneWord(*reinterpret_cast<const uint32_t *>(&Data[4 * Idx]));
5001 }
5002
5003 uint32_t Remainder = Str.size() % 4;
5004 uint32_t LastWord = 0;
5005 if (Remainder) {
5006 for (unsigned Idx = 0; Idx < Remainder; Idx++) {
5007 LastWord |= Data[4 * WordSize + Idx] << 8 * Idx;
5008 }
5009 }
5010
5011 WriteOneWord(LastWord);
5012 break;
5013 }
SJW88ed5fe2020-05-11 12:40:57 -05005014 case SPIRVOperandType::LITERAL_WORD: {
5015 WriteOneWord(Op.getLiteralNum()[0]);
5016 break;
5017 }
5018 case SPIRVOperandType::LITERAL_DWORD: {
5019 WriteOneWord(Op.getLiteralNum()[0]);
5020 WriteOneWord(Op.getLiteralNum()[1]);
David Neto22f144c2017-06-12 14:26:21 -04005021 break;
5022 }
5023 }
5024}
5025
5026void SPIRVProducerPass::WriteSPIRVBinary() {
SJW69939d52020-04-16 07:29:07 -05005027 for (int i = 0; i < kSectionCount; ++i) {
5028 WriteSPIRVBinary(SPIRVSections[i]);
5029 }
5030}
5031
5032void SPIRVProducerPass::WriteSPIRVBinary(SPIRVInstructionList &SPIRVInstList) {
SJW88ed5fe2020-05-11 12:40:57 -05005033 for (const auto &Inst : SPIRVInstList) {
5034 const auto &Ops = Inst.getOperands();
5035 spv::Op Opcode = static_cast<spv::Op>(Inst.getOpcode());
David Neto22f144c2017-06-12 14:26:21 -04005036
5037 switch (Opcode) {
5038 default: {
David Neto5c22a252018-03-15 16:07:41 -04005039 errs() << "Unsupported SPIR-V instruction opcode " << int(Opcode) << "\n";
David Neto22f144c2017-06-12 14:26:21 -04005040 llvm_unreachable("Unsupported SPIRV instruction");
5041 break;
5042 }
Marco Antognini68e5c512020-09-09 16:08:57 +01005043 case spv::OpUnreachable:
David Neto22f144c2017-06-12 14:26:21 -04005044 case spv::OpCapability:
5045 case spv::OpExtension:
5046 case spv::OpMemoryModel:
5047 case spv::OpEntryPoint:
5048 case spv::OpExecutionMode:
5049 case spv::OpSource:
5050 case spv::OpDecorate:
5051 case spv::OpMemberDecorate:
5052 case spv::OpBranch:
5053 case spv::OpBranchConditional:
5054 case spv::OpSelectionMerge:
5055 case spv::OpLoopMerge:
5056 case spv::OpStore:
5057 case spv::OpImageWrite:
5058 case spv::OpReturnValue:
5059 case spv::OpControlBarrier:
5060 case spv::OpMemoryBarrier:
5061 case spv::OpReturn:
5062 case spv::OpFunctionEnd:
alan-baker4986eff2020-10-29 13:38:00 -04005063 case spv::OpCopyMemory:
5064 case spv::OpAtomicStore: {
David Neto22f144c2017-06-12 14:26:21 -04005065 WriteWordCountAndOpcode(Inst);
5066 for (uint32_t i = 0; i < Ops.size(); i++) {
5067 WriteOperand(Ops[i]);
5068 }
5069 break;
5070 }
5071 case spv::OpTypeBool:
5072 case spv::OpTypeVoid:
5073 case spv::OpTypeSampler:
5074 case spv::OpLabel:
5075 case spv::OpExtInstImport:
5076 case spv::OpTypePointer:
5077 case spv::OpTypeRuntimeArray:
5078 case spv::OpTypeStruct:
5079 case spv::OpTypeImage:
5080 case spv::OpTypeSampledImage:
5081 case spv::OpTypeInt:
5082 case spv::OpTypeFloat:
5083 case spv::OpTypeArray:
5084 case spv::OpTypeVector:
alan-baker86ce19c2020-08-05 13:09:19 -04005085 case spv::OpTypeFunction:
5086 case spv::OpString: {
David Neto22f144c2017-06-12 14:26:21 -04005087 WriteWordCountAndOpcode(Inst);
5088 WriteResultID(Inst);
5089 for (uint32_t i = 0; i < Ops.size(); i++) {
5090 WriteOperand(Ops[i]);
5091 }
5092 break;
5093 }
5094 case spv::OpFunction:
5095 case spv::OpFunctionParameter:
5096 case spv::OpAccessChain:
5097 case spv::OpPtrAccessChain:
5098 case spv::OpInBoundsAccessChain:
5099 case spv::OpUConvert:
5100 case spv::OpSConvert:
5101 case spv::OpConvertFToU:
5102 case spv::OpConvertFToS:
5103 case spv::OpConvertUToF:
5104 case spv::OpConvertSToF:
5105 case spv::OpFConvert:
5106 case spv::OpConvertPtrToU:
5107 case spv::OpConvertUToPtr:
5108 case spv::OpBitcast:
alan-bakerc9c55ae2019-12-02 16:01:27 -05005109 case spv::OpFNegate:
David Neto22f144c2017-06-12 14:26:21 -04005110 case spv::OpIAdd:
alan-bakera52b7312020-10-26 08:58:51 -04005111 case spv::OpIAddCarry:
David Neto22f144c2017-06-12 14:26:21 -04005112 case spv::OpFAdd:
5113 case spv::OpISub:
5114 case spv::OpFSub:
5115 case spv::OpIMul:
5116 case spv::OpFMul:
5117 case spv::OpUDiv:
5118 case spv::OpSDiv:
5119 case spv::OpFDiv:
5120 case spv::OpUMod:
5121 case spv::OpSRem:
5122 case spv::OpFRem:
Kévin Petit8a560882019-03-21 15:24:34 +00005123 case spv::OpUMulExtended:
5124 case spv::OpSMulExtended:
David Neto22f144c2017-06-12 14:26:21 -04005125 case spv::OpBitwiseOr:
5126 case spv::OpBitwiseXor:
5127 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04005128 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04005129 case spv::OpShiftLeftLogical:
5130 case spv::OpShiftRightLogical:
5131 case spv::OpShiftRightArithmetic:
5132 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04005133 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04005134 case spv::OpCompositeExtract:
5135 case spv::OpVectorExtractDynamic:
5136 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04005137 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04005138 case spv::OpVectorInsertDynamic:
5139 case spv::OpVectorShuffle:
5140 case spv::OpIEqual:
5141 case spv::OpINotEqual:
5142 case spv::OpUGreaterThan:
5143 case spv::OpUGreaterThanEqual:
5144 case spv::OpULessThan:
5145 case spv::OpULessThanEqual:
5146 case spv::OpSGreaterThan:
5147 case spv::OpSGreaterThanEqual:
5148 case spv::OpSLessThan:
5149 case spv::OpSLessThanEqual:
5150 case spv::OpFOrdEqual:
5151 case spv::OpFOrdGreaterThan:
5152 case spv::OpFOrdGreaterThanEqual:
5153 case spv::OpFOrdLessThan:
5154 case spv::OpFOrdLessThanEqual:
5155 case spv::OpFOrdNotEqual:
5156 case spv::OpFUnordEqual:
5157 case spv::OpFUnordGreaterThan:
5158 case spv::OpFUnordGreaterThanEqual:
5159 case spv::OpFUnordLessThan:
5160 case spv::OpFUnordLessThanEqual:
5161 case spv::OpFUnordNotEqual:
5162 case spv::OpExtInst:
5163 case spv::OpIsInf:
5164 case spv::OpIsNan:
5165 case spv::OpAny:
5166 case spv::OpAll:
5167 case spv::OpUndef:
5168 case spv::OpConstantNull:
5169 case spv::OpLogicalOr:
5170 case spv::OpLogicalAnd:
5171 case spv::OpLogicalNot:
5172 case spv::OpLogicalNotEqual:
5173 case spv::OpConstantComposite:
5174 case spv::OpSpecConstantComposite:
5175 case spv::OpConstantTrue:
5176 case spv::OpConstantFalse:
5177 case spv::OpConstant:
5178 case spv::OpSpecConstant:
5179 case spv::OpVariable:
5180 case spv::OpFunctionCall:
5181 case spv::OpSampledImage:
alan-baker75090e42020-02-20 11:21:04 -05005182 case spv::OpImageFetch:
alan-bakerf6bc8252020-09-23 14:58:55 -04005183 case spv::OpImageRead:
David Neto22f144c2017-06-12 14:26:21 -04005184 case spv::OpImageSampleExplicitLod:
David Neto5c22a252018-03-15 16:07:41 -04005185 case spv::OpImageQuerySize:
alan-bakerce179f12019-12-06 19:02:22 -05005186 case spv::OpImageQuerySizeLod:
David Neto22f144c2017-06-12 14:26:21 -04005187 case spv::OpSelect:
5188 case spv::OpPhi:
5189 case spv::OpLoad:
alan-baker4986eff2020-10-29 13:38:00 -04005190 case spv::OpAtomicLoad:
David Neto22f144c2017-06-12 14:26:21 -04005191 case spv::OpAtomicIAdd:
5192 case spv::OpAtomicISub:
5193 case spv::OpAtomicExchange:
5194 case spv::OpAtomicIIncrement:
5195 case spv::OpAtomicIDecrement:
5196 case spv::OpAtomicCompareExchange:
5197 case spv::OpAtomicUMin:
5198 case spv::OpAtomicSMin:
5199 case spv::OpAtomicUMax:
5200 case spv::OpAtomicSMax:
5201 case spv::OpAtomicAnd:
5202 case spv::OpAtomicOr:
5203 case spv::OpAtomicXor:
SJW806a5d82020-07-15 12:51:38 -05005204 case spv::OpDot:
5205 case spv::OpGroupNonUniformAll:
5206 case spv::OpGroupNonUniformAny:
5207 case spv::OpGroupNonUniformBroadcast:
5208 case spv::OpGroupNonUniformIAdd:
5209 case spv::OpGroupNonUniformFAdd:
5210 case spv::OpGroupNonUniformSMin:
5211 case spv::OpGroupNonUniformUMin:
5212 case spv::OpGroupNonUniformFMin:
5213 case spv::OpGroupNonUniformSMax:
5214 case spv::OpGroupNonUniformUMax:
5215 case spv::OpGroupNonUniformFMax: {
David Neto22f144c2017-06-12 14:26:21 -04005216 WriteWordCountAndOpcode(Inst);
5217 WriteOperand(Ops[0]);
5218 WriteResultID(Inst);
5219 for (uint32_t i = 1; i < Ops.size(); i++) {
5220 WriteOperand(Ops[i]);
5221 }
5222 break;
5223 }
5224 }
5225 }
5226}
Alan Baker9bf93fb2018-08-28 16:59:26 -04005227
alan-bakerb6b09dc2018-11-08 16:59:28 -05005228bool SPIRVProducerPass::IsTypeNullable(const Type *type) const {
Alan Baker9bf93fb2018-08-28 16:59:26 -04005229 switch (type->getTypeID()) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05005230 case Type::HalfTyID:
5231 case Type::FloatTyID:
5232 case Type::DoubleTyID:
5233 case Type::IntegerTyID:
James Price59a1c752020-04-23 23:06:16 -04005234 case Type::FixedVectorTyID:
alan-bakerb6b09dc2018-11-08 16:59:28 -05005235 return true;
5236 case Type::PointerTyID: {
5237 const PointerType *pointer_type = cast<PointerType>(type);
5238 if (pointer_type->getPointerAddressSpace() !=
5239 AddressSpace::UniformConstant) {
5240 auto pointee_type = pointer_type->getPointerElementType();
5241 if (pointee_type->isStructTy() &&
5242 cast<StructType>(pointee_type)->isOpaque()) {
5243 // Images and samplers are not nullable.
5244 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04005245 }
Alan Baker9bf93fb2018-08-28 16:59:26 -04005246 }
alan-bakerb6b09dc2018-11-08 16:59:28 -05005247 return true;
5248 }
5249 case Type::ArrayTyID:
alan-baker8eb435a2020-04-08 00:42:06 -04005250 return IsTypeNullable(type->getArrayElementType());
alan-bakerb6b09dc2018-11-08 16:59:28 -05005251 case Type::StructTyID: {
5252 const StructType *struct_type = cast<StructType>(type);
5253 // Images and samplers are not nullable.
5254 if (struct_type->isOpaque())
Alan Baker9bf93fb2018-08-28 16:59:26 -04005255 return false;
alan-bakerb6b09dc2018-11-08 16:59:28 -05005256 for (const auto element : struct_type->elements()) {
5257 if (!IsTypeNullable(element))
5258 return false;
5259 }
5260 return true;
5261 }
5262 default:
5263 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04005264 }
5265}
Alan Bakerfcda9482018-10-02 17:09:59 -04005266
SJW77b87ad2020-04-21 14:37:52 -05005267void SPIRVProducerPass::PopulateUBOTypeMaps() {
Alan Bakerfcda9482018-10-02 17:09:59 -04005268 if (auto *offsets_md =
SJW77b87ad2020-04-21 14:37:52 -05005269 module->getNamedMetadata(clspv::RemappedTypeOffsetMetadataName())) {
Alan Bakerfcda9482018-10-02 17:09:59 -04005270 // Metdata is stored as key-value pair operands. The first element of each
5271 // operand is the type and the second is a vector of offsets.
5272 for (const auto *operand : offsets_md->operands()) {
5273 const auto *pair = cast<MDTuple>(operand);
5274 auto *type =
5275 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
5276 const auto *offset_vector = cast<MDTuple>(pair->getOperand(1));
5277 std::vector<uint32_t> offsets;
5278 for (const Metadata *offset_md : offset_vector->operands()) {
5279 const auto *constant_md = cast<ConstantAsMetadata>(offset_md);
alan-bakerb6b09dc2018-11-08 16:59:28 -05005280 offsets.push_back(static_cast<uint32_t>(
5281 cast<ConstantInt>(constant_md->getValue())->getZExtValue()));
Alan Bakerfcda9482018-10-02 17:09:59 -04005282 }
5283 RemappedUBOTypeOffsets.insert(std::make_pair(type, offsets));
5284 }
5285 }
5286
5287 if (auto *sizes_md =
SJW77b87ad2020-04-21 14:37:52 -05005288 module->getNamedMetadata(clspv::RemappedTypeSizesMetadataName())) {
Alan Bakerfcda9482018-10-02 17:09:59 -04005289 // Metadata is stored as key-value pair operands. The first element of each
5290 // operand is the type and the second is a triple of sizes: type size in
5291 // bits, store size and alloc size.
5292 for (const auto *operand : sizes_md->operands()) {
5293 const auto *pair = cast<MDTuple>(operand);
5294 auto *type =
5295 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
5296 const auto *size_triple = cast<MDTuple>(pair->getOperand(1));
5297 uint64_t type_size_in_bits =
5298 cast<ConstantInt>(
5299 cast<ConstantAsMetadata>(size_triple->getOperand(0))->getValue())
5300 ->getZExtValue();
5301 uint64_t type_store_size =
5302 cast<ConstantInt>(
5303 cast<ConstantAsMetadata>(size_triple->getOperand(1))->getValue())
5304 ->getZExtValue();
5305 uint64_t type_alloc_size =
5306 cast<ConstantInt>(
5307 cast<ConstantAsMetadata>(size_triple->getOperand(2))->getValue())
5308 ->getZExtValue();
5309 RemappedUBOTypeSizes.insert(std::make_pair(
5310 type, std::make_tuple(type_size_in_bits, type_store_size,
5311 type_alloc_size)));
5312 }
5313 }
5314}
5315
5316uint64_t SPIRVProducerPass::GetTypeSizeInBits(Type *type,
5317 const DataLayout &DL) {
5318 auto iter = RemappedUBOTypeSizes.find(type);
5319 if (iter != RemappedUBOTypeSizes.end()) {
5320 return std::get<0>(iter->second);
5321 }
5322
5323 return DL.getTypeSizeInBits(type);
5324}
5325
5326uint64_t SPIRVProducerPass::GetTypeStoreSize(Type *type, const DataLayout &DL) {
5327 auto iter = RemappedUBOTypeSizes.find(type);
5328 if (iter != RemappedUBOTypeSizes.end()) {
5329 return std::get<1>(iter->second);
5330 }
5331
5332 return DL.getTypeStoreSize(type);
5333}
5334
5335uint64_t SPIRVProducerPass::GetTypeAllocSize(Type *type, const DataLayout &DL) {
5336 auto iter = RemappedUBOTypeSizes.find(type);
5337 if (iter != RemappedUBOTypeSizes.end()) {
5338 return std::get<2>(iter->second);
5339 }
5340
5341 return DL.getTypeAllocSize(type);
5342}
alan-baker5b86ed72019-02-15 08:26:50 -05005343
Kévin Petitbbbda972020-03-03 19:16:31 +00005344uint32_t SPIRVProducerPass::GetExplicitLayoutStructMemberOffset(
5345 StructType *type, unsigned member, const DataLayout &DL) {
5346 const auto StructLayout = DL.getStructLayout(type);
5347 // Search for the correct offsets if this type was remapped.
5348 std::vector<uint32_t> *offsets = nullptr;
5349 auto iter = RemappedUBOTypeOffsets.find(type);
5350 if (iter != RemappedUBOTypeOffsets.end()) {
5351 offsets = &iter->second;
5352 }
5353 auto ByteOffset =
5354 static_cast<uint32_t>(StructLayout->getElementOffset(member));
5355 if (offsets) {
5356 ByteOffset = (*offsets)[member];
5357 }
5358
5359 return ByteOffset;
5360}
5361
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04005362void SPIRVProducerPass::setVariablePointersCapabilities(
5363 unsigned address_space) {
alan-baker5b86ed72019-02-15 08:26:50 -05005364 if (GetStorageClass(address_space) == spv::StorageClassStorageBuffer) {
SJW01901d92020-05-21 08:58:31 -05005365 setVariablePointersStorageBuffer();
alan-baker5b86ed72019-02-15 08:26:50 -05005366 } else {
SJW01901d92020-05-21 08:58:31 -05005367 setVariablePointers();
alan-baker5b86ed72019-02-15 08:26:50 -05005368 }
5369}
5370
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04005371Value *SPIRVProducerPass::GetBasePointer(Value *v) {
alan-baker5b86ed72019-02-15 08:26:50 -05005372 if (auto *gep = dyn_cast<GetElementPtrInst>(v)) {
5373 return GetBasePointer(gep->getPointerOperand());
5374 }
5375
5376 // Conservatively return |v|.
5377 return v;
5378}
5379
5380bool SPIRVProducerPass::sameResource(Value *lhs, Value *rhs) const {
5381 if (auto *lhs_call = dyn_cast<CallInst>(lhs)) {
5382 if (auto *rhs_call = dyn_cast<CallInst>(rhs)) {
alan-baker7506abb2020-09-10 15:02:55 -04005383 const auto &lhs_func_info =
5384 Builtins::Lookup(lhs_call->getCalledFunction());
5385 const auto &rhs_func_info =
5386 Builtins::Lookup(rhs_call->getCalledFunction());
SJW61531372020-06-09 07:31:08 -05005387 if (lhs_func_info.getType() == Builtins::kClspvResource &&
5388 rhs_func_info.getType() == Builtins::kClspvResource) {
alan-baker5b86ed72019-02-15 08:26:50 -05005389 // For resource accessors, match descriptor set and binding.
5390 if (lhs_call->getOperand(0) == rhs_call->getOperand(0) &&
5391 lhs_call->getOperand(1) == rhs_call->getOperand(1))
5392 return true;
SJW61531372020-06-09 07:31:08 -05005393 } else if (lhs_func_info.getType() == Builtins::kClspvLocal &&
5394 rhs_func_info.getType() == Builtins::kClspvLocal) {
alan-baker5b86ed72019-02-15 08:26:50 -05005395 // For workgroup resources, match spec id.
5396 if (lhs_call->getOperand(0) == rhs_call->getOperand(0))
5397 return true;
5398 }
5399 }
5400 }
5401
5402 return false;
5403}
5404
5405bool SPIRVProducerPass::selectFromSameObject(Instruction *inst) {
5406 assert(inst->getType()->isPointerTy());
5407 assert(GetStorageClass(inst->getType()->getPointerAddressSpace()) ==
5408 spv::StorageClassStorageBuffer);
5409 const bool hack_undef = clspv::Option::HackUndef();
5410 if (auto *select = dyn_cast<SelectInst>(inst)) {
5411 auto *true_base = GetBasePointer(select->getTrueValue());
5412 auto *false_base = GetBasePointer(select->getFalseValue());
5413
5414 if (true_base == false_base)
5415 return true;
5416
5417 // If either the true or false operand is a null, then we satisfy the same
5418 // object constraint.
5419 if (auto *true_cst = dyn_cast<Constant>(true_base)) {
5420 if (true_cst->isNullValue() || (hack_undef && isa<UndefValue>(true_base)))
5421 return true;
5422 }
5423
5424 if (auto *false_cst = dyn_cast<Constant>(false_base)) {
5425 if (false_cst->isNullValue() ||
5426 (hack_undef && isa<UndefValue>(false_base)))
5427 return true;
5428 }
5429
5430 if (sameResource(true_base, false_base))
5431 return true;
5432 } else if (auto *phi = dyn_cast<PHINode>(inst)) {
5433 Value *value = nullptr;
5434 bool ok = true;
5435 for (unsigned i = 0; ok && i != phi->getNumIncomingValues(); ++i) {
5436 auto *base = GetBasePointer(phi->getIncomingValue(i));
5437 // Null values satisfy the constraint of selecting of selecting from the
5438 // same object.
5439 if (!value) {
5440 if (auto *cst = dyn_cast<Constant>(base)) {
5441 if (!cst->isNullValue() && !(hack_undef && isa<UndefValue>(base)))
5442 value = base;
5443 } else {
5444 value = base;
5445 }
5446 } else if (base != value) {
5447 if (auto *base_cst = dyn_cast<Constant>(base)) {
5448 if (base_cst->isNullValue() || (hack_undef && isa<UndefValue>(base)))
5449 continue;
5450 }
5451
5452 if (sameResource(value, base))
5453 continue;
5454
5455 // Values don't represent the same base.
5456 ok = false;
5457 }
5458 }
5459
5460 return ok;
5461 }
5462
5463 // Conservatively return false.
5464 return false;
5465}
alan-bakere9308012019-03-15 10:25:13 -04005466
5467bool SPIRVProducerPass::CalledWithCoherentResource(Argument &Arg) {
5468 if (!Arg.getType()->isPointerTy() ||
5469 Arg.getType()->getPointerAddressSpace() != clspv::AddressSpace::Global) {
5470 // Only SSBOs need to be annotated as coherent.
5471 return false;
5472 }
5473
5474 DenseSet<Value *> visited;
5475 std::vector<Value *> stack;
5476 for (auto *U : Arg.getParent()->users()) {
5477 if (auto *call = dyn_cast<CallInst>(U)) {
5478 stack.push_back(call->getOperand(Arg.getArgNo()));
5479 }
5480 }
5481
5482 while (!stack.empty()) {
5483 Value *v = stack.back();
5484 stack.pop_back();
5485
5486 if (!visited.insert(v).second)
5487 continue;
5488
5489 auto *resource_call = dyn_cast<CallInst>(v);
5490 if (resource_call &&
SJW61531372020-06-09 07:31:08 -05005491 Builtins::Lookup(resource_call->getCalledFunction()).getType() ==
5492 Builtins::kClspvResource) {
alan-bakere9308012019-03-15 10:25:13 -04005493 // If this is a resource accessor function, check if the coherent operand
5494 // is set.
5495 const auto coherent =
5496 unsigned(dyn_cast<ConstantInt>(resource_call->getArgOperand(5))
5497 ->getZExtValue());
5498 if (coherent == 1)
5499 return true;
5500 } else if (auto *arg = dyn_cast<Argument>(v)) {
5501 // If this is a function argument, trace through its callers.
alan-bakere98f3f92019-04-08 15:06:36 -04005502 for (auto U : arg->getParent()->users()) {
alan-bakere9308012019-03-15 10:25:13 -04005503 if (auto *call = dyn_cast<CallInst>(U)) {
5504 stack.push_back(call->getOperand(arg->getArgNo()));
5505 }
5506 }
5507 } else if (auto *user = dyn_cast<User>(v)) {
5508 // If this is a user, traverse all operands that could lead to resource
5509 // variables.
5510 for (unsigned i = 0; i != user->getNumOperands(); ++i) {
5511 Value *operand = user->getOperand(i);
5512 if (operand->getType()->isPointerTy() &&
5513 operand->getType()->getPointerAddressSpace() ==
5514 clspv::AddressSpace::Global) {
5515 stack.push_back(operand);
5516 }
5517 }
5518 }
5519 }
5520
5521 // No coherent resource variables encountered.
5522 return false;
5523}
alan-baker06cad652019-12-03 17:56:47 -05005524
SJW77b87ad2020-04-21 14:37:52 -05005525void SPIRVProducerPass::PopulateStructuredCFGMaps() {
alan-baker06cad652019-12-03 17:56:47 -05005526 // First, track loop merges and continues.
5527 DenseSet<BasicBlock *> LoopMergesAndContinues;
SJW77b87ad2020-04-21 14:37:52 -05005528 for (auto &F : *module) {
alan-baker06cad652019-12-03 17:56:47 -05005529 if (F.isDeclaration())
5530 continue;
5531
5532 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
5533 const LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>(F).getLoopInfo();
5534 std::deque<BasicBlock *> order;
5535 DenseSet<BasicBlock *> visited;
5536 clspv::ComputeStructuredOrder(&*F.begin(), &DT, LI, &order, &visited);
5537
5538 for (auto BB : order) {
5539 auto terminator = BB->getTerminator();
5540 auto branch = dyn_cast<BranchInst>(terminator);
5541 if (LI.isLoopHeader(BB)) {
5542 auto L = LI.getLoopFor(BB);
5543 BasicBlock *ContinueBB = nullptr;
5544 BasicBlock *MergeBB = nullptr;
5545
5546 MergeBB = L->getExitBlock();
5547 if (!MergeBB) {
5548 // StructurizeCFG pass converts CFG into triangle shape and the cfg
5549 // has regions with single entry/exit. As a result, loop should not
5550 // have multiple exits.
5551 llvm_unreachable("Loop has multiple exits???");
5552 }
5553
5554 if (L->isLoopLatch(BB)) {
5555 ContinueBB = BB;
5556 } else {
5557 // From SPIR-V spec 2.11, Continue Target must dominate that back-edge
5558 // block.
5559 BasicBlock *Header = L->getHeader();
5560 BasicBlock *Latch = L->getLoopLatch();
5561 for (auto *loop_block : L->blocks()) {
5562 if (loop_block == Header) {
5563 continue;
5564 }
5565
5566 // Check whether block dominates block with back-edge.
5567 // The loop latch is the single block with a back-edge. If it was
5568 // possible, StructurizeCFG made the loop conform to this
5569 // requirement, otherwise |Latch| is a nullptr.
5570 if (DT.dominates(loop_block, Latch)) {
5571 ContinueBB = loop_block;
5572 }
5573 }
5574
5575 if (!ContinueBB) {
5576 llvm_unreachable("Wrong continue block from loop");
5577 }
5578 }
5579
5580 // Record the continue and merge blocks.
5581 MergeBlocks[BB] = MergeBB;
5582 ContinueBlocks[BB] = ContinueBB;
5583 LoopMergesAndContinues.insert(MergeBB);
5584 LoopMergesAndContinues.insert(ContinueBB);
5585 } else if (branch && branch->isConditional()) {
5586 auto L = LI.getLoopFor(BB);
5587 bool HasBackedge = false;
5588 while (L && !HasBackedge) {
5589 if (L->isLoopLatch(BB)) {
5590 HasBackedge = true;
5591 }
5592 L = L->getParentLoop();
5593 }
5594
5595 if (!HasBackedge) {
5596 // Only need a merge if the branch doesn't include a loop break or
5597 // continue.
5598 auto true_bb = branch->getSuccessor(0);
5599 auto false_bb = branch->getSuccessor(1);
5600 if (!LoopMergesAndContinues.count(true_bb) &&
5601 !LoopMergesAndContinues.count(false_bb)) {
5602 // StructurizeCFG pass already manipulated CFG. Just use false block
5603 // of branch instruction as merge block.
5604 MergeBlocks[BB] = false_bb;
5605 }
5606 }
5607 }
5608 }
5609 }
5610}
alan-baker86ce19c2020-08-05 13:09:19 -04005611
5612SPIRVID SPIRVProducerPass::getReflectionImport() {
5613 if (!ReflectionID.isValid()) {
5614 addSPIRVInst<kExtensions>(spv::OpExtension, "SPV_KHR_non_semantic_info");
5615 ReflectionID = addSPIRVInst<kImports>(spv::OpExtInstImport,
5616 "NonSemantic.ClspvReflection.1");
5617 }
5618 return ReflectionID;
5619}
5620
5621void SPIRVProducerPass::GenerateReflection() {
5622 GenerateKernelReflection();
5623 GeneratePushConstantReflection();
5624 GenerateSpecConstantReflection();
5625}
5626
5627void SPIRVProducerPass::GeneratePushConstantReflection() {
5628 if (auto GV = module->getGlobalVariable(clspv::PushConstantsVariableName())) {
5629 auto const &DL = module->getDataLayout();
5630 auto MD = GV->getMetadata(clspv::PushConstantsMetadataName());
5631 auto STy = cast<StructType>(GV->getValueType());
5632
5633 for (unsigned i = 0; i < STy->getNumElements(); i++) {
5634 auto pc = static_cast<clspv::PushConstant>(
5635 mdconst::extract<ConstantInt>(MD->getOperand(i))->getZExtValue());
5636 if (pc == PushConstant::KernelArgument)
5637 continue;
5638
5639 auto memberType = STy->getElementType(i);
5640 auto offset = GetExplicitLayoutStructMemberOffset(STy, i, DL);
5641 unsigned previousOffset = 0;
5642 if (i > 0) {
5643 previousOffset = GetExplicitLayoutStructMemberOffset(STy, i - 1, DL);
5644 }
5645 auto size = static_cast<uint32_t>(GetTypeSizeInBits(memberType, DL)) / 8;
5646 assert(isValidExplicitLayout(*module, STy, i,
5647 spv::StorageClassPushConstant, offset,
5648 previousOffset));
5649
5650 reflection::ExtInst pc_inst = reflection::ExtInstMax;
5651 switch (pc) {
5652 case PushConstant::GlobalOffset:
5653 pc_inst = reflection::ExtInstPushConstantGlobalOffset;
5654 break;
5655 case PushConstant::EnqueuedLocalSize:
5656 pc_inst = reflection::ExtInstPushConstantEnqueuedLocalSize;
5657 break;
5658 case PushConstant::GlobalSize:
5659 pc_inst = reflection::ExtInstPushConstantGlobalSize;
5660 break;
5661 case PushConstant::RegionOffset:
5662 pc_inst = reflection::ExtInstPushConstantRegionOffset;
5663 break;
5664 case PushConstant::NumWorkgroups:
5665 pc_inst = reflection::ExtInstPushConstantNumWorkgroups;
5666 break;
5667 case PushConstant::RegionGroupOffset:
5668 pc_inst = reflection::ExtInstPushConstantRegionGroupOffset;
5669 break;
5670 default:
5671 llvm_unreachable("Unhandled push constant");
5672 break;
5673 }
5674
5675 auto import_id = getReflectionImport();
5676 SPIRVOperandVec Ops;
5677 Ops << getSPIRVType(Type::getVoidTy(module->getContext())) << import_id
5678 << pc_inst << getSPIRVInt32Constant(offset)
5679 << getSPIRVInt32Constant(size);
5680 addSPIRVInst(spv::OpExtInst, Ops);
5681 }
5682 }
5683}
5684
5685void SPIRVProducerPass::GenerateSpecConstantReflection() {
5686 const uint32_t kMax = std::numeric_limits<uint32_t>::max();
5687 uint32_t wgsize_id[3] = {kMax, kMax, kMax};
5688 uint32_t global_offset_id[3] = {kMax, kMax, kMax};
5689 uint32_t work_dim_id = kMax;
5690 for (auto pair : clspv::GetSpecConstants(module)) {
5691 auto kind = pair.first;
5692 auto id = pair.second;
5693
5694 // Local memory size is only used for kernel arguments.
5695 if (kind == SpecConstant::kLocalMemorySize)
5696 continue;
5697
5698 switch (kind) {
5699 case SpecConstant::kWorkgroupSizeX:
5700 wgsize_id[0] = id;
5701 break;
5702 case SpecConstant::kWorkgroupSizeY:
5703 wgsize_id[1] = id;
5704 break;
5705 case SpecConstant::kWorkgroupSizeZ:
5706 wgsize_id[2] = id;
5707 break;
5708 case SpecConstant::kGlobalOffsetX:
5709 global_offset_id[0] = id;
5710 break;
5711 case SpecConstant::kGlobalOffsetY:
5712 global_offset_id[1] = id;
5713 break;
5714 case SpecConstant::kGlobalOffsetZ:
5715 global_offset_id[2] = id;
5716 break;
5717 case SpecConstant::kWorkDim:
5718 work_dim_id = id;
5719 break;
5720 default:
5721 llvm_unreachable("Unhandled spec constant");
5722 }
5723 }
5724
5725 auto import_id = getReflectionImport();
5726 auto void_id = getSPIRVType(Type::getVoidTy(module->getContext()));
5727 SPIRVOperandVec Ops;
5728 if (wgsize_id[0] != kMax) {
5729 assert(wgsize_id[1] != kMax);
5730 assert(wgsize_id[2] != kMax);
5731 Ops.clear();
5732 Ops << void_id << import_id << reflection::ExtInstSpecConstantWorkgroupSize
5733 << getSPIRVInt32Constant(wgsize_id[0])
5734 << getSPIRVInt32Constant(wgsize_id[1])
5735 << getSPIRVInt32Constant(wgsize_id[2]);
5736 addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
5737 }
5738 if (global_offset_id[0] != kMax) {
5739 assert(global_offset_id[1] != kMax);
5740 assert(global_offset_id[2] != kMax);
5741 Ops.clear();
5742 Ops << void_id << import_id << reflection::ExtInstSpecConstantGlobalOffset
5743 << getSPIRVInt32Constant(global_offset_id[0])
5744 << getSPIRVInt32Constant(global_offset_id[1])
5745 << getSPIRVInt32Constant(global_offset_id[2]);
5746 addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
5747 }
5748 if (work_dim_id != kMax) {
5749 Ops.clear();
5750 Ops << void_id << import_id << reflection::ExtInstSpecConstantWorkDim
5751 << getSPIRVInt32Constant(work_dim_id);
5752 addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
5753 }
5754}
5755
5756void SPIRVProducerPass::GenerateKernelReflection() {
5757 const auto &DL = module->getDataLayout();
5758 auto import_id = getReflectionImport();
5759 auto void_id = getSPIRVType(Type::getVoidTy(module->getContext()));
5760
5761 for (auto &F : *module) {
5762 if (F.isDeclaration() || F.getCallingConv() != CallingConv::SPIR_KERNEL) {
5763 continue;
5764 }
5765
5766 // OpString for the kernel name.
5767 auto kernel_name =
5768 addSPIRVInst<kDebug>(spv::OpString, F.getName().str().c_str());
5769
5770 // Kernel declaration
5771 // Ops[0] = void type
5772 // Ops[1] = reflection ext import
5773 // Ops[2] = function id
5774 // Ops[3] = kernel name
5775 SPIRVOperandVec Ops;
5776 Ops << void_id << import_id << reflection::ExtInstKernel << ValueMap[&F]
5777 << kernel_name;
5778 auto kernel_decl = addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
5779
5780 // Generate the required workgroup size property if it was specified.
5781 if (const MDNode *MD = F.getMetadata("reqd_work_group_size")) {
5782 uint32_t CurXDimCst = static_cast<uint32_t>(
5783 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
5784 uint32_t CurYDimCst = static_cast<uint32_t>(
5785 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
5786 uint32_t CurZDimCst = static_cast<uint32_t>(
5787 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
5788
5789 Ops.clear();
5790 Ops << void_id << import_id
5791 << reflection::ExtInstPropertyRequiredWorkgroupSize << kernel_decl
5792 << getSPIRVInt32Constant(CurXDimCst)
5793 << getSPIRVInt32Constant(CurYDimCst)
5794 << getSPIRVInt32Constant(CurZDimCst);
5795 addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
5796 }
5797
5798 auto &resource_var_at_index = FunctionToResourceVarsMap[&F];
5799 auto *func_ty = F.getFunctionType();
5800
5801 // If we've clustered POD arguments, then argument details are in metadata.
5802 // If an argument maps to a resource variable, then get descriptor set and
5803 // binding from the resource variable. Other info comes from the metadata.
5804 const auto *arg_map = F.getMetadata(clspv::KernelArgMapMetadataName());
5805 auto local_spec_id_md =
5806 module->getNamedMetadata(clspv::LocalSpecIdMetadataName());
5807 if (arg_map) {
5808 for (const auto &arg : arg_map->operands()) {
5809 const MDNode *arg_node = dyn_cast<MDNode>(arg.get());
5810 assert(arg_node->getNumOperands() == 6);
5811 const auto name =
5812 dyn_cast<MDString>(arg_node->getOperand(0))->getString();
5813 const auto old_index =
5814 dyn_extract<ConstantInt>(arg_node->getOperand(1))->getZExtValue();
5815 // Remapped argument index
5816 const int new_index = static_cast<int>(
5817 dyn_extract<ConstantInt>(arg_node->getOperand(2))->getSExtValue());
5818 const auto offset =
5819 dyn_extract<ConstantInt>(arg_node->getOperand(3))->getZExtValue();
5820 const auto size =
5821 dyn_extract<ConstantInt>(arg_node->getOperand(4))->getZExtValue();
5822 const auto argKind = clspv::GetArgKindFromName(
5823 dyn_cast<MDString>(arg_node->getOperand(5))->getString().str());
5824
5825 // If this is a local memory argument, find the right spec id for this
5826 // argument.
5827 int64_t spec_id = -1;
5828 if (argKind == clspv::ArgKind::Local) {
5829 for (auto spec_id_arg : local_spec_id_md->operands()) {
5830 if ((&F == dyn_cast<Function>(
5831 dyn_cast<ValueAsMetadata>(spec_id_arg->getOperand(0))
5832 ->getValue())) &&
5833 (static_cast<uint64_t>(new_index) ==
5834 mdconst::extract<ConstantInt>(spec_id_arg->getOperand(1))
5835 ->getZExtValue())) {
5836 spec_id =
5837 mdconst::extract<ConstantInt>(spec_id_arg->getOperand(2))
5838 ->getSExtValue();
5839 break;
5840 }
5841 }
5842 }
5843
5844 // Generate the specific argument instruction.
5845 const uint32_t ordinal = static_cast<uint32_t>(old_index);
5846 const uint32_t arg_offset = static_cast<uint32_t>(offset);
5847 const uint32_t arg_size = static_cast<uint32_t>(size);
5848 uint32_t elem_size = 0;
5849 uint32_t descriptor_set = 0;
5850 uint32_t binding = 0;
5851 if (spec_id > 0) {
5852 elem_size = static_cast<uint32_t>(
5853 GetTypeAllocSize(func_ty->getParamType(unsigned(new_index))
5854 ->getPointerElementType(),
5855 DL));
5856 } else if (new_index >= 0) {
5857 auto *info = resource_var_at_index[new_index];
5858 assert(info);
5859 descriptor_set = info->descriptor_set;
5860 binding = info->binding;
5861 }
5862 AddArgumentReflection(kernel_decl, name.str(), argKind, ordinal,
5863 descriptor_set, binding, arg_offset, arg_size,
5864 static_cast<uint32_t>(spec_id), elem_size);
5865 }
5866 } else {
5867 // There is no argument map.
5868 // Take descriptor info from the resource variable calls.
5869 // Take argument name and size from the arguments list.
5870
5871 SmallVector<Argument *, 4> arguments;
5872 for (auto &arg : F.args()) {
5873 arguments.push_back(&arg);
5874 }
5875
5876 unsigned arg_index = 0;
5877 for (auto *info : resource_var_at_index) {
5878 if (info) {
5879 auto arg = arguments[arg_index];
5880 unsigned arg_size = 0;
5881 if (info->arg_kind == clspv::ArgKind::Pod ||
5882 info->arg_kind == clspv::ArgKind::PodUBO ||
5883 info->arg_kind == clspv::ArgKind::PodPushConstant) {
5884 arg_size =
5885 static_cast<uint32_t>(DL.getTypeStoreSize(arg->getType()));
5886 }
5887
5888 // Local pointer arguments are unused in this case.
5889 // offset, spec_id and elem_size always 0.
5890 AddArgumentReflection(kernel_decl, arg->getName().str(),
5891 info->arg_kind, arg_index, info->descriptor_set,
5892 info->binding, 0, arg_size, 0, 0);
5893 }
5894 arg_index++;
5895 }
5896 // Generate mappings for pointer-to-local arguments.
5897 for (arg_index = 0; arg_index < arguments.size(); ++arg_index) {
5898 Argument *arg = arguments[arg_index];
5899 auto where = LocalArgSpecIds.find(arg);
5900 if (where != LocalArgSpecIds.end()) {
5901 auto &local_arg_info = LocalSpecIdInfoMap[where->second];
5902
5903 // descriptor_set, binding, offset and size are always 0.
5904 AddArgumentReflection(kernel_decl, arg->getName().str(),
5905 ArgKind::Local, arg_index, 0, 0, 0, 0,
5906 static_cast<uint32_t>(local_arg_info.spec_id),
5907 static_cast<uint32_t>(GetTypeAllocSize(
5908 local_arg_info.elem_type, DL)));
5909 }
5910 }
5911 }
5912 }
5913}
5914
5915void SPIRVProducerPass::AddArgumentReflection(
5916 SPIRVID kernel_decl, const std::string &name, clspv::ArgKind arg_kind,
5917 uint32_t ordinal, uint32_t descriptor_set, uint32_t binding,
5918 uint32_t offset, uint32_t size, uint32_t spec_id, uint32_t elem_size) {
5919 // Generate ArgumentInfo for this argument.
5920 // TODO: generate remaining optional operands.
5921 auto import_id = getReflectionImport();
5922 auto arg_name = addSPIRVInst<kDebug>(spv::OpString, name.c_str());
5923 auto void_id = getSPIRVType(Type::getVoidTy(module->getContext()));
5924 SPIRVOperandVec Ops;
5925 Ops << void_id << import_id << reflection::ExtInstArgumentInfo << arg_name;
5926 auto arg_info = addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
5927
5928 Ops.clear();
5929 Ops << void_id << import_id;
5930 reflection::ExtInst ext_inst = reflection::ExtInstMax;
5931 // Determine the extended instruction.
5932 switch (arg_kind) {
5933 case clspv::ArgKind::Buffer:
5934 ext_inst = reflection::ExtInstArgumentStorageBuffer;
5935 break;
5936 case clspv::ArgKind::BufferUBO:
5937 ext_inst = reflection::ExtInstArgumentUniform;
5938 break;
5939 case clspv::ArgKind::Local:
5940 ext_inst = reflection::ExtInstArgumentWorkgroup;
5941 break;
5942 case clspv::ArgKind::Pod:
5943 ext_inst = reflection::ExtInstArgumentPodStorageBuffer;
5944 break;
5945 case clspv::ArgKind::PodUBO:
5946 ext_inst = reflection::ExtInstArgumentPodUniform;
5947 break;
5948 case clspv::ArgKind::PodPushConstant:
5949 ext_inst = reflection::ExtInstArgumentPodPushConstant;
5950 break;
alan-bakerf6bc8252020-09-23 14:58:55 -04005951 case clspv::ArgKind::SampledImage:
alan-baker86ce19c2020-08-05 13:09:19 -04005952 ext_inst = reflection::ExtInstArgumentSampledImage;
5953 break;
alan-bakerf6bc8252020-09-23 14:58:55 -04005954 case clspv::ArgKind::StorageImage:
alan-baker86ce19c2020-08-05 13:09:19 -04005955 ext_inst = reflection::ExtInstArgumentStorageImage;
5956 break;
5957 case clspv::ArgKind::Sampler:
5958 ext_inst = reflection::ExtInstArgumentSampler;
5959 break;
5960 default:
5961 llvm_unreachable("Unhandled argument reflection");
5962 break;
5963 }
5964 Ops << ext_inst << kernel_decl << getSPIRVInt32Constant(ordinal);
5965
5966 // Add descriptor set and binding for applicable arguments.
5967 switch (arg_kind) {
5968 case clspv::ArgKind::Buffer:
5969 case clspv::ArgKind::BufferUBO:
5970 case clspv::ArgKind::Pod:
5971 case clspv::ArgKind::PodUBO:
alan-bakerf6bc8252020-09-23 14:58:55 -04005972 case clspv::ArgKind::SampledImage:
5973 case clspv::ArgKind::StorageImage:
alan-baker86ce19c2020-08-05 13:09:19 -04005974 case clspv::ArgKind::Sampler:
5975 Ops << getSPIRVInt32Constant(descriptor_set)
5976 << getSPIRVInt32Constant(binding);
5977 break;
5978 default:
5979 break;
5980 }
5981
5982 // Add remaining operands for arguments.
5983 switch (arg_kind) {
5984 case clspv::ArgKind::Local:
5985 Ops << getSPIRVInt32Constant(spec_id) << getSPIRVInt32Constant(elem_size);
5986 break;
5987 case clspv::ArgKind::Pod:
5988 case clspv::ArgKind::PodUBO:
5989 case clspv::ArgKind::PodPushConstant:
5990 Ops << getSPIRVInt32Constant(offset) << getSPIRVInt32Constant(size);
5991 break;
5992 default:
5993 break;
5994 }
5995 Ops << arg_info;
5996 addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
5997}