blob: c77adc4cefcfc74c37b4882b614742fb51995b2c [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
alan-bakere0902602020-03-23 08:43:40 -040046#include "spirv/unified1/spirv.hpp"
David Neto118188e2018-08-24 11:27:54 -040047
David Neto85082642018-03-24 06:55:20 -070048#include "clspv/AddressSpace.h"
alan-bakerf5e5f692018-11-27 08:33:24 -050049#include "clspv/DescriptorMap.h"
David Neto118188e2018-08-24 11:27:54 -040050#include "clspv/Option.h"
David Neto85082642018-03-24 06:55:20 -070051#include "clspv/spirv_c_strings.hpp"
52#include "clspv/spirv_glsl.hpp"
David Neto22f144c2017-06-12 14:26:21 -040053
David Neto4feb7a42017-10-06 17:29:42 -040054#include "ArgKind.h"
alan-bakerf67468c2019-11-25 15:51:49 -050055#include "Builtins.h"
alan-baker06cad652019-12-03 17:56:47 -050056#include "ComputeStructuredOrder.h"
David Neto85082642018-03-24 06:55:20 -070057#include "ConstantEmitter.h"
Alan Baker202c8c72018-08-13 13:47:44 -040058#include "Constants.h"
David Neto78383442018-06-15 20:31:56 -040059#include "DescriptorCounter.h"
alan-baker56f7aff2019-05-22 08:06:42 -040060#include "NormalizeGlobalVariable.h"
Diego Novilloa4c44fa2019-04-11 10:56:15 -040061#include "Passes.h"
alan-bakera1be3322020-04-20 12:48:18 -040062#include "SpecConstant.h"
alan-bakerce179f12019-12-06 19:02:22 -050063#include "Types.h"
David Neto48f56a42017-10-06 16:44:25 -040064
David Neto22f144c2017-06-12 14:26:21 -040065#if defined(_MSC_VER)
66#pragma warning(pop)
67#endif
68
69using namespace llvm;
70using namespace clspv;
SJW173c7e92020-03-16 08:44:47 -050071using namespace clspv::Builtins;
David Neto156783e2017-07-05 15:39:41 -040072using namespace mdconst;
David Neto22f144c2017-06-12 14:26:21 -040073
74namespace {
David Netocd8ca5f2017-10-02 23:34:11 -040075
David Neto862b7d82018-06-14 18:48:37 -040076cl::opt<bool> ShowResourceVars("show-rv", cl::init(false), cl::Hidden,
77 cl::desc("Show resource variable creation"));
78
alan-baker5ed87542020-03-23 11:05:22 -040079cl::opt<bool>
80 ShowProducerIR("show-producer-ir", cl::init(false), cl::ReallyHidden,
81 cl::desc("Dump the IR at the start of SPIRVProducer"));
82
David Neto862b7d82018-06-14 18:48:37 -040083// These hacks exist to help transition code generation algorithms
84// without making huge noise in detailed test output.
85const bool Hack_generate_runtime_array_stride_early = true;
86
David Neto3fbb4072017-10-16 11:28:14 -040087// The value of 1/pi. This value is from MSDN
88// https://msdn.microsoft.com/en-us/library/4hwaceh6.aspx
89const double kOneOverPi = 0.318309886183790671538;
90const glsl::ExtInst kGlslExtInstBad = static_cast<glsl::ExtInst>(0);
91
alan-bakerb6b09dc2018-11-08 16:59:28 -050092const char *kCompositeConstructFunctionPrefix = "clspv.composite_construct.";
David Netoab03f432017-11-03 17:00:44 -040093
SJW69939d52020-04-16 07:29:07 -050094// SPIRV Module Sections (per 2.4 of the SPIRV spec)
95// These are used to collect SPIRVInstructions by type on-the-fly.
96enum SPIRVSection {
97 kCapabilities,
98 kExtensions,
99 kImports,
100 kMemoryModel,
101 kEntryPoints,
102 kExecutionModes,
103
104 kDebug,
105 kAnnotations,
106
107 kTypes,
108 kConstants = kTypes,
109 kGlobalVariables,
110
111 kFunctions,
112
113 kSectionCount
114};
115
David Neto22f144c2017-06-12 14:26:21 -0400116enum SPIRVOperandType {
117 NUMBERID,
118 LITERAL_INTEGER,
119 LITERAL_STRING,
120 LITERAL_FLOAT
121};
122
123struct SPIRVOperand {
124 explicit SPIRVOperand(SPIRVOperandType Ty, uint32_t Num)
125 : Type(Ty), LiteralNum(1, Num) {}
126 explicit SPIRVOperand(SPIRVOperandType Ty, const char *Str)
127 : Type(Ty), LiteralStr(Str) {}
128 explicit SPIRVOperand(SPIRVOperandType Ty, StringRef Str)
129 : Type(Ty), LiteralStr(Str) {}
130 explicit SPIRVOperand(SPIRVOperandType Ty, ArrayRef<uint32_t> NumVec)
131 : Type(Ty), LiteralNum(NumVec.begin(), NumVec.end()) {}
132
James Price11010dc2019-12-19 13:53:09 -0500133 SPIRVOperandType getType() const { return Type; };
134 uint32_t getNumID() const { return LiteralNum[0]; };
135 std::string getLiteralStr() const { return LiteralStr; };
136 ArrayRef<uint32_t> getLiteralNum() const { return LiteralNum; };
David Neto22f144c2017-06-12 14:26:21 -0400137
David Neto87846742018-04-11 17:36:22 -0400138 uint32_t GetNumWords() const {
139 switch (Type) {
140 case NUMBERID:
141 return 1;
142 case LITERAL_INTEGER:
143 case LITERAL_FLOAT:
David Netoee2660d2018-06-28 16:31:29 -0400144 return uint32_t(LiteralNum.size());
David Neto87846742018-04-11 17:36:22 -0400145 case LITERAL_STRING:
146 // Account for the terminating null character.
David Netoee2660d2018-06-28 16:31:29 -0400147 return uint32_t((LiteralStr.size() + 4) / 4);
David Neto87846742018-04-11 17:36:22 -0400148 }
149 llvm_unreachable("Unhandled case in SPIRVOperand::GetNumWords()");
150 }
151
David Neto22f144c2017-06-12 14:26:21 -0400152private:
153 SPIRVOperandType Type;
154 std::string LiteralStr;
155 SmallVector<uint32_t, 4> LiteralNum;
156};
157
David Netoc6f3ab22018-04-06 18:02:31 -0400158class SPIRVOperandList {
159public:
David Netoef5ba2b2019-12-20 08:35:54 -0500160 typedef std::unique_ptr<SPIRVOperand> element_type;
161 typedef SmallVector<element_type, 8> container_type;
162 typedef container_type::iterator iterator;
David Netoc6f3ab22018-04-06 18:02:31 -0400163 SPIRVOperandList() {}
alan-bakerb6b09dc2018-11-08 16:59:28 -0500164 SPIRVOperandList(const SPIRVOperandList &other) = delete;
165 SPIRVOperandList(SPIRVOperandList &&other) {
David Netoc6f3ab22018-04-06 18:02:31 -0400166 contents_ = std::move(other.contents_);
167 other.contents_.clear();
168 }
David Netoef5ba2b2019-12-20 08:35:54 -0500169 iterator begin() { return contents_.begin(); }
170 iterator end() { return contents_.end(); }
171 operator ArrayRef<element_type>() { return contents_; }
172 void push_back(element_type op) { contents_.push_back(std::move(op)); }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500173 void clear() { contents_.clear(); }
David Netoc6f3ab22018-04-06 18:02:31 -0400174 size_t size() const { return contents_.size(); }
James Price11010dc2019-12-19 13:53:09 -0500175 const SPIRVOperand *operator[](size_t i) { return contents_[i].get(); }
David Netoc6f3ab22018-04-06 18:02:31 -0400176
David Netoef5ba2b2019-12-20 08:35:54 -0500177 const container_type &getOperands() const { return contents_; }
David Neto87846742018-04-11 17:36:22 -0400178
David Netoc6f3ab22018-04-06 18:02:31 -0400179private:
David Netoef5ba2b2019-12-20 08:35:54 -0500180 container_type contents_;
David Netoc6f3ab22018-04-06 18:02:31 -0400181};
182
James Price11010dc2019-12-19 13:53:09 -0500183SPIRVOperandList &operator<<(SPIRVOperandList &list,
David Netoef5ba2b2019-12-20 08:35:54 -0500184 std::unique_ptr<SPIRVOperand> elem) {
185 list.push_back(std::move(elem));
David Netoc6f3ab22018-04-06 18:02:31 -0400186 return list;
187}
188
David Netoef5ba2b2019-12-20 08:35:54 -0500189std::unique_ptr<SPIRVOperand> MkNum(uint32_t num) {
190 return std::make_unique<SPIRVOperand>(LITERAL_INTEGER, num);
David Netoc6f3ab22018-04-06 18:02:31 -0400191}
David Netoef5ba2b2019-12-20 08:35:54 -0500192std::unique_ptr<SPIRVOperand> MkInteger(ArrayRef<uint32_t> num_vec) {
193 return std::make_unique<SPIRVOperand>(LITERAL_INTEGER, num_vec);
David Neto257c3892018-04-11 13:19:45 -0400194}
David Netoef5ba2b2019-12-20 08:35:54 -0500195std::unique_ptr<SPIRVOperand> MkFloat(ArrayRef<uint32_t> num_vec) {
196 return std::make_unique<SPIRVOperand>(LITERAL_FLOAT, num_vec);
David Neto257c3892018-04-11 13:19:45 -0400197}
David Netoef5ba2b2019-12-20 08:35:54 -0500198std::unique_ptr<SPIRVOperand> MkId(uint32_t id) {
199 return std::make_unique<SPIRVOperand>(NUMBERID, id);
James Price11010dc2019-12-19 13:53:09 -0500200}
David Netoef5ba2b2019-12-20 08:35:54 -0500201std::unique_ptr<SPIRVOperand> MkString(StringRef str) {
202 return std::make_unique<SPIRVOperand>(LITERAL_STRING, str);
David Neto257c3892018-04-11 13:19:45 -0400203}
David Netoc6f3ab22018-04-06 18:02:31 -0400204
David Neto22f144c2017-06-12 14:26:21 -0400205struct SPIRVInstruction {
David Netoef5ba2b2019-12-20 08:35:54 -0500206 // Creates an instruction with an opcode and no result ID, and with the given
207 // operands. This computes its own word count. Takes ownership of the
208 // operands and clears |Ops|.
209 SPIRVInstruction(spv::Op Opc, SPIRVOperandList &Ops)
210 : WordCount(1), Opcode(static_cast<uint16_t>(Opc)), ResultID(0) {
James Price11010dc2019-12-19 13:53:09 -0500211 for (auto &operand : Ops) {
David Netoee2660d2018-06-28 16:31:29 -0400212 WordCount += uint16_t(operand->GetNumWords());
David Neto87846742018-04-11 17:36:22 -0400213 }
David Netoef5ba2b2019-12-20 08:35:54 -0500214 Operands.reserve(Ops.size());
215 for (auto &ptr : Ops) {
216 Operands.emplace_back(std::move(ptr));
217 ptr.reset(nullptr);
David Neto87846742018-04-11 17:36:22 -0400218 }
David Netoef5ba2b2019-12-20 08:35:54 -0500219 Ops.clear();
220 }
221 // Creates an instruction with an opcode and a no-zero result ID, and
222 // with the given operands. This computes its own word count. Takes ownership
223 // of the operands and clears |Ops|.
224 SPIRVInstruction(spv::Op Opc, uint32_t ResID, SPIRVOperandList &Ops)
225 : WordCount(2), Opcode(static_cast<uint16_t>(Opc)), ResultID(ResID) {
James Price11010dc2019-12-19 13:53:09 -0500226 for (auto &operand : Ops) {
David Neto87846742018-04-11 17:36:22 -0400227 WordCount += operand->GetNumWords();
228 }
David Netoef5ba2b2019-12-20 08:35:54 -0500229 Operands.reserve(Ops.size());
230 for (auto &ptr : Ops) {
231 Operands.emplace_back(std::move(ptr));
232 ptr.reset(nullptr);
233 }
234 if (ResID == 0) {
235 llvm_unreachable("Result ID of 0 was provided");
236 }
237 Ops.clear();
David Neto87846742018-04-11 17:36:22 -0400238 }
David Neto22f144c2017-06-12 14:26:21 -0400239
David Netoef5ba2b2019-12-20 08:35:54 -0500240 // Creates an instruction with an opcode and no result ID, and with the single
241 // operand. This computes its own word count.
242 SPIRVInstruction(spv::Op Opc, SPIRVOperandList::element_type operand)
243 : WordCount(1), Opcode(static_cast<uint16_t>(Opc)), ResultID(0) {
244 WordCount += operand->GetNumWords();
245 Operands.emplace_back(std::move(operand));
246 operand.reset(nullptr);
247 }
248 // Creates an instruction with an opcode and a non-zero result ID, and
249 // with the single operand. This computes its own word count.
250 SPIRVInstruction(spv::Op Opc, uint32_t ResID,
251 SPIRVOperandList::element_type operand)
252 : WordCount(2), Opcode(static_cast<uint16_t>(Opc)), ResultID(ResID) {
253 WordCount += operand->GetNumWords();
254 if (ResID == 0) {
255 llvm_unreachable("Result ID of 0 was provided");
256 }
257 Operands.emplace_back(std::move(operand));
258 operand.reset(nullptr);
259 }
260 // Creates an instruction with an opcode and a no-zero result ID, and no
261 // operands.
262 SPIRVInstruction(spv::Op Opc, uint32_t ResID)
263 : WordCount(2), Opcode(static_cast<uint16_t>(Opc)), ResultID(ResID) {
264 if (ResID == 0) {
265 llvm_unreachable("Result ID of 0 was provided");
266 }
267 }
268 // Creates an instruction with an opcode, no result ID, no type ID, and no
269 // operands.
270 SPIRVInstruction(spv::Op Opc)
271 : WordCount(1), Opcode(static_cast<uint16_t>(Opc)), ResultID(0) {}
272
David Netoee2660d2018-06-28 16:31:29 -0400273 uint32_t getWordCount() const { return WordCount; }
David Neto22f144c2017-06-12 14:26:21 -0400274 uint16_t getOpcode() const { return Opcode; }
275 uint32_t getResultID() const { return ResultID; }
David Netoef5ba2b2019-12-20 08:35:54 -0500276 ArrayRef<std::unique_ptr<SPIRVOperand>> getOperands() const {
James Price11010dc2019-12-19 13:53:09 -0500277 return Operands;
278 }
David Neto22f144c2017-06-12 14:26:21 -0400279
280private:
David Netoee2660d2018-06-28 16:31:29 -0400281 uint32_t WordCount; // Check the 16-bit bound at code generation time.
David Neto22f144c2017-06-12 14:26:21 -0400282 uint16_t Opcode;
283 uint32_t ResultID;
David Netoef5ba2b2019-12-20 08:35:54 -0500284 SmallVector<std::unique_ptr<SPIRVOperand>, 4> Operands;
David Neto22f144c2017-06-12 14:26:21 -0400285};
286
287struct SPIRVProducerPass final : public ModulePass {
David Neto22f144c2017-06-12 14:26:21 -0400288 typedef DenseMap<Type *, uint32_t> TypeMapType;
289 typedef UniqueVector<Type *> TypeList;
290 typedef DenseMap<Value *, uint32_t> ValueMapType;
David Netofb9a7972017-08-25 17:08:24 -0400291 typedef UniqueVector<Value *> ValueList;
David Neto22f144c2017-06-12 14:26:21 -0400292 typedef std::vector<std::pair<Value *, uint32_t>> EntryPointVecType;
293 typedef std::list<SPIRVInstruction *> SPIRVInstructionList;
David Neto87846742018-04-11 17:36:22 -0400294 // A vector of tuples, each of which is:
295 // - the LLVM instruction that we will later generate SPIR-V code for
296 // - where the SPIR-V instruction should be inserted
297 // - the result ID of the SPIR-V instruction
David Neto22f144c2017-06-12 14:26:21 -0400298 typedef std::vector<
299 std::tuple<Value *, SPIRVInstructionList::iterator, uint32_t>>
300 DeferredInstVecType;
301 typedef DenseMap<FunctionType *, std::pair<FunctionType *, uint32_t>>
302 GlobalConstFuncMapType;
303
David Neto44795152017-07-13 15:45:28 -0400304 explicit SPIRVProducerPass(
alan-bakerf5e5f692018-11-27 08:33:24 -0500305 raw_pwrite_stream &out,
306 std::vector<clspv::version0::DescriptorMapEntry> *descriptor_map_entries,
alan-baker00e7a582019-06-07 12:54:21 -0400307 ArrayRef<std::pair<unsigned, std::string>> samplerMap,
David Neto44795152017-07-13 15:45:28 -0400308 bool outputCInitList)
David Netoc2c368d2017-06-30 16:50:17 -0400309 : ModulePass(ID), samplerMap(samplerMap), out(out),
David Neto0676e6f2017-07-11 18:47:44 -0400310 binaryTempOut(binaryTempUnderlyingVector), binaryOut(&out),
alan-baker00e7a582019-06-07 12:54:21 -0400311 descriptorMapEntries(descriptor_map_entries),
David Neto0676e6f2017-07-11 18:47:44 -0400312 outputCInitList(outputCInitList), patchBoundOffset(0), nextID(1),
alan-baker5b86ed72019-02-15 08:26:50 -0500313 OpExtInstImportID(0), HasVariablePointersStorageBuffer(false),
314 HasVariablePointers(false), SamplerTy(nullptr), WorkgroupSizeValueID(0),
alan-bakera1be3322020-04-20 12:48:18 -0400315 WorkgroupSizeVarID(0) {}
David Neto22f144c2017-06-12 14:26:21 -0400316
James Price11010dc2019-12-19 13:53:09 -0500317 virtual ~SPIRVProducerPass() {
SJW69939d52020-04-16 07:29:07 -0500318 for (int i = 0; i < kSectionCount; ++i) {
319 for (auto *Inst : SPIRVSections[i]) {
320 delete Inst;
321 }
James Price11010dc2019-12-19 13:53:09 -0500322 }
323 }
324
David Neto22f144c2017-06-12 14:26:21 -0400325 void getAnalysisUsage(AnalysisUsage &AU) const override {
326 AU.addRequired<DominatorTreeWrapperPass>();
327 AU.addRequired<LoopInfoWrapperPass>();
328 }
329
330 virtual bool runOnModule(Module &module) override;
331
332 // output the SPIR-V header block
333 void outputHeader();
334
335 // patch the SPIR-V header block
336 void patchHeader();
337
338 uint32_t lookupType(Type *Ty) {
339 if (Ty->isPointerTy() &&
340 (Ty->getPointerAddressSpace() != AddressSpace::UniformConstant)) {
341 auto PointeeTy = Ty->getPointerElementType();
342 if (PointeeTy->isStructTy() &&
343 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
344 Ty = PointeeTy;
345 }
346 }
347
David Neto862b7d82018-06-14 18:48:37 -0400348 auto where = TypeMap.find(Ty);
349 if (where == TypeMap.end()) {
350 if (Ty) {
351 errs() << "Unhandled type " << *Ty << "\n";
352 } else {
353 errs() << "Unhandled type (null)\n";
354 }
David Netoe439d702018-03-23 13:14:08 -0700355 llvm_unreachable("\nUnhandled type!");
David Neto22f144c2017-06-12 14:26:21 -0400356 }
357
David Neto862b7d82018-06-14 18:48:37 -0400358 return where->second;
David Neto22f144c2017-06-12 14:26:21 -0400359 }
360 TypeMapType &getImageTypeMap() { return ImageTypeMap; }
alan-bakerabd82722019-12-03 17:14:51 -0500361 TypeList &getImageTypeList() { return ImageTypeList; }
David Neto22f144c2017-06-12 14:26:21 -0400362 TypeList &getTypeList() { return Types; };
363 ValueList &getConstantList() { return Constants; };
364 ValueMapType &getValueMap() { return ValueMap; }
365 ValueMapType &getAllocatedValueMap() { return AllocatedValueMap; }
SJW69939d52020-04-16 07:29:07 -0500366 SPIRVInstructionList &getSPIRVInstList(SPIRVSection Section) {
367 return SPIRVSections[Section];
368 };
David Neto22f144c2017-06-12 14:26:21 -0400369 EntryPointVecType &getEntryPointVec() { return EntryPointVec; };
370 DeferredInstVecType &getDeferredInstVec() { return DeferredInstVec; };
371 ValueList &getEntryPointInterfacesVec() { return EntryPointInterfacesVec; };
372 uint32_t &getOpExtInstImportID() { return OpExtInstImportID; };
373 std::vector<uint32_t> &getBuiltinDimVec() { return BuiltinDimensionVec; };
SJW2c317da2020-03-23 07:39:13 -0500374
alan-baker5b86ed72019-02-15 08:26:50 -0500375 bool hasVariablePointersStorageBuffer() {
376 return HasVariablePointersStorageBuffer;
377 }
378 void setVariablePointersStorageBuffer(bool Val) {
379 HasVariablePointersStorageBuffer = Val;
380 }
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400381 bool hasVariablePointers() { return HasVariablePointers; };
David Neto22f144c2017-06-12 14:26:21 -0400382 void setVariablePointers(bool Val) { HasVariablePointers = Val; };
alan-bakerb6b09dc2018-11-08 16:59:28 -0500383 ArrayRef<std::pair<unsigned, std::string>> &getSamplerMap() {
384 return samplerMap;
385 }
David Neto22f144c2017-06-12 14:26:21 -0400386 GlobalConstFuncMapType &getGlobalConstFuncTypeMap() {
387 return GlobalConstFuncTypeMap;
388 }
389 SmallPtrSet<Value *, 16> &getGlobalConstArgSet() {
390 return GlobalConstArgumentSet;
391 }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500392 TypeList &getTypesNeedingArrayStride() { return TypesNeedingArrayStride; }
David Neto22f144c2017-06-12 14:26:21 -0400393
David Netoc6f3ab22018-04-06 18:02:31 -0400394 void GenerateLLVMIRInfo(Module &M, const DataLayout &DL);
alan-bakerb6b09dc2018-11-08 16:59:28 -0500395 // Populate GlobalConstFuncTypeMap. Also, if module-scope __constant will
396 // *not* be converted to a storage buffer, replace each such global variable
397 // with one in the storage class expecgted by SPIR-V.
David Neto862b7d82018-06-14 18:48:37 -0400398 void FindGlobalConstVars(Module &M, const DataLayout &DL);
399 // Populate ResourceVarInfoList, FunctionToResourceVarsMap, and
400 // ModuleOrderedResourceVars.
401 void FindResourceVars(Module &M, const DataLayout &DL);
Alan Baker202c8c72018-08-13 13:47:44 -0400402 void FindWorkgroupVars(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400403 bool FindExtInst(Module &M);
404 void FindTypePerGlobalVar(GlobalVariable &GV);
405 void FindTypePerFunc(Function &F);
David Neto862b7d82018-06-14 18:48:37 -0400406 void FindTypesForSamplerMap(Module &M);
407 void FindTypesForResourceVars(Module &M);
alan-bakerb6b09dc2018-11-08 16:59:28 -0500408 // Inserts |Ty| and relevant sub-types into the |Types| member, indicating
409 // that |Ty| and its subtypes will need a corresponding SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400410 void FindType(Type *Ty);
411 void FindConstantPerGlobalVar(GlobalVariable &GV);
412 void FindConstantPerFunc(Function &F);
413 void FindConstant(Value *V);
414 void GenerateExtInstImport();
David Neto19a1bad2017-08-25 15:01:41 -0400415 // Generates instructions for SPIR-V types corresponding to the LLVM types
416 // saved in the |Types| member. A type follows its subtypes. IDs are
417 // allocated sequentially starting with the current value of nextID, and
418 // with a type following its subtypes. Also updates nextID to just beyond
419 // the last generated ID.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500420 void GenerateSPIRVTypes(LLVMContext &context, Module &module);
David Neto22f144c2017-06-12 14:26:21 -0400421 void GenerateSPIRVConstants();
David Neto5c22a252018-03-15 16:07:41 -0400422 void GenerateModuleInfo(Module &M);
alan-bakera1be3322020-04-20 12:48:18 -0400423 void GeneratePushConstantDescriptorMapEntries(Module &M);
424 void GenerateSpecConstantDescriptorMapEntries(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400425 void GenerateGlobalVar(GlobalVariable &GV);
alan-bakera1be3322020-04-20 12:48:18 -0400426 void GenerateWorkgroupVars(Module &M);
David Neto862b7d82018-06-14 18:48:37 -0400427 // Generate descriptor map entries for resource variables associated with
428 // arguments to F.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500429 void GenerateDescriptorMapInfo(const DataLayout &DL, Function &F);
David Neto22f144c2017-06-12 14:26:21 -0400430 void GenerateSamplers(Module &M);
David Neto862b7d82018-06-14 18:48:37 -0400431 // Generate OpVariables for %clspv.resource.var.* calls.
432 void GenerateResourceVars(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400433 void GenerateFuncPrologue(Function &F);
434 void GenerateFuncBody(Function &F);
David Netob6e2e062018-04-25 10:32:06 -0400435 void GenerateEntryPointInitialStores();
David Neto22f144c2017-06-12 14:26:21 -0400436 spv::Op GetSPIRVCmpOpcode(CmpInst *CmpI);
437 spv::Op GetSPIRVCastOpcode(Instruction &I);
438 spv::Op GetSPIRVBinaryOpcode(Instruction &I);
439 void GenerateInstruction(Instruction &I);
440 void GenerateFuncEpilogue();
441 void HandleDeferredInstruction();
alan-bakera1be3322020-04-20 12:48:18 -0400442 void HandleDeferredDecorations(Module &module);
David Neto22f144c2017-06-12 14:26:21 -0400443 bool is4xi8vec(Type *Ty) const;
444 spv::StorageClass GetStorageClass(unsigned AddrSpace) const;
David Neto862b7d82018-06-14 18:48:37 -0400445 spv::StorageClass GetStorageClassForArgKind(clspv::ArgKind arg_kind) const;
David Neto22f144c2017-06-12 14:26:21 -0400446 spv::BuiltIn GetBuiltin(StringRef globalVarName) const;
David Neto3fbb4072017-10-16 11:28:14 -0400447 // Returns the GLSL extended instruction enum that the given function
448 // call maps to. If none, then returns the 0 value, i.e. GLSLstd4580Bad.
David Neto22f144c2017-06-12 14:26:21 -0400449 glsl::ExtInst getExtInstEnum(StringRef Name);
David Neto3fbb4072017-10-16 11:28:14 -0400450 // Returns the GLSL extended instruction enum indirectly used by the given
451 // function. That is, to implement the given function, we use an extended
452 // instruction plus one more instruction. If none, then returns the 0 value,
453 // i.e. GLSLstd4580Bad.
454 glsl::ExtInst getIndirectExtInstEnum(StringRef Name);
455 // Returns the single GLSL extended instruction used directly or
456 // indirectly by the given function call.
457 glsl::ExtInst getDirectOrIndirectExtInstEnum(StringRef Name);
David Neto22f144c2017-06-12 14:26:21 -0400458 void WriteOneWord(uint32_t Word);
459 void WriteResultID(SPIRVInstruction *Inst);
460 void WriteWordCountAndOpcode(SPIRVInstruction *Inst);
David Netoef5ba2b2019-12-20 08:35:54 -0500461 void WriteOperand(const std::unique_ptr<SPIRVOperand> &Op);
David Neto22f144c2017-06-12 14:26:21 -0400462 void WriteSPIRVBinary();
SJW69939d52020-04-16 07:29:07 -0500463 void WriteSPIRVBinary(SPIRVInstructionList &SPIRVInstList);
David Neto22f144c2017-06-12 14:26:21 -0400464
Alan Baker9bf93fb2018-08-28 16:59:26 -0400465 // Returns true if |type| is compatible with OpConstantNull.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500466 bool IsTypeNullable(const Type *type) const;
Alan Baker9bf93fb2018-08-28 16:59:26 -0400467
Alan Bakerfcda9482018-10-02 17:09:59 -0400468 // Populate UBO remapped type maps.
469 void PopulateUBOTypeMaps(Module &module);
470
alan-baker06cad652019-12-03 17:56:47 -0500471 // Populate the merge and continue block maps.
472 void PopulateStructuredCFGMaps(Module &module);
473
Alan Bakerfcda9482018-10-02 17:09:59 -0400474 // Wrapped methods of DataLayout accessors. If |type| was remapped for UBOs,
475 // uses the internal map, otherwise it falls back on the data layout.
476 uint64_t GetTypeSizeInBits(Type *type, const DataLayout &DL);
477 uint64_t GetTypeStoreSize(Type *type, const DataLayout &DL);
478 uint64_t GetTypeAllocSize(Type *type, const DataLayout &DL);
Kévin Petitbbbda972020-03-03 19:16:31 +0000479 uint32_t GetExplicitLayoutStructMemberOffset(StructType *type,
480 unsigned member,
481 const DataLayout &DL);
Alan Bakerfcda9482018-10-02 17:09:59 -0400482
alan-baker5b86ed72019-02-15 08:26:50 -0500483 // Returns the base pointer of |v|.
484 Value *GetBasePointer(Value *v);
485
486 // Sets |HasVariablePointersStorageBuffer| or |HasVariablePointers| base on
487 // |address_space|.
488 void setVariablePointersCapabilities(unsigned address_space);
489
490 // Returns true if |lhs| and |rhs| represent the same resource or workgroup
491 // variable.
492 bool sameResource(Value *lhs, Value *rhs) const;
493
494 // Returns true if |inst| is phi or select that selects from the same
495 // structure (or null).
496 bool selectFromSameObject(Instruction *inst);
497
alan-bakere9308012019-03-15 10:25:13 -0400498 // Returns true if |Arg| is called with a coherent resource.
499 bool CalledWithCoherentResource(Argument &Arg);
500
David Neto22f144c2017-06-12 14:26:21 -0400501private:
502 static char ID;
David Neto44795152017-07-13 15:45:28 -0400503 ArrayRef<std::pair<unsigned, std::string>> samplerMap;
David Neto22f144c2017-06-12 14:26:21 -0400504 raw_pwrite_stream &out;
David Neto0676e6f2017-07-11 18:47:44 -0400505
506 // TODO(dneto): Wouldn't it be better to always just emit a binary, and then
507 // convert to other formats on demand?
508
509 // When emitting a C initialization list, the WriteSPIRVBinary method
510 // will actually write its words to this vector via binaryTempOut.
511 SmallVector<char, 100> binaryTempUnderlyingVector;
512 raw_svector_ostream binaryTempOut;
513
514 // Binary output writes to this stream, which might be |out| or
515 // |binaryTempOut|. It's the latter when we really want to write a C
516 // initializer list.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400517 raw_pwrite_stream *binaryOut;
alan-bakerf5e5f692018-11-27 08:33:24 -0500518 std::vector<version0::DescriptorMapEntry> *descriptorMapEntries;
David Neto0676e6f2017-07-11 18:47:44 -0400519 const bool outputCInitList; // If true, output look like {0x7023, ... , 5}
David Neto22f144c2017-06-12 14:26:21 -0400520 uint64_t patchBoundOffset;
521 uint32_t nextID;
522
alan-bakerf67468c2019-11-25 15:51:49 -0500523 // ID for OpTypeInt 32 1.
524 uint32_t int32ID = 0;
525 // ID for OpTypeVector %int 4.
526 uint32_t v4int32ID = 0;
527
David Neto19a1bad2017-08-25 15:01:41 -0400528 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400529 TypeMapType TypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400530 // Maps an LLVM image type to its SPIR-V ID.
David Neto22f144c2017-06-12 14:26:21 -0400531 TypeMapType ImageTypeMap;
alan-bakerabd82722019-12-03 17:14:51 -0500532 // A unique-vector of LLVM image types. This list is used to provide
533 // deterministic traversal of image types.
534 TypeList ImageTypeList;
David Neto19a1bad2017-08-25 15:01:41 -0400535 // A unique-vector of LLVM types that map to a SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400536 TypeList Types;
537 ValueList Constants;
David Neto19a1bad2017-08-25 15:01:41 -0400538 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400539 ValueMapType ValueMap;
540 ValueMapType AllocatedValueMap;
SJW69939d52020-04-16 07:29:07 -0500541 SPIRVInstructionList SPIRVSections[kSectionCount];
David Neto862b7d82018-06-14 18:48:37 -0400542
David Neto22f144c2017-06-12 14:26:21 -0400543 EntryPointVecType EntryPointVec;
544 DeferredInstVecType DeferredInstVec;
545 ValueList EntryPointInterfacesVec;
546 uint32_t OpExtInstImportID;
547 std::vector<uint32_t> BuiltinDimensionVec;
alan-baker5b86ed72019-02-15 08:26:50 -0500548 bool HasVariablePointersStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -0400549 bool HasVariablePointers;
550 Type *SamplerTy;
alan-baker09cb9802019-12-10 13:16:27 -0500551 DenseMap<unsigned, unsigned> SamplerLiteralToIDMap;
David Netoc77d9e22018-03-24 06:30:28 -0700552
553 // If a function F has a pointer-to-__constant parameter, then this variable
David Neto9ed8e2f2018-03-24 06:47:24 -0700554 // will map F's type to (G, index of the parameter), where in a first phase
555 // G is F's type. During FindTypePerFunc, G will be changed to F's type
556 // but replacing the pointer-to-constant parameter with
557 // pointer-to-ModuleScopePrivate.
David Netoc77d9e22018-03-24 06:30:28 -0700558 // TODO(dneto): This doesn't seem general enough? A function might have
559 // more than one such parameter.
David Neto22f144c2017-06-12 14:26:21 -0400560 GlobalConstFuncMapType GlobalConstFuncTypeMap;
561 SmallPtrSet<Value *, 16> GlobalConstArgumentSet;
David Neto1a1a0582017-07-07 12:01:44 -0400562 // An ordered set of pointer types of Base arguments to OpPtrAccessChain,
David Neto85082642018-03-24 06:55:20 -0700563 // or array types, and which point into transparent memory (StorageBuffer
564 // storage class). These will require an ArrayStride decoration.
David Neto1a1a0582017-07-07 12:01:44 -0400565 // See SPV_KHR_variable_pointers rev 13.
David Neto85082642018-03-24 06:55:20 -0700566 TypeList TypesNeedingArrayStride;
David Netoa60b00b2017-09-15 16:34:09 -0400567
568 // This is truly ugly, but works around what look like driver bugs.
569 // For get_local_size, an earlier part of the flow has created a module-scope
570 // variable in Private address space to hold the value for the workgroup
571 // size. Its intializer is a uint3 value marked as builtin WorkgroupSize.
572 // When this is present, save the IDs of the initializer value and variable
573 // in these two variables. We only ever do a vector load from it, and
574 // when we see one of those, substitute just the value of the intializer.
575 // This mimics what Glslang does, and that's what drivers are used to.
David Neto66cfe642018-03-24 06:13:56 -0700576 // TODO(dneto): Remove this once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -0400577 uint32_t WorkgroupSizeValueID;
578 uint32_t WorkgroupSizeVarID;
David Neto26aaf622017-10-23 18:11:53 -0400579
David Neto862b7d82018-06-14 18:48:37 -0400580 // Bookkeeping for mapping kernel arguments to resource variables.
581 struct ResourceVarInfo {
582 ResourceVarInfo(int index_arg, unsigned set_arg, unsigned binding_arg,
alan-bakere9308012019-03-15 10:25:13 -0400583 Function *fn, clspv::ArgKind arg_kind_arg, int coherent_arg)
David Neto862b7d82018-06-14 18:48:37 -0400584 : index(index_arg), descriptor_set(set_arg), binding(binding_arg),
alan-bakere9308012019-03-15 10:25:13 -0400585 var_fn(fn), arg_kind(arg_kind_arg), coherent(coherent_arg),
David Neto862b7d82018-06-14 18:48:37 -0400586 addr_space(fn->getReturnType()->getPointerAddressSpace()) {}
587 const int index; // Index into ResourceVarInfoList
588 const unsigned descriptor_set;
589 const unsigned binding;
590 Function *const var_fn; // The @clspv.resource.var.* function.
591 const clspv::ArgKind arg_kind;
alan-bakere9308012019-03-15 10:25:13 -0400592 const int coherent;
David Neto862b7d82018-06-14 18:48:37 -0400593 const unsigned addr_space; // The LLVM address space
594 // The SPIR-V ID of the OpVariable. Not populated at construction time.
595 uint32_t var_id = 0;
596 };
597 // A list of resource var info. Each one correponds to a module-scope
598 // resource variable we will have to create. Resource var indices are
599 // indices into this vector.
600 SmallVector<std::unique_ptr<ResourceVarInfo>, 8> ResourceVarInfoList;
601 // This is a vector of pointers of all the resource vars, but ordered by
602 // kernel function, and then by argument.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500603 UniqueVector<ResourceVarInfo *> ModuleOrderedResourceVars;
David Neto862b7d82018-06-14 18:48:37 -0400604 // Map a function to the ordered list of resource variables it uses, one for
605 // each argument. If an argument does not use a resource variable, it
606 // will have a null pointer entry.
607 using FunctionToResourceVarsMapType =
608 DenseMap<Function *, SmallVector<ResourceVarInfo *, 8>>;
609 FunctionToResourceVarsMapType FunctionToResourceVarsMap;
610
611 // What LLVM types map to SPIR-V types needing layout? These are the
612 // arrays and structures supporting storage buffers and uniform buffers.
613 TypeList TypesNeedingLayout;
614 // What LLVM struct types map to a SPIR-V struct type with Block decoration?
615 UniqueVector<StructType *> StructTypesNeedingBlock;
616 // For a call that represents a load from an opaque type (samplers, images),
617 // map it to the variable id it should load from.
618 DenseMap<CallInst *, uint32_t> ResourceVarDeferredLoadCalls;
David Neto85082642018-03-24 06:55:20 -0700619
David Netoc6f3ab22018-04-06 18:02:31 -0400620 // An ordered list of the kernel arguments of type pointer-to-local.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500621 using LocalArgList = SmallVector<Argument *, 8>;
David Netoc6f3ab22018-04-06 18:02:31 -0400622 LocalArgList LocalArgs;
623 // Information about a pointer-to-local argument.
624 struct LocalArgInfo {
625 // The SPIR-V ID of the array variable.
626 uint32_t variable_id;
627 // The element type of the
alan-bakerb6b09dc2018-11-08 16:59:28 -0500628 Type *elem_type;
David Netoc6f3ab22018-04-06 18:02:31 -0400629 // The ID of the array type.
630 uint32_t array_size_id;
631 // The ID of the array type.
632 uint32_t array_type_id;
633 // The ID of the pointer to the array type.
634 uint32_t ptr_array_type_id;
David Netoc6f3ab22018-04-06 18:02:31 -0400635 // The specialization constant ID of the array size.
636 int spec_id;
637 };
Alan Baker202c8c72018-08-13 13:47:44 -0400638 // A mapping from Argument to its assigned SpecId.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500639 DenseMap<const Argument *, int> LocalArgSpecIds;
Alan Baker202c8c72018-08-13 13:47:44 -0400640 // A mapping from SpecId to its LocalArgInfo.
641 DenseMap<int, LocalArgInfo> LocalSpecIdInfoMap;
Alan Bakerfcda9482018-10-02 17:09:59 -0400642 // A mapping from a remapped type to its real offsets.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500643 DenseMap<Type *, std::vector<uint32_t>> RemappedUBOTypeOffsets;
Alan Bakerfcda9482018-10-02 17:09:59 -0400644 // A mapping from a remapped type to its real sizes.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500645 DenseMap<Type *, std::tuple<uint64_t, uint64_t, uint64_t>>
646 RemappedUBOTypeSizes;
alan-baker06cad652019-12-03 17:56:47 -0500647
648 // Maps basic block to its merge block.
649 DenseMap<BasicBlock *, BasicBlock *> MergeBlocks;
650 // Maps basic block to its continue block.
651 DenseMap<BasicBlock *, BasicBlock *> ContinueBlocks;
David Neto22f144c2017-06-12 14:26:21 -0400652};
653
654char SPIRVProducerPass::ID;
David Netoc6f3ab22018-04-06 18:02:31 -0400655
alan-bakerb6b09dc2018-11-08 16:59:28 -0500656} // namespace
David Neto22f144c2017-06-12 14:26:21 -0400657
658namespace clspv {
alan-bakerf5e5f692018-11-27 08:33:24 -0500659ModulePass *createSPIRVProducerPass(
660 raw_pwrite_stream &out,
661 std::vector<version0::DescriptorMapEntry> *descriptor_map_entries,
alan-baker00e7a582019-06-07 12:54:21 -0400662 ArrayRef<std::pair<unsigned, std::string>> samplerMap,
alan-bakerf5e5f692018-11-27 08:33:24 -0500663 bool outputCInitList) {
664 return new SPIRVProducerPass(out, descriptor_map_entries, samplerMap,
alan-baker00e7a582019-06-07 12:54:21 -0400665 outputCInitList);
David Neto22f144c2017-06-12 14:26:21 -0400666}
David Netoc2c368d2017-06-30 16:50:17 -0400667} // namespace clspv
David Neto22f144c2017-06-12 14:26:21 -0400668
669bool SPIRVProducerPass::runOnModule(Module &module) {
alan-baker5ed87542020-03-23 11:05:22 -0400670 if (ShowProducerIR) {
671 llvm::outs() << module << "\n";
672 }
David Neto0676e6f2017-07-11 18:47:44 -0400673 binaryOut = outputCInitList ? &binaryTempOut : &out;
674
Alan Bakerfcda9482018-10-02 17:09:59 -0400675 PopulateUBOTypeMaps(module);
alan-baker06cad652019-12-03 17:56:47 -0500676 PopulateStructuredCFGMaps(module);
Alan Bakerfcda9482018-10-02 17:09:59 -0400677
David Neto22f144c2017-06-12 14:26:21 -0400678 // SPIR-V always begins with its header information
679 outputHeader();
680
David Netoc6f3ab22018-04-06 18:02:31 -0400681 const DataLayout &DL = module.getDataLayout();
682
David Neto22f144c2017-06-12 14:26:21 -0400683 // Gather information from the LLVM IR that we require.
David Netoc6f3ab22018-04-06 18:02:31 -0400684 GenerateLLVMIRInfo(module, DL);
David Neto22f144c2017-06-12 14:26:21 -0400685
David Neto22f144c2017-06-12 14:26:21 -0400686 // Collect information on global variables too.
687 for (GlobalVariable &GV : module.globals()) {
688 // If the GV is one of our special __spirv_* variables, remove the
689 // initializer as it was only placed there to force LLVM to not throw the
690 // value away.
Kévin Petitbbbda972020-03-03 19:16:31 +0000691 if (GV.getName().startswith("__spirv_") ||
692 GV.getAddressSpace() == clspv::AddressSpace::PushConstant) {
David Neto22f144c2017-06-12 14:26:21 -0400693 GV.setInitializer(nullptr);
694 }
695
696 // Collect types' information from global variable.
697 FindTypePerGlobalVar(GV);
698
699 // Collect constant information from global variable.
700 FindConstantPerGlobalVar(GV);
701
702 // If the variable is an input, entry points need to know about it.
703 if (AddressSpace::Input == GV.getType()->getPointerAddressSpace()) {
David Netofb9a7972017-08-25 17:08:24 -0400704 getEntryPointInterfacesVec().insert(&GV);
David Neto22f144c2017-06-12 14:26:21 -0400705 }
706 }
707
708 // If there are extended instructions, generate OpExtInstImport.
709 if (FindExtInst(module)) {
710 GenerateExtInstImport();
711 }
712
713 // Generate SPIRV instructions for types.
Alan Bakerfcda9482018-10-02 17:09:59 -0400714 GenerateSPIRVTypes(module.getContext(), module);
David Neto22f144c2017-06-12 14:26:21 -0400715
716 // Generate SPIRV constants.
717 GenerateSPIRVConstants();
718
alan-baker09cb9802019-12-10 13:16:27 -0500719 // Generate literal samplers if necessary.
720 GenerateSamplers(module);
David Neto22f144c2017-06-12 14:26:21 -0400721
Kévin Petitbbbda972020-03-03 19:16:31 +0000722 // Generate descriptor map entries for all push constants
alan-bakera1be3322020-04-20 12:48:18 -0400723 GeneratePushConstantDescriptorMapEntries(module);
Kévin Petitbbbda972020-03-03 19:16:31 +0000724
David Neto22f144c2017-06-12 14:26:21 -0400725 // Generate SPIRV variables.
726 for (GlobalVariable &GV : module.globals()) {
727 GenerateGlobalVar(GV);
728 }
David Neto862b7d82018-06-14 18:48:37 -0400729 GenerateResourceVars(module);
alan-bakera1be3322020-04-20 12:48:18 -0400730 GenerateWorkgroupVars(module);
David Neto22f144c2017-06-12 14:26:21 -0400731
732 // Generate SPIRV instructions for each function.
733 for (Function &F : module) {
734 if (F.isDeclaration()) {
735 continue;
736 }
737
David Neto862b7d82018-06-14 18:48:37 -0400738 GenerateDescriptorMapInfo(DL, F);
739
David Neto22f144c2017-06-12 14:26:21 -0400740 // Generate Function Prologue.
741 GenerateFuncPrologue(F);
742
743 // Generate SPIRV instructions for function body.
744 GenerateFuncBody(F);
745
746 // Generate Function Epilogue.
747 GenerateFuncEpilogue();
748 }
749
750 HandleDeferredInstruction();
alan-bakera1be3322020-04-20 12:48:18 -0400751 HandleDeferredDecorations(module);
752
753 // Generate descriptor map entries for module scope specialization constants.
754 GenerateSpecConstantDescriptorMapEntries(module);
David Neto22f144c2017-06-12 14:26:21 -0400755
756 // Generate SPIRV module information.
David Neto5c22a252018-03-15 16:07:41 -0400757 GenerateModuleInfo(module);
David Neto22f144c2017-06-12 14:26:21 -0400758
alan-baker00e7a582019-06-07 12:54:21 -0400759 WriteSPIRVBinary();
David Neto22f144c2017-06-12 14:26:21 -0400760
761 // We need to patch the SPIR-V header to set bound correctly.
762 patchHeader();
David Neto0676e6f2017-07-11 18:47:44 -0400763
764 if (outputCInitList) {
765 bool first = true;
David Neto0676e6f2017-07-11 18:47:44 -0400766 std::ostringstream os;
767
David Neto57fb0b92017-08-04 15:35:09 -0400768 auto emit_word = [&os, &first](uint32_t word) {
David Neto0676e6f2017-07-11 18:47:44 -0400769 if (!first)
David Neto57fb0b92017-08-04 15:35:09 -0400770 os << ",\n";
771 os << word;
David Neto0676e6f2017-07-11 18:47:44 -0400772 first = false;
773 };
774
775 os << "{";
David Neto57fb0b92017-08-04 15:35:09 -0400776 const std::string str(binaryTempOut.str());
777 for (unsigned i = 0; i < str.size(); i += 4) {
778 const uint32_t a = static_cast<unsigned char>(str[i]);
779 const uint32_t b = static_cast<unsigned char>(str[i + 1]);
780 const uint32_t c = static_cast<unsigned char>(str[i + 2]);
781 const uint32_t d = static_cast<unsigned char>(str[i + 3]);
782 emit_word(a | (b << 8) | (c << 16) | (d << 24));
David Neto0676e6f2017-07-11 18:47:44 -0400783 }
784 os << "}\n";
785 out << os.str();
786 }
787
David Neto22f144c2017-06-12 14:26:21 -0400788 return false;
789}
790
791void SPIRVProducerPass::outputHeader() {
alan-baker00e7a582019-06-07 12:54:21 -0400792 binaryOut->write(reinterpret_cast<const char *>(&spv::MagicNumber),
793 sizeof(spv::MagicNumber));
alan-bakere0902602020-03-23 08:43:40 -0400794 const uint32_t spv_version = 0x10000; // SPIR-V 1.0
795 binaryOut->write(reinterpret_cast<const char *>(&spv_version),
796 sizeof(spv_version));
David Neto22f144c2017-06-12 14:26:21 -0400797
alan-baker0c18ab02019-06-12 10:23:21 -0400798 // use Google's vendor ID
799 const uint32_t vendor = 21 << 16;
alan-baker00e7a582019-06-07 12:54:21 -0400800 binaryOut->write(reinterpret_cast<const char *>(&vendor), sizeof(vendor));
David Neto22f144c2017-06-12 14:26:21 -0400801
alan-baker00e7a582019-06-07 12:54:21 -0400802 // we record where we need to come back to and patch in the bound value
803 patchBoundOffset = binaryOut->tell();
David Neto22f144c2017-06-12 14:26:21 -0400804
alan-baker00e7a582019-06-07 12:54:21 -0400805 // output a bad bound for now
806 binaryOut->write(reinterpret_cast<const char *>(&nextID), sizeof(nextID));
David Neto22f144c2017-06-12 14:26:21 -0400807
alan-baker00e7a582019-06-07 12:54:21 -0400808 // output the schema (reserved for use and must be 0)
809 const uint32_t schema = 0;
810 binaryOut->write(reinterpret_cast<const char *>(&schema), sizeof(schema));
David Neto22f144c2017-06-12 14:26:21 -0400811}
812
813void SPIRVProducerPass::patchHeader() {
alan-baker00e7a582019-06-07 12:54:21 -0400814 // for a binary we just write the value of nextID over bound
815 binaryOut->pwrite(reinterpret_cast<char *>(&nextID), sizeof(nextID),
816 patchBoundOffset);
David Neto22f144c2017-06-12 14:26:21 -0400817}
818
David Netoc6f3ab22018-04-06 18:02:31 -0400819void SPIRVProducerPass::GenerateLLVMIRInfo(Module &M, const DataLayout &DL) {
David Neto22f144c2017-06-12 14:26:21 -0400820 // This function generates LLVM IR for function such as global variable for
821 // argument, constant and pointer type for argument access. These information
822 // is artificial one because we need Vulkan SPIR-V output. This function is
823 // executed ahead of FindType and FindConstant.
David Neto22f144c2017-06-12 14:26:21 -0400824 LLVMContext &Context = M.getContext();
825
David Neto862b7d82018-06-14 18:48:37 -0400826 FindGlobalConstVars(M, DL);
David Neto5c22a252018-03-15 16:07:41 -0400827
David Neto862b7d82018-06-14 18:48:37 -0400828 FindResourceVars(M, DL);
David Neto22f144c2017-06-12 14:26:21 -0400829
830 bool HasWorkGroupBuiltin = false;
831 for (GlobalVariable &GV : M.globals()) {
832 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
833 if (spv::BuiltInWorkgroupSize == BuiltinType) {
834 HasWorkGroupBuiltin = true;
835 }
836 }
837
David Neto862b7d82018-06-14 18:48:37 -0400838 FindTypesForSamplerMap(M);
839 FindTypesForResourceVars(M);
Alan Baker202c8c72018-08-13 13:47:44 -0400840 FindWorkgroupVars(M);
David Neto22f144c2017-06-12 14:26:21 -0400841
842 for (Function &F : M) {
Kévin Petitabef4522019-03-27 13:08:01 +0000843 if (F.isDeclaration()) {
David Neto22f144c2017-06-12 14:26:21 -0400844 continue;
845 }
846
847 for (BasicBlock &BB : F) {
848 for (Instruction &I : BB) {
849 if (I.getOpcode() == Instruction::ZExt ||
850 I.getOpcode() == Instruction::SExt ||
851 I.getOpcode() == Instruction::UIToFP) {
852 // If there is zext with i1 type, it will be changed to OpSelect. The
853 // OpSelect needs constant 0 and 1 so the constants are added here.
854
855 auto OpTy = I.getOperand(0)->getType();
856
Kévin Petit24272b62018-10-18 19:16:12 +0000857 if (OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -0400858 if (I.getOpcode() == Instruction::ZExt) {
David Neto22f144c2017-06-12 14:26:21 -0400859 FindConstant(Constant::getNullValue(I.getType()));
Kévin Petit7bfb8992019-02-26 13:45:08 +0000860 FindConstant(ConstantInt::get(I.getType(), 1));
David Neto22f144c2017-06-12 14:26:21 -0400861 } else if (I.getOpcode() == Instruction::SExt) {
David Neto22f144c2017-06-12 14:26:21 -0400862 FindConstant(Constant::getNullValue(I.getType()));
Kévin Petit7bfb8992019-02-26 13:45:08 +0000863 FindConstant(ConstantInt::getSigned(I.getType(), -1));
David Neto22f144c2017-06-12 14:26:21 -0400864 } else {
865 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
866 FindConstant(ConstantFP::get(Context, APFloat(1.0f)));
867 }
868 }
869 } else if (CallInst *Call = dyn_cast<CallInst>(&I)) {
David Neto862b7d82018-06-14 18:48:37 -0400870 StringRef callee_name = Call->getCalledFunction()->getName();
David Neto22f144c2017-06-12 14:26:21 -0400871
872 // Handle image type specially.
SJW173c7e92020-03-16 08:44:47 -0500873 if (IsImageBuiltin(callee_name)) {
David Neto22f144c2017-06-12 14:26:21 -0400874 TypeMapType &OpImageTypeMap = getImageTypeMap();
875 Type *ImageTy =
876 Call->getArgOperand(0)->getType()->getPointerElementType();
877 OpImageTypeMap[ImageTy] = 0;
alan-bakerabd82722019-12-03 17:14:51 -0500878 getImageTypeList().insert(ImageTy);
alan-baker75090e42020-02-20 11:21:04 -0500879 }
David Neto22f144c2017-06-12 14:26:21 -0400880
SJW173c7e92020-03-16 08:44:47 -0500881 if (IsSampledImageRead(callee_name)) {
alan-bakerf67468c2019-11-25 15:51:49 -0500882 // All sampled reads need a floating point 0 for the Lod operand.
David Neto22f144c2017-06-12 14:26:21 -0400883 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
SJW2c317da2020-03-23 07:39:13 -0500884 } else if (IsUnsampledImageRead(callee_name)) {
alan-baker75090e42020-02-20 11:21:04 -0500885 // All unsampled reads need an integer 0 for the Lod operand.
886 FindConstant(ConstantInt::get(Context, APInt(32, 0)));
SJW2c317da2020-03-23 07:39:13 -0500887 } else if (IsImageQuery(callee_name)) {
alan-bakerce179f12019-12-06 19:02:22 -0500888 Type *ImageTy = Call->getOperand(0)->getType();
889 const uint32_t dim = ImageDimensionality(ImageTy);
alan-baker7150a1d2020-02-25 08:31:06 -0500890 uint32_t components =
891 dim + (clspv::IsArrayImageType(ImageTy) ? 1 : 0);
alan-bakerce179f12019-12-06 19:02:22 -0500892 if (components > 1) {
893 // OpImageQuerySize* return |components| components.
894 FindType(VectorType::get(Type::getInt32Ty(Context), components));
895 if (dim == 3 && IsGetImageDim(callee_name)) {
896 // get_image_dim for 3D images returns an int4.
897 FindType(
898 VectorType::get(Type::getInt32Ty(Context), components + 1));
899 }
900 }
901
SJW173c7e92020-03-16 08:44:47 -0500902 if (IsSampledImageType(ImageTy)) {
alan-bakerce179f12019-12-06 19:02:22 -0500903 // All sampled image queries need a integer 0 for the Lod
904 // operand.
905 FindConstant(ConstantInt::get(Context, APInt(32, 0)));
906 }
David Neto5c22a252018-03-15 16:07:41 -0400907 }
David Neto22f144c2017-06-12 14:26:21 -0400908 }
909 }
910 }
911
Kévin Petitabef4522019-03-27 13:08:01 +0000912 // More things to do on kernel functions
913 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
914 if (const MDNode *MD =
915 dyn_cast<Function>(&F)->getMetadata("reqd_work_group_size")) {
916 // We generate constants if the WorkgroupSize builtin is being used.
917 if (HasWorkGroupBuiltin) {
918 // Collect constant information for work group size.
919 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(0)));
920 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(1)));
921 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(2)));
David Neto22f144c2017-06-12 14:26:21 -0400922 }
923 }
924 }
925
alan-bakerf67468c2019-11-25 15:51:49 -0500926 // TODO(alan-baker): make this better.
alan-bakerf906d2b2019-12-10 11:26:23 -0500927 if (M.getTypeByName("opencl.image1d_ro_t.float") ||
928 M.getTypeByName("opencl.image1d_ro_t.float.sampled") ||
929 M.getTypeByName("opencl.image1d_wo_t.float") ||
930 M.getTypeByName("opencl.image2d_ro_t.float") ||
alan-bakerf67468c2019-11-25 15:51:49 -0500931 M.getTypeByName("opencl.image2d_ro_t.float.sampled") ||
932 M.getTypeByName("opencl.image2d_wo_t.float") ||
933 M.getTypeByName("opencl.image3d_ro_t.float") ||
934 M.getTypeByName("opencl.image3d_ro_t.float.sampled") ||
alan-baker7150a1d2020-02-25 08:31:06 -0500935 M.getTypeByName("opencl.image3d_wo_t.float") ||
936 M.getTypeByName("opencl.image1d_array_ro_t.float") ||
937 M.getTypeByName("opencl.image1d_array_ro_t.float.sampled") ||
938 M.getTypeByName("opencl.image1d_array_wo_t.float") ||
939 M.getTypeByName("opencl.image2d_array_ro_t.float") ||
940 M.getTypeByName("opencl.image2d_array_ro_t.float.sampled") ||
941 M.getTypeByName("opencl.image2d_array_wo_t.float")) {
alan-bakerf67468c2019-11-25 15:51:49 -0500942 FindType(Type::getFloatTy(Context));
alan-bakerf906d2b2019-12-10 11:26:23 -0500943 } else if (M.getTypeByName("opencl.image1d_ro_t.uint") ||
944 M.getTypeByName("opencl.image1d_ro_t.uint.sampled") ||
945 M.getTypeByName("opencl.image1d_wo_t.uint") ||
946 M.getTypeByName("opencl.image2d_ro_t.uint") ||
alan-bakerf67468c2019-11-25 15:51:49 -0500947 M.getTypeByName("opencl.image2d_ro_t.uint.sampled") ||
948 M.getTypeByName("opencl.image2d_wo_t.uint") ||
949 M.getTypeByName("opencl.image3d_ro_t.uint") ||
950 M.getTypeByName("opencl.image3d_ro_t.uint.sampled") ||
alan-baker7150a1d2020-02-25 08:31:06 -0500951 M.getTypeByName("opencl.image3d_wo_t.uint") ||
952 M.getTypeByName("opencl.image1d_array_ro_t.uint") ||
953 M.getTypeByName("opencl.image1d_array_ro_t.uint.sampled") ||
954 M.getTypeByName("opencl.image1d_array_wo_t.uint") ||
955 M.getTypeByName("opencl.image2d_array_ro_t.uint") ||
956 M.getTypeByName("opencl.image2d_array_ro_t.uint.sampled") ||
957 M.getTypeByName("opencl.image2d_array_wo_t.uint")) {
alan-bakerf67468c2019-11-25 15:51:49 -0500958 FindType(Type::getInt32Ty(Context));
alan-bakerf906d2b2019-12-10 11:26:23 -0500959 } else if (M.getTypeByName("opencl.image1d_ro_t.int") ||
960 M.getTypeByName("opencl.image1d_ro_t.int.sampled") ||
961 M.getTypeByName("opencl.image1d_wo_t.int") ||
962 M.getTypeByName("opencl.image2d_ro_t.int") ||
alan-bakerf67468c2019-11-25 15:51:49 -0500963 M.getTypeByName("opencl.image2d_ro_t.int.sampled") ||
964 M.getTypeByName("opencl.image2d_wo_t.int") ||
965 M.getTypeByName("opencl.image3d_ro_t.int") ||
966 M.getTypeByName("opencl.image3d_ro_t.int.sampled") ||
alan-baker7150a1d2020-02-25 08:31:06 -0500967 M.getTypeByName("opencl.image3d_wo_t.int") ||
968 M.getTypeByName("opencl.image1d_array_ro_t.int") ||
969 M.getTypeByName("opencl.image1d_array_ro_t.int.sampled") ||
970 M.getTypeByName("opencl.image1d_array_wo_t.int") ||
971 M.getTypeByName("opencl.image2d_array_ro_t.int") ||
972 M.getTypeByName("opencl.image2d_array_ro_t.int.sampled") ||
973 M.getTypeByName("opencl.image2d_array_wo_t.int")) {
alan-bakerf67468c2019-11-25 15:51:49 -0500974 // Nothing for now...
975 } else {
976 // This was likely an UndefValue.
David Neto22f144c2017-06-12 14:26:21 -0400977 FindType(Type::getFloatTy(Context));
978 }
979
980 // Collect types' information from function.
981 FindTypePerFunc(F);
982
983 // Collect constant information from function.
984 FindConstantPerFunc(F);
985 }
986}
987
David Neto862b7d82018-06-14 18:48:37 -0400988void SPIRVProducerPass::FindGlobalConstVars(Module &M, const DataLayout &DL) {
alan-baker56f7aff2019-05-22 08:06:42 -0400989 clspv::NormalizeGlobalVariables(M);
990
David Neto862b7d82018-06-14 18:48:37 -0400991 SmallVector<GlobalVariable *, 8> GVList;
992 SmallVector<GlobalVariable *, 8> DeadGVList;
993 for (GlobalVariable &GV : M.globals()) {
994 if (GV.getType()->getAddressSpace() == AddressSpace::Constant) {
995 if (GV.use_empty()) {
996 DeadGVList.push_back(&GV);
997 } else {
998 GVList.push_back(&GV);
999 }
1000 }
1001 }
1002
1003 // Remove dead global __constant variables.
1004 for (auto GV : DeadGVList) {
1005 GV->eraseFromParent();
1006 }
1007 DeadGVList.clear();
1008
1009 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
1010 // For now, we only support a single storage buffer.
1011 if (GVList.size() > 0) {
1012 assert(GVList.size() == 1);
1013 const auto *GV = GVList[0];
1014 const auto constants_byte_size =
Alan Bakerfcda9482018-10-02 17:09:59 -04001015 (GetTypeSizeInBits(GV->getInitializer()->getType(), DL)) / 8;
David Neto862b7d82018-06-14 18:48:37 -04001016 const size_t kConstantMaxSize = 65536;
1017 if (constants_byte_size > kConstantMaxSize) {
1018 outs() << "Max __constant capacity of " << kConstantMaxSize
1019 << " bytes exceeded: " << constants_byte_size << " bytes used\n";
1020 llvm_unreachable("Max __constant capacity exceeded");
1021 }
1022 }
1023 } else {
1024 // Change global constant variable's address space to ModuleScopePrivate.
1025 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
1026 for (auto GV : GVList) {
1027 // Create new gv with ModuleScopePrivate address space.
1028 Type *NewGVTy = GV->getType()->getPointerElementType();
1029 GlobalVariable *NewGV = new GlobalVariable(
1030 M, NewGVTy, false, GV->getLinkage(), GV->getInitializer(), "",
1031 nullptr, GV->getThreadLocalMode(), AddressSpace::ModuleScopePrivate);
1032 NewGV->takeName(GV);
1033
1034 const SmallVector<User *, 8> GVUsers(GV->user_begin(), GV->user_end());
1035 SmallVector<User *, 8> CandidateUsers;
1036
1037 auto record_called_function_type_as_user =
1038 [&GlobalConstFuncTyMap](Value *gv, CallInst *call) {
1039 // Find argument index.
1040 unsigned index = 0;
1041 for (unsigned i = 0; i < call->getNumArgOperands(); i++) {
1042 if (gv == call->getOperand(i)) {
1043 // TODO(dneto): Should we break here?
1044 index = i;
1045 }
1046 }
1047
1048 // Record function type with global constant.
1049 GlobalConstFuncTyMap[call->getFunctionType()] =
1050 std::make_pair(call->getFunctionType(), index);
1051 };
1052
1053 for (User *GVU : GVUsers) {
1054 if (CallInst *Call = dyn_cast<CallInst>(GVU)) {
1055 record_called_function_type_as_user(GV, Call);
1056 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(GVU)) {
1057 // Check GEP users.
1058 for (User *GEPU : GEP->users()) {
1059 if (CallInst *GEPCall = dyn_cast<CallInst>(GEPU)) {
1060 record_called_function_type_as_user(GEP, GEPCall);
1061 }
1062 }
1063 }
1064
1065 CandidateUsers.push_back(GVU);
1066 }
1067
1068 for (User *U : CandidateUsers) {
1069 // Update users of gv with new gv.
alan-bakered80f572019-02-11 17:28:26 -05001070 if (!isa<Constant>(U)) {
1071 // #254: Can't change operands of a constant, but this shouldn't be
1072 // something that sticks around in the module.
1073 U->replaceUsesOfWith(GV, NewGV);
1074 }
David Neto862b7d82018-06-14 18:48:37 -04001075 }
1076
1077 // Delete original gv.
1078 GV->eraseFromParent();
1079 }
1080 }
1081}
1082
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001083void SPIRVProducerPass::FindResourceVars(Module &M, const DataLayout &) {
David Neto862b7d82018-06-14 18:48:37 -04001084 ResourceVarInfoList.clear();
1085 FunctionToResourceVarsMap.clear();
1086 ModuleOrderedResourceVars.reset();
1087 // Normally, there is one resource variable per clspv.resource.var.*
1088 // function, since that is unique'd by arg type and index. By design,
1089 // we can share these resource variables across kernels because all
1090 // kernels use the same descriptor set.
1091 //
1092 // But if the user requested distinct descriptor sets per kernel, then
1093 // the descriptor allocator has made different (set,binding) pairs for
1094 // the same (type,arg_index) pair. Since we can decorate a resource
1095 // variable with only exactly one DescriptorSet and Binding, we are
1096 // forced in this case to make distinct resource variables whenever
Kévin Petitbbbda972020-03-03 19:16:31 +00001097 // the same clspv.resource.var.X function is seen with disintct
David Neto862b7d82018-06-14 18:48:37 -04001098 // (set,binding) values.
1099 const bool always_distinct_sets =
1100 clspv::Option::DistinctKernelDescriptorSets();
1101 for (Function &F : M) {
1102 // Rely on the fact the resource var functions have a stable ordering
1103 // in the module.
Alan Baker202c8c72018-08-13 13:47:44 -04001104 if (F.getName().startswith(clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001105 // Find all calls to this function with distinct set and binding pairs.
1106 // Save them in ResourceVarInfoList.
1107
1108 // Determine uniqueness of the (set,binding) pairs only withing this
1109 // one resource-var builtin function.
1110 using SetAndBinding = std::pair<unsigned, unsigned>;
1111 // Maps set and binding to the resource var info.
1112 DenseMap<SetAndBinding, ResourceVarInfo *> set_and_binding_map;
1113 bool first_use = true;
1114 for (auto &U : F.uses()) {
1115 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
1116 const auto set = unsigned(
1117 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
1118 const auto binding = unsigned(
1119 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
1120 const auto arg_kind = clspv::ArgKind(
1121 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
1122 const auto arg_index = unsigned(
1123 dyn_cast<ConstantInt>(call->getArgOperand(3))->getZExtValue());
alan-bakere9308012019-03-15 10:25:13 -04001124 const auto coherent = unsigned(
1125 dyn_cast<ConstantInt>(call->getArgOperand(5))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04001126
1127 // Find or make the resource var info for this combination.
1128 ResourceVarInfo *rv = nullptr;
1129 if (always_distinct_sets) {
1130 // Make a new resource var any time we see a different
1131 // (set,binding) pair.
1132 SetAndBinding key{set, binding};
1133 auto where = set_and_binding_map.find(key);
1134 if (where == set_and_binding_map.end()) {
1135 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
alan-bakere9308012019-03-15 10:25:13 -04001136 binding, &F, arg_kind, coherent);
David Neto862b7d82018-06-14 18:48:37 -04001137 ResourceVarInfoList.emplace_back(rv);
1138 set_and_binding_map[key] = rv;
1139 } else {
1140 rv = where->second;
1141 }
1142 } else {
1143 // The default is to make exactly one resource for each
1144 // clspv.resource.var.* function.
1145 if (first_use) {
1146 first_use = false;
1147 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
alan-bakere9308012019-03-15 10:25:13 -04001148 binding, &F, arg_kind, coherent);
David Neto862b7d82018-06-14 18:48:37 -04001149 ResourceVarInfoList.emplace_back(rv);
1150 } else {
1151 rv = ResourceVarInfoList.back().get();
1152 }
1153 }
1154
1155 // Now populate FunctionToResourceVarsMap.
1156 auto &mapping =
1157 FunctionToResourceVarsMap[call->getParent()->getParent()];
1158 while (mapping.size() <= arg_index) {
1159 mapping.push_back(nullptr);
1160 }
1161 mapping[arg_index] = rv;
1162 }
1163 }
1164 }
1165 }
1166
1167 // Populate ModuleOrderedResourceVars.
1168 for (Function &F : M) {
1169 auto where = FunctionToResourceVarsMap.find(&F);
1170 if (where != FunctionToResourceVarsMap.end()) {
1171 for (auto &rv : where->second) {
1172 if (rv != nullptr) {
1173 ModuleOrderedResourceVars.insert(rv);
1174 }
1175 }
1176 }
1177 }
1178 if (ShowResourceVars) {
1179 for (auto *info : ModuleOrderedResourceVars) {
1180 outs() << "MORV index " << info->index << " (" << info->descriptor_set
1181 << "," << info->binding << ") " << *(info->var_fn->getReturnType())
1182 << "\n";
1183 }
1184 }
1185}
1186
David Neto22f144c2017-06-12 14:26:21 -04001187bool SPIRVProducerPass::FindExtInst(Module &M) {
1188 LLVMContext &Context = M.getContext();
1189 bool HasExtInst = false;
1190
1191 for (Function &F : M) {
1192 for (BasicBlock &BB : F) {
1193 for (Instruction &I : BB) {
1194 if (CallInst *Call = dyn_cast<CallInst>(&I)) {
1195 Function *Callee = Call->getCalledFunction();
1196 // Check whether this call is for extend instructions.
David Neto3fbb4072017-10-16 11:28:14 -04001197 auto callee_name = Callee->getName();
1198 const glsl::ExtInst EInst = getExtInstEnum(callee_name);
1199 const glsl::ExtInst IndirectEInst =
1200 getIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04001201
David Neto3fbb4072017-10-16 11:28:14 -04001202 HasExtInst |=
1203 (EInst != kGlslExtInstBad) || (IndirectEInst != kGlslExtInstBad);
1204
1205 if (IndirectEInst) {
1206 // Register extra constants if needed.
1207
1208 // Registers a type and constant for computing the result of the
1209 // given instruction. If the result of the instruction is a vector,
1210 // then make a splat vector constant with the same number of
1211 // elements.
1212 auto register_constant = [this, &I](Constant *constant) {
1213 FindType(constant->getType());
1214 FindConstant(constant);
1215 if (auto *vectorTy = dyn_cast<VectorType>(I.getType())) {
1216 // Register the splat vector of the value with the same
1217 // width as the result of the instruction.
1218 auto *vec_constant = ConstantVector::getSplat(
alan-baker7261e062020-03-15 14:35:48 -04001219 {static_cast<unsigned>(vectorTy->getNumElements()), false},
David Neto3fbb4072017-10-16 11:28:14 -04001220 constant);
1221 FindConstant(vec_constant);
1222 FindType(vec_constant->getType());
1223 }
1224 };
1225 switch (IndirectEInst) {
1226 case glsl::ExtInstFindUMsb:
1227 // clz needs OpExtInst and OpISub with constant 31, or splat
1228 // vector of 31. Add it to the constant list here.
1229 register_constant(
1230 ConstantInt::get(Type::getInt32Ty(Context), 31));
1231 break;
1232 case glsl::ExtInstAcos:
1233 case glsl::ExtInstAsin:
Kévin Petiteb9f90a2018-09-29 12:29:34 +01001234 case glsl::ExtInstAtan:
David Neto3fbb4072017-10-16 11:28:14 -04001235 case glsl::ExtInstAtan2:
1236 // We need 1/pi for acospi, asinpi, atan2pi.
1237 register_constant(
1238 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
1239 break;
1240 default:
1241 assert(false && "internally inconsistent");
1242 }
David Neto22f144c2017-06-12 14:26:21 -04001243 }
1244 }
1245 }
1246 }
1247 }
1248
1249 return HasExtInst;
1250}
1251
1252void SPIRVProducerPass::FindTypePerGlobalVar(GlobalVariable &GV) {
1253 // Investigate global variable's type.
1254 FindType(GV.getType());
1255}
1256
1257void SPIRVProducerPass::FindTypePerFunc(Function &F) {
1258 // Investigate function's type.
1259 FunctionType *FTy = F.getFunctionType();
1260
1261 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
1262 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
David Neto9ed8e2f2018-03-24 06:47:24 -07001263 // Handle a regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04001264 if (GlobalConstFuncTyMap.count(FTy)) {
1265 uint32_t GVCstArgIdx = GlobalConstFuncTypeMap[FTy].second;
1266 SmallVector<Type *, 4> NewFuncParamTys;
1267 for (unsigned i = 0; i < FTy->getNumParams(); i++) {
1268 Type *ParamTy = FTy->getParamType(i);
1269 if (i == GVCstArgIdx) {
1270 Type *EleTy = ParamTy->getPointerElementType();
1271 ParamTy = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1272 }
1273
1274 NewFuncParamTys.push_back(ParamTy);
1275 }
1276
1277 FunctionType *NewFTy =
1278 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1279 GlobalConstFuncTyMap[FTy] = std::make_pair(NewFTy, GVCstArgIdx);
1280 FTy = NewFTy;
1281 }
1282
1283 FindType(FTy);
1284 } else {
1285 // As kernel functions do not have parameters, create new function type and
1286 // add it to type map.
1287 SmallVector<Type *, 4> NewFuncParamTys;
1288 FunctionType *NewFTy =
1289 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1290 FindType(NewFTy);
1291 }
1292
1293 // Investigate instructions' type in function body.
1294 for (BasicBlock &BB : F) {
1295 for (Instruction &I : BB) {
1296 if (isa<ShuffleVectorInst>(I)) {
1297 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1298 // Ignore type for mask of shuffle vector instruction.
1299 if (i == 2) {
1300 continue;
1301 }
1302
1303 Value *Op = I.getOperand(i);
1304 if (!isa<MetadataAsValue>(Op)) {
1305 FindType(Op->getType());
1306 }
1307 }
1308
1309 FindType(I.getType());
1310 continue;
1311 }
1312
David Neto862b7d82018-06-14 18:48:37 -04001313 CallInst *Call = dyn_cast<CallInst>(&I);
1314
1315 if (Call && Call->getCalledFunction()->getName().startswith(
Alan Baker202c8c72018-08-13 13:47:44 -04001316 clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001317 // This is a fake call representing access to a resource variable.
1318 // We handle that elsewhere.
1319 continue;
1320 }
1321
Alan Baker202c8c72018-08-13 13:47:44 -04001322 if (Call && Call->getCalledFunction()->getName().startswith(
1323 clspv::WorkgroupAccessorFunction())) {
1324 // This is a fake call representing access to a workgroup variable.
1325 // We handle that elsewhere.
1326 continue;
1327 }
1328
alan-bakerf083bed2020-01-29 08:15:42 -05001329 // #497: InsertValue and ExtractValue map to OpCompositeInsert and
1330 // OpCompositeExtract which takes literal values for indices. As a result
1331 // don't map the type of indices.
1332 if (I.getOpcode() == Instruction::ExtractValue) {
1333 FindType(I.getOperand(0)->getType());
1334 continue;
1335 }
1336 if (I.getOpcode() == Instruction::InsertValue) {
1337 FindType(I.getOperand(0)->getType());
1338 FindType(I.getOperand(1)->getType());
1339 continue;
1340 }
1341
1342 // #497: InsertElement and ExtractElement map to OpCompositeExtract if
1343 // the index is a constant. In such a case don't map the index type.
1344 if (I.getOpcode() == Instruction::ExtractElement) {
1345 FindType(I.getOperand(0)->getType());
1346 Value *op1 = I.getOperand(1);
1347 if (!isa<Constant>(op1) || isa<GlobalValue>(op1)) {
1348 FindType(op1->getType());
1349 }
1350 continue;
1351 }
1352 if (I.getOpcode() == Instruction::InsertElement) {
1353 FindType(I.getOperand(0)->getType());
1354 FindType(I.getOperand(1)->getType());
1355 Value *op2 = I.getOperand(2);
1356 if (!isa<Constant>(op2) || isa<GlobalValue>(op2)) {
1357 FindType(op2->getType());
1358 }
1359 continue;
1360 }
1361
David Neto22f144c2017-06-12 14:26:21 -04001362 // Work through the operands of the instruction.
1363 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1364 Value *const Op = I.getOperand(i);
1365 // If any of the operands is a constant, find the type!
1366 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1367 FindType(Op->getType());
1368 }
1369 }
1370
1371 for (Use &Op : I.operands()) {
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001372 if (isa<CallInst>(&I)) {
David Neto22f144c2017-06-12 14:26:21 -04001373 // Avoid to check call instruction's type.
1374 break;
1375 }
Alan Baker202c8c72018-08-13 13:47:44 -04001376 if (CallInst *OpCall = dyn_cast<CallInst>(Op)) {
1377 if (OpCall && OpCall->getCalledFunction()->getName().startswith(
1378 clspv::WorkgroupAccessorFunction())) {
1379 // This is a fake call representing access to a workgroup variable.
1380 // We handle that elsewhere.
1381 continue;
1382 }
1383 }
David Neto22f144c2017-06-12 14:26:21 -04001384 if (!isa<MetadataAsValue>(&Op)) {
1385 FindType(Op->getType());
1386 continue;
1387 }
1388 }
1389
David Neto22f144c2017-06-12 14:26:21 -04001390 // We don't want to track the type of this call as we are going to replace
1391 // it.
Kévin Petitdf71de32019-04-09 14:09:50 +01001392 if (Call && (clspv::LiteralSamplerFunction() ==
David Neto22f144c2017-06-12 14:26:21 -04001393 Call->getCalledFunction()->getName())) {
1394 continue;
1395 }
1396
1397 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
1398 // If gep's base operand has ModuleScopePrivate address space, make gep
1399 // return ModuleScopePrivate address space.
1400 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate) {
1401 // Add pointer type with private address space for global constant to
1402 // type list.
1403 Type *EleTy = I.getType()->getPointerElementType();
1404 Type *NewPTy =
1405 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1406
1407 FindType(NewPTy);
1408 continue;
1409 }
1410 }
1411
1412 FindType(I.getType());
1413 }
1414 }
1415}
1416
David Neto862b7d82018-06-14 18:48:37 -04001417void SPIRVProducerPass::FindTypesForSamplerMap(Module &M) {
1418 // If we are using a sampler map, find the type of the sampler.
Kévin Petitdf71de32019-04-09 14:09:50 +01001419 if (M.getFunction(clspv::LiteralSamplerFunction()) ||
David Neto862b7d82018-06-14 18:48:37 -04001420 0 < getSamplerMap().size()) {
1421 auto SamplerStructTy = M.getTypeByName("opencl.sampler_t");
1422 if (!SamplerStructTy) {
1423 SamplerStructTy = StructType::create(M.getContext(), "opencl.sampler_t");
1424 }
1425
1426 SamplerTy = SamplerStructTy->getPointerTo(AddressSpace::UniformConstant);
1427
1428 FindType(SamplerTy);
1429 }
1430}
1431
1432void SPIRVProducerPass::FindTypesForResourceVars(Module &M) {
1433 // Record types so they are generated.
1434 TypesNeedingLayout.reset();
1435 StructTypesNeedingBlock.reset();
1436
1437 // To match older clspv codegen, generate the float type first if required
1438 // for images.
1439 for (const auto *info : ModuleOrderedResourceVars) {
1440 if (info->arg_kind == clspv::ArgKind::ReadOnlyImage ||
1441 info->arg_kind == clspv::ArgKind::WriteOnlyImage) {
alan-bakerf67468c2019-11-25 15:51:49 -05001442 if (IsIntImageType(info->var_fn->getReturnType())) {
1443 // Nothing for now...
1444 } else if (IsUintImageType(info->var_fn->getReturnType())) {
1445 FindType(Type::getInt32Ty(M.getContext()));
1446 }
1447
1448 // We need "float" either for the sampled type or for the Lod operand.
David Neto862b7d82018-06-14 18:48:37 -04001449 FindType(Type::getFloatTy(M.getContext()));
David Neto862b7d82018-06-14 18:48:37 -04001450 }
1451 }
1452
1453 for (const auto *info : ModuleOrderedResourceVars) {
1454 Type *type = info->var_fn->getReturnType();
1455
1456 switch (info->arg_kind) {
1457 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04001458 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04001459 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1460 StructTypesNeedingBlock.insert(sty);
1461 } else {
1462 errs() << *type << "\n";
1463 llvm_unreachable("Buffer arguments must map to structures!");
1464 }
1465 break;
1466 case clspv::ArgKind::Pod:
alan-baker9b0ec3c2020-04-06 14:45:34 -04001467 case clspv::ArgKind::PodUBO:
1468 case clspv::ArgKind::PodPushConstant:
David Neto862b7d82018-06-14 18:48:37 -04001469 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1470 StructTypesNeedingBlock.insert(sty);
1471 } else {
1472 errs() << *type << "\n";
1473 llvm_unreachable("POD arguments must map to structures!");
1474 }
1475 break;
1476 case clspv::ArgKind::ReadOnlyImage:
1477 case clspv::ArgKind::WriteOnlyImage:
1478 case clspv::ArgKind::Sampler:
1479 // Sampler and image types map to the pointee type but
1480 // in the uniform constant address space.
1481 type = PointerType::get(type->getPointerElementType(),
1482 clspv::AddressSpace::UniformConstant);
1483 break;
1484 default:
1485 break;
1486 }
1487
1488 // The converted type is the type of the OpVariable we will generate.
1489 // If the pointee type is an array of size zero, FindType will convert it
1490 // to a runtime array.
1491 FindType(type);
1492 }
1493
alan-bakerdcd97412019-09-16 15:32:30 -04001494 // If module constants are clustered in a storage buffer then that struct
1495 // needs layout decorations.
1496 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
1497 for (GlobalVariable &GV : M.globals()) {
1498 PointerType *PTy = cast<PointerType>(GV.getType());
1499 const auto AS = PTy->getAddressSpace();
1500 const bool module_scope_constant_external_init =
1501 (AS == AddressSpace::Constant) && GV.hasInitializer();
1502 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
1503 if (module_scope_constant_external_init &&
1504 spv::BuiltInMax == BuiltinType) {
1505 StructTypesNeedingBlock.insert(
1506 cast<StructType>(PTy->getPointerElementType()));
1507 }
1508 }
1509 }
1510
Kévin Petitbbbda972020-03-03 19:16:31 +00001511 for (const GlobalVariable &GV : M.globals()) {
1512 if (GV.getAddressSpace() == clspv::AddressSpace::PushConstant) {
1513 auto Ty = cast<PointerType>(GV.getType())->getPointerElementType();
1514 assert(Ty->isStructTy() && "Push constants have to be structures.");
1515 auto STy = cast<StructType>(Ty);
1516 StructTypesNeedingBlock.insert(STy);
1517 }
1518 }
1519
David Neto862b7d82018-06-14 18:48:37 -04001520 // Traverse the arrays and structures underneath each Block, and
1521 // mark them as needing layout.
1522 std::vector<Type *> work_list(StructTypesNeedingBlock.begin(),
1523 StructTypesNeedingBlock.end());
1524 while (!work_list.empty()) {
1525 Type *type = work_list.back();
1526 work_list.pop_back();
1527 TypesNeedingLayout.insert(type);
1528 switch (type->getTypeID()) {
1529 case Type::ArrayTyID:
1530 work_list.push_back(type->getArrayElementType());
1531 if (!Hack_generate_runtime_array_stride_early) {
1532 // Remember this array type for deferred decoration.
1533 TypesNeedingArrayStride.insert(type);
1534 }
1535 break;
1536 case Type::StructTyID:
1537 for (auto *elem_ty : cast<StructType>(type)->elements()) {
1538 work_list.push_back(elem_ty);
1539 }
1540 default:
1541 // This type and its contained types don't get layout.
1542 break;
1543 }
1544 }
1545}
1546
Alan Baker202c8c72018-08-13 13:47:44 -04001547void SPIRVProducerPass::FindWorkgroupVars(Module &M) {
1548 // The SpecId assignment for pointer-to-local arguments is recorded in
1549 // module-level metadata. Translate that information into local argument
1550 // information.
1551 NamedMDNode *nmd = M.getNamedMetadata(clspv::LocalSpecIdMetadataName());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001552 if (!nmd)
1553 return;
Alan Baker202c8c72018-08-13 13:47:44 -04001554 for (auto operand : nmd->operands()) {
1555 MDTuple *tuple = cast<MDTuple>(operand);
1556 ValueAsMetadata *fn_md = cast<ValueAsMetadata>(tuple->getOperand(0));
1557 Function *func = cast<Function>(fn_md->getValue());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001558 ConstantAsMetadata *arg_index_md =
1559 cast<ConstantAsMetadata>(tuple->getOperand(1));
1560 int arg_index = static_cast<int>(
1561 cast<ConstantInt>(arg_index_md->getValue())->getSExtValue());
1562 Argument *arg = &*(func->arg_begin() + arg_index);
Alan Baker202c8c72018-08-13 13:47:44 -04001563
1564 ConstantAsMetadata *spec_id_md =
1565 cast<ConstantAsMetadata>(tuple->getOperand(2));
alan-bakerb6b09dc2018-11-08 16:59:28 -05001566 int spec_id = static_cast<int>(
1567 cast<ConstantInt>(spec_id_md->getValue())->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04001568
Alan Baker202c8c72018-08-13 13:47:44 -04001569 LocalArgSpecIds[arg] = spec_id;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001570 if (LocalSpecIdInfoMap.count(spec_id))
1571 continue;
Alan Baker202c8c72018-08-13 13:47:44 -04001572
1573 // We haven't seen this SpecId yet, so generate the LocalArgInfo for it.
1574 LocalArgInfo info{nextID, arg->getType()->getPointerElementType(),
1575 nextID + 1, nextID + 2,
1576 nextID + 3, spec_id};
1577 LocalSpecIdInfoMap[spec_id] = info;
1578 nextID += 4;
1579
1580 // Ensure the types necessary for this argument get generated.
1581 Type *IdxTy = Type::getInt32Ty(M.getContext());
1582 FindConstant(ConstantInt::get(IdxTy, 0));
1583 FindType(IdxTy);
1584 FindType(arg->getType());
1585 }
1586}
1587
David Neto22f144c2017-06-12 14:26:21 -04001588void SPIRVProducerPass::FindType(Type *Ty) {
1589 TypeList &TyList = getTypeList();
1590
1591 if (0 != TyList.idFor(Ty)) {
1592 return;
1593 }
1594
1595 if (Ty->isPointerTy()) {
1596 auto AddrSpace = Ty->getPointerAddressSpace();
1597 if ((AddressSpace::Constant == AddrSpace) ||
1598 (AddressSpace::Global == AddrSpace)) {
1599 auto PointeeTy = Ty->getPointerElementType();
1600
1601 if (PointeeTy->isStructTy() &&
1602 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1603 FindType(PointeeTy);
1604 auto ActualPointerTy =
1605 PointeeTy->getPointerTo(AddressSpace::UniformConstant);
1606 FindType(ActualPointerTy);
1607 return;
1608 }
1609 }
1610 }
1611
David Neto862b7d82018-06-14 18:48:37 -04001612 // By convention, LLVM array type with 0 elements will map to
1613 // OpTypeRuntimeArray. Otherwise, it will map to OpTypeArray, which
1614 // has a constant number of elements. We need to support type of the
1615 // constant.
1616 if (auto *arrayTy = dyn_cast<ArrayType>(Ty)) {
1617 if (arrayTy->getNumElements() > 0) {
1618 LLVMContext &Context = Ty->getContext();
1619 FindType(Type::getInt32Ty(Context));
1620 }
David Neto22f144c2017-06-12 14:26:21 -04001621 }
1622
1623 for (Type *SubTy : Ty->subtypes()) {
1624 FindType(SubTy);
1625 }
1626
1627 TyList.insert(Ty);
1628}
1629
1630void SPIRVProducerPass::FindConstantPerGlobalVar(GlobalVariable &GV) {
1631 // If the global variable has a (non undef) initializer.
1632 if (GV.hasInitializer() && !isa<UndefValue>(GV.getInitializer())) {
David Neto862b7d82018-06-14 18:48:37 -04001633 // Generate the constant if it's not the initializer to a module scope
1634 // constant that we will expect in a storage buffer.
1635 const bool module_scope_constant_external_init =
1636 (GV.getType()->getPointerAddressSpace() == AddressSpace::Constant) &&
1637 clspv::Option::ModuleConstantsInStorageBuffer();
1638 if (!module_scope_constant_external_init) {
1639 FindConstant(GV.getInitializer());
1640 }
David Neto22f144c2017-06-12 14:26:21 -04001641 }
1642}
1643
1644void SPIRVProducerPass::FindConstantPerFunc(Function &F) {
1645 // Investigate constants in function body.
1646 for (BasicBlock &BB : F) {
1647 for (Instruction &I : BB) {
David Neto862b7d82018-06-14 18:48:37 -04001648 if (auto *call = dyn_cast<CallInst>(&I)) {
1649 auto name = call->getCalledFunction()->getName();
Kévin Petitdf71de32019-04-09 14:09:50 +01001650 if (name == clspv::LiteralSamplerFunction()) {
David Neto862b7d82018-06-14 18:48:37 -04001651 // We've handled these constants elsewhere, so skip it.
1652 continue;
1653 }
Alan Baker202c8c72018-08-13 13:47:44 -04001654 if (name.startswith(clspv::ResourceAccessorFunction())) {
1655 continue;
1656 }
1657 if (name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001658 continue;
1659 }
Kévin Petit617a76d2019-04-04 13:54:16 +01001660 if (name.startswith(clspv::SPIRVOpIntrinsicFunction())) {
1661 // Skip the first operand that has the SPIR-V Opcode
1662 for (unsigned i = 1; i < I.getNumOperands(); i++) {
1663 if (isa<Constant>(I.getOperand(i)) &&
1664 !isa<GlobalValue>(I.getOperand(i))) {
1665 FindConstant(I.getOperand(i));
1666 }
1667 }
1668 continue;
1669 }
David Neto22f144c2017-06-12 14:26:21 -04001670 }
1671
1672 if (isa<AllocaInst>(I)) {
1673 // Alloca instruction has constant for the number of element. Ignore it.
1674 continue;
1675 } else if (isa<ShuffleVectorInst>(I)) {
1676 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1677 // Ignore constant for mask of shuffle vector instruction.
1678 if (i == 2) {
1679 continue;
1680 }
1681
1682 if (isa<Constant>(I.getOperand(i)) &&
1683 !isa<GlobalValue>(I.getOperand(i))) {
1684 FindConstant(I.getOperand(i));
1685 }
1686 }
1687
1688 continue;
1689 } else if (isa<InsertElementInst>(I)) {
1690 // Handle InsertElement with <4 x i8> specially.
1691 Type *CompositeTy = I.getOperand(0)->getType();
1692 if (is4xi8vec(CompositeTy)) {
1693 LLVMContext &Context = CompositeTy->getContext();
1694 if (isa<Constant>(I.getOperand(0))) {
1695 FindConstant(I.getOperand(0));
1696 }
1697
1698 if (isa<Constant>(I.getOperand(1))) {
1699 FindConstant(I.getOperand(1));
1700 }
1701
1702 // Add mask constant 0xFF.
1703 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1704 FindConstant(CstFF);
1705
1706 // Add shift amount constant.
1707 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
1708 uint64_t Idx = CI->getZExtValue();
1709 Constant *CstShiftAmount =
1710 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1711 FindConstant(CstShiftAmount);
1712 }
1713
1714 continue;
1715 }
1716
1717 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1718 // Ignore constant for index of InsertElement instruction.
1719 if (i == 2) {
1720 continue;
1721 }
1722
1723 if (isa<Constant>(I.getOperand(i)) &&
1724 !isa<GlobalValue>(I.getOperand(i))) {
1725 FindConstant(I.getOperand(i));
1726 }
1727 }
1728
1729 continue;
1730 } else if (isa<ExtractElementInst>(I)) {
1731 // Handle ExtractElement with <4 x i8> specially.
1732 Type *CompositeTy = I.getOperand(0)->getType();
1733 if (is4xi8vec(CompositeTy)) {
1734 LLVMContext &Context = CompositeTy->getContext();
1735 if (isa<Constant>(I.getOperand(0))) {
1736 FindConstant(I.getOperand(0));
1737 }
1738
1739 // Add mask constant 0xFF.
1740 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1741 FindConstant(CstFF);
1742
1743 // Add shift amount constant.
1744 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
1745 uint64_t Idx = CI->getZExtValue();
1746 Constant *CstShiftAmount =
1747 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1748 FindConstant(CstShiftAmount);
1749 } else {
1750 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
1751 FindConstant(Cst8);
1752 }
1753
1754 continue;
1755 }
1756
1757 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1758 // Ignore constant for index of ExtractElement instruction.
1759 if (i == 1) {
1760 continue;
1761 }
1762
1763 if (isa<Constant>(I.getOperand(i)) &&
1764 !isa<GlobalValue>(I.getOperand(i))) {
1765 FindConstant(I.getOperand(i));
1766 }
1767 }
1768
1769 continue;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001770 } else if ((Instruction::Xor == I.getOpcode()) &&
1771 I.getType()->isIntegerTy(1)) {
1772 // We special case for Xor where the type is i1 and one of the arguments
1773 // is a constant 1 (true), this is an OpLogicalNot in SPIR-V, and we
1774 // don't need the constant
David Neto22f144c2017-06-12 14:26:21 -04001775 bool foundConstantTrue = false;
1776 for (Use &Op : I.operands()) {
1777 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1778 auto CI = cast<ConstantInt>(Op);
1779
1780 if (CI->isZero() || foundConstantTrue) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05001781 // If we already found the true constant, we might (probably only
1782 // on -O0) have an OpLogicalNot which is taking a constant
1783 // argument, so discover it anyway.
David Neto22f144c2017-06-12 14:26:21 -04001784 FindConstant(Op);
1785 } else {
1786 foundConstantTrue = true;
1787 }
1788 }
1789 }
1790
1791 continue;
David Netod2de94a2017-08-28 17:27:47 -04001792 } else if (isa<TruncInst>(I)) {
alan-bakerb39c8262019-03-08 14:03:37 -05001793 // Special case if i8 is not generally handled.
1794 if (!clspv::Option::Int8Support()) {
1795 // For truncation to i8 we mask against 255.
1796 Type *ToTy = I.getType();
1797 if (8u == ToTy->getPrimitiveSizeInBits()) {
1798 LLVMContext &Context = ToTy->getContext();
1799 Constant *Cst255 =
1800 ConstantInt::get(Type::getInt32Ty(Context), 0xff);
1801 FindConstant(Cst255);
1802 }
David Netod2de94a2017-08-28 17:27:47 -04001803 }
Neil Henning39672102017-09-29 14:33:13 +01001804 } else if (isa<AtomicRMWInst>(I)) {
1805 LLVMContext &Context = I.getContext();
1806
1807 FindConstant(
1808 ConstantInt::get(Type::getInt32Ty(Context), spv::ScopeDevice));
1809 FindConstant(ConstantInt::get(
1810 Type::getInt32Ty(Context),
1811 spv::MemorySemanticsUniformMemoryMask |
1812 spv::MemorySemanticsSequentiallyConsistentMask));
David Neto22f144c2017-06-12 14:26:21 -04001813 }
1814
1815 for (Use &Op : I.operands()) {
1816 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1817 FindConstant(Op);
1818 }
1819 }
1820 }
1821 }
1822}
1823
1824void SPIRVProducerPass::FindConstant(Value *V) {
David Neto22f144c2017-06-12 14:26:21 -04001825 ValueList &CstList = getConstantList();
1826
David Netofb9a7972017-08-25 17:08:24 -04001827 // If V is already tracked, ignore it.
1828 if (0 != CstList.idFor(V)) {
David Neto22f144c2017-06-12 14:26:21 -04001829 return;
1830 }
1831
David Neto862b7d82018-06-14 18:48:37 -04001832 if (isa<GlobalValue>(V) && clspv::Option::ModuleConstantsInStorageBuffer()) {
1833 return;
1834 }
1835
David Neto22f144c2017-06-12 14:26:21 -04001836 Constant *Cst = cast<Constant>(V);
David Neto862b7d82018-06-14 18:48:37 -04001837 Type *CstTy = Cst->getType();
David Neto22f144c2017-06-12 14:26:21 -04001838
1839 // Handle constant with <4 x i8> type specially.
David Neto22f144c2017-06-12 14:26:21 -04001840 if (is4xi8vec(CstTy)) {
1841 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001842 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001843 }
1844 }
1845
1846 if (Cst->getNumOperands()) {
1847 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end(); I != E;
1848 ++I) {
1849 FindConstant(*I);
1850 }
1851
David Netofb9a7972017-08-25 17:08:24 -04001852 CstList.insert(Cst);
David Neto22f144c2017-06-12 14:26:21 -04001853 return;
1854 } else if (const ConstantDataSequential *CDS =
1855 dyn_cast<ConstantDataSequential>(Cst)) {
1856 // Add constants for each element to constant list.
1857 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
1858 Constant *EleCst = CDS->getElementAsConstant(i);
1859 FindConstant(EleCst);
1860 }
1861 }
1862
1863 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001864 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001865 }
1866}
1867
1868spv::StorageClass SPIRVProducerPass::GetStorageClass(unsigned AddrSpace) const {
1869 switch (AddrSpace) {
1870 default:
1871 llvm_unreachable("Unsupported OpenCL address space");
1872 case AddressSpace::Private:
1873 return spv::StorageClassFunction;
1874 case AddressSpace::Global:
David Neto22f144c2017-06-12 14:26:21 -04001875 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001876 case AddressSpace::Constant:
1877 return clspv::Option::ConstantArgsInUniformBuffer()
1878 ? spv::StorageClassUniform
1879 : spv::StorageClassStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -04001880 case AddressSpace::Input:
1881 return spv::StorageClassInput;
1882 case AddressSpace::Local:
1883 return spv::StorageClassWorkgroup;
1884 case AddressSpace::UniformConstant:
1885 return spv::StorageClassUniformConstant;
David Neto9ed8e2f2018-03-24 06:47:24 -07001886 case AddressSpace::Uniform:
David Netoe439d702018-03-23 13:14:08 -07001887 return spv::StorageClassUniform;
David Neto22f144c2017-06-12 14:26:21 -04001888 case AddressSpace::ModuleScopePrivate:
1889 return spv::StorageClassPrivate;
Kévin Petitbbbda972020-03-03 19:16:31 +00001890 case AddressSpace::PushConstant:
1891 return spv::StorageClassPushConstant;
David Neto22f144c2017-06-12 14:26:21 -04001892 }
1893}
1894
David Neto862b7d82018-06-14 18:48:37 -04001895spv::StorageClass
1896SPIRVProducerPass::GetStorageClassForArgKind(clspv::ArgKind arg_kind) const {
1897 switch (arg_kind) {
1898 case clspv::ArgKind::Buffer:
1899 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001900 case clspv::ArgKind::BufferUBO:
1901 return spv::StorageClassUniform;
David Neto862b7d82018-06-14 18:48:37 -04001902 case clspv::ArgKind::Pod:
alan-baker9b0ec3c2020-04-06 14:45:34 -04001903 return spv::StorageClassStorageBuffer;
1904 case clspv::ArgKind::PodUBO:
1905 return spv::StorageClassUniform;
1906 case clspv::ArgKind::PodPushConstant:
1907 return spv::StorageClassPushConstant;
David Neto862b7d82018-06-14 18:48:37 -04001908 case clspv::ArgKind::Local:
1909 return spv::StorageClassWorkgroup;
1910 case clspv::ArgKind::ReadOnlyImage:
1911 case clspv::ArgKind::WriteOnlyImage:
1912 case clspv::ArgKind::Sampler:
1913 return spv::StorageClassUniformConstant;
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001914 default:
1915 llvm_unreachable("Unsupported storage class for argument kind");
David Neto862b7d82018-06-14 18:48:37 -04001916 }
1917}
1918
David Neto22f144c2017-06-12 14:26:21 -04001919spv::BuiltIn SPIRVProducerPass::GetBuiltin(StringRef Name) const {
1920 return StringSwitch<spv::BuiltIn>(Name)
1921 .Case("__spirv_GlobalInvocationId", spv::BuiltInGlobalInvocationId)
1922 .Case("__spirv_LocalInvocationId", spv::BuiltInLocalInvocationId)
1923 .Case("__spirv_WorkgroupSize", spv::BuiltInWorkgroupSize)
1924 .Case("__spirv_NumWorkgroups", spv::BuiltInNumWorkgroups)
1925 .Case("__spirv_WorkgroupId", spv::BuiltInWorkgroupId)
1926 .Default(spv::BuiltInMax);
1927}
1928
1929void SPIRVProducerPass::GenerateExtInstImport() {
SJW69939d52020-04-16 07:29:07 -05001930 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kImports);
David Neto22f144c2017-06-12 14:26:21 -04001931 uint32_t &ExtInstImportID = getOpExtInstImportID();
1932
1933 //
1934 // Generate OpExtInstImport.
1935 //
1936 // Ops[0] ... Ops[n] = Name (Literal String)
David Neto22f144c2017-06-12 14:26:21 -04001937 ExtInstImportID = nextID;
David Neto87846742018-04-11 17:36:22 -04001938 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpExtInstImport, nextID++,
1939 MkString("GLSL.std.450")));
David Neto22f144c2017-06-12 14:26:21 -04001940}
1941
alan-bakerb6b09dc2018-11-08 16:59:28 -05001942void SPIRVProducerPass::GenerateSPIRVTypes(LLVMContext &Context,
1943 Module &module) {
SJW69939d52020-04-16 07:29:07 -05001944 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kTypes);
David Neto22f144c2017-06-12 14:26:21 -04001945 ValueMapType &VMap = getValueMap();
1946 ValueMapType &AllocatedVMap = getAllocatedValueMap();
Alan Bakerfcda9482018-10-02 17:09:59 -04001947 const auto &DL = module.getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04001948
1949 // Map for OpTypeRuntimeArray. If argument has pointer type, 2 spirv type
1950 // instructions are generated. They are OpTypePointer and OpTypeRuntimeArray.
1951 DenseMap<Type *, uint32_t> OpRuntimeTyMap;
1952
1953 for (Type *Ty : getTypeList()) {
1954 // Update TypeMap with nextID for reference later.
1955 TypeMap[Ty] = nextID;
1956
1957 switch (Ty->getTypeID()) {
1958 default: {
1959 Ty->print(errs());
1960 llvm_unreachable("Unsupported type???");
1961 break;
1962 }
1963 case Type::MetadataTyID:
1964 case Type::LabelTyID: {
1965 // Ignore these types.
1966 break;
1967 }
1968 case Type::PointerTyID: {
1969 PointerType *PTy = cast<PointerType>(Ty);
1970 unsigned AddrSpace = PTy->getAddressSpace();
1971
1972 // For the purposes of our Vulkan SPIR-V type system, constant and global
1973 // are conflated.
1974 bool UseExistingOpTypePointer = false;
1975 if (AddressSpace::Constant == AddrSpace) {
Alan Bakerfcda9482018-10-02 17:09:59 -04001976 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1977 AddrSpace = AddressSpace::Global;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001978 // Check to see if we already created this type (for instance, if we
1979 // had a constant <type>* and a global <type>*, the type would be
1980 // created by one of these types, and shared by both).
Alan Bakerfcda9482018-10-02 17:09:59 -04001981 auto GlobalTy = PTy->getPointerElementType()->getPointerTo(AddrSpace);
1982 if (0 < TypeMap.count(GlobalTy)) {
1983 TypeMap[PTy] = TypeMap[GlobalTy];
1984 UseExistingOpTypePointer = true;
1985 break;
1986 }
David Neto22f144c2017-06-12 14:26:21 -04001987 }
1988 } else if (AddressSpace::Global == AddrSpace) {
Alan Bakerfcda9482018-10-02 17:09:59 -04001989 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1990 AddrSpace = AddressSpace::Constant;
David Neto22f144c2017-06-12 14:26:21 -04001991
alan-bakerb6b09dc2018-11-08 16:59:28 -05001992 // Check to see if we already created this type (for instance, if we
1993 // had a constant <type>* and a global <type>*, the type would be
1994 // created by one of these types, and shared by both).
1995 auto ConstantTy =
1996 PTy->getPointerElementType()->getPointerTo(AddrSpace);
Alan Bakerfcda9482018-10-02 17:09:59 -04001997 if (0 < TypeMap.count(ConstantTy)) {
1998 TypeMap[PTy] = TypeMap[ConstantTy];
1999 UseExistingOpTypePointer = true;
2000 }
David Neto22f144c2017-06-12 14:26:21 -04002001 }
2002 }
2003
David Neto862b7d82018-06-14 18:48:37 -04002004 const bool HasArgUser = true;
David Neto22f144c2017-06-12 14:26:21 -04002005
David Neto862b7d82018-06-14 18:48:37 -04002006 if (HasArgUser && !UseExistingOpTypePointer) {
David Neto22f144c2017-06-12 14:26:21 -04002007 //
2008 // Generate OpTypePointer.
2009 //
2010
2011 // OpTypePointer
2012 // Ops[0] = Storage Class
2013 // Ops[1] = Element Type ID
2014 SPIRVOperandList Ops;
2015
David Neto257c3892018-04-11 13:19:45 -04002016 Ops << MkNum(GetStorageClass(AddrSpace))
2017 << MkId(lookupType(PTy->getElementType()));
David Neto22f144c2017-06-12 14:26:21 -04002018
David Neto87846742018-04-11 17:36:22 -04002019 auto *Inst = new SPIRVInstruction(spv::OpTypePointer, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002020 SPIRVInstList.push_back(Inst);
2021 }
David Neto22f144c2017-06-12 14:26:21 -04002022 break;
2023 }
2024 case Type::StructTyID: {
David Neto22f144c2017-06-12 14:26:21 -04002025 StructType *STy = cast<StructType>(Ty);
2026
2027 // Handle sampler type.
2028 if (STy->isOpaque()) {
2029 if (STy->getName().equals("opencl.sampler_t")) {
2030 //
2031 // Generate OpTypeSampler
2032 //
2033 // Empty Ops.
2034 SPIRVOperandList Ops;
2035
David Neto87846742018-04-11 17:36:22 -04002036 auto *Inst = new SPIRVInstruction(spv::OpTypeSampler, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002037 SPIRVInstList.push_back(Inst);
2038 break;
alan-bakerf906d2b2019-12-10 11:26:23 -05002039 } else if (STy->getName().startswith("opencl.image1d_ro_t") ||
2040 STy->getName().startswith("opencl.image1d_wo_t") ||
alan-baker7150a1d2020-02-25 08:31:06 -05002041 STy->getName().startswith("opencl.image1d_array_ro_t") ||
2042 STy->getName().startswith("opencl.image1d_array_wo_t") ||
alan-bakerf906d2b2019-12-10 11:26:23 -05002043 STy->getName().startswith("opencl.image2d_ro_t") ||
alan-bakerf67468c2019-11-25 15:51:49 -05002044 STy->getName().startswith("opencl.image2d_wo_t") ||
alan-baker7150a1d2020-02-25 08:31:06 -05002045 STy->getName().startswith("opencl.image2d_array_ro_t") ||
2046 STy->getName().startswith("opencl.image2d_array_wo_t") ||
alan-bakerf67468c2019-11-25 15:51:49 -05002047 STy->getName().startswith("opencl.image3d_ro_t") ||
2048 STy->getName().startswith("opencl.image3d_wo_t")) {
David Neto22f144c2017-06-12 14:26:21 -04002049 //
2050 // Generate OpTypeImage
2051 //
2052 // Ops[0] = Sampled Type ID
2053 // Ops[1] = Dim ID
2054 // Ops[2] = Depth (Literal Number)
2055 // Ops[3] = Arrayed (Literal Number)
2056 // Ops[4] = MS (Literal Number)
2057 // Ops[5] = Sampled (Literal Number)
2058 // Ops[6] = Image Format ID
2059 //
2060 SPIRVOperandList Ops;
2061
alan-bakerf67468c2019-11-25 15:51:49 -05002062 uint32_t ImageTyID = nextID++;
2063 uint32_t SampledTyID = 0;
2064 if (STy->getName().contains(".float")) {
2065 SampledTyID = lookupType(Type::getFloatTy(Context));
2066 } else if (STy->getName().contains(".uint")) {
2067 SampledTyID = lookupType(Type::getInt32Ty(Context));
2068 } else if (STy->getName().contains(".int")) {
2069 // Generate a signed 32-bit integer if necessary.
2070 if (int32ID == 0) {
2071 int32ID = nextID++;
2072 SPIRVOperandList intOps;
2073 intOps << MkNum(32);
2074 intOps << MkNum(1);
2075 auto signed_int =
2076 new SPIRVInstruction(spv::OpTypeInt, int32ID, intOps);
2077 SPIRVInstList.push_back(signed_int);
2078 }
2079 SampledTyID = int32ID;
2080
2081 // Generate a vec4 of the signed int if necessary.
2082 if (v4int32ID == 0) {
2083 v4int32ID = nextID++;
2084 SPIRVOperandList vecOps;
2085 vecOps << MkId(int32ID);
2086 vecOps << MkNum(4);
2087 auto int_vec =
2088 new SPIRVInstruction(spv::OpTypeVector, v4int32ID, vecOps);
2089 SPIRVInstList.push_back(int_vec);
2090 }
2091 } else {
2092 // This was likely an UndefValue.
2093 SampledTyID = lookupType(Type::getFloatTy(Context));
2094 }
David Neto257c3892018-04-11 13:19:45 -04002095 Ops << MkId(SampledTyID);
David Neto22f144c2017-06-12 14:26:21 -04002096
2097 spv::Dim DimID = spv::Dim2D;
alan-bakerf906d2b2019-12-10 11:26:23 -05002098 if (STy->getName().startswith("opencl.image1d_ro_t") ||
alan-baker7150a1d2020-02-25 08:31:06 -05002099 STy->getName().startswith("opencl.image1d_wo_t") ||
2100 STy->getName().startswith("opencl.image1d_array_ro_t") ||
2101 STy->getName().startswith("opencl.image1d_array_wo_t")) {
alan-bakerf906d2b2019-12-10 11:26:23 -05002102 DimID = spv::Dim1D;
2103 } else if (STy->getName().startswith("opencl.image3d_ro_t") ||
2104 STy->getName().startswith("opencl.image3d_wo_t")) {
David Neto22f144c2017-06-12 14:26:21 -04002105 DimID = spv::Dim3D;
2106 }
David Neto257c3892018-04-11 13:19:45 -04002107 Ops << MkNum(DimID);
David Neto22f144c2017-06-12 14:26:21 -04002108
2109 // TODO: Set up Depth.
David Neto257c3892018-04-11 13:19:45 -04002110 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04002111
alan-baker7150a1d2020-02-25 08:31:06 -05002112 uint32_t arrayed = STy->getName().contains("_array_") ? 1 : 0;
2113 Ops << MkNum(arrayed);
David Neto22f144c2017-06-12 14:26:21 -04002114
2115 // TODO: Set up MS.
David Neto257c3892018-04-11 13:19:45 -04002116 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04002117
alan-baker7150a1d2020-02-25 08:31:06 -05002118 // Set up Sampled.
David Neto22f144c2017-06-12 14:26:21 -04002119 //
2120 // From Spec
2121 //
2122 // 0 indicates this is only known at run time, not at compile time
2123 // 1 indicates will be used with sampler
2124 // 2 indicates will be used without a sampler (a storage image)
2125 uint32_t Sampled = 1;
alan-bakerf67468c2019-11-25 15:51:49 -05002126 if (!STy->getName().contains(".sampled")) {
David Neto22f144c2017-06-12 14:26:21 -04002127 Sampled = 2;
2128 }
David Neto257c3892018-04-11 13:19:45 -04002129 Ops << MkNum(Sampled);
David Neto22f144c2017-06-12 14:26:21 -04002130
2131 // TODO: Set up Image Format.
David Neto257c3892018-04-11 13:19:45 -04002132 Ops << MkNum(spv::ImageFormatUnknown);
David Neto22f144c2017-06-12 14:26:21 -04002133
alan-bakerf67468c2019-11-25 15:51:49 -05002134 auto *Inst = new SPIRVInstruction(spv::OpTypeImage, ImageTyID, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002135 SPIRVInstList.push_back(Inst);
2136 break;
2137 }
2138 }
2139
2140 //
2141 // Generate OpTypeStruct
2142 //
2143 // Ops[0] ... Ops[n] = Member IDs
2144 SPIRVOperandList Ops;
2145
2146 for (auto *EleTy : STy->elements()) {
David Neto862b7d82018-06-14 18:48:37 -04002147 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04002148 }
2149
David Neto22f144c2017-06-12 14:26:21 -04002150 uint32_t STyID = nextID;
2151
alan-bakerb6b09dc2018-11-08 16:59:28 -05002152 auto *Inst = new SPIRVInstruction(spv::OpTypeStruct, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002153 SPIRVInstList.push_back(Inst);
2154
2155 // Generate OpMemberDecorate.
Kévin Petitbbbda972020-03-03 19:16:31 +00002156 if (TypesNeedingLayout.idFor(STy)) {
2157 for (unsigned MemberIdx = 0; MemberIdx < STy->getNumElements();
2158 MemberIdx++) {
2159 // Ops[0] = Structure Type ID
2160 // Ops[1] = Member Index(Literal Number)
2161 // Ops[2] = Decoration (Offset)
2162 // Ops[3] = Byte Offset (Literal Number)
2163 Ops.clear();
David Netoc463b372017-08-10 15:32:21 -04002164
Kévin Petitbbbda972020-03-03 19:16:31 +00002165 Ops << MkId(STyID) << MkNum(MemberIdx)
2166 << MkNum(spv::DecorationOffset);
David Neto22f144c2017-06-12 14:26:21 -04002167
Kévin Petitbbbda972020-03-03 19:16:31 +00002168 const auto ByteOffset =
2169 GetExplicitLayoutStructMemberOffset(STy, MemberIdx, DL);
David Neto22f144c2017-06-12 14:26:21 -04002170
Kévin Petitbbbda972020-03-03 19:16:31 +00002171 Ops << MkNum(ByteOffset);
2172
2173 auto *DecoInst = new SPIRVInstruction(spv::OpMemberDecorate, Ops);
SJW69939d52020-04-16 07:29:07 -05002174 getSPIRVInstList(kAnnotations).push_back(DecoInst);
Alan Bakerfcda9482018-10-02 17:09:59 -04002175 }
David Neto22f144c2017-06-12 14:26:21 -04002176 }
2177
2178 // Generate OpDecorate.
David Neto862b7d82018-06-14 18:48:37 -04002179 if (StructTypesNeedingBlock.idFor(STy)) {
2180 Ops.clear();
2181 // Use Block decorations with StorageBuffer storage class.
2182 Ops << MkId(STyID) << MkNum(spv::DecorationBlock);
David Neto22f144c2017-06-12 14:26:21 -04002183
David Neto862b7d82018-06-14 18:48:37 -04002184 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
SJW69939d52020-04-16 07:29:07 -05002185 getSPIRVInstList(kAnnotations).push_back(DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04002186 }
2187 break;
2188 }
2189 case Type::IntegerTyID: {
alan-baker0e64a592019-11-18 13:36:25 -05002190 uint32_t BitWidth = static_cast<uint32_t>(Ty->getPrimitiveSizeInBits());
David Neto22f144c2017-06-12 14:26:21 -04002191
2192 if (BitWidth == 1) {
David Netoef5ba2b2019-12-20 08:35:54 -05002193 auto *Inst = new SPIRVInstruction(spv::OpTypeBool, nextID++);
David Neto22f144c2017-06-12 14:26:21 -04002194 SPIRVInstList.push_back(Inst);
2195 } else {
alan-bakerb39c8262019-03-08 14:03:37 -05002196 if (!clspv::Option::Int8Support()) {
2197 // i8 is added to TypeMap as i32.
2198 // No matter what LLVM type is requested first, always alias the
2199 // second one's SPIR-V type to be the same as the one we generated
2200 // first.
2201 unsigned aliasToWidth = 0;
2202 if (BitWidth == 8) {
2203 aliasToWidth = 32;
2204 BitWidth = 32;
2205 } else if (BitWidth == 32) {
2206 aliasToWidth = 8;
2207 }
2208 if (aliasToWidth) {
2209 Type *otherType = Type::getIntNTy(Ty->getContext(), aliasToWidth);
2210 auto where = TypeMap.find(otherType);
2211 if (where == TypeMap.end()) {
2212 // Go ahead and make it, but also map the other type to it.
2213 TypeMap[otherType] = nextID;
2214 } else {
2215 // Alias this SPIR-V type the existing type.
2216 TypeMap[Ty] = where->second;
2217 break;
2218 }
David Neto391aeb12017-08-26 15:51:58 -04002219 }
David Neto22f144c2017-06-12 14:26:21 -04002220 }
2221
David Neto257c3892018-04-11 13:19:45 -04002222 SPIRVOperandList Ops;
2223 Ops << MkNum(BitWidth) << MkNum(0 /* not signed */);
David Neto22f144c2017-06-12 14:26:21 -04002224
2225 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002226 new SPIRVInstruction(spv::OpTypeInt, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002227 }
2228 break;
2229 }
2230 case Type::HalfTyID:
2231 case Type::FloatTyID:
2232 case Type::DoubleTyID: {
alan-baker0e64a592019-11-18 13:36:25 -05002233 uint32_t BitWidth = static_cast<uint32_t>(Ty->getPrimitiveSizeInBits());
James Price11010dc2019-12-19 13:53:09 -05002234 auto WidthOp = MkNum(BitWidth);
David Neto22f144c2017-06-12 14:26:21 -04002235
2236 SPIRVInstList.push_back(
David Netoef5ba2b2019-12-20 08:35:54 -05002237 new SPIRVInstruction(spv::OpTypeFloat, nextID++, std::move(WidthOp)));
David Neto22f144c2017-06-12 14:26:21 -04002238 break;
2239 }
2240 case Type::ArrayTyID: {
David Neto22f144c2017-06-12 14:26:21 -04002241 ArrayType *ArrTy = cast<ArrayType>(Ty);
David Neto862b7d82018-06-14 18:48:37 -04002242 const uint64_t Length = ArrTy->getArrayNumElements();
2243 if (Length == 0) {
2244 // By convention, map it to a RuntimeArray.
David Neto22f144c2017-06-12 14:26:21 -04002245
David Neto862b7d82018-06-14 18:48:37 -04002246 // Only generate the type once.
2247 // TODO(dneto): Can it ever be generated more than once?
2248 // Doesn't LLVM type uniqueness guarantee we'll only see this
2249 // once?
2250 Type *EleTy = ArrTy->getArrayElementType();
2251 if (OpRuntimeTyMap.count(EleTy) == 0) {
2252 uint32_t OpTypeRuntimeArrayID = nextID;
2253 OpRuntimeTyMap[Ty] = nextID;
David Neto22f144c2017-06-12 14:26:21 -04002254
David Neto862b7d82018-06-14 18:48:37 -04002255 //
2256 // Generate OpTypeRuntimeArray.
2257 //
David Neto22f144c2017-06-12 14:26:21 -04002258
David Neto862b7d82018-06-14 18:48:37 -04002259 // OpTypeRuntimeArray
2260 // Ops[0] = Element Type ID
2261 SPIRVOperandList Ops;
2262 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04002263
David Neto862b7d82018-06-14 18:48:37 -04002264 SPIRVInstList.push_back(
2265 new SPIRVInstruction(spv::OpTypeRuntimeArray, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002266
David Neto862b7d82018-06-14 18:48:37 -04002267 if (Hack_generate_runtime_array_stride_early) {
2268 // Generate OpDecorate.
David Neto22f144c2017-06-12 14:26:21 -04002269
David Neto862b7d82018-06-14 18:48:37 -04002270 // Ops[0] = Target ID
2271 // Ops[1] = Decoration (ArrayStride)
2272 // Ops[2] = Stride Number(Literal Number)
2273 Ops.clear();
David Neto85082642018-03-24 06:55:20 -07002274
David Neto862b7d82018-06-14 18:48:37 -04002275 Ops << MkId(OpTypeRuntimeArrayID)
2276 << MkNum(spv::DecorationArrayStride)
Alan Bakerfcda9482018-10-02 17:09:59 -04002277 << MkNum(static_cast<uint32_t>(GetTypeAllocSize(EleTy, DL)));
David Neto22f144c2017-06-12 14:26:21 -04002278
David Neto862b7d82018-06-14 18:48:37 -04002279 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
SJW69939d52020-04-16 07:29:07 -05002280 getSPIRVInstList(kAnnotations).push_back(DecoInst);
David Neto862b7d82018-06-14 18:48:37 -04002281 }
2282 }
David Neto22f144c2017-06-12 14:26:21 -04002283
David Neto862b7d82018-06-14 18:48:37 -04002284 } else {
David Neto22f144c2017-06-12 14:26:21 -04002285
David Neto862b7d82018-06-14 18:48:37 -04002286 //
2287 // Generate OpConstant and OpTypeArray.
2288 //
2289
2290 //
2291 // Generate OpConstant for array length.
2292 //
2293 // Ops[0] = Result Type ID
2294 // Ops[1] .. Ops[n] = Values LiteralNumber
2295 SPIRVOperandList Ops;
2296
2297 Type *LengthTy = Type::getInt32Ty(Context);
2298 uint32_t ResTyID = lookupType(LengthTy);
2299 Ops << MkId(ResTyID);
2300
2301 assert(Length < UINT32_MAX);
2302 Ops << MkNum(static_cast<uint32_t>(Length));
2303
2304 // Add constant for length to constant list.
2305 Constant *CstLength = ConstantInt::get(LengthTy, Length);
2306 AllocatedVMap[CstLength] = nextID;
2307 VMap[CstLength] = nextID;
2308 uint32_t LengthID = nextID;
2309
2310 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
2311 SPIRVInstList.push_back(CstInst);
2312
2313 // Remember to generate ArrayStride later
2314 getTypesNeedingArrayStride().insert(Ty);
2315
2316 //
2317 // Generate OpTypeArray.
2318 //
2319 // Ops[0] = Element Type ID
2320 // Ops[1] = Array Length Constant ID
2321 Ops.clear();
2322
2323 uint32_t EleTyID = lookupType(ArrTy->getElementType());
2324 Ops << MkId(EleTyID) << MkId(LengthID);
2325
2326 // Update TypeMap with nextID.
2327 TypeMap[Ty] = nextID;
2328
2329 auto *ArrayInst = new SPIRVInstruction(spv::OpTypeArray, nextID++, Ops);
2330 SPIRVInstList.push_back(ArrayInst);
2331 }
David Neto22f144c2017-06-12 14:26:21 -04002332 break;
2333 }
2334 case Type::VectorTyID: {
James Pricecf53df42020-04-20 14:41:24 -04002335 auto VecTy = cast<VectorType>(Ty);
2336
alan-bakerb39c8262019-03-08 14:03:37 -05002337 // <4 x i8> is changed to i32 if i8 is not generally supported.
2338 if (!clspv::Option::Int8Support() &&
James Pricecf53df42020-04-20 14:41:24 -04002339 VecTy->getElementType() == Type::getInt8Ty(Context)) {
2340 if (VecTy->getNumElements() == 4) {
2341 TypeMap[Ty] = lookupType(VecTy->getElementType());
David Neto22f144c2017-06-12 14:26:21 -04002342 break;
2343 } else {
2344 Ty->print(errs());
2345 llvm_unreachable("Support above i8 vector type");
2346 }
2347 }
2348
2349 // Ops[0] = Component Type ID
2350 // Ops[1] = Component Count (Literal Number)
David Neto257c3892018-04-11 13:19:45 -04002351 SPIRVOperandList Ops;
James Pricecf53df42020-04-20 14:41:24 -04002352 Ops << MkId(lookupType(VecTy->getElementType()))
2353 << MkNum(VecTy->getNumElements());
David Neto22f144c2017-06-12 14:26:21 -04002354
alan-bakerb6b09dc2018-11-08 16:59:28 -05002355 SPIRVInstruction *inst =
2356 new SPIRVInstruction(spv::OpTypeVector, nextID++, Ops);
David Netoc6f3ab22018-04-06 18:02:31 -04002357 SPIRVInstList.push_back(inst);
David Neto22f144c2017-06-12 14:26:21 -04002358 break;
2359 }
2360 case Type::VoidTyID: {
David Netoef5ba2b2019-12-20 08:35:54 -05002361 auto *Inst = new SPIRVInstruction(spv::OpTypeVoid, nextID++);
David Neto22f144c2017-06-12 14:26:21 -04002362 SPIRVInstList.push_back(Inst);
2363 break;
2364 }
2365 case Type::FunctionTyID: {
2366 // Generate SPIRV instruction for function type.
2367 FunctionType *FTy = cast<FunctionType>(Ty);
2368
2369 // Ops[0] = Return Type ID
2370 // Ops[1] ... Ops[n] = Parameter Type IDs
2371 SPIRVOperandList Ops;
2372
2373 // Find SPIRV instruction for return type
David Netoc6f3ab22018-04-06 18:02:31 -04002374 Ops << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04002375
2376 // Find SPIRV instructions for parameter types
2377 for (unsigned k = 0; k < FTy->getNumParams(); k++) {
2378 // Find SPIRV instruction for parameter type.
2379 auto ParamTy = FTy->getParamType(k);
2380 if (ParamTy->isPointerTy()) {
2381 auto PointeeTy = ParamTy->getPointerElementType();
2382 if (PointeeTy->isStructTy() &&
2383 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
2384 ParamTy = PointeeTy;
2385 }
2386 }
2387
David Netoc6f3ab22018-04-06 18:02:31 -04002388 Ops << MkId(lookupType(ParamTy));
David Neto22f144c2017-06-12 14:26:21 -04002389 }
2390
David Neto87846742018-04-11 17:36:22 -04002391 auto *Inst = new SPIRVInstruction(spv::OpTypeFunction, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002392 SPIRVInstList.push_back(Inst);
2393 break;
2394 }
2395 }
2396 }
2397
2398 // Generate OpTypeSampledImage.
alan-bakerabd82722019-12-03 17:14:51 -05002399 for (auto &ImgTy : getImageTypeList()) {
David Neto22f144c2017-06-12 14:26:21 -04002400 //
2401 // Generate OpTypeSampledImage.
2402 //
2403 // Ops[0] = Image Type ID
2404 //
2405 SPIRVOperandList Ops;
2406
David Netoc6f3ab22018-04-06 18:02:31 -04002407 Ops << MkId(TypeMap[ImgTy]);
David Neto22f144c2017-06-12 14:26:21 -04002408
alan-bakerabd82722019-12-03 17:14:51 -05002409 // Update the image type map.
2410 getImageTypeMap()[ImgTy] = nextID;
David Neto22f144c2017-06-12 14:26:21 -04002411
David Neto87846742018-04-11 17:36:22 -04002412 auto *Inst = new SPIRVInstruction(spv::OpTypeSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002413 SPIRVInstList.push_back(Inst);
2414 }
David Netoc6f3ab22018-04-06 18:02:31 -04002415
2416 // Generate types for pointer-to-local arguments.
alan-bakera1be3322020-04-20 12:48:18 -04002417 for (auto pair : clspv::GetSpecConstants(&module)) {
2418 auto kind = pair.first;
2419 auto spec_id = pair.second;
2420
2421 if (kind != SpecConstant::kLocalMemorySize)
2422 continue;
2423
alan-bakerb6b09dc2018-11-08 16:59:28 -05002424 LocalArgInfo &arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04002425
2426 // Generate the spec constant.
2427 SPIRVOperandList Ops;
2428 Ops << MkId(lookupType(Type::getInt32Ty(Context))) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04002429 SPIRVInstList.push_back(
2430 new SPIRVInstruction(spv::OpSpecConstant, arg_info.array_size_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002431
2432 // Generate the array type.
2433 Ops.clear();
2434 // The element type must have been created.
2435 uint32_t elem_ty_id = lookupType(arg_info.elem_type);
2436 assert(elem_ty_id);
2437 Ops << MkId(elem_ty_id) << MkId(arg_info.array_size_id);
2438
2439 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002440 new SPIRVInstruction(spv::OpTypeArray, arg_info.array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002441
2442 Ops.clear();
2443 Ops << MkNum(spv::StorageClassWorkgroup) << MkId(arg_info.array_type_id);
David Neto87846742018-04-11 17:36:22 -04002444 SPIRVInstList.push_back(new SPIRVInstruction(
2445 spv::OpTypePointer, arg_info.ptr_array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002446 }
David Neto22f144c2017-06-12 14:26:21 -04002447}
2448
2449void SPIRVProducerPass::GenerateSPIRVConstants() {
SJW69939d52020-04-16 07:29:07 -05002450 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kConstants);
David Neto22f144c2017-06-12 14:26:21 -04002451 ValueMapType &VMap = getValueMap();
2452 ValueMapType &AllocatedVMap = getAllocatedValueMap();
2453 ValueList &CstList = getConstantList();
David Neto482550a2018-03-24 05:21:07 -07002454 const bool hack_undef = clspv::Option::HackUndef();
David Neto22f144c2017-06-12 14:26:21 -04002455
2456 for (uint32_t i = 0; i < CstList.size(); i++) {
David Netofb9a7972017-08-25 17:08:24 -04002457 // UniqueVector ids are 1-based.
alan-bakerb6b09dc2018-11-08 16:59:28 -05002458 Constant *Cst = cast<Constant>(CstList[i + 1]);
David Neto22f144c2017-06-12 14:26:21 -04002459
2460 // OpTypeArray's constant was already generated.
David Netofb9a7972017-08-25 17:08:24 -04002461 if (AllocatedVMap.find_as(Cst) != AllocatedVMap.end()) {
David Neto22f144c2017-06-12 14:26:21 -04002462 continue;
2463 }
2464
David Netofb9a7972017-08-25 17:08:24 -04002465 // Set ValueMap with nextID for reference later.
David Neto22f144c2017-06-12 14:26:21 -04002466 VMap[Cst] = nextID;
2467
2468 //
2469 // Generate OpConstant.
2470 //
2471
2472 // Ops[0] = Result Type ID
2473 // Ops[1] .. Ops[n] = Values LiteralNumber
2474 SPIRVOperandList Ops;
2475
David Neto257c3892018-04-11 13:19:45 -04002476 Ops << MkId(lookupType(Cst->getType()));
David Neto22f144c2017-06-12 14:26:21 -04002477
2478 std::vector<uint32_t> LiteralNum;
David Neto22f144c2017-06-12 14:26:21 -04002479 spv::Op Opcode = spv::OpNop;
2480
2481 if (isa<UndefValue>(Cst)) {
2482 // Ops[0] = Result Type ID
David Netoc66b3352017-10-20 14:28:46 -04002483 Opcode = spv::OpUndef;
Alan Baker9bf93fb2018-08-28 16:59:26 -04002484 if (hack_undef && IsTypeNullable(Cst->getType())) {
2485 Opcode = spv::OpConstantNull;
David Netoc66b3352017-10-20 14:28:46 -04002486 }
David Neto22f144c2017-06-12 14:26:21 -04002487 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(Cst)) {
2488 unsigned BitWidth = CI->getBitWidth();
2489 if (BitWidth == 1) {
2490 // If the bitwidth of constant is 1, generate OpConstantTrue or
2491 // OpConstantFalse.
2492 if (CI->getZExtValue()) {
2493 // Ops[0] = Result Type ID
2494 Opcode = spv::OpConstantTrue;
2495 } else {
2496 // Ops[0] = Result Type ID
2497 Opcode = spv::OpConstantFalse;
2498 }
David Neto22f144c2017-06-12 14:26:21 -04002499 } else {
2500 auto V = CI->getZExtValue();
2501 LiteralNum.push_back(V & 0xFFFFFFFF);
2502
2503 if (BitWidth > 32) {
2504 LiteralNum.push_back(V >> 32);
2505 }
2506
2507 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002508
David Neto257c3892018-04-11 13:19:45 -04002509 Ops << MkInteger(LiteralNum);
David Neto22f144c2017-06-12 14:26:21 -04002510 }
2511 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Cst)) {
2512 uint64_t FPVal = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
2513 Type *CFPTy = CFP->getType();
2514 if (CFPTy->isFloatTy()) {
2515 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
Kévin Petit02ee34e2019-04-04 19:03:22 +01002516 } else if (CFPTy->isDoubleTy()) {
2517 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
2518 LiteralNum.push_back(FPVal >> 32);
alan-baker089bf932020-01-07 16:35:45 -05002519 } else if (CFPTy->isHalfTy()) {
2520 LiteralNum.push_back(FPVal & 0xFFFF);
David Neto22f144c2017-06-12 14:26:21 -04002521 } else {
2522 CFPTy->print(errs());
2523 llvm_unreachable("Implement this ConstantFP Type");
2524 }
2525
2526 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002527
David Neto257c3892018-04-11 13:19:45 -04002528 Ops << MkFloat(LiteralNum);
David Neto22f144c2017-06-12 14:26:21 -04002529 } else if (isa<ConstantDataSequential>(Cst) &&
2530 cast<ConstantDataSequential>(Cst)->isString()) {
2531 Cst->print(errs());
2532 llvm_unreachable("Implement this Constant");
2533
2534 } else if (const ConstantDataSequential *CDS =
2535 dyn_cast<ConstantDataSequential>(Cst)) {
David Neto49351ac2017-08-26 17:32:20 -04002536 // Let's convert <4 x i8> constant to int constant specially.
2537 // This case occurs when all the values are specified as constant
2538 // ints.
2539 Type *CstTy = Cst->getType();
2540 if (is4xi8vec(CstTy)) {
2541 LLVMContext &Context = CstTy->getContext();
2542
2543 //
2544 // Generate OpConstant with OpTypeInt 32 0.
2545 //
Neil Henning39672102017-09-29 14:33:13 +01002546 uint32_t IntValue = 0;
2547 for (unsigned k = 0; k < 4; k++) {
2548 const uint64_t Val = CDS->getElementAsInteger(k);
David Neto49351ac2017-08-26 17:32:20 -04002549 IntValue = (IntValue << 8) | (Val & 0xffu);
2550 }
2551
2552 Type *i32 = Type::getInt32Ty(Context);
2553 Constant *CstInt = ConstantInt::get(i32, IntValue);
2554 // If this constant is already registered on VMap, use it.
2555 if (VMap.count(CstInt)) {
2556 uint32_t CstID = VMap[CstInt];
2557 VMap[Cst] = CstID;
2558 continue;
2559 }
2560
David Neto257c3892018-04-11 13:19:45 -04002561 Ops << MkNum(IntValue);
David Neto49351ac2017-08-26 17:32:20 -04002562
David Neto87846742018-04-11 17:36:22 -04002563 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto49351ac2017-08-26 17:32:20 -04002564 SPIRVInstList.push_back(CstInst);
2565
2566 continue;
2567 }
2568
2569 // A normal constant-data-sequential case.
David Neto22f144c2017-06-12 14:26:21 -04002570 for (unsigned k = 0; k < CDS->getNumElements(); k++) {
2571 Constant *EleCst = CDS->getElementAsConstant(k);
2572 uint32_t EleCstID = VMap[EleCst];
David Neto257c3892018-04-11 13:19:45 -04002573 Ops << MkId(EleCstID);
David Neto22f144c2017-06-12 14:26:21 -04002574 }
2575
2576 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002577 } else if (const ConstantAggregate *CA = dyn_cast<ConstantAggregate>(Cst)) {
2578 // Let's convert <4 x i8> constant to int constant specially.
David Neto49351ac2017-08-26 17:32:20 -04002579 // This case occurs when at least one of the values is an undef.
David Neto22f144c2017-06-12 14:26:21 -04002580 Type *CstTy = Cst->getType();
2581 if (is4xi8vec(CstTy)) {
2582 LLVMContext &Context = CstTy->getContext();
2583
2584 //
2585 // Generate OpConstant with OpTypeInt 32 0.
2586 //
Neil Henning39672102017-09-29 14:33:13 +01002587 uint32_t IntValue = 0;
David Neto22f144c2017-06-12 14:26:21 -04002588 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end();
2589 I != E; ++I) {
2590 uint64_t Val = 0;
alan-bakerb6b09dc2018-11-08 16:59:28 -05002591 const Value *CV = *I;
Neil Henning39672102017-09-29 14:33:13 +01002592 if (auto *CI2 = dyn_cast<ConstantInt>(CV)) {
2593 Val = CI2->getZExtValue();
David Neto22f144c2017-06-12 14:26:21 -04002594 }
David Neto49351ac2017-08-26 17:32:20 -04002595 IntValue = (IntValue << 8) | (Val & 0xffu);
David Neto22f144c2017-06-12 14:26:21 -04002596 }
2597
David Neto49351ac2017-08-26 17:32:20 -04002598 Type *i32 = Type::getInt32Ty(Context);
2599 Constant *CstInt = ConstantInt::get(i32, IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002600 // If this constant is already registered on VMap, use it.
2601 if (VMap.count(CstInt)) {
2602 uint32_t CstID = VMap[CstInt];
2603 VMap[Cst] = CstID;
David Neto19a1bad2017-08-25 15:01:41 -04002604 continue;
David Neto22f144c2017-06-12 14:26:21 -04002605 }
2606
David Neto257c3892018-04-11 13:19:45 -04002607 Ops << MkNum(IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002608
David Neto87846742018-04-11 17:36:22 -04002609 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002610 SPIRVInstList.push_back(CstInst);
2611
David Neto19a1bad2017-08-25 15:01:41 -04002612 continue;
David Neto22f144c2017-06-12 14:26:21 -04002613 }
2614
2615 // We use a constant composite in SPIR-V for our constant aggregate in
2616 // LLVM.
2617 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002618
2619 for (unsigned k = 0; k < CA->getNumOperands(); k++) {
2620 // Look up the ID of the element of this aggregate (which we will
2621 // previously have created a constant for).
2622 uint32_t ElementConstantID = VMap[CA->getAggregateElement(k)];
2623
2624 // And add an operand to the composite we are constructing
David Neto257c3892018-04-11 13:19:45 -04002625 Ops << MkId(ElementConstantID);
David Neto22f144c2017-06-12 14:26:21 -04002626 }
2627 } else if (Cst->isNullValue()) {
2628 Opcode = spv::OpConstantNull;
David Neto22f144c2017-06-12 14:26:21 -04002629 } else {
2630 Cst->print(errs());
2631 llvm_unreachable("Unsupported Constant???");
2632 }
2633
alan-baker5b86ed72019-02-15 08:26:50 -05002634 if (Opcode == spv::OpConstantNull && Cst->getType()->isPointerTy()) {
2635 // Null pointer requires variable pointers.
2636 setVariablePointersCapabilities(Cst->getType()->getPointerAddressSpace());
2637 }
2638
David Neto87846742018-04-11 17:36:22 -04002639 auto *CstInst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002640 SPIRVInstList.push_back(CstInst);
2641 }
2642}
2643
2644void SPIRVProducerPass::GenerateSamplers(Module &M) {
SJW69939d52020-04-16 07:29:07 -05002645 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kGlobalVariables);
David Neto22f144c2017-06-12 14:26:21 -04002646
alan-bakerb6b09dc2018-11-08 16:59:28 -05002647 auto &sampler_map = getSamplerMap();
alan-baker09cb9802019-12-10 13:16:27 -05002648 SamplerLiteralToIDMap.clear();
David Neto862b7d82018-06-14 18:48:37 -04002649 DenseMap<unsigned, unsigned> SamplerLiteralToDescriptorSetMap;
2650 DenseMap<unsigned, unsigned> SamplerLiteralToBindingMap;
David Neto22f144c2017-06-12 14:26:21 -04002651
David Neto862b7d82018-06-14 18:48:37 -04002652 // We might have samplers in the sampler map that are not used
2653 // in the translation unit. We need to allocate variables
2654 // for them and bindings too.
2655 DenseSet<unsigned> used_bindings;
David Neto22f144c2017-06-12 14:26:21 -04002656
Kévin Petitdf71de32019-04-09 14:09:50 +01002657 auto *var_fn = M.getFunction(clspv::LiteralSamplerFunction());
alan-baker09cb9802019-12-10 13:16:27 -05002658 // Return if there are no literal samplers.
alan-bakerb6b09dc2018-11-08 16:59:28 -05002659 if (!var_fn)
2660 return;
alan-baker09cb9802019-12-10 13:16:27 -05002661
David Neto862b7d82018-06-14 18:48:37 -04002662 for (auto user : var_fn->users()) {
2663 // Populate SamplerLiteralToDescriptorSetMap and
2664 // SamplerLiteralToBindingMap.
2665 //
2666 // Look for calls like
2667 // call %opencl.sampler_t addrspace(2)*
2668 // @clspv.sampler.var.literal(
2669 // i32 descriptor,
2670 // i32 binding,
alan-baker09cb9802019-12-10 13:16:27 -05002671 // i32 (index-into-sampler-map|sampler_mask))
alan-bakerb6b09dc2018-11-08 16:59:28 -05002672 if (auto *call = dyn_cast<CallInst>(user)) {
alan-baker09cb9802019-12-10 13:16:27 -05002673 const auto third_param = static_cast<unsigned>(
alan-bakerb6b09dc2018-11-08 16:59:28 -05002674 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
alan-baker09cb9802019-12-10 13:16:27 -05002675 auto sampler_value = third_param;
2676 if (clspv::Option::UseSamplerMap()) {
2677 if (third_param >= sampler_map.size()) {
2678 errs() << "Out of bounds index to sampler map: " << third_param;
2679 llvm_unreachable("bad sampler init: out of bounds");
2680 }
2681 sampler_value = sampler_map[third_param].first;
David Neto862b7d82018-06-14 18:48:37 -04002682 }
2683
David Neto862b7d82018-06-14 18:48:37 -04002684 const auto descriptor_set = static_cast<unsigned>(
2685 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
2686 const auto binding = static_cast<unsigned>(
2687 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
2688
2689 SamplerLiteralToDescriptorSetMap[sampler_value] = descriptor_set;
2690 SamplerLiteralToBindingMap[sampler_value] = binding;
2691 used_bindings.insert(binding);
2692 }
2693 }
2694
alan-baker09cb9802019-12-10 13:16:27 -05002695 DenseSet<size_t> seen;
2696 for (auto user : var_fn->users()) {
2697 if (!isa<CallInst>(user))
2698 continue;
2699
2700 auto call = cast<CallInst>(user);
2701 const unsigned third_param = static_cast<unsigned>(
2702 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
2703
2704 // Already allocated a variable for this value.
2705 if (!seen.insert(third_param).second)
2706 continue;
2707
2708 auto sampler_value = third_param;
2709 if (clspv::Option::UseSamplerMap()) {
2710 sampler_value = sampler_map[third_param].first;
2711 }
2712
David Neto22f144c2017-06-12 14:26:21 -04002713 // Generate OpVariable.
2714 //
2715 // GIDOps[0] : Result Type ID
2716 // GIDOps[1] : Storage Class
2717 SPIRVOperandList Ops;
2718
David Neto257c3892018-04-11 13:19:45 -04002719 Ops << MkId(lookupType(SamplerTy))
2720 << MkNum(spv::StorageClassUniformConstant);
David Neto22f144c2017-06-12 14:26:21 -04002721
David Neto862b7d82018-06-14 18:48:37 -04002722 auto sampler_var_id = nextID++;
2723 auto *Inst = new SPIRVInstruction(spv::OpVariable, sampler_var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002724 SPIRVInstList.push_back(Inst);
2725
alan-baker09cb9802019-12-10 13:16:27 -05002726 SamplerLiteralToIDMap[sampler_value] = sampler_var_id;
David Neto22f144c2017-06-12 14:26:21 -04002727
David Neto862b7d82018-06-14 18:48:37 -04002728 unsigned descriptor_set;
2729 unsigned binding;
alan-baker09cb9802019-12-10 13:16:27 -05002730 if (SamplerLiteralToBindingMap.find(sampler_value) ==
alan-bakerb6b09dc2018-11-08 16:59:28 -05002731 SamplerLiteralToBindingMap.end()) {
David Neto862b7d82018-06-14 18:48:37 -04002732 // This sampler is not actually used. Find the next one.
2733 for (binding = 0; used_bindings.count(binding); binding++)
2734 ;
2735 descriptor_set = 0; // Literal samplers always use descriptor set 0.
2736 used_bindings.insert(binding);
2737 } else {
alan-baker09cb9802019-12-10 13:16:27 -05002738 descriptor_set = SamplerLiteralToDescriptorSetMap[sampler_value];
2739 binding = SamplerLiteralToBindingMap[sampler_value];
alan-bakercff80152019-06-15 00:38:00 -04002740
alan-baker09cb9802019-12-10 13:16:27 -05002741 version0::DescriptorMapEntry::SamplerData sampler_data = {sampler_value};
alan-bakercff80152019-06-15 00:38:00 -04002742 descriptorMapEntries->emplace_back(std::move(sampler_data),
2743 descriptor_set, binding);
David Neto862b7d82018-06-14 18:48:37 -04002744 }
2745
SJW69939d52020-04-16 07:29:07 -05002746 // Ops[0] = Target ID
2747 // Ops[1] = Decoration (DescriptorSet)
2748 // Ops[2] = LiteralNumber according to Decoration
2749 Ops.clear();
2750
David Neto862b7d82018-06-14 18:48:37 -04002751 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationDescriptorSet)
2752 << MkNum(descriptor_set);
David Neto22f144c2017-06-12 14:26:21 -04002753
David Neto87846742018-04-11 17:36:22 -04002754 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
SJW69939d52020-04-16 07:29:07 -05002755 getSPIRVInstList(kAnnotations).push_back(DescDecoInst);
David Neto22f144c2017-06-12 14:26:21 -04002756
2757 // Ops[0] = Target ID
2758 // Ops[1] = Decoration (Binding)
2759 // Ops[2] = LiteralNumber according to Decoration
2760 Ops.clear();
David Neto862b7d82018-06-14 18:48:37 -04002761 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationBinding)
2762 << MkNum(binding);
David Neto22f144c2017-06-12 14:26:21 -04002763
David Neto87846742018-04-11 17:36:22 -04002764 auto *BindDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
SJW69939d52020-04-16 07:29:07 -05002765 getSPIRVInstList(kAnnotations).push_back(BindDecoInst);
David Neto22f144c2017-06-12 14:26:21 -04002766 }
David Neto862b7d82018-06-14 18:48:37 -04002767}
David Neto22f144c2017-06-12 14:26:21 -04002768
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01002769void SPIRVProducerPass::GenerateResourceVars(Module &) {
SJW69939d52020-04-16 07:29:07 -05002770 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kGlobalVariables);
David Neto862b7d82018-06-14 18:48:37 -04002771 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04002772
David Neto862b7d82018-06-14 18:48:37 -04002773 // Generate variables. Make one for each of resource var info object.
2774 for (auto *info : ModuleOrderedResourceVars) {
2775 Type *type = info->var_fn->getReturnType();
2776 // Remap the address space for opaque types.
2777 switch (info->arg_kind) {
2778 case clspv::ArgKind::Sampler:
2779 case clspv::ArgKind::ReadOnlyImage:
2780 case clspv::ArgKind::WriteOnlyImage:
2781 type = PointerType::get(type->getPointerElementType(),
2782 clspv::AddressSpace::UniformConstant);
2783 break;
2784 default:
2785 break;
2786 }
David Neto22f144c2017-06-12 14:26:21 -04002787
David Neto862b7d82018-06-14 18:48:37 -04002788 info->var_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04002789
David Neto862b7d82018-06-14 18:48:37 -04002790 const auto type_id = lookupType(type);
2791 const auto sc = GetStorageClassForArgKind(info->arg_kind);
2792 SPIRVOperandList Ops;
2793 Ops << MkId(type_id) << MkNum(sc);
David Neto22f144c2017-06-12 14:26:21 -04002794
David Neto862b7d82018-06-14 18:48:37 -04002795 auto *Inst = new SPIRVInstruction(spv::OpVariable, info->var_id, Ops);
2796 SPIRVInstList.push_back(Inst);
2797
2798 // Map calls to the variable-builtin-function.
2799 for (auto &U : info->var_fn->uses()) {
2800 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
2801 const auto set = unsigned(
2802 dyn_cast<ConstantInt>(call->getOperand(0))->getZExtValue());
2803 const auto binding = unsigned(
2804 dyn_cast<ConstantInt>(call->getOperand(1))->getZExtValue());
2805 if (set == info->descriptor_set && binding == info->binding) {
2806 switch (info->arg_kind) {
2807 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002808 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002809 case clspv::ArgKind::Pod:
alan-baker9b0ec3c2020-04-06 14:45:34 -04002810 case clspv::ArgKind::PodUBO:
2811 case clspv::ArgKind::PodPushConstant:
David Neto862b7d82018-06-14 18:48:37 -04002812 // The call maps to the variable directly.
2813 VMap[call] = info->var_id;
2814 break;
2815 case clspv::ArgKind::Sampler:
2816 case clspv::ArgKind::ReadOnlyImage:
2817 case clspv::ArgKind::WriteOnlyImage:
2818 // The call maps to a load we generate later.
2819 ResourceVarDeferredLoadCalls[call] = info->var_id;
2820 break;
2821 default:
2822 llvm_unreachable("Unhandled arg kind");
2823 }
2824 }
David Neto22f144c2017-06-12 14:26:21 -04002825 }
David Neto862b7d82018-06-14 18:48:37 -04002826 }
2827 }
David Neto22f144c2017-06-12 14:26:21 -04002828
David Neto862b7d82018-06-14 18:48:37 -04002829 // Generate associated decorations.
SJW69939d52020-04-16 07:29:07 -05002830 SPIRVInstructionList &Annotations = getSPIRVInstList(kAnnotations);
David Neto862b7d82018-06-14 18:48:37 -04002831
2832 SPIRVOperandList Ops;
2833 for (auto *info : ModuleOrderedResourceVars) {
alan-baker9b0ec3c2020-04-06 14:45:34 -04002834 // Push constants don't need descriptor set or binding decorations.
2835 if (info->arg_kind == clspv::ArgKind::PodPushConstant)
2836 continue;
2837
David Neto862b7d82018-06-14 18:48:37 -04002838 // Decorate with DescriptorSet and Binding.
2839 Ops.clear();
2840 Ops << MkId(info->var_id) << MkNum(spv::DecorationDescriptorSet)
2841 << MkNum(info->descriptor_set);
SJW69939d52020-04-16 07:29:07 -05002842 Annotations.push_back(new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto862b7d82018-06-14 18:48:37 -04002843
2844 Ops.clear();
2845 Ops << MkId(info->var_id) << MkNum(spv::DecorationBinding)
2846 << MkNum(info->binding);
SJW69939d52020-04-16 07:29:07 -05002847 Annotations.push_back(new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto862b7d82018-06-14 18:48:37 -04002848
alan-bakere9308012019-03-15 10:25:13 -04002849 if (info->coherent) {
2850 // Decorate with Coherent if required for the variable.
2851 Ops.clear();
2852 Ops << MkId(info->var_id) << MkNum(spv::DecorationCoherent);
SJW69939d52020-04-16 07:29:07 -05002853 Annotations.push_back(new SPIRVInstruction(spv::OpDecorate, Ops));
alan-bakere9308012019-03-15 10:25:13 -04002854 }
2855
David Neto862b7d82018-06-14 18:48:37 -04002856 // Generate NonWritable and NonReadable
2857 switch (info->arg_kind) {
2858 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002859 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002860 if (info->var_fn->getReturnType()->getPointerAddressSpace() ==
2861 clspv::AddressSpace::Constant) {
2862 Ops.clear();
2863 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonWritable);
SJW69939d52020-04-16 07:29:07 -05002864 Annotations.push_back(new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002865 }
David Neto862b7d82018-06-14 18:48:37 -04002866 break;
David Neto862b7d82018-06-14 18:48:37 -04002867 case clspv::ArgKind::WriteOnlyImage:
2868 Ops.clear();
2869 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonReadable);
SJW69939d52020-04-16 07:29:07 -05002870 Annotations.push_back(new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto862b7d82018-06-14 18:48:37 -04002871 break;
2872 default:
2873 break;
David Neto22f144c2017-06-12 14:26:21 -04002874 }
2875 }
2876}
2877
Kévin Petitbbbda972020-03-03 19:16:31 +00002878namespace {
2879
2880bool isScalarType(Type *type) {
2881 return type->isIntegerTy() || type->isFloatTy();
2882}
2883
2884uint64_t structAlignment(StructType *type,
2885 std::function<uint64_t(Type *)> alignFn) {
2886 uint64_t maxAlign = 1;
2887 for (unsigned i = 0; i < type->getStructNumElements(); i++) {
2888 uint64_t align = alignFn(type->getStructElementType(i));
2889 maxAlign = std::max(align, maxAlign);
2890 }
2891 return maxAlign;
2892}
2893
2894uint64_t scalarAlignment(Type *type) {
2895 // A scalar of size N has a scalar alignment of N.
2896 if (isScalarType(type)) {
2897 return type->getScalarSizeInBits() / 8;
2898 }
2899
2900 // A vector or matrix type has a scalar alignment equal to that of its
2901 // component type.
James Pricecf53df42020-04-20 14:41:24 -04002902 if (auto vec_type = dyn_cast<VectorType>(type)) {
2903 return scalarAlignment(vec_type->getElementType());
Kévin Petitbbbda972020-03-03 19:16:31 +00002904 }
2905
2906 // An array type has a scalar alignment equal to that of its element type.
2907 if (type->isArrayTy()) {
2908 return scalarAlignment(type->getArrayElementType());
2909 }
2910
2911 // A structure has a scalar alignment equal to the largest scalar alignment of
2912 // any of its members.
2913 if (type->isStructTy()) {
2914 return structAlignment(cast<StructType>(type), scalarAlignment);
2915 }
2916
2917 llvm_unreachable("Unsupported type");
2918}
2919
2920uint64_t baseAlignment(Type *type) {
2921 // A scalar has a base alignment equal to its scalar alignment.
2922 if (isScalarType(type)) {
2923 return scalarAlignment(type);
2924 }
2925
James Pricecf53df42020-04-20 14:41:24 -04002926 if (auto vec_type = dyn_cast<VectorType>(type)) {
2927 unsigned numElems = vec_type->getNumElements();
Kévin Petitbbbda972020-03-03 19:16:31 +00002928
2929 // A two-component vector has a base alignment equal to twice its scalar
2930 // alignment.
2931 if (numElems == 2) {
2932 return 2 * scalarAlignment(type);
2933 }
2934 // A three- or four-component vector has a base alignment equal to four
2935 // times its scalar alignment.
2936 if ((numElems == 3) || (numElems == 4)) {
2937 return 4 * scalarAlignment(type);
2938 }
2939 }
2940
2941 // An array has a base alignment equal to the base alignment of its element
2942 // type.
2943 if (type->isArrayTy()) {
2944 return baseAlignment(type->getArrayElementType());
2945 }
2946
2947 // A structure has a base alignment equal to the largest base alignment of any
2948 // of its members.
2949 if (type->isStructTy()) {
2950 return structAlignment(cast<StructType>(type), baseAlignment);
2951 }
2952
2953 // TODO A row-major matrix of C columns has a base alignment equal to the base
2954 // alignment of a vector of C matrix components.
2955 // TODO A column-major matrix has a base alignment equal to the base alignment
2956 // of the matrix column type.
2957
2958 llvm_unreachable("Unsupported type");
2959}
2960
2961uint64_t extendedAlignment(Type *type) {
2962 // A scalar, vector or matrix type has an extended alignment equal to its base
2963 // alignment.
2964 // TODO matrix type
2965 if (isScalarType(type) || type->isVectorTy()) {
2966 return baseAlignment(type);
2967 }
2968
2969 // An array or structure type has an extended alignment equal to the largest
2970 // extended alignment of any of its members, rounded up to a multiple of 16
2971 if (type->isStructTy()) {
2972 auto salign = structAlignment(cast<StructType>(type), extendedAlignment);
2973 return alignTo(salign, 16);
2974 }
2975
2976 if (type->isArrayTy()) {
2977 auto salign = extendedAlignment(type->getArrayElementType());
2978 return alignTo(salign, 16);
2979 }
2980
2981 llvm_unreachable("Unsupported type");
2982}
2983
2984uint64_t standardAlignment(Type *type, spv::StorageClass sclass) {
2985 // If the scalarBlockLayout feature is enabled on the device then every member
2986 // must be aligned according to its scalar alignment
2987 if (clspv::Option::ScalarBlockLayout()) {
2988 return scalarAlignment(type);
2989 }
2990
2991 // All vectors must be aligned according to their scalar alignment
2992 if (type->isVectorTy()) {
2993 return scalarAlignment(type);
2994 }
2995
2996 // If the uniformBufferStandardLayout feature is not enabled on the device,
2997 // then any member of an OpTypeStruct with a storage class of Uniform and a
2998 // decoration of Block must be aligned according to its extended alignment.
2999 if (!clspv::Option::Std430UniformBufferLayout() &&
3000 sclass == spv::StorageClassUniform) {
3001 return extendedAlignment(type);
3002 }
3003
3004 // Every other member must be aligned according to its base alignment
3005 return baseAlignment(type);
3006}
3007
3008bool improperlyStraddles(const DataLayout &DL, Type *type, unsigned offset) {
3009 assert(type->isVectorTy());
3010
3011 auto size = DL.getTypeStoreSize(type);
3012
3013 // It is a vector with total size less than or equal to 16 bytes, and has
3014 // Offset decorations placing its first byte at F and its last byte at L,
3015 // where floor(F / 16) != floor(L / 16).
3016 if ((size <= 16) && (offset % 16 + size > 16)) {
3017 return true;
3018 }
3019
3020 // It is a vector with total size greater than 16 bytes and has its Offset
3021 // decorations placing its first byte at a non-integer multiple of 16
3022 if ((size > 16) && (offset % 16 != 0)) {
3023 return true;
3024 }
3025
3026 return false;
3027}
3028
3029// See 14.5 Shader Resource Interface in Vulkan spec
3030bool isValidExplicitLayout(Module &M, StructType *STy, unsigned Member,
3031 spv::StorageClass SClass, unsigned Offset,
3032 unsigned PreviousMemberOffset) {
3033
3034 auto MemberType = STy->getElementType(Member);
3035 auto Align = standardAlignment(MemberType, SClass);
3036 auto &DL = M.getDataLayout();
3037
3038 // The Offset decoration of any member must be a multiple of its alignment
3039 if (Offset % Align != 0) {
3040 return false;
3041 }
3042
3043 // TODO Any ArrayStride or MatrixStride decoration must be a multiple of the
3044 // alignment of the array or matrix as defined above
3045
3046 if (!clspv::Option::ScalarBlockLayout()) {
3047 // Vectors must not improperly straddle, as defined above
3048 if (MemberType->isVectorTy() &&
3049 improperlyStraddles(DL, MemberType, Offset)) {
3050 return true;
3051 }
3052
3053 // The Offset decoration of a member must not place it between the end
3054 // of a structure or an array and the next multiple of the alignment of that
3055 // structure or array
3056 if (Member > 0) {
3057 auto PType = STy->getElementType(Member - 1);
3058 if (PType->isStructTy() || PType->isArrayTy()) {
3059 auto PAlign = standardAlignment(PType, SClass);
3060 if (Offset - PreviousMemberOffset < PAlign) {
3061 return false;
3062 }
3063 }
3064 }
3065 }
3066
3067 return true;
3068}
3069
3070} // namespace
3071
alan-bakera1be3322020-04-20 12:48:18 -04003072void SPIRVProducerPass::GeneratePushConstantDescriptorMapEntries(Module &M) {
Kévin Petitbbbda972020-03-03 19:16:31 +00003073
3074 if (auto GV = M.getGlobalVariable(clspv::PushConstantsVariableName())) {
3075 auto const &DL = M.getDataLayout();
3076 auto MD = GV->getMetadata(clspv::PushConstantsMetadataName());
3077 auto STy = cast<StructType>(GV->getValueType());
3078
3079 for (unsigned i = 0; i < STy->getNumElements(); i++) {
3080 auto pc = static_cast<clspv::PushConstant>(
3081 mdconst::extract<ConstantInt>(MD->getOperand(i))->getZExtValue());
3082 auto memberType = STy->getElementType(i);
3083 auto offset = GetExplicitLayoutStructMemberOffset(STy, i, DL);
3084 unsigned previousOffset = 0;
3085 if (i > 0) {
3086 previousOffset = GetExplicitLayoutStructMemberOffset(STy, i - 1, DL);
3087 }
3088 auto size = static_cast<uint32_t>(GetTypeSizeInBits(memberType, DL)) / 8;
3089 assert(isValidExplicitLayout(M, STy, i, spv::StorageClassPushConstant,
3090 offset, previousOffset));
3091 version0::DescriptorMapEntry::PushConstantData data = {pc, offset, size};
3092 descriptorMapEntries->emplace_back(std::move(data));
3093 }
3094 }
3095}
3096
alan-bakera1be3322020-04-20 12:48:18 -04003097void SPIRVProducerPass::GenerateSpecConstantDescriptorMapEntries(Module &M) {
3098 for (auto pair : clspv::GetSpecConstants(&M)) {
3099 auto kind = pair.first;
3100 auto id = pair.second;
3101
3102 // Local memory size is only used for kernel arguments.
3103 if (kind == SpecConstant::kLocalMemorySize)
3104 continue;
3105
3106 version0::DescriptorMapEntry::SpecConstantData data = {kind, id};
3107 descriptorMapEntries->emplace_back(std::move(data));
3108 }
3109}
3110
David Neto22f144c2017-06-12 14:26:21 -04003111void SPIRVProducerPass::GenerateGlobalVar(GlobalVariable &GV) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05003112 Module &M = *GV.getParent();
SJW69939d52020-04-16 07:29:07 -05003113 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kGlobalVariables);
David Neto22f144c2017-06-12 14:26:21 -04003114 ValueMapType &VMap = getValueMap();
3115 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
David Neto85082642018-03-24 06:55:20 -07003116 const DataLayout &DL = GV.getParent()->getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04003117
3118 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
3119 Type *Ty = GV.getType();
3120 PointerType *PTy = cast<PointerType>(Ty);
3121
3122 uint32_t InitializerID = 0;
3123
3124 // Workgroup size is handled differently (it goes into a constant)
3125 if (spv::BuiltInWorkgroupSize == BuiltinType) {
3126 std::vector<bool> HasMDVec;
3127 uint32_t PrevXDimCst = 0xFFFFFFFF;
3128 uint32_t PrevYDimCst = 0xFFFFFFFF;
3129 uint32_t PrevZDimCst = 0xFFFFFFFF;
3130 for (Function &Func : *GV.getParent()) {
3131 if (Func.isDeclaration()) {
3132 continue;
3133 }
3134
3135 // We only need to check kernels.
3136 if (Func.getCallingConv() != CallingConv::SPIR_KERNEL) {
3137 continue;
3138 }
3139
3140 if (const MDNode *MD =
3141 dyn_cast<Function>(&Func)->getMetadata("reqd_work_group_size")) {
3142 uint32_t CurXDimCst = static_cast<uint32_t>(
3143 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
3144 uint32_t CurYDimCst = static_cast<uint32_t>(
3145 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
3146 uint32_t CurZDimCst = static_cast<uint32_t>(
3147 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
3148
3149 if (PrevXDimCst == 0xFFFFFFFF && PrevYDimCst == 0xFFFFFFFF &&
3150 PrevZDimCst == 0xFFFFFFFF) {
3151 PrevXDimCst = CurXDimCst;
3152 PrevYDimCst = CurYDimCst;
3153 PrevZDimCst = CurZDimCst;
3154 } else if (CurXDimCst != PrevXDimCst || CurYDimCst != PrevYDimCst ||
3155 CurZDimCst != PrevZDimCst) {
3156 llvm_unreachable(
3157 "reqd_work_group_size must be the same across all kernels");
3158 } else {
3159 continue;
3160 }
3161
3162 //
3163 // Generate OpConstantComposite.
3164 //
3165 // Ops[0] : Result Type ID
3166 // Ops[1] : Constant size for x dimension.
3167 // Ops[2] : Constant size for y dimension.
3168 // Ops[3] : Constant size for z dimension.
3169 SPIRVOperandList Ops;
3170
3171 uint32_t XDimCstID =
3172 VMap[mdconst::extract<ConstantInt>(MD->getOperand(0))];
3173 uint32_t YDimCstID =
3174 VMap[mdconst::extract<ConstantInt>(MD->getOperand(1))];
3175 uint32_t ZDimCstID =
3176 VMap[mdconst::extract<ConstantInt>(MD->getOperand(2))];
3177
3178 InitializerID = nextID;
3179
David Neto257c3892018-04-11 13:19:45 -04003180 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
3181 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04003182
David Neto87846742018-04-11 17:36:22 -04003183 auto *Inst =
3184 new SPIRVInstruction(spv::OpConstantComposite, nextID++, Ops);
alan-bakera1be3322020-04-20 12:48:18 -04003185 getSPIRVInstList(kConstants).push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04003186
3187 HasMDVec.push_back(true);
3188 } else {
3189 HasMDVec.push_back(false);
3190 }
3191 }
3192
3193 // Check all kernels have same definitions for work_group_size.
3194 bool HasMD = false;
3195 if (!HasMDVec.empty()) {
3196 HasMD = HasMDVec[0];
3197 for (uint32_t i = 1; i < HasMDVec.size(); i++) {
3198 if (HasMD != HasMDVec[i]) {
3199 llvm_unreachable(
3200 "Kernels should have consistent work group size definition");
3201 }
3202 }
3203 }
3204
3205 // If all kernels do not have metadata for reqd_work_group_size, generate
3206 // OpSpecConstants for x/y/z dimension.
3207 if (!HasMD) {
3208 //
3209 // Generate OpSpecConstants for x/y/z dimension.
3210 //
3211 // Ops[0] : Result Type ID
3212 // Ops[1] : Constant size for x/y/z dimension (Literal Number).
3213 uint32_t XDimCstID = 0;
3214 uint32_t YDimCstID = 0;
3215 uint32_t ZDimCstID = 0;
3216
alan-bakera1be3322020-04-20 12:48:18 -04003217 // Allocate spec constants for workgroup size.
3218 clspv::AddWorkgroupSpecConstants(&M);
3219
David Neto22f144c2017-06-12 14:26:21 -04003220 SPIRVOperandList Ops;
James Pricecf53df42020-04-20 14:41:24 -04003221 uint32_t result_type_id = lookupType(
3222 cast<VectorType>(Ty->getPointerElementType())->getElementType());
David Neto22f144c2017-06-12 14:26:21 -04003223
David Neto257c3892018-04-11 13:19:45 -04003224 // X Dimension
3225 Ops << MkId(result_type_id) << MkNum(1);
3226 XDimCstID = nextID++;
alan-bakera1be3322020-04-20 12:48:18 -04003227 getSPIRVInstList(kConstants)
3228 .push_back(new SPIRVInstruction(spv::OpSpecConstant, XDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003229
3230 // Y Dimension
3231 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003232 Ops << MkId(result_type_id) << MkNum(1);
3233 YDimCstID = nextID++;
alan-bakera1be3322020-04-20 12:48:18 -04003234 getSPIRVInstList(kConstants)
3235 .push_back(new SPIRVInstruction(spv::OpSpecConstant, YDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003236
3237 // Z Dimension
3238 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003239 Ops << MkId(result_type_id) << MkNum(1);
3240 ZDimCstID = nextID++;
alan-bakera1be3322020-04-20 12:48:18 -04003241 getSPIRVInstList(kConstants)
3242 .push_back(new SPIRVInstruction(spv::OpSpecConstant, ZDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003243
David Neto257c3892018-04-11 13:19:45 -04003244 BuiltinDimVec.push_back(XDimCstID);
3245 BuiltinDimVec.push_back(YDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04003246 BuiltinDimVec.push_back(ZDimCstID);
3247
David Neto22f144c2017-06-12 14:26:21 -04003248 //
3249 // Generate OpSpecConstantComposite.
3250 //
3251 // Ops[0] : Result Type ID
3252 // Ops[1] : Constant size for x dimension.
3253 // Ops[2] : Constant size for y dimension.
3254 // Ops[3] : Constant size for z dimension.
3255 InitializerID = nextID;
3256
3257 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003258 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
3259 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04003260
David Neto87846742018-04-11 17:36:22 -04003261 auto *Inst =
3262 new SPIRVInstruction(spv::OpSpecConstantComposite, nextID++, Ops);
alan-bakera1be3322020-04-20 12:48:18 -04003263 getSPIRVInstList(kConstants).push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04003264 }
3265 }
3266
David Neto22f144c2017-06-12 14:26:21 -04003267 VMap[&GV] = nextID;
3268
3269 //
3270 // Generate OpVariable.
3271 //
3272 // GIDOps[0] : Result Type ID
3273 // GIDOps[1] : Storage Class
3274 SPIRVOperandList Ops;
3275
David Neto85082642018-03-24 06:55:20 -07003276 const auto AS = PTy->getAddressSpace();
David Netoc6f3ab22018-04-06 18:02:31 -04003277 Ops << MkId(lookupType(Ty)) << MkNum(GetStorageClass(AS));
David Neto22f144c2017-06-12 14:26:21 -04003278
David Neto85082642018-03-24 06:55:20 -07003279 const bool module_scope_constant_external_init =
David Neto862b7d82018-06-14 18:48:37 -04003280 (AS == AddressSpace::Constant) && GV.hasInitializer() &&
David Neto85082642018-03-24 06:55:20 -07003281 clspv::Option::ModuleConstantsInStorageBuffer();
3282
Kévin Petit23d5f182019-08-13 16:21:29 +01003283 if (GV.hasInitializer()) {
3284 auto GVInit = GV.getInitializer();
3285 if (!isa<UndefValue>(GVInit) && !module_scope_constant_external_init) {
3286 assert(VMap.count(GVInit) == 1);
3287 InitializerID = VMap[GVInit];
David Neto85082642018-03-24 06:55:20 -07003288 }
3289 }
Kévin Petit23d5f182019-08-13 16:21:29 +01003290
3291 if (0 != InitializerID) {
Kévin Petitbbbda972020-03-03 19:16:31 +00003292 // Emit the ID of the initializer as part of the variable definition.
Kévin Petit23d5f182019-08-13 16:21:29 +01003293 Ops << MkId(InitializerID);
3294 }
David Neto85082642018-03-24 06:55:20 -07003295 const uint32_t var_id = nextID++;
3296
David Neto87846742018-04-11 17:36:22 -04003297 auto *Inst = new SPIRVInstruction(spv::OpVariable, var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003298 SPIRVInstList.push_back(Inst);
3299
SJW69939d52020-04-16 07:29:07 -05003300 SPIRVInstructionList &Annotations = getSPIRVInstList(kAnnotations);
David Neto22f144c2017-06-12 14:26:21 -04003301 // If we have a builtin.
3302 if (spv::BuiltInMax != BuiltinType) {
David Neto22f144c2017-06-12 14:26:21 -04003303 //
3304 // Generate OpDecorate.
3305 //
3306 // DOps[0] = Target ID
3307 // DOps[1] = Decoration (Builtin)
3308 // DOps[2] = BuiltIn ID
3309 uint32_t ResultID;
3310
3311 // WorkgroupSize is different, we decorate the constant composite that has
3312 // its value, rather than the variable that we use to access the value.
3313 if (spv::BuiltInWorkgroupSize == BuiltinType) {
3314 ResultID = InitializerID;
David Netoa60b00b2017-09-15 16:34:09 -04003315 // Save both the value and variable IDs for later.
3316 WorkgroupSizeValueID = InitializerID;
3317 WorkgroupSizeVarID = VMap[&GV];
David Neto22f144c2017-06-12 14:26:21 -04003318 } else {
3319 ResultID = VMap[&GV];
3320 }
3321
3322 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04003323 DOps << MkId(ResultID) << MkNum(spv::DecorationBuiltIn)
3324 << MkNum(BuiltinType);
David Neto22f144c2017-06-12 14:26:21 -04003325
David Neto87846742018-04-11 17:36:22 -04003326 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, DOps);
SJW69939d52020-04-16 07:29:07 -05003327 Annotations.push_back(DescDecoInst);
David Neto85082642018-03-24 06:55:20 -07003328 } else if (module_scope_constant_external_init) {
3329 // This module scope constant is initialized from a storage buffer with data
3330 // provided by the host at binding 0 of the next descriptor set.
David Neto78383442018-06-15 20:31:56 -04003331 const uint32_t descriptor_set = TakeDescriptorIndex(&M);
David Neto85082642018-03-24 06:55:20 -07003332
David Neto862b7d82018-06-14 18:48:37 -04003333 // Emit the intializer to the descriptor map file.
David Neto85082642018-03-24 06:55:20 -07003334 // Use "kind,buffer" to indicate storage buffer. We might want to expand
3335 // that later to other types, like uniform buffer.
alan-bakerf5e5f692018-11-27 08:33:24 -05003336 std::string hexbytes;
3337 llvm::raw_string_ostream str(hexbytes);
3338 clspv::ConstantEmitter(DL, str).Emit(GV.getInitializer());
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003339 version0::DescriptorMapEntry::ConstantData constant_data = {ArgKind::Buffer,
3340 str.str()};
3341 descriptorMapEntries->emplace_back(std::move(constant_data), descriptor_set,
3342 0);
David Neto85082642018-03-24 06:55:20 -07003343
David Neto85082642018-03-24 06:55:20 -07003344 SPIRVOperandList DOps;
David Neto85082642018-03-24 06:55:20 -07003345
3346 // OpDecorate %var DescriptorSet <descriptor_set>
David Neto257c3892018-04-11 13:19:45 -04003347 DOps << MkId(var_id) << MkNum(spv::DecorationDescriptorSet)
3348 << MkNum(descriptor_set);
SJW69939d52020-04-16 07:29:07 -05003349 Annotations.push_back(new SPIRVInstruction(spv::OpDecorate, DOps));
3350
3351 // OpDecorate %var Binding <binding>
3352 DOps.clear();
3353 DOps << MkId(var_id) << MkNum(spv::DecorationBinding) << MkNum(0);
3354 Annotations.push_back(new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto22f144c2017-06-12 14:26:21 -04003355 }
3356}
3357
alan-bakera1be3322020-04-20 12:48:18 -04003358void SPIRVProducerPass::GenerateWorkgroupVars(Module &M) {
SJW69939d52020-04-16 07:29:07 -05003359 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kGlobalVariables);
alan-bakera1be3322020-04-20 12:48:18 -04003360 auto spec_constant_md = M.getNamedMetadata(clspv::SpecConstantMetadataName());
3361 if (!spec_constant_md)
3362 return;
3363
3364 for (auto pair : clspv::GetSpecConstants(&M)) {
3365 auto kind = pair.first;
3366 auto spec_id = pair.second;
3367
3368 if (kind != SpecConstant::kLocalMemorySize)
3369 continue;
3370
alan-bakerb6b09dc2018-11-08 16:59:28 -05003371 LocalArgInfo &info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04003372
3373 // Generate OpVariable.
3374 //
3375 // GIDOps[0] : Result Type ID
3376 // GIDOps[1] : Storage Class
3377 SPIRVOperandList Ops;
3378 Ops << MkId(info.ptr_array_type_id) << MkNum(spv::StorageClassWorkgroup);
3379
3380 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04003381 new SPIRVInstruction(spv::OpVariable, info.variable_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04003382 }
3383}
3384
David Neto862b7d82018-06-14 18:48:37 -04003385void SPIRVProducerPass::GenerateDescriptorMapInfo(const DataLayout &DL,
3386 Function &F) {
David Netoc5fb5242018-07-30 13:28:31 -04003387 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
3388 return;
3389 }
Kévin Petit717f8572020-04-06 17:31:53 +01003390 // Add entries for each kernel
3391 version0::DescriptorMapEntry::KernelDeclData kernel_decl_data = {
3392 F.getName().str()};
3393 descriptorMapEntries->emplace_back(std::move(kernel_decl_data));
3394
David Neto862b7d82018-06-14 18:48:37 -04003395 // Gather the list of resources that are used by this function's arguments.
3396 auto &resource_var_at_index = FunctionToResourceVarsMap[&F];
3397
alan-bakerf5e5f692018-11-27 08:33:24 -05003398 // TODO(alan-baker): This should become unnecessary by fixing the rest of the
3399 // flow to generate pod_ubo arguments earlier.
David Neto862b7d82018-06-14 18:48:37 -04003400 auto remap_arg_kind = [](StringRef argKind) {
alan-bakerf5e5f692018-11-27 08:33:24 -05003401 std::string kind =
3402 clspv::Option::PodArgsInUniformBuffer() && argKind.equals("pod")
3403 ? "pod_ubo"
alan-baker21574d32020-01-29 16:00:31 -05003404 : argKind.str();
alan-bakerf5e5f692018-11-27 08:33:24 -05003405 return GetArgKindFromName(kind);
David Neto862b7d82018-06-14 18:48:37 -04003406 };
3407
3408 auto *fty = F.getType()->getPointerElementType();
3409 auto *func_ty = dyn_cast<FunctionType>(fty);
3410
alan-baker038e9242019-04-19 22:14:41 -04003411 // If we've clustered POD arguments, then argument details are in metadata.
David Neto862b7d82018-06-14 18:48:37 -04003412 // If an argument maps to a resource variable, then get descriptor set and
3413 // binding from the resoure variable. Other info comes from the metadata.
3414 const auto *arg_map = F.getMetadata("kernel_arg_map");
3415 if (arg_map) {
3416 for (const auto &arg : arg_map->operands()) {
3417 const MDNode *arg_node = dyn_cast<MDNode>(arg.get());
Kévin PETITa353c832018-03-20 23:21:21 +00003418 assert(arg_node->getNumOperands() == 7);
David Neto862b7d82018-06-14 18:48:37 -04003419 const auto name =
3420 dyn_cast<MDString>(arg_node->getOperand(0))->getString();
3421 const auto old_index =
3422 dyn_extract<ConstantInt>(arg_node->getOperand(1))->getZExtValue();
3423 // Remapped argument index
alan-bakerb6b09dc2018-11-08 16:59:28 -05003424 const size_t new_index = static_cast<size_t>(
3425 dyn_extract<ConstantInt>(arg_node->getOperand(2))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04003426 const auto offset =
3427 dyn_extract<ConstantInt>(arg_node->getOperand(3))->getZExtValue();
Kévin PETITa353c832018-03-20 23:21:21 +00003428 const auto arg_size =
3429 dyn_extract<ConstantInt>(arg_node->getOperand(4))->getZExtValue();
David Neto862b7d82018-06-14 18:48:37 -04003430 const auto argKind = remap_arg_kind(
Kévin PETITa353c832018-03-20 23:21:21 +00003431 dyn_cast<MDString>(arg_node->getOperand(5))->getString());
David Neto862b7d82018-06-14 18:48:37 -04003432 const auto spec_id =
Kévin PETITa353c832018-03-20 23:21:21 +00003433 dyn_extract<ConstantInt>(arg_node->getOperand(6))->getSExtValue();
alan-bakerf5e5f692018-11-27 08:33:24 -05003434
3435 uint32_t descriptor_set = 0;
3436 uint32_t binding = 0;
3437 version0::DescriptorMapEntry::KernelArgData kernel_data = {
alan-baker21574d32020-01-29 16:00:31 -05003438 F.getName().str(), name.str(), static_cast<uint32_t>(old_index),
3439 argKind, static_cast<uint32_t>(spec_id),
alan-bakerf5e5f692018-11-27 08:33:24 -05003440 // This will be set below for pointer-to-local args.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003441 0, static_cast<uint32_t>(offset), static_cast<uint32_t>(arg_size)};
David Neto862b7d82018-06-14 18:48:37 -04003442 if (spec_id > 0) {
alan-bakerf5e5f692018-11-27 08:33:24 -05003443 kernel_data.local_element_size = static_cast<uint32_t>(GetTypeAllocSize(
3444 func_ty->getParamType(unsigned(new_index))->getPointerElementType(),
3445 DL));
David Neto862b7d82018-06-14 18:48:37 -04003446 } else {
3447 auto *info = resource_var_at_index[new_index];
3448 assert(info);
alan-bakerf5e5f692018-11-27 08:33:24 -05003449 descriptor_set = info->descriptor_set;
3450 binding = info->binding;
David Neto862b7d82018-06-14 18:48:37 -04003451 }
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003452 descriptorMapEntries->emplace_back(std::move(kernel_data), descriptor_set,
3453 binding);
David Neto862b7d82018-06-14 18:48:37 -04003454 }
3455 } else {
3456 // There is no argument map.
3457 // Take descriptor info from the resource variable calls.
Kévin PETITa353c832018-03-20 23:21:21 +00003458 // Take argument name and size from the arguments list.
David Neto862b7d82018-06-14 18:48:37 -04003459
3460 SmallVector<Argument *, 4> arguments;
3461 for (auto &arg : F.args()) {
3462 arguments.push_back(&arg);
3463 }
3464
3465 unsigned arg_index = 0;
3466 for (auto *info : resource_var_at_index) {
3467 if (info) {
Kévin PETITa353c832018-03-20 23:21:21 +00003468 auto arg = arguments[arg_index];
alan-bakerb6b09dc2018-11-08 16:59:28 -05003469 unsigned arg_size = 0;
alan-baker9b0ec3c2020-04-06 14:45:34 -04003470 if (info->arg_kind == clspv::ArgKind::Pod ||
3471 info->arg_kind == clspv::ArgKind::PodUBO ||
3472 info->arg_kind == clspv::ArgKind::PodPushConstant) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05003473 arg_size = static_cast<uint32_t>(DL.getTypeStoreSize(arg->getType()));
Kévin PETITa353c832018-03-20 23:21:21 +00003474 }
3475
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003476 // Local pointer arguments are unused in this case. Offset is always
3477 // zero.
alan-bakerf5e5f692018-11-27 08:33:24 -05003478 version0::DescriptorMapEntry::KernelArgData kernel_data = {
alan-baker21574d32020-01-29 16:00:31 -05003479 F.getName().str(),
3480 arg->getName().str(),
3481 arg_index,
3482 remap_arg_kind(clspv::GetArgKindName(info->arg_kind)),
3483 0,
3484 0,
3485 0,
3486 arg_size};
alan-bakerf5e5f692018-11-27 08:33:24 -05003487 descriptorMapEntries->emplace_back(std::move(kernel_data),
3488 info->descriptor_set, info->binding);
David Neto862b7d82018-06-14 18:48:37 -04003489 }
3490 arg_index++;
3491 }
3492 // Generate mappings for pointer-to-local arguments.
3493 for (arg_index = 0; arg_index < arguments.size(); ++arg_index) {
3494 Argument *arg = arguments[arg_index];
Alan Baker202c8c72018-08-13 13:47:44 -04003495 auto where = LocalArgSpecIds.find(arg);
3496 if (where != LocalArgSpecIds.end()) {
3497 auto &local_arg_info = LocalSpecIdInfoMap[where->second];
alan-bakerf5e5f692018-11-27 08:33:24 -05003498 // Pod arguments members are unused in this case.
3499 version0::DescriptorMapEntry::KernelArgData kernel_data = {
alan-baker21574d32020-01-29 16:00:31 -05003500 F.getName().str(),
3501 arg->getName().str(),
alan-bakerf5e5f692018-11-27 08:33:24 -05003502 arg_index,
3503 ArgKind::Local,
3504 static_cast<uint32_t>(local_arg_info.spec_id),
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003505 static_cast<uint32_t>(
3506 GetTypeAllocSize(local_arg_info.elem_type, DL)),
alan-bakerf5e5f692018-11-27 08:33:24 -05003507 0,
3508 0};
3509 // Pointer-to-local arguments do not utilize descriptor set and binding.
3510 descriptorMapEntries->emplace_back(std::move(kernel_data), 0, 0);
David Neto862b7d82018-06-14 18:48:37 -04003511 }
3512 }
3513 }
3514}
3515
David Neto22f144c2017-06-12 14:26:21 -04003516void SPIRVProducerPass::GenerateFuncPrologue(Function &F) {
SJW69939d52020-04-16 07:29:07 -05003517 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kFunctions);
David Neto22f144c2017-06-12 14:26:21 -04003518 ValueMapType &VMap = getValueMap();
3519 EntryPointVecType &EntryPoints = getEntryPointVec();
David Neto22f144c2017-06-12 14:26:21 -04003520 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
3521 auto &GlobalConstArgSet = getGlobalConstArgSet();
3522
3523 FunctionType *FTy = F.getFunctionType();
3524
3525 //
David Neto22f144c2017-06-12 14:26:21 -04003526 // Generate OPFunction.
3527 //
3528
3529 // FOps[0] : Result Type ID
3530 // FOps[1] : Function Control
3531 // FOps[2] : Function Type ID
3532 SPIRVOperandList FOps;
3533
3534 // Find SPIRV instruction for return type.
David Neto257c3892018-04-11 13:19:45 -04003535 FOps << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04003536
3537 // Check function attributes for SPIRV Function Control.
3538 uint32_t FuncControl = spv::FunctionControlMaskNone;
3539 if (F.hasFnAttribute(Attribute::AlwaysInline)) {
3540 FuncControl |= spv::FunctionControlInlineMask;
3541 }
3542 if (F.hasFnAttribute(Attribute::NoInline)) {
3543 FuncControl |= spv::FunctionControlDontInlineMask;
3544 }
3545 // TODO: Check llvm attribute for Function Control Pure.
3546 if (F.hasFnAttribute(Attribute::ReadOnly)) {
3547 FuncControl |= spv::FunctionControlPureMask;
3548 }
3549 // TODO: Check llvm attribute for Function Control Const.
3550 if (F.hasFnAttribute(Attribute::ReadNone)) {
3551 FuncControl |= spv::FunctionControlConstMask;
3552 }
3553
David Neto257c3892018-04-11 13:19:45 -04003554 FOps << MkNum(FuncControl);
David Neto22f144c2017-06-12 14:26:21 -04003555
3556 uint32_t FTyID;
3557 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3558 SmallVector<Type *, 4> NewFuncParamTys;
3559 FunctionType *NewFTy =
3560 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
3561 FTyID = lookupType(NewFTy);
3562 } else {
David Neto9ed8e2f2018-03-24 06:47:24 -07003563 // Handle regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04003564 if (GlobalConstFuncTyMap.count(FTy)) {
3565 FTyID = lookupType(GlobalConstFuncTyMap[FTy].first);
3566 } else {
3567 FTyID = lookupType(FTy);
3568 }
3569 }
3570
David Neto257c3892018-04-11 13:19:45 -04003571 FOps << MkId(FTyID);
David Neto22f144c2017-06-12 14:26:21 -04003572
3573 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3574 EntryPoints.push_back(std::make_pair(&F, nextID));
3575 }
3576
3577 VMap[&F] = nextID;
3578
David Neto482550a2018-03-24 05:21:07 -07003579 if (clspv::Option::ShowIDs()) {
David Netob05675d2018-02-16 12:37:49 -05003580 errs() << "Function " << F.getName() << " is " << nextID << "\n";
3581 }
David Neto22f144c2017-06-12 14:26:21 -04003582 // Generate SPIRV instruction for function.
David Neto87846742018-04-11 17:36:22 -04003583 auto *FuncInst = new SPIRVInstruction(spv::OpFunction, nextID++, FOps);
David Neto22f144c2017-06-12 14:26:21 -04003584 SPIRVInstList.push_back(FuncInst);
3585
3586 //
3587 // Generate OpFunctionParameter for Normal function.
3588 //
3589
3590 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
alan-bakere9308012019-03-15 10:25:13 -04003591
David Neto22f144c2017-06-12 14:26:21 -04003592 // Iterate Argument for name instead of param type from function type.
3593 unsigned ArgIdx = 0;
3594 for (Argument &Arg : F.args()) {
alan-bakere9308012019-03-15 10:25:13 -04003595 uint32_t param_id = nextID++;
3596 VMap[&Arg] = param_id;
3597
3598 if (CalledWithCoherentResource(Arg)) {
3599 // If the arg is passed a coherent resource ever, then decorate this
3600 // parameter with Coherent too.
3601 SPIRVOperandList decoration_ops;
3602 decoration_ops << MkId(param_id) << MkNum(spv::DecorationCoherent);
SJW69939d52020-04-16 07:29:07 -05003603 getSPIRVInstList(kAnnotations)
3604 .push_back(new SPIRVInstruction(spv::OpDecorate, decoration_ops));
alan-bakere9308012019-03-15 10:25:13 -04003605 }
David Neto22f144c2017-06-12 14:26:21 -04003606
3607 // ParamOps[0] : Result Type ID
3608 SPIRVOperandList ParamOps;
3609
3610 // Find SPIRV instruction for parameter type.
3611 uint32_t ParamTyID = lookupType(Arg.getType());
3612 if (PointerType *PTy = dyn_cast<PointerType>(Arg.getType())) {
3613 if (GlobalConstFuncTyMap.count(FTy)) {
3614 if (ArgIdx == GlobalConstFuncTyMap[FTy].second) {
3615 Type *EleTy = PTy->getPointerElementType();
3616 Type *ArgTy =
3617 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
3618 ParamTyID = lookupType(ArgTy);
3619 GlobalConstArgSet.insert(&Arg);
3620 }
3621 }
3622 }
David Neto257c3892018-04-11 13:19:45 -04003623 ParamOps << MkId(ParamTyID);
David Neto22f144c2017-06-12 14:26:21 -04003624
3625 // Generate SPIRV instruction for parameter.
David Neto87846742018-04-11 17:36:22 -04003626 auto *ParamInst =
alan-bakere9308012019-03-15 10:25:13 -04003627 new SPIRVInstruction(spv::OpFunctionParameter, param_id, ParamOps);
David Neto22f144c2017-06-12 14:26:21 -04003628 SPIRVInstList.push_back(ParamInst);
3629
3630 ArgIdx++;
3631 }
3632 }
3633}
3634
alan-bakerb6b09dc2018-11-08 16:59:28 -05003635void SPIRVProducerPass::GenerateModuleInfo(Module &module) {
David Neto22f144c2017-06-12 14:26:21 -04003636 EntryPointVecType &EntryPoints = getEntryPointVec();
3637 ValueMapType &VMap = getValueMap();
3638 ValueList &EntryPointInterfaces = getEntryPointInterfacesVec();
David Neto22f144c2017-06-12 14:26:21 -04003639 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
3640
SJW69939d52020-04-16 07:29:07 -05003641 SPIRVInstructionList &SPIRVCapabilities = getSPIRVInstList(kCapabilities);
David Neto22f144c2017-06-12 14:26:21 -04003642 //
3643 // Generate OpCapability
3644 //
3645 // TODO: Which llvm information is mapped to SPIRV Capapbility?
3646
3647 // Ops[0] = Capability
3648 SPIRVOperandList Ops;
3649
David Neto87846742018-04-11 17:36:22 -04003650 auto *CapInst =
David Netoef5ba2b2019-12-20 08:35:54 -05003651 new SPIRVInstruction(spv::OpCapability, MkNum(spv::CapabilityShader));
SJW69939d52020-04-16 07:29:07 -05003652 SPIRVCapabilities.push_back(CapInst);
David Neto22f144c2017-06-12 14:26:21 -04003653
alan-bakerf906d2b2019-12-10 11:26:23 -05003654 bool write_without_format = false;
3655 bool sampled_1d = false;
3656 bool image_1d = false;
David Neto22f144c2017-06-12 14:26:21 -04003657 for (Type *Ty : getTypeList()) {
alan-bakerb39c8262019-03-08 14:03:37 -05003658 if (clspv::Option::Int8Support() && Ty->isIntegerTy(8)) {
3659 // Generate OpCapability for i8 type.
SJW69939d52020-04-16 07:29:07 -05003660 SPIRVCapabilities.push_back(
David Netoef5ba2b2019-12-20 08:35:54 -05003661 new SPIRVInstruction(spv::OpCapability, MkNum(spv::CapabilityInt8)));
alan-bakerb39c8262019-03-08 14:03:37 -05003662 } else if (Ty->isIntegerTy(16)) {
David Neto22f144c2017-06-12 14:26:21 -04003663 // Generate OpCapability for i16 type.
SJW69939d52020-04-16 07:29:07 -05003664 SPIRVCapabilities.push_back(
David Netoef5ba2b2019-12-20 08:35:54 -05003665 new SPIRVInstruction(spv::OpCapability, MkNum(spv::CapabilityInt16)));
David Neto22f144c2017-06-12 14:26:21 -04003666 } else if (Ty->isIntegerTy(64)) {
3667 // Generate OpCapability for i64 type.
SJW69939d52020-04-16 07:29:07 -05003668 SPIRVCapabilities.push_back(
David Netoef5ba2b2019-12-20 08:35:54 -05003669 new SPIRVInstruction(spv::OpCapability, MkNum(spv::CapabilityInt64)));
David Neto22f144c2017-06-12 14:26:21 -04003670 } else if (Ty->isHalfTy()) {
3671 // Generate OpCapability for half type.
SJW69939d52020-04-16 07:29:07 -05003672 SPIRVCapabilities.push_back(new SPIRVInstruction(
3673 spv::OpCapability, MkNum(spv::CapabilityFloat16)));
David Neto22f144c2017-06-12 14:26:21 -04003674 } else if (Ty->isDoubleTy()) {
3675 // Generate OpCapability for double type.
SJW69939d52020-04-16 07:29:07 -05003676 SPIRVCapabilities.push_back(new SPIRVInstruction(
3677 spv::OpCapability, MkNum(spv::CapabilityFloat64)));
David Neto22f144c2017-06-12 14:26:21 -04003678 } else if (auto *STy = dyn_cast<StructType>(Ty)) {
3679 if (STy->isOpaque()) {
alan-bakerf906d2b2019-12-10 11:26:23 -05003680 if (STy->getName().startswith("opencl.image1d_wo_t") ||
alan-baker7150a1d2020-02-25 08:31:06 -05003681 STy->getName().startswith("opencl.image1d_array_wo_t") ||
alan-bakerf906d2b2019-12-10 11:26:23 -05003682 STy->getName().startswith("opencl.image2d_wo_t") ||
alan-baker7150a1d2020-02-25 08:31:06 -05003683 STy->getName().startswith("opencl.image2d_array_wo_t") ||
alan-bakerf67468c2019-11-25 15:51:49 -05003684 STy->getName().startswith("opencl.image3d_wo_t")) {
alan-bakerf906d2b2019-12-10 11:26:23 -05003685 write_without_format = true;
3686 }
3687 if (STy->getName().startswith("opencl.image1d_ro_t") ||
alan-baker7150a1d2020-02-25 08:31:06 -05003688 STy->getName().startswith("opencl.image1d_wo_t") ||
3689 STy->getName().startswith("opencl.image1d_array_ro_t") ||
3690 STy->getName().startswith("opencl.image1d_array_wo_t")) {
alan-bakerf906d2b2019-12-10 11:26:23 -05003691 if (STy->getName().contains(".sampled"))
3692 sampled_1d = true;
3693 else
3694 image_1d = true;
David Neto22f144c2017-06-12 14:26:21 -04003695 }
3696 }
3697 }
3698 }
3699
alan-bakerf906d2b2019-12-10 11:26:23 -05003700 if (write_without_format) {
3701 // Generate OpCapability for write only image type.
SJW69939d52020-04-16 07:29:07 -05003702 SPIRVCapabilities.push_back(new SPIRVInstruction(
3703 spv::OpCapability,
3704 {MkNum(spv::CapabilityStorageImageWriteWithoutFormat)}));
alan-bakerf906d2b2019-12-10 11:26:23 -05003705 }
3706 if (image_1d) {
3707 // Generate OpCapability for unsampled 1D image type.
SJW69939d52020-04-16 07:29:07 -05003708 SPIRVCapabilities.push_back(new SPIRVInstruction(
3709 spv::OpCapability, {MkNum(spv::CapabilityImage1D)}));
alan-bakerf906d2b2019-12-10 11:26:23 -05003710 } else if (sampled_1d) {
3711 // Generate OpCapability for sampled 1D image type.
SJW69939d52020-04-16 07:29:07 -05003712 SPIRVCapabilities.push_back(new SPIRVInstruction(
3713 spv::OpCapability, {MkNum(spv::CapabilitySampled1D)}));
alan-bakerf906d2b2019-12-10 11:26:23 -05003714 }
3715
David Neto5c22a252018-03-15 16:07:41 -04003716 { // OpCapability ImageQuery
3717 bool hasImageQuery = false;
alan-bakerf67468c2019-11-25 15:51:49 -05003718 for (const auto &SymVal : module.getValueSymbolTable()) {
3719 if (auto F = dyn_cast<Function>(SymVal.getValue())) {
SJW173c7e92020-03-16 08:44:47 -05003720 if (IsImageQuery(F)) {
alan-bakerf67468c2019-11-25 15:51:49 -05003721 hasImageQuery = true;
3722 break;
3723 }
David Neto5c22a252018-03-15 16:07:41 -04003724 }
3725 }
alan-bakerf67468c2019-11-25 15:51:49 -05003726
David Neto5c22a252018-03-15 16:07:41 -04003727 if (hasImageQuery) {
SJW69939d52020-04-16 07:29:07 -05003728 SPIRVCapabilities.push_back(new SPIRVInstruction(
3729 spv::OpCapability, {MkNum(spv::CapabilityImageQuery)}));
David Neto5c22a252018-03-15 16:07:41 -04003730 }
3731 }
3732
David Neto22f144c2017-06-12 14:26:21 -04003733 if (hasVariablePointers()) {
3734 //
David Neto22f144c2017-06-12 14:26:21 -04003735 // Generate OpCapability.
3736 //
3737 // Ops[0] = Capability
3738 //
3739 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003740 Ops << MkNum(spv::CapabilityVariablePointers);
David Neto22f144c2017-06-12 14:26:21 -04003741
SJW69939d52020-04-16 07:29:07 -05003742 SPIRVCapabilities.push_back(new SPIRVInstruction(spv::OpCapability, Ops));
alan-baker5b86ed72019-02-15 08:26:50 -05003743 } else if (hasVariablePointersStorageBuffer()) {
3744 //
3745 // Generate OpCapability.
3746 //
3747 // Ops[0] = Capability
3748 //
3749 Ops.clear();
3750 Ops << MkNum(spv::CapabilityVariablePointersStorageBuffer);
David Neto22f144c2017-06-12 14:26:21 -04003751
SJW69939d52020-04-16 07:29:07 -05003752 SPIRVCapabilities.push_back(new SPIRVInstruction(spv::OpCapability, Ops));
alan-baker5b86ed72019-02-15 08:26:50 -05003753 }
3754
SJW69939d52020-04-16 07:29:07 -05003755 SPIRVInstructionList &SPIRVExtensions = getSPIRVInstList(kExtensions);
alan-baker5b86ed72019-02-15 08:26:50 -05003756 // Always add the storage buffer extension
3757 {
David Neto22f144c2017-06-12 14:26:21 -04003758 //
3759 // Generate OpExtension.
3760 //
3761 // Ops[0] = Name (Literal String)
3762 //
alan-baker5b86ed72019-02-15 08:26:50 -05003763 auto *ExtensionInst = new SPIRVInstruction(
3764 spv::OpExtension, {MkString("SPV_KHR_storage_buffer_storage_class")});
SJW69939d52020-04-16 07:29:07 -05003765 SPIRVExtensions.push_back(ExtensionInst);
alan-baker5b86ed72019-02-15 08:26:50 -05003766 }
David Neto22f144c2017-06-12 14:26:21 -04003767
alan-baker5b86ed72019-02-15 08:26:50 -05003768 if (hasVariablePointers() || hasVariablePointersStorageBuffer()) {
3769 //
3770 // Generate OpExtension.
3771 //
3772 // Ops[0] = Name (Literal String)
3773 //
3774 auto *ExtensionInst = new SPIRVInstruction(
3775 spv::OpExtension, {MkString("SPV_KHR_variable_pointers")});
SJW69939d52020-04-16 07:29:07 -05003776 SPIRVExtensions.push_back(ExtensionInst);
David Neto22f144c2017-06-12 14:26:21 -04003777 }
3778
3779 //
3780 // Generate OpMemoryModel
3781 //
3782 // Memory model for Vulkan will always be GLSL450.
3783
3784 // Ops[0] = Addressing Model
3785 // Ops[1] = Memory Model
3786 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003787 Ops << MkNum(spv::AddressingModelLogical) << MkNum(spv::MemoryModelGLSL450);
David Neto22f144c2017-06-12 14:26:21 -04003788
David Neto87846742018-04-11 17:36:22 -04003789 auto *MemModelInst = new SPIRVInstruction(spv::OpMemoryModel, Ops);
SJW69939d52020-04-16 07:29:07 -05003790 getSPIRVInstList(kMemoryModel).push_back(MemModelInst);
David Neto22f144c2017-06-12 14:26:21 -04003791
SJW69939d52020-04-16 07:29:07 -05003792 SPIRVInstructionList &SPIRVEntryPoints = getSPIRVInstList(kEntryPoints);
David Neto22f144c2017-06-12 14:26:21 -04003793 //
3794 // Generate OpEntryPoint
3795 //
3796 for (auto EntryPoint : EntryPoints) {
3797 // Ops[0] = Execution Model
3798 // Ops[1] = EntryPoint ID
3799 // Ops[2] = Name (Literal String)
3800 // ...
3801 //
3802 // TODO: Do we need to consider Interface ID for forward references???
3803 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05003804 const StringRef &name = EntryPoint.first->getName();
David Neto257c3892018-04-11 13:19:45 -04003805 Ops << MkNum(spv::ExecutionModelGLCompute) << MkId(EntryPoint.second)
3806 << MkString(name);
David Neto22f144c2017-06-12 14:26:21 -04003807
David Neto22f144c2017-06-12 14:26:21 -04003808 for (Value *Interface : EntryPointInterfaces) {
David Neto257c3892018-04-11 13:19:45 -04003809 Ops << MkId(VMap[Interface]);
David Neto22f144c2017-06-12 14:26:21 -04003810 }
3811
David Neto87846742018-04-11 17:36:22 -04003812 auto *EntryPointInst = new SPIRVInstruction(spv::OpEntryPoint, Ops);
SJW69939d52020-04-16 07:29:07 -05003813 SPIRVEntryPoints.push_back(EntryPointInst);
David Neto22f144c2017-06-12 14:26:21 -04003814 }
3815
SJW69939d52020-04-16 07:29:07 -05003816 SPIRVInstructionList &SPIRVExecutionModes = getSPIRVInstList(kExecutionModes);
David Neto22f144c2017-06-12 14:26:21 -04003817 for (auto EntryPoint : EntryPoints) {
3818 if (const MDNode *MD = dyn_cast<Function>(EntryPoint.first)
3819 ->getMetadata("reqd_work_group_size")) {
3820
3821 if (!BuiltinDimVec.empty()) {
3822 llvm_unreachable(
3823 "Kernels should have consistent work group size definition");
3824 }
3825
3826 //
3827 // Generate OpExecutionMode
3828 //
3829
3830 // Ops[0] = Entry Point ID
3831 // Ops[1] = Execution Mode
3832 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
3833 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05003834 Ops << MkId(EntryPoint.second) << MkNum(spv::ExecutionModeLocalSize);
David Neto22f144c2017-06-12 14:26:21 -04003835
3836 uint32_t XDim = static_cast<uint32_t>(
3837 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
3838 uint32_t YDim = static_cast<uint32_t>(
3839 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
3840 uint32_t ZDim = static_cast<uint32_t>(
3841 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
3842
David Neto257c3892018-04-11 13:19:45 -04003843 Ops << MkNum(XDim) << MkNum(YDim) << MkNum(ZDim);
David Neto22f144c2017-06-12 14:26:21 -04003844
David Neto87846742018-04-11 17:36:22 -04003845 auto *ExecModeInst = new SPIRVInstruction(spv::OpExecutionMode, Ops);
SJW69939d52020-04-16 07:29:07 -05003846 SPIRVExecutionModes.push_back(ExecModeInst);
David Neto22f144c2017-06-12 14:26:21 -04003847 }
3848 }
3849
3850 //
3851 // Generate OpSource.
3852 //
3853 // Ops[0] = SourceLanguage ID
3854 // Ops[1] = Version (LiteralNum)
3855 //
3856 Ops.clear();
Kévin Petitf0515712020-01-07 18:29:20 +00003857 switch (clspv::Option::Language()) {
3858 case clspv::Option::SourceLanguage::OpenCL_C_10:
3859 Ops << MkNum(spv::SourceLanguageOpenCL_C) << MkNum(100);
3860 break;
3861 case clspv::Option::SourceLanguage::OpenCL_C_11:
3862 Ops << MkNum(spv::SourceLanguageOpenCL_C) << MkNum(110);
3863 break;
3864 case clspv::Option::SourceLanguage::OpenCL_C_12:
Kévin Petit0fc88042019-04-09 23:25:02 +01003865 Ops << MkNum(spv::SourceLanguageOpenCL_C) << MkNum(120);
Kévin Petitf0515712020-01-07 18:29:20 +00003866 break;
3867 case clspv::Option::SourceLanguage::OpenCL_C_20:
3868 Ops << MkNum(spv::SourceLanguageOpenCL_C) << MkNum(200);
3869 break;
3870 case clspv::Option::SourceLanguage::OpenCL_CPP:
3871 Ops << MkNum(spv::SourceLanguageOpenCL_CPP) << MkNum(100);
3872 break;
3873 default:
3874 Ops << MkNum(spv::SourceLanguageUnknown) << MkNum(0);
3875 break;
Kévin Petit0fc88042019-04-09 23:25:02 +01003876 }
David Neto22f144c2017-06-12 14:26:21 -04003877
David Neto87846742018-04-11 17:36:22 -04003878 auto *OpenSourceInst = new SPIRVInstruction(spv::OpSource, Ops);
SJW69939d52020-04-16 07:29:07 -05003879 getSPIRVInstList(kDebug).push_back(OpenSourceInst);
David Neto22f144c2017-06-12 14:26:21 -04003880
3881 if (!BuiltinDimVec.empty()) {
SJW69939d52020-04-16 07:29:07 -05003882 SPIRVInstructionList &SPIRVAnnotations = getSPIRVInstList(kAnnotations);
David Neto22f144c2017-06-12 14:26:21 -04003883 //
3884 // Generate OpDecorates for x/y/z dimension.
3885 //
3886 // Ops[0] = Target ID
3887 // Ops[1] = Decoration (SpecId)
David Neto257c3892018-04-11 13:19:45 -04003888 // Ops[2] = Specialization Constant ID (Literal Number)
David Neto22f144c2017-06-12 14:26:21 -04003889
3890 // X Dimension
3891 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003892 Ops << MkId(BuiltinDimVec[0]) << MkNum(spv::DecorationSpecId) << MkNum(0);
SJW69939d52020-04-16 07:29:07 -05003893 SPIRVAnnotations.push_back(new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003894
3895 // Y Dimension
3896 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003897 Ops << MkId(BuiltinDimVec[1]) << MkNum(spv::DecorationSpecId) << MkNum(1);
SJW69939d52020-04-16 07:29:07 -05003898 SPIRVAnnotations.push_back(new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003899
3900 // Z Dimension
3901 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003902 Ops << MkId(BuiltinDimVec[2]) << MkNum(spv::DecorationSpecId) << MkNum(2);
SJW69939d52020-04-16 07:29:07 -05003903 SPIRVAnnotations.push_back(new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003904 }
3905}
3906
David Netob6e2e062018-04-25 10:32:06 -04003907void SPIRVProducerPass::GenerateEntryPointInitialStores() {
3908 // Work around a driver bug. Initializers on Private variables might not
3909 // work. So the start of the kernel should store the initializer value to the
3910 // variables. Yes, *every* entry point pays this cost if *any* entry point
3911 // uses this builtin. At this point I judge this to be an acceptable tradeoff
3912 // of complexity vs. runtime, for a broken driver.
alan-bakerb6b09dc2018-11-08 16:59:28 -05003913 // TODO(dneto): Remove this at some point once fixed drivers are widely
3914 // available.
David Netob6e2e062018-04-25 10:32:06 -04003915 if (WorkgroupSizeVarID) {
3916 assert(WorkgroupSizeValueID);
3917
3918 SPIRVOperandList Ops;
3919 Ops << MkId(WorkgroupSizeVarID) << MkId(WorkgroupSizeValueID);
3920
3921 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
SJW69939d52020-04-16 07:29:07 -05003922 getSPIRVInstList(kFunctions).push_back(Inst);
David Netob6e2e062018-04-25 10:32:06 -04003923 }
3924}
3925
David Neto22f144c2017-06-12 14:26:21 -04003926void SPIRVProducerPass::GenerateFuncBody(Function &F) {
SJW69939d52020-04-16 07:29:07 -05003927 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kFunctions);
David Neto22f144c2017-06-12 14:26:21 -04003928 ValueMapType &VMap = getValueMap();
3929
David Netob6e2e062018-04-25 10:32:06 -04003930 const bool IsKernel = F.getCallingConv() == CallingConv::SPIR_KERNEL;
David Neto22f144c2017-06-12 14:26:21 -04003931
3932 for (BasicBlock &BB : F) {
3933 // Register BasicBlock to ValueMap.
3934 VMap[&BB] = nextID;
3935
3936 //
3937 // Generate OpLabel for Basic Block.
3938 //
3939 SPIRVOperandList Ops;
David Neto87846742018-04-11 17:36:22 -04003940 auto *Inst = new SPIRVInstruction(spv::OpLabel, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003941 SPIRVInstList.push_back(Inst);
3942
David Neto6dcd4712017-06-23 11:06:47 -04003943 // OpVariable instructions must come first.
3944 for (Instruction &I : BB) {
alan-baker5b86ed72019-02-15 08:26:50 -05003945 if (auto *alloca = dyn_cast<AllocaInst>(&I)) {
3946 // Allocating a pointer requires variable pointers.
3947 if (alloca->getAllocatedType()->isPointerTy()) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003948 setVariablePointersCapabilities(
3949 alloca->getAllocatedType()->getPointerAddressSpace());
alan-baker5b86ed72019-02-15 08:26:50 -05003950 }
David Neto6dcd4712017-06-23 11:06:47 -04003951 GenerateInstruction(I);
3952 }
3953 }
3954
David Neto22f144c2017-06-12 14:26:21 -04003955 if (&BB == &F.getEntryBlock() && IsKernel) {
David Netob6e2e062018-04-25 10:32:06 -04003956 if (clspv::Option::HackInitializers()) {
3957 GenerateEntryPointInitialStores();
3958 }
David Neto22f144c2017-06-12 14:26:21 -04003959 }
3960
3961 for (Instruction &I : BB) {
David Neto6dcd4712017-06-23 11:06:47 -04003962 if (!isa<AllocaInst>(I)) {
3963 GenerateInstruction(I);
3964 }
David Neto22f144c2017-06-12 14:26:21 -04003965 }
3966 }
3967}
3968
3969spv::Op SPIRVProducerPass::GetSPIRVCmpOpcode(CmpInst *I) {
3970 const std::map<CmpInst::Predicate, spv::Op> Map = {
3971 {CmpInst::ICMP_EQ, spv::OpIEqual},
3972 {CmpInst::ICMP_NE, spv::OpINotEqual},
3973 {CmpInst::ICMP_UGT, spv::OpUGreaterThan},
3974 {CmpInst::ICMP_UGE, spv::OpUGreaterThanEqual},
3975 {CmpInst::ICMP_ULT, spv::OpULessThan},
3976 {CmpInst::ICMP_ULE, spv::OpULessThanEqual},
3977 {CmpInst::ICMP_SGT, spv::OpSGreaterThan},
3978 {CmpInst::ICMP_SGE, spv::OpSGreaterThanEqual},
3979 {CmpInst::ICMP_SLT, spv::OpSLessThan},
3980 {CmpInst::ICMP_SLE, spv::OpSLessThanEqual},
3981 {CmpInst::FCMP_OEQ, spv::OpFOrdEqual},
3982 {CmpInst::FCMP_OGT, spv::OpFOrdGreaterThan},
3983 {CmpInst::FCMP_OGE, spv::OpFOrdGreaterThanEqual},
3984 {CmpInst::FCMP_OLT, spv::OpFOrdLessThan},
3985 {CmpInst::FCMP_OLE, spv::OpFOrdLessThanEqual},
3986 {CmpInst::FCMP_ONE, spv::OpFOrdNotEqual},
3987 {CmpInst::FCMP_UEQ, spv::OpFUnordEqual},
3988 {CmpInst::FCMP_UGT, spv::OpFUnordGreaterThan},
3989 {CmpInst::FCMP_UGE, spv::OpFUnordGreaterThanEqual},
3990 {CmpInst::FCMP_ULT, spv::OpFUnordLessThan},
3991 {CmpInst::FCMP_ULE, spv::OpFUnordLessThanEqual},
3992 {CmpInst::FCMP_UNE, spv::OpFUnordNotEqual}};
3993
3994 assert(0 != Map.count(I->getPredicate()));
3995
3996 return Map.at(I->getPredicate());
3997}
3998
3999spv::Op SPIRVProducerPass::GetSPIRVCastOpcode(Instruction &I) {
4000 const std::map<unsigned, spv::Op> Map{
4001 {Instruction::Trunc, spv::OpUConvert},
4002 {Instruction::ZExt, spv::OpUConvert},
4003 {Instruction::SExt, spv::OpSConvert},
4004 {Instruction::FPToUI, spv::OpConvertFToU},
4005 {Instruction::FPToSI, spv::OpConvertFToS},
4006 {Instruction::UIToFP, spv::OpConvertUToF},
4007 {Instruction::SIToFP, spv::OpConvertSToF},
4008 {Instruction::FPTrunc, spv::OpFConvert},
4009 {Instruction::FPExt, spv::OpFConvert},
4010 {Instruction::BitCast, spv::OpBitcast}};
4011
4012 assert(0 != Map.count(I.getOpcode()));
4013
4014 return Map.at(I.getOpcode());
4015}
4016
4017spv::Op SPIRVProducerPass::GetSPIRVBinaryOpcode(Instruction &I) {
Kévin Petit24272b62018-10-18 19:16:12 +00004018 if (I.getType()->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04004019 switch (I.getOpcode()) {
4020 default:
4021 break;
4022 case Instruction::Or:
4023 return spv::OpLogicalOr;
4024 case Instruction::And:
4025 return spv::OpLogicalAnd;
4026 case Instruction::Xor:
4027 return spv::OpLogicalNotEqual;
4028 }
4029 }
4030
alan-bakerb6b09dc2018-11-08 16:59:28 -05004031 const std::map<unsigned, spv::Op> Map{
David Neto22f144c2017-06-12 14:26:21 -04004032 {Instruction::Add, spv::OpIAdd},
4033 {Instruction::FAdd, spv::OpFAdd},
4034 {Instruction::Sub, spv::OpISub},
4035 {Instruction::FSub, spv::OpFSub},
4036 {Instruction::Mul, spv::OpIMul},
4037 {Instruction::FMul, spv::OpFMul},
4038 {Instruction::UDiv, spv::OpUDiv},
4039 {Instruction::SDiv, spv::OpSDiv},
4040 {Instruction::FDiv, spv::OpFDiv},
4041 {Instruction::URem, spv::OpUMod},
4042 {Instruction::SRem, spv::OpSRem},
4043 {Instruction::FRem, spv::OpFRem},
4044 {Instruction::Or, spv::OpBitwiseOr},
4045 {Instruction::Xor, spv::OpBitwiseXor},
4046 {Instruction::And, spv::OpBitwiseAnd},
4047 {Instruction::Shl, spv::OpShiftLeftLogical},
4048 {Instruction::LShr, spv::OpShiftRightLogical},
4049 {Instruction::AShr, spv::OpShiftRightArithmetic}};
4050
4051 assert(0 != Map.count(I.getOpcode()));
4052
4053 return Map.at(I.getOpcode());
4054}
4055
4056void SPIRVProducerPass::GenerateInstruction(Instruction &I) {
SJW69939d52020-04-16 07:29:07 -05004057 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kFunctions);
David Neto22f144c2017-06-12 14:26:21 -04004058 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04004059 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
4060 LLVMContext &Context = I.getParent()->getParent()->getParent()->getContext();
4061
4062 // Register Instruction to ValueMap.
4063 if (0 == VMap[&I]) {
4064 VMap[&I] = nextID;
4065 }
4066
4067 switch (I.getOpcode()) {
4068 default: {
4069 if (Instruction::isCast(I.getOpcode())) {
4070 //
4071 // Generate SPIRV instructions for cast operators.
4072 //
4073
David Netod2de94a2017-08-28 17:27:47 -04004074 auto Ty = I.getType();
David Neto22f144c2017-06-12 14:26:21 -04004075 auto OpTy = I.getOperand(0)->getType();
David Netod2de94a2017-08-28 17:27:47 -04004076 auto toI8 = Ty == Type::getInt8Ty(Context);
4077 auto fromI32 = OpTy == Type::getInt32Ty(Context);
David Neto22f144c2017-06-12 14:26:21 -04004078 // Handle zext, sext and uitofp with i1 type specially.
4079 if ((I.getOpcode() == Instruction::ZExt ||
4080 I.getOpcode() == Instruction::SExt ||
4081 I.getOpcode() == Instruction::UIToFP) &&
alan-bakerb6b09dc2018-11-08 16:59:28 -05004082 OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04004083 //
4084 // Generate OpSelect.
4085 //
4086
4087 // Ops[0] = Result Type ID
4088 // Ops[1] = Condition ID
4089 // Ops[2] = True Constant ID
4090 // Ops[3] = False Constant ID
4091 SPIRVOperandList Ops;
4092
David Neto257c3892018-04-11 13:19:45 -04004093 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004094
David Neto22f144c2017-06-12 14:26:21 -04004095 uint32_t CondID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04004096 Ops << MkId(CondID);
David Neto22f144c2017-06-12 14:26:21 -04004097
4098 uint32_t TrueID = 0;
4099 if (I.getOpcode() == Instruction::ZExt) {
Kévin Petit7bfb8992019-02-26 13:45:08 +00004100 TrueID = VMap[ConstantInt::get(I.getType(), 1)];
David Neto22f144c2017-06-12 14:26:21 -04004101 } else if (I.getOpcode() == Instruction::SExt) {
Kévin Petit7bfb8992019-02-26 13:45:08 +00004102 TrueID = VMap[ConstantInt::getSigned(I.getType(), -1)];
David Neto22f144c2017-06-12 14:26:21 -04004103 } else {
4104 TrueID = VMap[ConstantFP::get(Context, APFloat(1.0f))];
4105 }
David Neto257c3892018-04-11 13:19:45 -04004106 Ops << MkId(TrueID);
David Neto22f144c2017-06-12 14:26:21 -04004107
4108 uint32_t FalseID = 0;
4109 if (I.getOpcode() == Instruction::ZExt) {
4110 FalseID = VMap[Constant::getNullValue(I.getType())];
4111 } else if (I.getOpcode() == Instruction::SExt) {
4112 FalseID = VMap[Constant::getNullValue(I.getType())];
4113 } else {
4114 FalseID = VMap[ConstantFP::get(Context, APFloat(0.0f))];
4115 }
David Neto257c3892018-04-11 13:19:45 -04004116 Ops << MkId(FalseID);
David Neto22f144c2017-06-12 14:26:21 -04004117
David Neto87846742018-04-11 17:36:22 -04004118 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004119 SPIRVInstList.push_back(Inst);
alan-bakerb39c8262019-03-08 14:03:37 -05004120 } else if (!clspv::Option::Int8Support() &&
4121 I.getOpcode() == Instruction::Trunc && fromI32 && toI8) {
David Netod2de94a2017-08-28 17:27:47 -04004122 // The SPIR-V target type is a 32-bit int. Keep only the bottom
4123 // 8 bits.
4124 // Before:
4125 // %result = trunc i32 %a to i8
4126 // After
4127 // %result = OpBitwiseAnd %uint %a %uint_255
4128
4129 SPIRVOperandList Ops;
4130
David Neto257c3892018-04-11 13:19:45 -04004131 Ops << MkId(lookupType(OpTy)) << MkId(VMap[I.getOperand(0)]);
David Netod2de94a2017-08-28 17:27:47 -04004132
4133 Type *UintTy = Type::getInt32Ty(Context);
4134 uint32_t MaskID = VMap[ConstantInt::get(UintTy, 255)];
David Neto257c3892018-04-11 13:19:45 -04004135 Ops << MkId(MaskID);
David Netod2de94a2017-08-28 17:27:47 -04004136
David Neto87846742018-04-11 17:36:22 -04004137 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Netod2de94a2017-08-28 17:27:47 -04004138 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04004139 } else {
4140 // Ops[0] = Result Type ID
4141 // Ops[1] = Source Value ID
4142 SPIRVOperandList Ops;
4143
David Neto257c3892018-04-11 13:19:45 -04004144 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004145
David Neto87846742018-04-11 17:36:22 -04004146 auto *Inst = new SPIRVInstruction(GetSPIRVCastOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004147 SPIRVInstList.push_back(Inst);
4148 }
4149 } else if (isa<BinaryOperator>(I)) {
4150 //
4151 // Generate SPIRV instructions for binary operators.
4152 //
4153
4154 // Handle xor with i1 type specially.
4155 if (I.getOpcode() == Instruction::Xor &&
4156 I.getType() == Type::getInt1Ty(Context) &&
Kévin Petit24272b62018-10-18 19:16:12 +00004157 ((isa<ConstantInt>(I.getOperand(0)) &&
4158 !cast<ConstantInt>(I.getOperand(0))->isZero()) ||
4159 (isa<ConstantInt>(I.getOperand(1)) &&
4160 !cast<ConstantInt>(I.getOperand(1))->isZero()))) {
David Neto22f144c2017-06-12 14:26:21 -04004161 //
4162 // Generate OpLogicalNot.
4163 //
4164 // Ops[0] = Result Type ID
4165 // Ops[1] = Operand
4166 SPIRVOperandList Ops;
4167
David Neto257c3892018-04-11 13:19:45 -04004168 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004169
4170 Value *CondV = I.getOperand(0);
4171 if (isa<Constant>(I.getOperand(0))) {
4172 CondV = I.getOperand(1);
4173 }
David Neto257c3892018-04-11 13:19:45 -04004174 Ops << MkId(VMap[CondV]);
David Neto22f144c2017-06-12 14:26:21 -04004175
David Neto87846742018-04-11 17:36:22 -04004176 auto *Inst = new SPIRVInstruction(spv::OpLogicalNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004177 SPIRVInstList.push_back(Inst);
4178 } else {
4179 // Ops[0] = Result Type ID
4180 // Ops[1] = Operand 0
4181 // Ops[2] = Operand 1
4182 SPIRVOperandList Ops;
4183
David Neto257c3892018-04-11 13:19:45 -04004184 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
4185 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004186
David Neto87846742018-04-11 17:36:22 -04004187 auto *Inst =
4188 new SPIRVInstruction(GetSPIRVBinaryOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004189 SPIRVInstList.push_back(Inst);
4190 }
alan-bakerc9c55ae2019-12-02 16:01:27 -05004191 } else if (I.getOpcode() == Instruction::FNeg) {
4192 // The only unary operator.
4193 //
4194 // Ops[0] = Result Type ID
4195 // Ops[1] = Operand 0
4196 SPIRVOperandList ops;
4197
4198 ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
4199 auto *Inst = new SPIRVInstruction(spv::OpFNegate, nextID++, ops);
4200 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04004201 } else {
4202 I.print(errs());
4203 llvm_unreachable("Unsupported instruction???");
4204 }
4205 break;
4206 }
4207 case Instruction::GetElementPtr: {
4208 auto &GlobalConstArgSet = getGlobalConstArgSet();
4209
4210 //
4211 // Generate OpAccessChain.
4212 //
4213 GetElementPtrInst *GEP = cast<GetElementPtrInst>(&I);
4214
4215 //
4216 // Generate OpAccessChain.
4217 //
4218
4219 // Ops[0] = Result Type ID
4220 // Ops[1] = Base ID
4221 // Ops[2] ... Ops[n] = Indexes ID
4222 SPIRVOperandList Ops;
4223
alan-bakerb6b09dc2018-11-08 16:59:28 -05004224 PointerType *ResultType = cast<PointerType>(GEP->getType());
David Neto22f144c2017-06-12 14:26:21 -04004225 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate ||
4226 GlobalConstArgSet.count(GEP->getPointerOperand())) {
4227 // Use pointer type with private address space for global constant.
4228 Type *EleTy = I.getType()->getPointerElementType();
David Neto1a1a0582017-07-07 12:01:44 -04004229 ResultType = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
David Neto22f144c2017-06-12 14:26:21 -04004230 }
David Neto257c3892018-04-11 13:19:45 -04004231
4232 Ops << MkId(lookupType(ResultType));
David Neto22f144c2017-06-12 14:26:21 -04004233
David Neto862b7d82018-06-14 18:48:37 -04004234 // Generate the base pointer.
4235 Ops << MkId(VMap[GEP->getPointerOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04004236
David Neto862b7d82018-06-14 18:48:37 -04004237 // TODO(dneto): Simplify the following?
David Neto22f144c2017-06-12 14:26:21 -04004238
4239 //
4240 // Follows below rules for gep.
4241 //
David Neto862b7d82018-06-14 18:48:37 -04004242 // 1. If gep's first index is 0 generate OpAccessChain and ignore gep's
4243 // first index.
David Neto22f144c2017-06-12 14:26:21 -04004244 // 2. If gep's first index is not 0, generate OpPtrAccessChain and use gep's
4245 // first index.
4246 // 3. If gep's first index is not constant, generate OpPtrAccessChain and
4247 // use gep's first index.
4248 // 4. If it is not above case 1, 2 and 3, generate OpAccessChain and use
4249 // gep's first index.
4250 //
4251 spv::Op Opcode = spv::OpAccessChain;
4252 unsigned offset = 0;
4253 if (ConstantInt *CstInt = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
David Neto862b7d82018-06-14 18:48:37 -04004254 if (CstInt->getZExtValue() == 0) {
David Neto22f144c2017-06-12 14:26:21 -04004255 offset = 1;
David Neto862b7d82018-06-14 18:48:37 -04004256 } else if (CstInt->getZExtValue() != 0) {
David Neto22f144c2017-06-12 14:26:21 -04004257 Opcode = spv::OpPtrAccessChain;
David Neto22f144c2017-06-12 14:26:21 -04004258 }
David Neto862b7d82018-06-14 18:48:37 -04004259 } else {
David Neto22f144c2017-06-12 14:26:21 -04004260 Opcode = spv::OpPtrAccessChain;
David Neto1a1a0582017-07-07 12:01:44 -04004261 }
4262
4263 if (Opcode == spv::OpPtrAccessChain) {
David Neto1a1a0582017-07-07 12:01:44 -04004264 // Do we need to generate ArrayStride? Check against the GEP result type
4265 // rather than the pointer type of the base because when indexing into
4266 // an OpenCL program-scope constant, we'll swap out the LLVM base pointer
4267 // for something else in the SPIR-V.
4268 // E.g. see test/PointerAccessChain/pointer_index_is_constant_1.cl
alan-baker5b86ed72019-02-15 08:26:50 -05004269 auto address_space = ResultType->getAddressSpace();
4270 setVariablePointersCapabilities(address_space);
4271 switch (GetStorageClass(address_space)) {
Alan Bakerfcda9482018-10-02 17:09:59 -04004272 case spv::StorageClassStorageBuffer:
4273 case spv::StorageClassUniform:
David Neto1a1a0582017-07-07 12:01:44 -04004274 // Save the need to generate an ArrayStride decoration. But defer
4275 // generation until later, so we only make one decoration.
David Neto85082642018-03-24 06:55:20 -07004276 getTypesNeedingArrayStride().insert(ResultType);
Alan Bakerfcda9482018-10-02 17:09:59 -04004277 break;
4278 default:
4279 break;
David Neto1a1a0582017-07-07 12:01:44 -04004280 }
David Neto22f144c2017-06-12 14:26:21 -04004281 }
4282
4283 for (auto II = GEP->idx_begin() + offset; II != GEP->idx_end(); II++) {
David Neto257c3892018-04-11 13:19:45 -04004284 Ops << MkId(VMap[*II]);
David Neto22f144c2017-06-12 14:26:21 -04004285 }
4286
David Neto87846742018-04-11 17:36:22 -04004287 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004288 SPIRVInstList.push_back(Inst);
4289 break;
4290 }
4291 case Instruction::ExtractValue: {
4292 ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
4293 // Ops[0] = Result Type ID
4294 // Ops[1] = Composite ID
4295 // Ops[2] ... Ops[n] = Indexes (Literal Number)
4296 SPIRVOperandList Ops;
4297
David Neto257c3892018-04-11 13:19:45 -04004298 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004299
4300 uint32_t CompositeID = VMap[EVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04004301 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04004302
4303 for (auto &Index : EVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04004304 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04004305 }
4306
David Neto87846742018-04-11 17:36:22 -04004307 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004308 SPIRVInstList.push_back(Inst);
4309 break;
4310 }
4311 case Instruction::InsertValue: {
4312 InsertValueInst *IVI = cast<InsertValueInst>(&I);
4313 // Ops[0] = Result Type ID
4314 // Ops[1] = Object ID
4315 // Ops[2] = Composite ID
4316 // Ops[3] ... Ops[n] = Indexes (Literal Number)
4317 SPIRVOperandList Ops;
4318
4319 uint32_t ResTyID = lookupType(I.getType());
David Neto257c3892018-04-11 13:19:45 -04004320 Ops << MkId(ResTyID);
David Neto22f144c2017-06-12 14:26:21 -04004321
4322 uint32_t ObjectID = VMap[IVI->getInsertedValueOperand()];
David Neto257c3892018-04-11 13:19:45 -04004323 Ops << MkId(ObjectID);
David Neto22f144c2017-06-12 14:26:21 -04004324
4325 uint32_t CompositeID = VMap[IVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04004326 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04004327
4328 for (auto &Index : IVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04004329 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04004330 }
4331
David Neto87846742018-04-11 17:36:22 -04004332 auto *Inst = new SPIRVInstruction(spv::OpCompositeInsert, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004333 SPIRVInstList.push_back(Inst);
4334 break;
4335 }
4336 case Instruction::Select: {
4337 //
4338 // Generate OpSelect.
4339 //
4340
4341 // Ops[0] = Result Type ID
4342 // Ops[1] = Condition ID
4343 // Ops[2] = True Constant ID
4344 // Ops[3] = False Constant ID
4345 SPIRVOperandList Ops;
4346
4347 // Find SPIRV instruction for parameter type.
4348 auto Ty = I.getType();
4349 if (Ty->isPointerTy()) {
4350 auto PointeeTy = Ty->getPointerElementType();
4351 if (PointeeTy->isStructTy() &&
4352 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
4353 Ty = PointeeTy;
alan-baker5b86ed72019-02-15 08:26:50 -05004354 } else {
4355 // Selecting between pointers requires variable pointers.
4356 setVariablePointersCapabilities(Ty->getPointerAddressSpace());
4357 if (!hasVariablePointers() && !selectFromSameObject(&I)) {
4358 setVariablePointers(true);
4359 }
David Neto22f144c2017-06-12 14:26:21 -04004360 }
4361 }
4362
David Neto257c3892018-04-11 13:19:45 -04004363 Ops << MkId(lookupType(Ty)) << MkId(VMap[I.getOperand(0)])
4364 << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004365
David Neto87846742018-04-11 17:36:22 -04004366 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004367 SPIRVInstList.push_back(Inst);
4368 break;
4369 }
4370 case Instruction::ExtractElement: {
4371 // Handle <4 x i8> type manually.
4372 Type *CompositeTy = I.getOperand(0)->getType();
4373 if (is4xi8vec(CompositeTy)) {
4374 //
4375 // Generate OpShiftRightLogical and OpBitwiseAnd for extractelement with
4376 // <4 x i8>.
4377 //
4378
4379 //
4380 // Generate OpShiftRightLogical
4381 //
4382 // Ops[0] = Result Type ID
4383 // Ops[1] = Operand 0
4384 // Ops[2] = Operand 1
4385 //
4386 SPIRVOperandList Ops;
4387
David Neto257c3892018-04-11 13:19:45 -04004388 Ops << MkId(lookupType(CompositeTy));
David Neto22f144c2017-06-12 14:26:21 -04004389
4390 uint32_t Op0ID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04004391 Ops << MkId(Op0ID);
David Neto22f144c2017-06-12 14:26:21 -04004392
4393 uint32_t Op1ID = 0;
4394 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
4395 // Handle constant index.
4396 uint64_t Idx = CI->getZExtValue();
4397 Value *ShiftAmount =
4398 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
4399 Op1ID = VMap[ShiftAmount];
4400 } else {
4401 // Handle variable index.
4402 SPIRVOperandList TmpOps;
4403
David Neto257c3892018-04-11 13:19:45 -04004404 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
4405 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004406
4407 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04004408 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04004409
4410 Op1ID = nextID;
4411
David Neto87846742018-04-11 17:36:22 -04004412 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04004413 SPIRVInstList.push_back(TmpInst);
4414 }
David Neto257c3892018-04-11 13:19:45 -04004415 Ops << MkId(Op1ID);
David Neto22f144c2017-06-12 14:26:21 -04004416
4417 uint32_t ShiftID = nextID;
4418
David Neto87846742018-04-11 17:36:22 -04004419 auto *Inst =
4420 new SPIRVInstruction(spv::OpShiftRightLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004421 SPIRVInstList.push_back(Inst);
4422
4423 //
4424 // Generate OpBitwiseAnd
4425 //
4426 // Ops[0] = Result Type ID
4427 // Ops[1] = Operand 0
4428 // Ops[2] = Operand 1
4429 //
4430 Ops.clear();
4431
David Neto257c3892018-04-11 13:19:45 -04004432 Ops << MkId(lookupType(CompositeTy)) << MkId(ShiftID);
David Neto22f144c2017-06-12 14:26:21 -04004433
4434 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
David Neto257c3892018-04-11 13:19:45 -04004435 Ops << MkId(VMap[CstFF]);
David Neto22f144c2017-06-12 14:26:21 -04004436
David Neto9b2d6252017-09-06 15:47:37 -04004437 // Reset mapping for this value to the result of the bitwise and.
4438 VMap[&I] = nextID;
4439
David Neto87846742018-04-11 17:36:22 -04004440 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004441 SPIRVInstList.push_back(Inst);
4442 break;
4443 }
4444
4445 // Ops[0] = Result Type ID
4446 // Ops[1] = Composite ID
4447 // Ops[2] ... Ops[n] = Indexes (Literal Number)
4448 SPIRVOperandList Ops;
4449
David Neto257c3892018-04-11 13:19:45 -04004450 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004451
4452 spv::Op Opcode = spv::OpCompositeExtract;
4453 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
David Neto257c3892018-04-11 13:19:45 -04004454 Ops << MkNum(static_cast<uint32_t>(CI->getZExtValue()));
David Neto22f144c2017-06-12 14:26:21 -04004455 } else {
David Neto257c3892018-04-11 13:19:45 -04004456 Ops << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004457 Opcode = spv::OpVectorExtractDynamic;
4458 }
4459
David Neto87846742018-04-11 17:36:22 -04004460 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004461 SPIRVInstList.push_back(Inst);
4462 break;
4463 }
4464 case Instruction::InsertElement: {
4465 // Handle <4 x i8> type manually.
4466 Type *CompositeTy = I.getOperand(0)->getType();
4467 if (is4xi8vec(CompositeTy)) {
4468 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
4469 uint32_t CstFFID = VMap[CstFF];
4470
4471 uint32_t ShiftAmountID = 0;
4472 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
4473 // Handle constant index.
4474 uint64_t Idx = CI->getZExtValue();
4475 Value *ShiftAmount =
4476 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
4477 ShiftAmountID = VMap[ShiftAmount];
4478 } else {
4479 // Handle variable index.
4480 SPIRVOperandList TmpOps;
4481
David Neto257c3892018-04-11 13:19:45 -04004482 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
4483 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004484
4485 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04004486 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04004487
4488 ShiftAmountID = nextID;
4489
David Neto87846742018-04-11 17:36:22 -04004490 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04004491 SPIRVInstList.push_back(TmpInst);
4492 }
4493
4494 //
4495 // Generate mask operations.
4496 //
4497
4498 // ShiftLeft mask according to index of insertelement.
4499 SPIRVOperandList Ops;
4500
David Neto257c3892018-04-11 13:19:45 -04004501 const uint32_t ResTyID = lookupType(CompositeTy);
4502 Ops << MkId(ResTyID) << MkId(CstFFID) << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04004503
4504 uint32_t MaskID = nextID;
4505
David Neto87846742018-04-11 17:36:22 -04004506 auto *Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004507 SPIRVInstList.push_back(Inst);
4508
4509 // Inverse mask.
4510 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004511 Ops << MkId(ResTyID) << MkId(MaskID);
David Neto22f144c2017-06-12 14:26:21 -04004512
4513 uint32_t InvMaskID = nextID;
4514
David Neto87846742018-04-11 17:36:22 -04004515 Inst = new SPIRVInstruction(spv::OpNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004516 SPIRVInstList.push_back(Inst);
4517
4518 // Apply mask.
4519 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004520 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(0)]) << MkId(InvMaskID);
David Neto22f144c2017-06-12 14:26:21 -04004521
4522 uint32_t OrgValID = nextID;
4523
David Neto87846742018-04-11 17:36:22 -04004524 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004525 SPIRVInstList.push_back(Inst);
4526
4527 // Create correct value according to index of insertelement.
4528 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05004529 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(1)])
4530 << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04004531
4532 uint32_t InsertValID = nextID;
4533
David Neto87846742018-04-11 17:36:22 -04004534 Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004535 SPIRVInstList.push_back(Inst);
4536
4537 // Insert value to original value.
4538 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004539 Ops << MkId(ResTyID) << MkId(OrgValID) << MkId(InsertValID);
David Neto22f144c2017-06-12 14:26:21 -04004540
David Netoa394f392017-08-26 20:45:29 -04004541 VMap[&I] = nextID;
4542
David Neto87846742018-04-11 17:36:22 -04004543 Inst = new SPIRVInstruction(spv::OpBitwiseOr, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004544 SPIRVInstList.push_back(Inst);
4545
4546 break;
4547 }
4548
David Neto22f144c2017-06-12 14:26:21 -04004549 SPIRVOperandList Ops;
4550
James Priced26efea2018-06-09 23:28:32 +01004551 // Ops[0] = Result Type ID
4552 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004553
4554 spv::Op Opcode = spv::OpCompositeInsert;
4555 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
David Neto257c3892018-04-11 13:19:45 -04004556 const auto value = CI->getZExtValue();
4557 assert(value <= UINT32_MAX);
James Priced26efea2018-06-09 23:28:32 +01004558 // Ops[1] = Object ID
4559 // Ops[2] = Composite ID
4560 // Ops[3] ... Ops[n] = Indexes (Literal Number)
alan-bakerb6b09dc2018-11-08 16:59:28 -05004561 Ops << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(0)])
James Priced26efea2018-06-09 23:28:32 +01004562 << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004563 } else {
James Priced26efea2018-06-09 23:28:32 +01004564 // Ops[1] = Composite ID
4565 // Ops[2] = Object ID
4566 // Ops[3] ... Ops[n] = Indexes (Literal Number)
alan-bakerb6b09dc2018-11-08 16:59:28 -05004567 Ops << MkId(VMap[I.getOperand(0)]) << MkId(VMap[I.getOperand(1)])
James Priced26efea2018-06-09 23:28:32 +01004568 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004569 Opcode = spv::OpVectorInsertDynamic;
4570 }
4571
David Neto87846742018-04-11 17:36:22 -04004572 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004573 SPIRVInstList.push_back(Inst);
4574 break;
4575 }
4576 case Instruction::ShuffleVector: {
4577 // Ops[0] = Result Type ID
4578 // Ops[1] = Vector 1 ID
4579 // Ops[2] = Vector 2 ID
4580 // Ops[3] ... Ops[n] = Components (Literal Number)
4581 SPIRVOperandList Ops;
4582
David Neto257c3892018-04-11 13:19:45 -04004583 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
4584 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004585
alan-bakerc9666712020-04-01 16:31:21 -04004586 auto shuffle = cast<ShuffleVectorInst>(&I);
4587 SmallVector<int, 4> mask;
4588 shuffle->getShuffleMask(mask);
4589 for (auto i : mask) {
4590 if (i == UndefMaskElem) {
4591 if (clspv::Option::HackUndef())
4592 // Use 0 instead of undef.
David Neto257c3892018-04-11 13:19:45 -04004593 Ops << MkNum(0);
alan-bakerc9666712020-04-01 16:31:21 -04004594 else
4595 // Undef for shuffle in SPIR-V.
4596 Ops << MkNum(0xffffffff);
David Neto22f144c2017-06-12 14:26:21 -04004597 } else {
alan-bakerc9666712020-04-01 16:31:21 -04004598 Ops << MkNum(i);
David Neto22f144c2017-06-12 14:26:21 -04004599 }
4600 }
4601
David Neto87846742018-04-11 17:36:22 -04004602 auto *Inst = new SPIRVInstruction(spv::OpVectorShuffle, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004603 SPIRVInstList.push_back(Inst);
4604 break;
4605 }
4606 case Instruction::ICmp:
4607 case Instruction::FCmp: {
4608 CmpInst *CmpI = cast<CmpInst>(&I);
4609
David Netod4ca2e62017-07-06 18:47:35 -04004610 // Pointer equality is invalid.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004611 Type *ArgTy = CmpI->getOperand(0)->getType();
David Netod4ca2e62017-07-06 18:47:35 -04004612 if (isa<PointerType>(ArgTy)) {
4613 CmpI->print(errs());
alan-baker21574d32020-01-29 16:00:31 -05004614 std::string name = I.getParent()->getParent()->getName().str();
David Netod4ca2e62017-07-06 18:47:35 -04004615 errs()
4616 << "\nPointer equality test is not supported by SPIR-V for Vulkan, "
4617 << "in function " << name << "\n";
4618 llvm_unreachable("Pointer equality check is invalid");
4619 break;
4620 }
4621
David Neto257c3892018-04-11 13:19:45 -04004622 // Ops[0] = Result Type ID
4623 // Ops[1] = Operand 1 ID
4624 // Ops[2] = Operand 2 ID
4625 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04004626
David Neto257c3892018-04-11 13:19:45 -04004627 Ops << MkId(lookupType(CmpI->getType())) << MkId(VMap[CmpI->getOperand(0)])
4628 << MkId(VMap[CmpI->getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004629
4630 spv::Op Opcode = GetSPIRVCmpOpcode(CmpI);
David Neto87846742018-04-11 17:36:22 -04004631 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004632 SPIRVInstList.push_back(Inst);
4633 break;
4634 }
4635 case Instruction::Br: {
4636 // Branch instrucion is deferred because it needs label's ID. Record slot's
4637 // location on SPIRVInstructionList.
4638 DeferredInsts.push_back(
4639 std::make_tuple(&I, --SPIRVInstList.end(), 0 /* No id */));
4640 break;
4641 }
4642 case Instruction::Switch: {
4643 I.print(errs());
4644 llvm_unreachable("Unsupported instruction???");
4645 break;
4646 }
4647 case Instruction::IndirectBr: {
4648 I.print(errs());
4649 llvm_unreachable("Unsupported instruction???");
4650 break;
4651 }
4652 case Instruction::PHI: {
4653 // Branch instrucion is deferred because it needs label's ID. Record slot's
4654 // location on SPIRVInstructionList.
4655 DeferredInsts.push_back(
4656 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4657 break;
4658 }
4659 case Instruction::Alloca: {
4660 //
4661 // Generate OpVariable.
4662 //
4663 // Ops[0] : Result Type ID
4664 // Ops[1] : Storage Class
4665 SPIRVOperandList Ops;
4666
David Neto257c3892018-04-11 13:19:45 -04004667 Ops << MkId(lookupType(I.getType())) << MkNum(spv::StorageClassFunction);
David Neto22f144c2017-06-12 14:26:21 -04004668
David Neto87846742018-04-11 17:36:22 -04004669 auto *Inst = new SPIRVInstruction(spv::OpVariable, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004670 SPIRVInstList.push_back(Inst);
4671 break;
4672 }
4673 case Instruction::Load: {
4674 LoadInst *LD = cast<LoadInst>(&I);
4675 //
4676 // Generate OpLoad.
4677 //
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04004678
alan-baker5b86ed72019-02-15 08:26:50 -05004679 if (LD->getType()->isPointerTy()) {
4680 // Loading a pointer requires variable pointers.
4681 setVariablePointersCapabilities(LD->getType()->getPointerAddressSpace());
4682 }
David Neto22f144c2017-06-12 14:26:21 -04004683
David Neto0a2f98d2017-09-15 19:38:40 -04004684 uint32_t ResTyID = lookupType(LD->getType());
David Netoa60b00b2017-09-15 16:34:09 -04004685 uint32_t PointerID = VMap[LD->getPointerOperand()];
4686
4687 // This is a hack to work around what looks like a driver bug.
4688 // When we're loading from the special variable holding the WorkgroupSize
David Neto0a2f98d2017-09-15 19:38:40 -04004689 // builtin value, use an OpBitWiseAnd of the value's ID rather than
4690 // generating a load.
David Neto66cfe642018-03-24 06:13:56 -07004691 // TODO(dneto): Remove this awful hack once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -04004692 if (PointerID == WorkgroupSizeVarID) {
David Neto0a2f98d2017-09-15 19:38:40 -04004693 // Generate a bitwise-and of the original value with itself.
4694 // We should have been able to get away with just an OpCopyObject,
4695 // but we need something more complex to get past certain driver bugs.
4696 // This is ridiculous, but necessary.
4697 // TODO(dneto): Revisit this once drivers fix their bugs.
4698
4699 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004700 Ops << MkId(ResTyID) << MkId(WorkgroupSizeValueID)
4701 << MkId(WorkgroupSizeValueID);
David Neto0a2f98d2017-09-15 19:38:40 -04004702
David Neto87846742018-04-11 17:36:22 -04004703 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto0a2f98d2017-09-15 19:38:40 -04004704 SPIRVInstList.push_back(Inst);
David Netoa60b00b2017-09-15 16:34:09 -04004705 break;
4706 }
4707
4708 // This is the normal path. Generate a load.
4709
David Neto22f144c2017-06-12 14:26:21 -04004710 // Ops[0] = Result Type ID
4711 // Ops[1] = Pointer ID
4712 // Ops[2] ... Ops[n] = Optional Memory Access
4713 //
4714 // TODO: Do we need to implement Optional Memory Access???
David Neto0a2f98d2017-09-15 19:38:40 -04004715
David Neto22f144c2017-06-12 14:26:21 -04004716 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004717 Ops << MkId(ResTyID) << MkId(PointerID);
David Neto22f144c2017-06-12 14:26:21 -04004718
David Neto87846742018-04-11 17:36:22 -04004719 auto *Inst = new SPIRVInstruction(spv::OpLoad, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004720 SPIRVInstList.push_back(Inst);
4721 break;
4722 }
4723 case Instruction::Store: {
4724 StoreInst *ST = cast<StoreInst>(&I);
4725 //
4726 // Generate OpStore.
4727 //
4728
alan-baker5b86ed72019-02-15 08:26:50 -05004729 if (ST->getValueOperand()->getType()->isPointerTy()) {
4730 // Storing a pointer requires variable pointers.
4731 setVariablePointersCapabilities(
4732 ST->getValueOperand()->getType()->getPointerAddressSpace());
4733 }
4734
David Neto22f144c2017-06-12 14:26:21 -04004735 // Ops[0] = Pointer ID
4736 // Ops[1] = Object ID
4737 // Ops[2] ... Ops[n] = Optional Memory Access (later???)
4738 //
4739 // TODO: Do we need to implement Optional Memory Access???
David Neto257c3892018-04-11 13:19:45 -04004740 SPIRVOperandList Ops;
4741 Ops << MkId(VMap[ST->getPointerOperand()])
4742 << MkId(VMap[ST->getValueOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04004743
David Neto87846742018-04-11 17:36:22 -04004744 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004745 SPIRVInstList.push_back(Inst);
4746 break;
4747 }
4748 case Instruction::AtomicCmpXchg: {
4749 I.print(errs());
4750 llvm_unreachable("Unsupported instruction???");
4751 break;
4752 }
4753 case Instruction::AtomicRMW: {
Neil Henning39672102017-09-29 14:33:13 +01004754 AtomicRMWInst *AtomicRMW = dyn_cast<AtomicRMWInst>(&I);
4755
4756 spv::Op opcode;
4757
4758 switch (AtomicRMW->getOperation()) {
4759 default:
4760 I.print(errs());
4761 llvm_unreachable("Unsupported instruction???");
4762 case llvm::AtomicRMWInst::Add:
4763 opcode = spv::OpAtomicIAdd;
4764 break;
4765 case llvm::AtomicRMWInst::Sub:
4766 opcode = spv::OpAtomicISub;
4767 break;
4768 case llvm::AtomicRMWInst::Xchg:
4769 opcode = spv::OpAtomicExchange;
4770 break;
4771 case llvm::AtomicRMWInst::Min:
4772 opcode = spv::OpAtomicSMin;
4773 break;
4774 case llvm::AtomicRMWInst::Max:
4775 opcode = spv::OpAtomicSMax;
4776 break;
4777 case llvm::AtomicRMWInst::UMin:
4778 opcode = spv::OpAtomicUMin;
4779 break;
4780 case llvm::AtomicRMWInst::UMax:
4781 opcode = spv::OpAtomicUMax;
4782 break;
4783 case llvm::AtomicRMWInst::And:
4784 opcode = spv::OpAtomicAnd;
4785 break;
4786 case llvm::AtomicRMWInst::Or:
4787 opcode = spv::OpAtomicOr;
4788 break;
4789 case llvm::AtomicRMWInst::Xor:
4790 opcode = spv::OpAtomicXor;
4791 break;
4792 }
4793
4794 //
4795 // Generate OpAtomic*.
4796 //
4797 SPIRVOperandList Ops;
4798
David Neto257c3892018-04-11 13:19:45 -04004799 Ops << MkId(lookupType(I.getType()))
4800 << MkId(VMap[AtomicRMW->getPointerOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004801
4802 auto IntTy = Type::getInt32Ty(I.getContext());
Neil Henning39672102017-09-29 14:33:13 +01004803 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
David Neto257c3892018-04-11 13:19:45 -04004804 Ops << MkId(VMap[ConstantScopeDevice]);
Neil Henning39672102017-09-29 14:33:13 +01004805
4806 const auto ConstantMemorySemantics = ConstantInt::get(
4807 IntTy, spv::MemorySemanticsUniformMemoryMask |
4808 spv::MemorySemanticsSequentiallyConsistentMask);
David Neto257c3892018-04-11 13:19:45 -04004809 Ops << MkId(VMap[ConstantMemorySemantics]);
Neil Henning39672102017-09-29 14:33:13 +01004810
David Neto257c3892018-04-11 13:19:45 -04004811 Ops << MkId(VMap[AtomicRMW->getValOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004812
4813 VMap[&I] = nextID;
4814
David Neto87846742018-04-11 17:36:22 -04004815 auto *Inst = new SPIRVInstruction(opcode, nextID++, Ops);
Neil Henning39672102017-09-29 14:33:13 +01004816 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04004817 break;
4818 }
4819 case Instruction::Fence: {
4820 I.print(errs());
4821 llvm_unreachable("Unsupported instruction???");
4822 break;
4823 }
4824 case Instruction::Call: {
4825 CallInst *Call = dyn_cast<CallInst>(&I);
4826 Function *Callee = Call->getCalledFunction();
4827
Alan Baker202c8c72018-08-13 13:47:44 -04004828 if (Callee->getName().startswith(clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04004829 if (ResourceVarDeferredLoadCalls.count(Call) && Call->hasNUsesOrMore(1)) {
4830 // Generate an OpLoad
4831 SPIRVOperandList Ops;
4832 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004833
David Neto862b7d82018-06-14 18:48:37 -04004834 Ops << MkId(lookupType(Call->getType()->getPointerElementType()))
4835 << MkId(ResourceVarDeferredLoadCalls[Call]);
4836
4837 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
4838 SPIRVInstList.push_back(Inst);
4839 VMap[Call] = load_id;
4840 break;
4841
4842 } else {
4843 // This maps to an OpVariable we've already generated.
4844 // No code is generated for the call.
4845 }
4846 break;
alan-bakerb6b09dc2018-11-08 16:59:28 -05004847 } else if (Callee->getName().startswith(
4848 clspv::WorkgroupAccessorFunction())) {
Alan Baker202c8c72018-08-13 13:47:44 -04004849 // Don't codegen an instruction here, but instead map this call directly
4850 // to the workgroup variable id.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004851 int spec_id = static_cast<int>(
4852 cast<ConstantInt>(Call->getOperand(0))->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04004853 const auto &info = LocalSpecIdInfoMap[spec_id];
4854 VMap[Call] = info.variable_id;
4855 break;
David Neto862b7d82018-06-14 18:48:37 -04004856 }
4857
4858 // Sampler initializers become a load of the corresponding sampler.
4859
Kévin Petitdf71de32019-04-09 14:09:50 +01004860 if (Callee->getName().equals(clspv::LiteralSamplerFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04004861 // Map this to a load from the variable.
alan-baker09cb9802019-12-10 13:16:27 -05004862 const auto third_param = static_cast<unsigned>(
4863 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue());
4864 auto sampler_value = third_param;
4865 if (clspv::Option::UseSamplerMap()) {
4866 sampler_value = getSamplerMap()[third_param].first;
4867 }
David Neto862b7d82018-06-14 18:48:37 -04004868
4869 // Generate an OpLoad
David Neto22f144c2017-06-12 14:26:21 -04004870 SPIRVOperandList Ops;
David Neto862b7d82018-06-14 18:48:37 -04004871 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004872
David Neto257c3892018-04-11 13:19:45 -04004873 Ops << MkId(lookupType(SamplerTy->getPointerElementType()))
alan-baker09cb9802019-12-10 13:16:27 -05004874 << MkId(SamplerLiteralToIDMap[sampler_value]);
David Neto22f144c2017-06-12 14:26:21 -04004875
David Neto862b7d82018-06-14 18:48:37 -04004876 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004877 SPIRVInstList.push_back(Inst);
David Neto862b7d82018-06-14 18:48:37 -04004878 VMap[Call] = load_id;
David Neto22f144c2017-06-12 14:26:21 -04004879 break;
4880 }
4881
Kévin Petit349c9502019-03-28 17:24:14 +00004882 // Handle SPIR-V intrinsics
Kévin Petit9b340262019-06-19 18:31:11 +01004883 spv::Op opcode = StringSwitch<spv::Op>(Callee->getName())
4884 .Case("spirv.atomic_xor", spv::OpAtomicXor)
4885 .Default(spv::OpNop);
David Neto22f144c2017-06-12 14:26:21 -04004886
Kévin Petit617a76d2019-04-04 13:54:16 +01004887 // If the switch above didn't have an entry maybe the intrinsic
4888 // is using the name mangling logic.
4889 bool usesMangler = false;
4890 if (opcode == spv::OpNop) {
4891 if (Callee->getName().startswith(clspv::SPIRVOpIntrinsicFunction())) {
4892 auto OpCst = cast<ConstantInt>(Call->getOperand(0));
4893 opcode = static_cast<spv::Op>(OpCst->getZExtValue());
4894 usesMangler = true;
4895 }
4896 }
4897
Kévin Petit349c9502019-03-28 17:24:14 +00004898 if (opcode != spv::OpNop) {
4899
David Neto22f144c2017-06-12 14:26:21 -04004900 SPIRVOperandList Ops;
4901
Kévin Petit349c9502019-03-28 17:24:14 +00004902 if (!I.getType()->isVoidTy()) {
4903 Ops << MkId(lookupType(I.getType()));
4904 }
David Neto22f144c2017-06-12 14:26:21 -04004905
Kévin Petit617a76d2019-04-04 13:54:16 +01004906 unsigned firstOperand = usesMangler ? 1 : 0;
4907 for (unsigned i = firstOperand; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004908 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004909 }
4910
Kévin Petit349c9502019-03-28 17:24:14 +00004911 if (!I.getType()->isVoidTy()) {
4912 VMap[&I] = nextID;
Kévin Petit8a560882019-03-21 15:24:34 +00004913 }
4914
Kévin Petit349c9502019-03-28 17:24:14 +00004915 SPIRVInstruction *Inst;
4916 if (!I.getType()->isVoidTy()) {
4917 Inst = new SPIRVInstruction(opcode, nextID++, Ops);
4918 } else {
4919 Inst = new SPIRVInstruction(opcode, Ops);
4920 }
Kévin Petit8a560882019-03-21 15:24:34 +00004921 SPIRVInstList.push_back(Inst);
4922 break;
4923 }
4924
David Neto22f144c2017-06-12 14:26:21 -04004925 // spirv.copy_memory.* intrinsics become OpMemoryMemory's.
4926 if (Callee->getName().startswith("spirv.copy_memory")) {
4927 //
4928 // Generate OpCopyMemory.
4929 //
4930
4931 // Ops[0] = Dst ID
4932 // Ops[1] = Src ID
4933 // Ops[2] = Memory Access
4934 // Ops[3] = Alignment
4935
4936 auto IsVolatile =
4937 dyn_cast<ConstantInt>(Call->getArgOperand(3))->getZExtValue() != 0;
4938
4939 auto VolatileMemoryAccess = (IsVolatile) ? spv::MemoryAccessVolatileMask
4940 : spv::MemoryAccessMaskNone;
4941
4942 auto MemoryAccess = VolatileMemoryAccess | spv::MemoryAccessAlignedMask;
4943
4944 auto Alignment =
4945 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4946
David Neto257c3892018-04-11 13:19:45 -04004947 SPIRVOperandList Ops;
4948 Ops << MkId(VMap[Call->getArgOperand(0)])
4949 << MkId(VMap[Call->getArgOperand(1)]) << MkNum(MemoryAccess)
4950 << MkNum(static_cast<uint32_t>(Alignment));
David Neto22f144c2017-06-12 14:26:21 -04004951
David Neto87846742018-04-11 17:36:22 -04004952 auto *Inst = new SPIRVInstruction(spv::OpCopyMemory, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004953
4954 SPIRVInstList.push_back(Inst);
4955
4956 break;
4957 }
4958
SJW2c317da2020-03-23 07:39:13 -05004959 // read_image is converted to OpSampledImage and OpImageSampleExplicitLod.
4960 // Additionally, OpTypeSampledImage is generated.
SJW173c7e92020-03-16 08:44:47 -05004961 if (IsSampledImageRead(Callee)) {
David Neto22f144c2017-06-12 14:26:21 -04004962 //
4963 // Generate OpSampledImage.
4964 //
4965 // Ops[0] = Result Type ID
4966 // Ops[1] = Image ID
4967 // Ops[2] = Sampler ID
4968 //
4969 SPIRVOperandList Ops;
4970
4971 Value *Image = Call->getArgOperand(0);
4972 Value *Sampler = Call->getArgOperand(1);
4973 Value *Coordinate = Call->getArgOperand(2);
4974
4975 TypeMapType &OpImageTypeMap = getImageTypeMap();
4976 Type *ImageTy = Image->getType()->getPointerElementType();
4977 uint32_t ImageTyID = OpImageTypeMap[ImageTy];
David Neto22f144c2017-06-12 14:26:21 -04004978 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004979 uint32_t SamplerID = VMap[Sampler];
David Neto257c3892018-04-11 13:19:45 -04004980
4981 Ops << MkId(ImageTyID) << MkId(ImageID) << MkId(SamplerID);
David Neto22f144c2017-06-12 14:26:21 -04004982
4983 uint32_t SampledImageID = nextID;
4984
David Neto87846742018-04-11 17:36:22 -04004985 auto *Inst = new SPIRVInstruction(spv::OpSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004986 SPIRVInstList.push_back(Inst);
4987
4988 //
4989 // Generate OpImageSampleExplicitLod.
4990 //
4991 // Ops[0] = Result Type ID
4992 // Ops[1] = Sampled Image ID
4993 // Ops[2] = Coordinate ID
4994 // Ops[3] = Image Operands Type ID
4995 // Ops[4] ... Ops[n] = Operands ID
4996 //
4997 Ops.clear();
4998
alan-bakerf67468c2019-11-25 15:51:49 -05004999 const bool is_int_image = IsIntImageType(Image->getType());
5000 uint32_t result_type = 0;
5001 if (is_int_image) {
5002 result_type = v4int32ID;
5003 } else {
5004 result_type = lookupType(Call->getType());
5005 }
5006
5007 Ops << MkId(result_type) << MkId(SampledImageID) << MkId(VMap[Coordinate])
5008 << MkNum(spv::ImageOperandsLodMask);
David Neto22f144c2017-06-12 14:26:21 -04005009
5010 Constant *CstFP0 = ConstantFP::get(Context, APFloat(0.0f));
David Neto257c3892018-04-11 13:19:45 -04005011 Ops << MkId(VMap[CstFP0]);
David Neto22f144c2017-06-12 14:26:21 -04005012
alan-bakerf67468c2019-11-25 15:51:49 -05005013 uint32_t final_id = nextID++;
5014 VMap[&I] = final_id;
David Neto22f144c2017-06-12 14:26:21 -04005015
alan-bakerf67468c2019-11-25 15:51:49 -05005016 uint32_t image_id = final_id;
5017 if (is_int_image) {
5018 // Int image requires a bitcast from v4int to v4uint.
5019 image_id = nextID++;
5020 }
5021
5022 Inst = new SPIRVInstruction(spv::OpImageSampleExplicitLod, image_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04005023 SPIRVInstList.push_back(Inst);
alan-bakerf67468c2019-11-25 15:51:49 -05005024
5025 if (is_int_image) {
5026 // Generate the bitcast.
5027 Ops.clear();
5028 Ops << MkId(lookupType(Call->getType())) << MkId(image_id);
5029 Inst = new SPIRVInstruction(spv::OpBitcast, final_id, Ops);
5030 SPIRVInstList.push_back(Inst);
5031 }
David Neto22f144c2017-06-12 14:26:21 -04005032 break;
5033 }
5034
alan-baker75090e42020-02-20 11:21:04 -05005035 // read_image (without a sampler) is mapped to OpImageFetch.
SJW173c7e92020-03-16 08:44:47 -05005036 if (IsUnsampledImageRead(Callee)) {
alan-baker75090e42020-02-20 11:21:04 -05005037 Value *Image = Call->getArgOperand(0);
5038 Value *Coordinate = Call->getArgOperand(1);
5039
5040 //
5041 // Generate OpImageFetch
5042 //
5043 // Ops[0] = Result Type ID
5044 // Ops[1] = Image ID
5045 // Ops[2] = Coordinate ID
5046 // Ops[3] = Lod
5047 // Ops[4] = 0
5048 //
5049 SPIRVOperandList Ops;
5050
5051 const bool is_int_image = IsIntImageType(Image->getType());
5052 uint32_t result_type = 0;
5053 if (is_int_image) {
5054 result_type = v4int32ID;
5055 } else {
5056 result_type = lookupType(Call->getType());
5057 }
5058
5059 Ops << MkId(result_type) << MkId(VMap[Image]) << MkId(VMap[Coordinate])
5060 << MkNum(spv::ImageOperandsLodMask);
5061
5062 Constant *CstInt0 = ConstantInt::get(Context, APInt(32, 0));
5063 Ops << MkId(VMap[CstInt0]);
5064
5065 uint32_t final_id = nextID++;
5066 VMap[&I] = final_id;
5067
5068 uint32_t image_id = final_id;
5069 if (is_int_image) {
5070 // Int image requires a bitcast from v4int to v4uint.
5071 image_id = nextID++;
5072 }
5073
5074 auto *Inst = new SPIRVInstruction(spv::OpImageFetch, image_id, Ops);
5075 SPIRVInstList.push_back(Inst);
5076
5077 if (is_int_image) {
5078 // Generate the bitcast.
5079 Ops.clear();
5080 Ops << MkId(lookupType(Call->getType())) << MkId(image_id);
5081 Inst = new SPIRVInstruction(spv::OpBitcast, final_id, Ops);
5082 SPIRVInstList.push_back(Inst);
5083 }
5084 break;
5085 }
5086
alan-bakerf67468c2019-11-25 15:51:49 -05005087 // write_image is mapped to OpImageWrite.
SJW173c7e92020-03-16 08:44:47 -05005088 if (IsImageWrite(Callee)) {
David Neto22f144c2017-06-12 14:26:21 -04005089 //
5090 // Generate OpImageWrite.
5091 //
5092 // Ops[0] = Image ID
5093 // Ops[1] = Coordinate ID
5094 // Ops[2] = Texel ID
5095 // Ops[3] = (Optional) Image Operands Type (Literal Number)
5096 // Ops[4] ... Ops[n] = (Optional) Operands ID
5097 //
5098 SPIRVOperandList Ops;
5099
5100 Value *Image = Call->getArgOperand(0);
5101 Value *Coordinate = Call->getArgOperand(1);
5102 Value *Texel = Call->getArgOperand(2);
5103
5104 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04005105 uint32_t CoordinateID = VMap[Coordinate];
David Neto22f144c2017-06-12 14:26:21 -04005106 uint32_t TexelID = VMap[Texel];
alan-bakerf67468c2019-11-25 15:51:49 -05005107
5108 const bool is_int_image = IsIntImageType(Image->getType());
5109 if (is_int_image) {
5110 // Generate a bitcast to v4int and use it as the texel value.
5111 uint32_t castID = nextID++;
5112 Ops << MkId(v4int32ID) << MkId(TexelID);
5113 auto cast = new SPIRVInstruction(spv::OpBitcast, castID, Ops);
5114 SPIRVInstList.push_back(cast);
5115 Ops.clear();
5116 TexelID = castID;
5117 }
David Neto257c3892018-04-11 13:19:45 -04005118 Ops << MkId(ImageID) << MkId(CoordinateID) << MkId(TexelID);
David Neto22f144c2017-06-12 14:26:21 -04005119
David Neto87846742018-04-11 17:36:22 -04005120 auto *Inst = new SPIRVInstruction(spv::OpImageWrite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04005121 SPIRVInstList.push_back(Inst);
5122 break;
5123 }
5124
alan-bakerce179f12019-12-06 19:02:22 -05005125 // get_image_* is mapped to OpImageQuerySize or OpImageQuerySizeLod
SJW173c7e92020-03-16 08:44:47 -05005126 if (IsImageQuery(Callee)) {
David Neto5c22a252018-03-15 16:07:41 -04005127 //
alan-bakerce179f12019-12-06 19:02:22 -05005128 // Generate OpImageQuerySize[Lod]
David Neto5c22a252018-03-15 16:07:41 -04005129 //
5130 // Ops[0] = Image ID
5131 //
alan-bakerce179f12019-12-06 19:02:22 -05005132 // Result type has components equal to the dimensionality of the image,
5133 // plus 1 if the image is arrayed.
5134 //
alan-bakerf906d2b2019-12-10 11:26:23 -05005135 // %sizes = OpImageQuerySize[Lod] %uint[2|3|4] %im [%uint_0]
David Neto5c22a252018-03-15 16:07:41 -04005136 SPIRVOperandList Ops;
5137
5138 // Implement:
alan-bakerce179f12019-12-06 19:02:22 -05005139 // %sizes = OpImageQuerySize[Lod] %uint[2|3|4] %im [%uint_0]
5140 uint32_t SizesTypeID = 0;
5141
David Neto5c22a252018-03-15 16:07:41 -04005142 Value *Image = Call->getArgOperand(0);
alan-bakerce179f12019-12-06 19:02:22 -05005143 const uint32_t dim = ImageDimensionality(Image->getType());
alan-baker7150a1d2020-02-25 08:31:06 -05005144 const uint32_t components =
5145 dim + (IsArrayImageType(Image->getType()) ? 1 : 0);
alan-bakerce179f12019-12-06 19:02:22 -05005146 if (components == 1) {
alan-bakerce179f12019-12-06 19:02:22 -05005147 SizesTypeID = TypeMap[Type::getInt32Ty(Context)];
5148 } else {
alan-baker7150a1d2020-02-25 08:31:06 -05005149 SizesTypeID =
5150 TypeMap[VectorType::get(Type::getInt32Ty(Context), components)];
alan-bakerce179f12019-12-06 19:02:22 -05005151 }
David Neto5c22a252018-03-15 16:07:41 -04005152 uint32_t ImageID = VMap[Image];
David Neto257c3892018-04-11 13:19:45 -04005153 Ops << MkId(SizesTypeID) << MkId(ImageID);
alan-bakerce179f12019-12-06 19:02:22 -05005154 spv::Op query_opcode = spv::OpImageQuerySize;
SJW173c7e92020-03-16 08:44:47 -05005155 if (IsSampledImageType(Image->getType())) {
alan-bakerce179f12019-12-06 19:02:22 -05005156 query_opcode = spv::OpImageQuerySizeLod;
5157 // Need explicit 0 for Lod operand.
5158 Constant *CstInt0 = ConstantInt::get(Context, APInt(32, 0));
5159 Ops << MkId(VMap[CstInt0]);
5160 }
David Neto5c22a252018-03-15 16:07:41 -04005161
5162 uint32_t SizesID = nextID++;
alan-bakerce179f12019-12-06 19:02:22 -05005163 auto *QueryInst = new SPIRVInstruction(query_opcode, SizesID, Ops);
David Neto5c22a252018-03-15 16:07:41 -04005164 SPIRVInstList.push_back(QueryInst);
5165
alan-bakerce179f12019-12-06 19:02:22 -05005166 // May require an extra instruction to create the appropriate result of
5167 // the builtin function.
SJW173c7e92020-03-16 08:44:47 -05005168 if (IsGetImageDim(Callee)) {
alan-bakerce179f12019-12-06 19:02:22 -05005169 if (dim == 3) {
5170 // get_image_dim returns an int4 for 3D images.
5171 //
5172 // Reset value map entry since we generated an intermediate
5173 // instruction.
5174 VMap[&I] = nextID;
David Neto5c22a252018-03-15 16:07:41 -04005175
alan-bakerce179f12019-12-06 19:02:22 -05005176 // Implement:
5177 // %result = OpCompositeConstruct %uint4 %sizes %uint_0
5178 Ops.clear();
5179 Ops << MkId(lookupType(VectorType::get(Type::getInt32Ty(Context), 4)))
5180 << MkId(SizesID);
David Neto5c22a252018-03-15 16:07:41 -04005181
alan-bakerce179f12019-12-06 19:02:22 -05005182 Constant *CstInt0 = ConstantInt::get(Context, APInt(32, 0));
5183 Ops << MkId(VMap[CstInt0]);
David Neto5c22a252018-03-15 16:07:41 -04005184
alan-bakerce179f12019-12-06 19:02:22 -05005185 auto *Inst =
5186 new SPIRVInstruction(spv::OpCompositeConstruct, nextID++, Ops);
5187 SPIRVInstList.push_back(Inst);
5188 } else if (dim != components) {
5189 // get_image_dim return an int2 regardless of the arrayedness of the
5190 // image. If the image is arrayed an element must be dropped from the
5191 // query result.
5192 //
5193 // Reset value map entry since we generated an intermediate
5194 // instruction.
5195 VMap[&I] = nextID;
5196
5197 // Implement:
5198 // %result = OpVectorShuffle %uint2 %sizes %sizes 0 1
5199 Ops.clear();
5200 Ops << MkId(lookupType(VectorType::get(Type::getInt32Ty(Context), 2)))
5201 << MkId(SizesID) << MkId(SizesID) << MkNum(0) << MkNum(1);
5202
5203 auto *Inst =
5204 new SPIRVInstruction(spv::OpVectorShuffle, nextID++, Ops);
5205 SPIRVInstList.push_back(Inst);
5206 }
5207 } else if (components > 1) {
5208 // Reset value map entry since we generated an intermediate instruction.
5209 VMap[&I] = nextID;
5210
5211 // Implement:
5212 // %result = OpCompositeExtract %uint %sizes <component number>
5213 Ops.clear();
5214 Ops << MkId(TypeMap[I.getType()]) << MkId(SizesID);
5215
5216 uint32_t component = 0;
5217 if (IsGetImageHeight(Callee))
5218 component = 1;
5219 else if (IsGetImageDepth(Callee))
5220 component = 2;
5221 Ops << MkNum(component);
5222
5223 auto *Inst =
5224 new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
5225 SPIRVInstList.push_back(Inst);
5226 }
David Neto5c22a252018-03-15 16:07:41 -04005227 break;
5228 }
5229
David Neto22f144c2017-06-12 14:26:21 -04005230 // Call instrucion is deferred because it needs function's ID. Record
5231 // slot's location on SPIRVInstructionList.
5232 DeferredInsts.push_back(
5233 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
5234
David Neto3fbb4072017-10-16 11:28:14 -04005235 // Check whether the implementation of this call uses an extended
5236 // instruction plus one more value-producing instruction. If so, then
5237 // reserve the id for the extra value-producing slot.
5238 glsl::ExtInst EInst = getIndirectExtInstEnum(Callee->getName());
5239 if (EInst != kGlslExtInstBad) {
5240 // Reserve a spot for the extra value.
David Neto4d02a532017-09-17 12:57:44 -04005241 // Increase nextID.
David Neto22f144c2017-06-12 14:26:21 -04005242 VMap[&I] = nextID;
5243 nextID++;
5244 }
5245 break;
5246 }
5247 case Instruction::Ret: {
5248 unsigned NumOps = I.getNumOperands();
5249 if (NumOps == 0) {
5250 //
5251 // Generate OpReturn.
5252 //
David Netoef5ba2b2019-12-20 08:35:54 -05005253 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpReturn));
David Neto22f144c2017-06-12 14:26:21 -04005254 } else {
5255 //
5256 // Generate OpReturnValue.
5257 //
5258
5259 // Ops[0] = Return Value ID
5260 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04005261
5262 Ops << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04005263
David Neto87846742018-04-11 17:36:22 -04005264 auto *Inst = new SPIRVInstruction(spv::OpReturnValue, Ops);
David Neto22f144c2017-06-12 14:26:21 -04005265 SPIRVInstList.push_back(Inst);
5266 break;
5267 }
5268 break;
5269 }
5270 }
5271}
5272
5273void SPIRVProducerPass::GenerateFuncEpilogue() {
SJW69939d52020-04-16 07:29:07 -05005274 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kFunctions);
David Neto22f144c2017-06-12 14:26:21 -04005275
5276 //
5277 // Generate OpFunctionEnd
5278 //
5279
David Netoef5ba2b2019-12-20 08:35:54 -05005280 auto *Inst = new SPIRVInstruction(spv::OpFunctionEnd);
David Neto22f144c2017-06-12 14:26:21 -04005281 SPIRVInstList.push_back(Inst);
5282}
5283
5284bool SPIRVProducerPass::is4xi8vec(Type *Ty) const {
alan-bakerb39c8262019-03-08 14:03:37 -05005285 // Don't specialize <4 x i8> if i8 is generally supported.
5286 if (clspv::Option::Int8Support())
5287 return false;
5288
David Neto22f144c2017-06-12 14:26:21 -04005289 LLVMContext &Context = Ty->getContext();
James Pricecf53df42020-04-20 14:41:24 -04005290 if (auto VecTy = dyn_cast<VectorType>(Ty)) {
5291 if (VecTy->getElementType() == Type::getInt8Ty(Context) &&
5292 VecTy->getNumElements() == 4) {
David Neto22f144c2017-06-12 14:26:21 -04005293 return true;
5294 }
5295 }
5296
5297 return false;
5298}
5299
5300void SPIRVProducerPass::HandleDeferredInstruction() {
SJW69939d52020-04-16 07:29:07 -05005301 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kFunctions);
David Neto22f144c2017-06-12 14:26:21 -04005302 ValueMapType &VMap = getValueMap();
5303 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
5304
5305 for (auto DeferredInst = DeferredInsts.rbegin();
5306 DeferredInst != DeferredInsts.rend(); ++DeferredInst) {
5307 Value *Inst = std::get<0>(*DeferredInst);
5308 SPIRVInstructionList::iterator InsertPoint = ++std::get<1>(*DeferredInst);
5309 if (InsertPoint != SPIRVInstList.end()) {
5310 while ((*InsertPoint)->getOpcode() == spv::OpPhi) {
5311 ++InsertPoint;
5312 }
5313 }
5314
5315 if (BranchInst *Br = dyn_cast<BranchInst>(Inst)) {
alan-baker06cad652019-12-03 17:56:47 -05005316 // Check whether this branch needs to be preceeded by merge instruction.
David Neto22f144c2017-06-12 14:26:21 -04005317 BasicBlock *BrBB = Br->getParent();
alan-baker06cad652019-12-03 17:56:47 -05005318 if (ContinueBlocks.count(BrBB)) {
David Neto22f144c2017-06-12 14:26:21 -04005319 //
5320 // Generate OpLoopMerge.
5321 //
5322 // Ops[0] = Merge Block ID
5323 // Ops[1] = Continue Target ID
5324 // Ops[2] = Selection Control
5325 SPIRVOperandList Ops;
5326
alan-baker06cad652019-12-03 17:56:47 -05005327 auto MergeBB = MergeBlocks[BrBB];
5328 auto ContinueBB = ContinueBlocks[BrBB];
David Neto22f144c2017-06-12 14:26:21 -04005329 uint32_t MergeBBID = VMap[MergeBB];
David Neto22f144c2017-06-12 14:26:21 -04005330 uint32_t ContinueBBID = VMap[ContinueBB];
David Neto257c3892018-04-11 13:19:45 -04005331 Ops << MkId(MergeBBID) << MkId(ContinueBBID)
alan-baker06cad652019-12-03 17:56:47 -05005332 << MkNum(spv::LoopControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04005333
David Neto87846742018-04-11 17:36:22 -04005334 auto *MergeInst = new SPIRVInstruction(spv::OpLoopMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04005335 SPIRVInstList.insert(InsertPoint, MergeInst);
alan-baker06cad652019-12-03 17:56:47 -05005336 } else if (MergeBlocks.count(BrBB)) {
5337 //
5338 // Generate OpSelectionMerge.
5339 //
5340 // Ops[0] = Merge Block ID
5341 // Ops[1] = Selection Control
5342 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04005343
alan-baker06cad652019-12-03 17:56:47 -05005344 auto MergeBB = MergeBlocks[BrBB];
5345 uint32_t MergeBBID = VMap[MergeBB];
5346 Ops << MkId(MergeBBID) << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04005347
alan-baker06cad652019-12-03 17:56:47 -05005348 auto *MergeInst = new SPIRVInstruction(spv::OpSelectionMerge, Ops);
5349 SPIRVInstList.insert(InsertPoint, MergeInst);
David Neto22f144c2017-06-12 14:26:21 -04005350 }
5351
5352 if (Br->isConditional()) {
5353 //
5354 // Generate OpBranchConditional.
5355 //
5356 // Ops[0] = Condition ID
5357 // Ops[1] = True Label ID
5358 // Ops[2] = False Label ID
5359 // Ops[3] ... Ops[n] = Branch weights (Literal Number)
5360 SPIRVOperandList Ops;
5361
5362 uint32_t CondID = VMap[Br->getCondition()];
David Neto22f144c2017-06-12 14:26:21 -04005363 uint32_t TrueBBID = VMap[Br->getSuccessor(0)];
David Neto22f144c2017-06-12 14:26:21 -04005364 uint32_t FalseBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04005365
5366 Ops << MkId(CondID) << MkId(TrueBBID) << MkId(FalseBBID);
David Neto22f144c2017-06-12 14:26:21 -04005367
David Neto87846742018-04-11 17:36:22 -04005368 auto *BrInst = new SPIRVInstruction(spv::OpBranchConditional, Ops);
David Neto22f144c2017-06-12 14:26:21 -04005369 SPIRVInstList.insert(InsertPoint, BrInst);
5370 } else {
5371 //
5372 // Generate OpBranch.
5373 //
5374 // Ops[0] = Target Label ID
5375 SPIRVOperandList Ops;
5376
5377 uint32_t TargetID = VMap[Br->getSuccessor(0)];
David Neto257c3892018-04-11 13:19:45 -04005378 Ops << MkId(TargetID);
David Neto22f144c2017-06-12 14:26:21 -04005379
David Neto87846742018-04-11 17:36:22 -04005380 SPIRVInstList.insert(InsertPoint,
5381 new SPIRVInstruction(spv::OpBranch, Ops));
David Neto22f144c2017-06-12 14:26:21 -04005382 }
5383 } else if (PHINode *PHI = dyn_cast<PHINode>(Inst)) {
alan-baker5ed87542020-03-23 11:05:22 -04005384 if (PHI->getType()->isPointerTy() && !IsSamplerType(PHI->getType()) &&
5385 !IsImageType(PHI->getType())) {
alan-baker5b86ed72019-02-15 08:26:50 -05005386 // OpPhi on pointers requires variable pointers.
5387 setVariablePointersCapabilities(
5388 PHI->getType()->getPointerAddressSpace());
5389 if (!hasVariablePointers() && !selectFromSameObject(PHI)) {
5390 setVariablePointers(true);
5391 }
5392 }
5393
David Neto22f144c2017-06-12 14:26:21 -04005394 //
5395 // Generate OpPhi.
5396 //
5397 // Ops[0] = Result Type ID
5398 // Ops[1] ... Ops[n] = (Variable ID, Parent ID) pairs
5399 SPIRVOperandList Ops;
5400
David Neto257c3892018-04-11 13:19:45 -04005401 Ops << MkId(lookupType(PHI->getType()));
David Neto22f144c2017-06-12 14:26:21 -04005402
David Neto22f144c2017-06-12 14:26:21 -04005403 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
5404 uint32_t VarID = VMap[PHI->getIncomingValue(i)];
David Neto22f144c2017-06-12 14:26:21 -04005405 uint32_t ParentID = VMap[PHI->getIncomingBlock(i)];
David Neto257c3892018-04-11 13:19:45 -04005406 Ops << MkId(VarID) << MkId(ParentID);
David Neto22f144c2017-06-12 14:26:21 -04005407 }
5408
5409 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005410 InsertPoint,
5411 new SPIRVInstruction(spv::OpPhi, std::get<2>(*DeferredInst), Ops));
David Neto22f144c2017-06-12 14:26:21 -04005412 } else if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
5413 Function *Callee = Call->getCalledFunction();
SJW2c317da2020-03-23 07:39:13 -05005414 LLVMContext &Context = Callee->getContext();
5415 auto IntTy = Type::getInt32Ty(Context);
5416 auto callee_code = Builtins::Lookup(Callee);
David Neto3fbb4072017-10-16 11:28:14 -04005417 auto callee_name = Callee->getName();
5418 glsl::ExtInst EInst = getDirectOrIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04005419
5420 if (EInst) {
5421 uint32_t &ExtInstImportID = getOpExtInstImportID();
5422
5423 //
5424 // Generate OpExtInst.
5425 //
5426
5427 // Ops[0] = Result Type ID
5428 // Ops[1] = Set ID (OpExtInstImport ID)
5429 // Ops[2] = Instruction Number (Literal Number)
5430 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
5431 SPIRVOperandList Ops;
5432
David Neto862b7d82018-06-14 18:48:37 -04005433 Ops << MkId(lookupType(Call->getType())) << MkId(ExtInstImportID)
5434 << MkNum(EInst);
David Neto22f144c2017-06-12 14:26:21 -04005435
David Neto22f144c2017-06-12 14:26:21 -04005436 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5437 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
David Neto257c3892018-04-11 13:19:45 -04005438 Ops << MkId(VMap[Call->getOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04005439 }
5440
David Neto87846742018-04-11 17:36:22 -04005441 auto *ExtInst = new SPIRVInstruction(spv::OpExtInst,
5442 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04005443 SPIRVInstList.insert(InsertPoint, ExtInst);
5444
David Neto3fbb4072017-10-16 11:28:14 -04005445 const auto IndirectExtInst = getIndirectExtInstEnum(callee_name);
5446 if (IndirectExtInst != kGlslExtInstBad) {
5447 // Generate one more instruction that uses the result of the extended
5448 // instruction. Its result id is one more than the id of the
5449 // extended instruction.
David Neto3fbb4072017-10-16 11:28:14 -04005450 auto generate_extra_inst = [this, &Context, &Call, &DeferredInst,
5451 &VMap, &SPIRVInstList, &InsertPoint](
5452 spv::Op opcode, Constant *constant) {
5453 //
5454 // Generate instruction like:
5455 // result = opcode constant <extinst-result>
5456 //
5457 // Ops[0] = Result Type ID
5458 // Ops[1] = Operand 0 ;; the constant, suitably splatted
5459 // Ops[2] = Operand 1 ;; the result of the extended instruction
5460 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04005461
David Neto3fbb4072017-10-16 11:28:14 -04005462 Type *resultTy = Call->getType();
David Neto257c3892018-04-11 13:19:45 -04005463 Ops << MkId(lookupType(resultTy));
David Neto3fbb4072017-10-16 11:28:14 -04005464
5465 if (auto *vectorTy = dyn_cast<VectorType>(resultTy)) {
5466 constant = ConstantVector::getSplat(
alan-baker7261e062020-03-15 14:35:48 -04005467 {static_cast<unsigned>(vectorTy->getNumElements()), false},
5468 constant);
David Neto3fbb4072017-10-16 11:28:14 -04005469 }
David Neto257c3892018-04-11 13:19:45 -04005470 Ops << MkId(VMap[constant]) << MkId(std::get<2>(*DeferredInst));
David Neto3fbb4072017-10-16 11:28:14 -04005471
5472 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005473 InsertPoint, new SPIRVInstruction(
5474 opcode, std::get<2>(*DeferredInst) + 1, Ops));
David Neto3fbb4072017-10-16 11:28:14 -04005475 };
5476
5477 switch (IndirectExtInst) {
5478 case glsl::ExtInstFindUMsb: // Implementing clz
SJW2c317da2020-03-23 07:39:13 -05005479 generate_extra_inst(spv::OpISub, ConstantInt::get(IntTy, 31));
David Neto3fbb4072017-10-16 11:28:14 -04005480 break;
5481 case glsl::ExtInstAcos: // Implementing acospi
5482 case glsl::ExtInstAsin: // Implementing asinpi
Kévin Petiteb9f90a2018-09-29 12:29:34 +01005483 case glsl::ExtInstAtan: // Implementing atanpi
David Neto3fbb4072017-10-16 11:28:14 -04005484 case glsl::ExtInstAtan2: // Implementing atan2pi
5485 generate_extra_inst(
5486 spv::OpFMul,
5487 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
5488 break;
5489
5490 default:
5491 assert(false && "internally inconsistent");
David Neto4d02a532017-09-17 12:57:44 -04005492 }
David Neto22f144c2017-06-12 14:26:21 -04005493 }
David Neto3fbb4072017-10-16 11:28:14 -04005494
SJW2c317da2020-03-23 07:39:13 -05005495 } else if (callee_code == Builtins::kPopcount) {
David Neto22f144c2017-06-12 14:26:21 -04005496 //
5497 // Generate OpBitCount
5498 //
5499 // Ops[0] = Result Type ID
5500 // Ops[1] = Base ID
David Neto257c3892018-04-11 13:19:45 -04005501 SPIRVOperandList Ops;
5502 Ops << MkId(lookupType(Call->getType()))
5503 << MkId(VMap[Call->getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04005504
5505 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005506 InsertPoint, new SPIRVInstruction(spv::OpBitCount,
David Neto22f144c2017-06-12 14:26:21 -04005507 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005508
David Neto862b7d82018-06-14 18:48:37 -04005509 } else if (callee_name.startswith(kCompositeConstructFunctionPrefix)) {
David Netoab03f432017-11-03 17:00:44 -04005510
5511 // Generate an OpCompositeConstruct
5512 SPIRVOperandList Ops;
5513
5514 // The result type.
David Neto257c3892018-04-11 13:19:45 -04005515 Ops << MkId(lookupType(Call->getType()));
David Netoab03f432017-11-03 17:00:44 -04005516
5517 for (Use &use : Call->arg_operands()) {
David Neto257c3892018-04-11 13:19:45 -04005518 Ops << MkId(VMap[use.get()]);
David Netoab03f432017-11-03 17:00:44 -04005519 }
5520
5521 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005522 InsertPoint, new SPIRVInstruction(spv::OpCompositeConstruct,
5523 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005524
Alan Baker202c8c72018-08-13 13:47:44 -04005525 } else if (callee_name.startswith(clspv::ResourceAccessorFunction())) {
5526
5527 // We have already mapped the call's result value to an ID.
5528 // Don't generate any code now.
5529
5530 } else if (callee_name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04005531
5532 // We have already mapped the call's result value to an ID.
5533 // Don't generate any code now.
5534
David Neto22f144c2017-06-12 14:26:21 -04005535 } else {
alan-baker5b86ed72019-02-15 08:26:50 -05005536 if (Call->getType()->isPointerTy()) {
5537 // Functions returning pointers require variable pointers.
5538 setVariablePointersCapabilities(
5539 Call->getType()->getPointerAddressSpace());
5540 }
5541
David Neto22f144c2017-06-12 14:26:21 -04005542 //
5543 // Generate OpFunctionCall.
5544 //
5545
5546 // Ops[0] = Result Type ID
5547 // Ops[1] = Callee Function ID
5548 // Ops[2] ... Ops[n] = Argument 0, ... , Argument n
5549 SPIRVOperandList Ops;
5550
David Neto862b7d82018-06-14 18:48:37 -04005551 Ops << MkId(lookupType(Call->getType()));
David Neto22f144c2017-06-12 14:26:21 -04005552
5553 uint32_t CalleeID = VMap[Callee];
David Neto43568eb2017-10-13 18:25:25 -04005554 if (CalleeID == 0) {
5555 errs() << "Can't translate function call. Missing builtin? "
David Neto862b7d82018-06-14 18:48:37 -04005556 << callee_name << " in: " << *Call << "\n";
David Neto43568eb2017-10-13 18:25:25 -04005557 // TODO(dneto): Can we error out? Enabling this llvm_unreachable
5558 // causes an infinite loop. Instead, go ahead and generate
5559 // the bad function call. A validator will catch the 0-Id.
5560 // llvm_unreachable("Can't translate function call");
5561 }
David Neto22f144c2017-06-12 14:26:21 -04005562
David Neto257c3892018-04-11 13:19:45 -04005563 Ops << MkId(CalleeID);
David Neto22f144c2017-06-12 14:26:21 -04005564
David Neto22f144c2017-06-12 14:26:21 -04005565 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5566 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
alan-baker5b86ed72019-02-15 08:26:50 -05005567 auto *operand = Call->getOperand(i);
alan-bakerd4d50652019-12-03 17:17:15 -05005568 auto *operand_type = operand->getType();
5569 // Images and samplers can be passed as function parameters without
5570 // variable pointers.
5571 if (operand_type->isPointerTy() && !IsImageType(operand_type) &&
5572 !IsSamplerType(operand_type)) {
alan-baker5b86ed72019-02-15 08:26:50 -05005573 auto sc =
5574 GetStorageClass(operand->getType()->getPointerAddressSpace());
5575 if (sc == spv::StorageClassStorageBuffer) {
5576 // Passing SSBO by reference requires variable pointers storage
5577 // buffer.
5578 setVariablePointersStorageBuffer(true);
5579 } else if (sc == spv::StorageClassWorkgroup) {
5580 // Workgroup references require variable pointers if they are not
5581 // memory object declarations.
5582 if (auto *operand_call = dyn_cast<CallInst>(operand)) {
5583 // Workgroup accessor represents a variable reference.
5584 if (!operand_call->getCalledFunction()->getName().startswith(
5585 clspv::WorkgroupAccessorFunction()))
5586 setVariablePointers(true);
5587 } else {
5588 // Arguments are function parameters.
5589 if (!isa<Argument>(operand))
5590 setVariablePointers(true);
5591 }
5592 }
5593 }
5594 Ops << MkId(VMap[operand]);
David Neto22f144c2017-06-12 14:26:21 -04005595 }
5596
David Neto87846742018-04-11 17:36:22 -04005597 auto *CallInst = new SPIRVInstruction(spv::OpFunctionCall,
5598 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04005599 SPIRVInstList.insert(InsertPoint, CallInst);
5600 }
5601 }
5602 }
5603}
5604
alan-bakera1be3322020-04-20 12:48:18 -04005605void SPIRVProducerPass::HandleDeferredDecorations(Module &module) {
5606 const auto &DL = module.getDataLayout();
Alan Baker202c8c72018-08-13 13:47:44 -04005607 if (getTypesNeedingArrayStride().empty() && LocalArgSpecIds.empty()) {
David Neto1a1a0582017-07-07 12:01:44 -04005608 return;
David Netoc6f3ab22018-04-06 18:02:31 -04005609 }
David Neto1a1a0582017-07-07 12:01:44 -04005610
SJW69939d52020-04-16 07:29:07 -05005611 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kAnnotations);
David Neto1a1a0582017-07-07 12:01:44 -04005612
David Netoc6f3ab22018-04-06 18:02:31 -04005613 // Insert ArrayStride decorations on pointer types, due to OpPtrAccessChain
5614 // instructions we generated earlier.
David Neto85082642018-03-24 06:55:20 -07005615 for (auto *type : getTypesNeedingArrayStride()) {
5616 Type *elemTy = nullptr;
5617 if (auto *ptrTy = dyn_cast<PointerType>(type)) {
5618 elemTy = ptrTy->getElementType();
alan-bakerb6b09dc2018-11-08 16:59:28 -05005619 } else if (auto *arrayTy = dyn_cast<ArrayType>(type)) {
alan-baker8eb435a2020-04-08 00:42:06 -04005620 elemTy = arrayTy->getElementType();
5621 } else if (auto *vecTy = dyn_cast<VectorType>(type)) {
5622 elemTy = vecTy->getElementType();
David Neto85082642018-03-24 06:55:20 -07005623 } else {
5624 errs() << "Unhandled strided type " << *type << "\n";
5625 llvm_unreachable("Unhandled strided type");
5626 }
David Neto1a1a0582017-07-07 12:01:44 -04005627
5628 // Ops[0] = Target ID
5629 // Ops[1] = Decoration (ArrayStride)
5630 // Ops[2] = Stride number (Literal Number)
5631 SPIRVOperandList Ops;
5632
David Neto85082642018-03-24 06:55:20 -07005633 // Same as DL.getIndexedOffsetInType( elemTy, { 1 } );
Alan Bakerfcda9482018-10-02 17:09:59 -04005634 const uint32_t stride = static_cast<uint32_t>(GetTypeAllocSize(elemTy, DL));
David Neto257c3892018-04-11 13:19:45 -04005635
5636 Ops << MkId(lookupType(type)) << MkNum(spv::DecorationArrayStride)
5637 << MkNum(stride);
David Neto1a1a0582017-07-07 12:01:44 -04005638
David Neto87846742018-04-11 17:36:22 -04005639 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
SJW69939d52020-04-16 07:29:07 -05005640 SPIRVInstList.push_back(DecoInst);
David Neto1a1a0582017-07-07 12:01:44 -04005641 }
David Netoc6f3ab22018-04-06 18:02:31 -04005642
5643 // Emit SpecId decorations targeting the array size value.
alan-bakera1be3322020-04-20 12:48:18 -04005644 for (auto pair : clspv::GetSpecConstants(&module)) {
5645 auto kind = pair.first;
5646 auto spec_id = pair.second;
5647
5648 if (kind != SpecConstant::kLocalMemorySize)
5649 continue;
5650
alan-bakerb6b09dc2018-11-08 16:59:28 -05005651 LocalArgInfo &arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04005652 SPIRVOperandList Ops;
5653 Ops << MkId(arg_info.array_size_id) << MkNum(spv::DecorationSpecId)
5654 << MkNum(arg_info.spec_id);
SJW69939d52020-04-16 07:29:07 -05005655 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpDecorate, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04005656 }
David Neto1a1a0582017-07-07 12:01:44 -04005657}
5658
David Neto22f144c2017-06-12 14:26:21 -04005659glsl::ExtInst SPIRVProducerPass::getExtInstEnum(StringRef Name) {
SJW2c317da2020-03-23 07:39:13 -05005660
5661 const auto &fi = Builtins::Lookup(Name);
5662 switch (fi) {
5663 case Builtins::kClamp: {
5664 auto param_type = fi.getParameter(0);
5665 if (param_type.type_id == Type::FloatTyID) {
5666 return glsl::ExtInst::ExtInstFClamp;
5667 }
5668 return param_type.is_signed ? glsl::ExtInst::ExtInstSClamp
5669 : glsl::ExtInst::ExtInstUClamp;
5670 }
5671 case Builtins::kMax: {
5672 auto param_type = fi.getParameter(0);
5673 if (param_type.type_id == Type::FloatTyID) {
5674 return glsl::ExtInst::ExtInstFMax;
5675 }
5676 return param_type.is_signed ? glsl::ExtInst::ExtInstSMax
5677 : glsl::ExtInst::ExtInstUMax;
5678 }
5679 case Builtins::kMin: {
5680 auto param_type = fi.getParameter(0);
5681 if (param_type.type_id == Type::FloatTyID) {
5682 return glsl::ExtInst::ExtInstFMin;
5683 }
5684 return param_type.is_signed ? glsl::ExtInst::ExtInstSMin
5685 : glsl::ExtInst::ExtInstUMin;
5686 }
5687 case Builtins::kAbs:
5688 return glsl::ExtInst::ExtInstSAbs;
5689 case Builtins::kFmax:
5690 return glsl::ExtInst::ExtInstFMax;
5691 case Builtins::kFmin:
5692 return glsl::ExtInst::ExtInstFMin;
5693 case Builtins::kDegrees:
5694 return glsl::ExtInst::ExtInstDegrees;
5695 case Builtins::kRadians:
5696 return glsl::ExtInst::ExtInstRadians;
5697 case Builtins::kMix:
5698 return glsl::ExtInst::ExtInstFMix;
5699 case Builtins::kAcos:
5700 case Builtins::kAcospi:
5701 return glsl::ExtInst::ExtInstAcos;
5702 case Builtins::kAcosh:
5703 return glsl::ExtInst::ExtInstAcosh;
5704 case Builtins::kAsin:
5705 case Builtins::kAsinpi:
5706 return glsl::ExtInst::ExtInstAsin;
5707 case Builtins::kAsinh:
5708 return glsl::ExtInst::ExtInstAsinh;
5709 case Builtins::kAtan:
5710 case Builtins::kAtanpi:
5711 return glsl::ExtInst::ExtInstAtan;
5712 case Builtins::kAtanh:
5713 return glsl::ExtInst::ExtInstAtanh;
5714 case Builtins::kAtan2:
5715 case Builtins::kAtan2pi:
5716 return glsl::ExtInst::ExtInstAtan2;
5717 case Builtins::kCeil:
5718 return glsl::ExtInst::ExtInstCeil;
5719 case Builtins::kSin:
5720 case Builtins::kHalfSin:
5721 case Builtins::kNativeSin:
5722 return glsl::ExtInst::ExtInstSin;
5723 case Builtins::kSinh:
5724 return glsl::ExtInst::ExtInstSinh;
5725 case Builtins::kCos:
5726 case Builtins::kHalfCos:
5727 case Builtins::kNativeCos:
5728 return glsl::ExtInst::ExtInstCos;
5729 case Builtins::kCosh:
5730 return glsl::ExtInst::ExtInstCosh;
5731 case Builtins::kTan:
5732 case Builtins::kHalfTan:
5733 case Builtins::kNativeTan:
5734 return glsl::ExtInst::ExtInstTan;
5735 case Builtins::kTanh:
5736 return glsl::ExtInst::ExtInstTanh;
5737 case Builtins::kExp:
5738 case Builtins::kHalfExp:
5739 case Builtins::kNativeExp:
5740 return glsl::ExtInst::ExtInstExp;
5741 case Builtins::kExp2:
5742 case Builtins::kHalfExp2:
5743 case Builtins::kNativeExp2:
5744 return glsl::ExtInst::ExtInstExp2;
5745 case Builtins::kLog:
5746 case Builtins::kHalfLog:
5747 case Builtins::kNativeLog:
5748 return glsl::ExtInst::ExtInstLog;
5749 case Builtins::kLog2:
5750 case Builtins::kHalfLog2:
5751 case Builtins::kNativeLog2:
5752 return glsl::ExtInst::ExtInstLog2;
5753 case Builtins::kFabs:
5754 return glsl::ExtInst::ExtInstFAbs;
5755 case Builtins::kFma:
5756 return glsl::ExtInst::ExtInstFma;
5757 case Builtins::kFloor:
5758 return glsl::ExtInst::ExtInstFloor;
5759 case Builtins::kLdexp:
5760 return glsl::ExtInst::ExtInstLdexp;
5761 case Builtins::kPow:
5762 case Builtins::kPowr:
5763 case Builtins::kHalfPowr:
5764 case Builtins::kNativePowr:
5765 return glsl::ExtInst::ExtInstPow;
5766 case Builtins::kRound:
5767 return glsl::ExtInst::ExtInstRound;
5768 case Builtins::kSqrt:
5769 case Builtins::kHalfSqrt:
5770 case Builtins::kNativeSqrt:
5771 return glsl::ExtInst::ExtInstSqrt;
5772 case Builtins::kRsqrt:
5773 case Builtins::kHalfRsqrt:
5774 case Builtins::kNativeRsqrt:
5775 return glsl::ExtInst::ExtInstInverseSqrt;
5776 case Builtins::kTrunc:
5777 return glsl::ExtInst::ExtInstTrunc;
5778 case Builtins::kFrexp:
5779 return glsl::ExtInst::ExtInstFrexp;
5780 case Builtins::kFract:
5781 return glsl::ExtInst::ExtInstFract;
5782 case Builtins::kSign:
5783 return glsl::ExtInst::ExtInstFSign;
5784 case Builtins::kLength:
5785 case Builtins::kFastLength:
5786 return glsl::ExtInst::ExtInstLength;
5787 case Builtins::kDistance:
5788 case Builtins::kFastDistance:
5789 return glsl::ExtInst::ExtInstDistance;
5790 case Builtins::kStep:
5791 return glsl::ExtInst::ExtInstStep;
5792 case Builtins::kSmoothstep:
5793 return glsl::ExtInst::ExtInstSmoothStep;
5794 case Builtins::kCross:
5795 return glsl::ExtInst::ExtInstCross;
5796 case Builtins::kNormalize:
5797 case Builtins::kFastNormalize:
5798 return glsl::ExtInst::ExtInstNormalize;
5799 default:
5800 break;
5801 }
5802
David Neto22f144c2017-06-12 14:26:21 -04005803 return StringSwitch<glsl::ExtInst>(Name)
David Neto22f144c2017-06-12 14:26:21 -04005804 .StartsWith("llvm.fmuladd.", glsl::ExtInst::ExtInstFma)
5805 .Case("spirv.unpack.v2f16", glsl::ExtInst::ExtInstUnpackHalf2x16)
5806 .Case("spirv.pack.v2f16", glsl::ExtInst::ExtInstPackHalf2x16)
David Neto3fbb4072017-10-16 11:28:14 -04005807 .Default(kGlslExtInstBad);
5808}
5809
5810glsl::ExtInst SPIRVProducerPass::getIndirectExtInstEnum(StringRef Name) {
SJW2c317da2020-03-23 07:39:13 -05005811 switch (Builtins::Lookup(Name)) {
5812 case Builtins::kClz:
5813 return glsl::ExtInst::ExtInstFindUMsb;
5814 case Builtins::kAcospi:
5815 return glsl::ExtInst::ExtInstAcos;
5816 case Builtins::kAsinpi:
5817 return glsl::ExtInst::ExtInstAsin;
5818 case Builtins::kAtanpi:
5819 return glsl::ExtInst::ExtInstAtan;
5820 case Builtins::kAtan2pi:
5821 return glsl::ExtInst::ExtInstAtan2;
5822 default:
5823 break;
5824 }
5825 return kGlslExtInstBad;
David Neto3fbb4072017-10-16 11:28:14 -04005826}
5827
alan-bakerb6b09dc2018-11-08 16:59:28 -05005828glsl::ExtInst
5829SPIRVProducerPass::getDirectOrIndirectExtInstEnum(StringRef Name) {
David Neto3fbb4072017-10-16 11:28:14 -04005830 auto direct = getExtInstEnum(Name);
5831 if (direct != kGlslExtInstBad)
5832 return direct;
5833 return getIndirectExtInstEnum(Name);
David Neto22f144c2017-06-12 14:26:21 -04005834}
5835
David Neto22f144c2017-06-12 14:26:21 -04005836void SPIRVProducerPass::WriteOneWord(uint32_t Word) {
David Neto0676e6f2017-07-11 18:47:44 -04005837 binaryOut->write(reinterpret_cast<const char *>(&Word), sizeof(uint32_t));
David Neto22f144c2017-06-12 14:26:21 -04005838}
5839
5840void SPIRVProducerPass::WriteResultID(SPIRVInstruction *Inst) {
5841 WriteOneWord(Inst->getResultID());
5842}
5843
5844void SPIRVProducerPass::WriteWordCountAndOpcode(SPIRVInstruction *Inst) {
5845 // High 16 bit : Word Count
5846 // Low 16 bit : Opcode
5847 uint32_t Word = Inst->getOpcode();
David Netoee2660d2018-06-28 16:31:29 -04005848 const uint32_t count = Inst->getWordCount();
5849 if (count > 65535) {
5850 errs() << "Word count limit of 65535 exceeded: " << count << "\n";
5851 llvm_unreachable("Word count too high");
5852 }
David Neto22f144c2017-06-12 14:26:21 -04005853 Word |= Inst->getWordCount() << 16;
5854 WriteOneWord(Word);
5855}
5856
David Netoef5ba2b2019-12-20 08:35:54 -05005857void SPIRVProducerPass::WriteOperand(const std::unique_ptr<SPIRVOperand> &Op) {
David Neto22f144c2017-06-12 14:26:21 -04005858 SPIRVOperandType OpTy = Op->getType();
5859 switch (OpTy) {
5860 default: {
5861 llvm_unreachable("Unsupported SPIRV Operand Type???");
5862 break;
5863 }
5864 case SPIRVOperandType::NUMBERID: {
5865 WriteOneWord(Op->getNumID());
5866 break;
5867 }
5868 case SPIRVOperandType::LITERAL_STRING: {
5869 std::string Str = Op->getLiteralStr();
5870 const char *Data = Str.c_str();
5871 size_t WordSize = Str.size() / 4;
5872 for (unsigned Idx = 0; Idx < WordSize; Idx++) {
5873 WriteOneWord(*reinterpret_cast<const uint32_t *>(&Data[4 * Idx]));
5874 }
5875
5876 uint32_t Remainder = Str.size() % 4;
5877 uint32_t LastWord = 0;
5878 if (Remainder) {
5879 for (unsigned Idx = 0; Idx < Remainder; Idx++) {
5880 LastWord |= Data[4 * WordSize + Idx] << 8 * Idx;
5881 }
5882 }
5883
5884 WriteOneWord(LastWord);
5885 break;
5886 }
5887 case SPIRVOperandType::LITERAL_INTEGER:
5888 case SPIRVOperandType::LITERAL_FLOAT: {
5889 auto LiteralNum = Op->getLiteralNum();
5890 // TODO: Handle LiteranNum carefully.
5891 for (auto Word : LiteralNum) {
5892 WriteOneWord(Word);
5893 }
5894 break;
5895 }
5896 }
5897}
5898
5899void SPIRVProducerPass::WriteSPIRVBinary() {
SJW69939d52020-04-16 07:29:07 -05005900 for (int i = 0; i < kSectionCount; ++i) {
5901 WriteSPIRVBinary(SPIRVSections[i]);
5902 }
5903}
5904
5905void SPIRVProducerPass::WriteSPIRVBinary(SPIRVInstructionList &SPIRVInstList) {
David Neto22f144c2017-06-12 14:26:21 -04005906
5907 for (auto Inst : SPIRVInstList) {
David Netoef5ba2b2019-12-20 08:35:54 -05005908 const auto &Ops = Inst->getOperands();
David Neto22f144c2017-06-12 14:26:21 -04005909 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5910
5911 switch (Opcode) {
5912 default: {
David Neto5c22a252018-03-15 16:07:41 -04005913 errs() << "Unsupported SPIR-V instruction opcode " << int(Opcode) << "\n";
David Neto22f144c2017-06-12 14:26:21 -04005914 llvm_unreachable("Unsupported SPIRV instruction");
5915 break;
5916 }
5917 case spv::OpCapability:
5918 case spv::OpExtension:
5919 case spv::OpMemoryModel:
5920 case spv::OpEntryPoint:
5921 case spv::OpExecutionMode:
5922 case spv::OpSource:
5923 case spv::OpDecorate:
5924 case spv::OpMemberDecorate:
5925 case spv::OpBranch:
5926 case spv::OpBranchConditional:
5927 case spv::OpSelectionMerge:
5928 case spv::OpLoopMerge:
5929 case spv::OpStore:
5930 case spv::OpImageWrite:
5931 case spv::OpReturnValue:
5932 case spv::OpControlBarrier:
5933 case spv::OpMemoryBarrier:
5934 case spv::OpReturn:
5935 case spv::OpFunctionEnd:
5936 case spv::OpCopyMemory: {
5937 WriteWordCountAndOpcode(Inst);
5938 for (uint32_t i = 0; i < Ops.size(); i++) {
5939 WriteOperand(Ops[i]);
5940 }
5941 break;
5942 }
5943 case spv::OpTypeBool:
5944 case spv::OpTypeVoid:
5945 case spv::OpTypeSampler:
5946 case spv::OpLabel:
5947 case spv::OpExtInstImport:
5948 case spv::OpTypePointer:
5949 case spv::OpTypeRuntimeArray:
5950 case spv::OpTypeStruct:
5951 case spv::OpTypeImage:
5952 case spv::OpTypeSampledImage:
5953 case spv::OpTypeInt:
5954 case spv::OpTypeFloat:
5955 case spv::OpTypeArray:
5956 case spv::OpTypeVector:
5957 case spv::OpTypeFunction: {
5958 WriteWordCountAndOpcode(Inst);
5959 WriteResultID(Inst);
5960 for (uint32_t i = 0; i < Ops.size(); i++) {
5961 WriteOperand(Ops[i]);
5962 }
5963 break;
5964 }
5965 case spv::OpFunction:
5966 case spv::OpFunctionParameter:
5967 case spv::OpAccessChain:
5968 case spv::OpPtrAccessChain:
5969 case spv::OpInBoundsAccessChain:
5970 case spv::OpUConvert:
5971 case spv::OpSConvert:
5972 case spv::OpConvertFToU:
5973 case spv::OpConvertFToS:
5974 case spv::OpConvertUToF:
5975 case spv::OpConvertSToF:
5976 case spv::OpFConvert:
5977 case spv::OpConvertPtrToU:
5978 case spv::OpConvertUToPtr:
5979 case spv::OpBitcast:
alan-bakerc9c55ae2019-12-02 16:01:27 -05005980 case spv::OpFNegate:
David Neto22f144c2017-06-12 14:26:21 -04005981 case spv::OpIAdd:
5982 case spv::OpFAdd:
5983 case spv::OpISub:
5984 case spv::OpFSub:
5985 case spv::OpIMul:
5986 case spv::OpFMul:
5987 case spv::OpUDiv:
5988 case spv::OpSDiv:
5989 case spv::OpFDiv:
5990 case spv::OpUMod:
5991 case spv::OpSRem:
5992 case spv::OpFRem:
Kévin Petit8a560882019-03-21 15:24:34 +00005993 case spv::OpUMulExtended:
5994 case spv::OpSMulExtended:
David Neto22f144c2017-06-12 14:26:21 -04005995 case spv::OpBitwiseOr:
5996 case spv::OpBitwiseXor:
5997 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04005998 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04005999 case spv::OpShiftLeftLogical:
6000 case spv::OpShiftRightLogical:
6001 case spv::OpShiftRightArithmetic:
6002 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04006003 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04006004 case spv::OpCompositeExtract:
6005 case spv::OpVectorExtractDynamic:
6006 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04006007 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04006008 case spv::OpVectorInsertDynamic:
6009 case spv::OpVectorShuffle:
6010 case spv::OpIEqual:
6011 case spv::OpINotEqual:
6012 case spv::OpUGreaterThan:
6013 case spv::OpUGreaterThanEqual:
6014 case spv::OpULessThan:
6015 case spv::OpULessThanEqual:
6016 case spv::OpSGreaterThan:
6017 case spv::OpSGreaterThanEqual:
6018 case spv::OpSLessThan:
6019 case spv::OpSLessThanEqual:
6020 case spv::OpFOrdEqual:
6021 case spv::OpFOrdGreaterThan:
6022 case spv::OpFOrdGreaterThanEqual:
6023 case spv::OpFOrdLessThan:
6024 case spv::OpFOrdLessThanEqual:
6025 case spv::OpFOrdNotEqual:
6026 case spv::OpFUnordEqual:
6027 case spv::OpFUnordGreaterThan:
6028 case spv::OpFUnordGreaterThanEqual:
6029 case spv::OpFUnordLessThan:
6030 case spv::OpFUnordLessThanEqual:
6031 case spv::OpFUnordNotEqual:
6032 case spv::OpExtInst:
6033 case spv::OpIsInf:
6034 case spv::OpIsNan:
6035 case spv::OpAny:
6036 case spv::OpAll:
6037 case spv::OpUndef:
6038 case spv::OpConstantNull:
6039 case spv::OpLogicalOr:
6040 case spv::OpLogicalAnd:
6041 case spv::OpLogicalNot:
6042 case spv::OpLogicalNotEqual:
6043 case spv::OpConstantComposite:
6044 case spv::OpSpecConstantComposite:
6045 case spv::OpConstantTrue:
6046 case spv::OpConstantFalse:
6047 case spv::OpConstant:
6048 case spv::OpSpecConstant:
6049 case spv::OpVariable:
6050 case spv::OpFunctionCall:
6051 case spv::OpSampledImage:
alan-baker75090e42020-02-20 11:21:04 -05006052 case spv::OpImageFetch:
David Neto22f144c2017-06-12 14:26:21 -04006053 case spv::OpImageSampleExplicitLod:
David Neto5c22a252018-03-15 16:07:41 -04006054 case spv::OpImageQuerySize:
alan-bakerce179f12019-12-06 19:02:22 -05006055 case spv::OpImageQuerySizeLod:
David Neto22f144c2017-06-12 14:26:21 -04006056 case spv::OpSelect:
6057 case spv::OpPhi:
6058 case spv::OpLoad:
6059 case spv::OpAtomicIAdd:
6060 case spv::OpAtomicISub:
6061 case spv::OpAtomicExchange:
6062 case spv::OpAtomicIIncrement:
6063 case spv::OpAtomicIDecrement:
6064 case spv::OpAtomicCompareExchange:
6065 case spv::OpAtomicUMin:
6066 case spv::OpAtomicSMin:
6067 case spv::OpAtomicUMax:
6068 case spv::OpAtomicSMax:
6069 case spv::OpAtomicAnd:
6070 case spv::OpAtomicOr:
6071 case spv::OpAtomicXor:
6072 case spv::OpDot: {
6073 WriteWordCountAndOpcode(Inst);
6074 WriteOperand(Ops[0]);
6075 WriteResultID(Inst);
6076 for (uint32_t i = 1; i < Ops.size(); i++) {
6077 WriteOperand(Ops[i]);
6078 }
6079 break;
6080 }
6081 }
6082 }
6083}
Alan Baker9bf93fb2018-08-28 16:59:26 -04006084
alan-bakerb6b09dc2018-11-08 16:59:28 -05006085bool SPIRVProducerPass::IsTypeNullable(const Type *type) const {
Alan Baker9bf93fb2018-08-28 16:59:26 -04006086 switch (type->getTypeID()) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05006087 case Type::HalfTyID:
6088 case Type::FloatTyID:
6089 case Type::DoubleTyID:
6090 case Type::IntegerTyID:
6091 case Type::VectorTyID:
6092 return true;
6093 case Type::PointerTyID: {
6094 const PointerType *pointer_type = cast<PointerType>(type);
6095 if (pointer_type->getPointerAddressSpace() !=
6096 AddressSpace::UniformConstant) {
6097 auto pointee_type = pointer_type->getPointerElementType();
6098 if (pointee_type->isStructTy() &&
6099 cast<StructType>(pointee_type)->isOpaque()) {
6100 // Images and samplers are not nullable.
6101 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04006102 }
Alan Baker9bf93fb2018-08-28 16:59:26 -04006103 }
alan-bakerb6b09dc2018-11-08 16:59:28 -05006104 return true;
6105 }
6106 case Type::ArrayTyID:
alan-baker8eb435a2020-04-08 00:42:06 -04006107 return IsTypeNullable(type->getArrayElementType());
alan-bakerb6b09dc2018-11-08 16:59:28 -05006108 case Type::StructTyID: {
6109 const StructType *struct_type = cast<StructType>(type);
6110 // Images and samplers are not nullable.
6111 if (struct_type->isOpaque())
Alan Baker9bf93fb2018-08-28 16:59:26 -04006112 return false;
alan-bakerb6b09dc2018-11-08 16:59:28 -05006113 for (const auto element : struct_type->elements()) {
6114 if (!IsTypeNullable(element))
6115 return false;
6116 }
6117 return true;
6118 }
6119 default:
6120 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04006121 }
6122}
Alan Bakerfcda9482018-10-02 17:09:59 -04006123
6124void SPIRVProducerPass::PopulateUBOTypeMaps(Module &module) {
6125 if (auto *offsets_md =
6126 module.getNamedMetadata(clspv::RemappedTypeOffsetMetadataName())) {
6127 // Metdata is stored as key-value pair operands. The first element of each
6128 // operand is the type and the second is a vector of offsets.
6129 for (const auto *operand : offsets_md->operands()) {
6130 const auto *pair = cast<MDTuple>(operand);
6131 auto *type =
6132 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
6133 const auto *offset_vector = cast<MDTuple>(pair->getOperand(1));
6134 std::vector<uint32_t> offsets;
6135 for (const Metadata *offset_md : offset_vector->operands()) {
6136 const auto *constant_md = cast<ConstantAsMetadata>(offset_md);
alan-bakerb6b09dc2018-11-08 16:59:28 -05006137 offsets.push_back(static_cast<uint32_t>(
6138 cast<ConstantInt>(constant_md->getValue())->getZExtValue()));
Alan Bakerfcda9482018-10-02 17:09:59 -04006139 }
6140 RemappedUBOTypeOffsets.insert(std::make_pair(type, offsets));
6141 }
6142 }
6143
6144 if (auto *sizes_md =
6145 module.getNamedMetadata(clspv::RemappedTypeSizesMetadataName())) {
6146 // Metadata is stored as key-value pair operands. The first element of each
6147 // operand is the type and the second is a triple of sizes: type size in
6148 // bits, store size and alloc size.
6149 for (const auto *operand : sizes_md->operands()) {
6150 const auto *pair = cast<MDTuple>(operand);
6151 auto *type =
6152 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
6153 const auto *size_triple = cast<MDTuple>(pair->getOperand(1));
6154 uint64_t type_size_in_bits =
6155 cast<ConstantInt>(
6156 cast<ConstantAsMetadata>(size_triple->getOperand(0))->getValue())
6157 ->getZExtValue();
6158 uint64_t type_store_size =
6159 cast<ConstantInt>(
6160 cast<ConstantAsMetadata>(size_triple->getOperand(1))->getValue())
6161 ->getZExtValue();
6162 uint64_t type_alloc_size =
6163 cast<ConstantInt>(
6164 cast<ConstantAsMetadata>(size_triple->getOperand(2))->getValue())
6165 ->getZExtValue();
6166 RemappedUBOTypeSizes.insert(std::make_pair(
6167 type, std::make_tuple(type_size_in_bits, type_store_size,
6168 type_alloc_size)));
6169 }
6170 }
6171}
6172
6173uint64_t SPIRVProducerPass::GetTypeSizeInBits(Type *type,
6174 const DataLayout &DL) {
6175 auto iter = RemappedUBOTypeSizes.find(type);
6176 if (iter != RemappedUBOTypeSizes.end()) {
6177 return std::get<0>(iter->second);
6178 }
6179
6180 return DL.getTypeSizeInBits(type);
6181}
6182
6183uint64_t SPIRVProducerPass::GetTypeStoreSize(Type *type, const DataLayout &DL) {
6184 auto iter = RemappedUBOTypeSizes.find(type);
6185 if (iter != RemappedUBOTypeSizes.end()) {
6186 return std::get<1>(iter->second);
6187 }
6188
6189 return DL.getTypeStoreSize(type);
6190}
6191
6192uint64_t SPIRVProducerPass::GetTypeAllocSize(Type *type, const DataLayout &DL) {
6193 auto iter = RemappedUBOTypeSizes.find(type);
6194 if (iter != RemappedUBOTypeSizes.end()) {
6195 return std::get<2>(iter->second);
6196 }
6197
6198 return DL.getTypeAllocSize(type);
6199}
alan-baker5b86ed72019-02-15 08:26:50 -05006200
Kévin Petitbbbda972020-03-03 19:16:31 +00006201uint32_t SPIRVProducerPass::GetExplicitLayoutStructMemberOffset(
6202 StructType *type, unsigned member, const DataLayout &DL) {
6203 const auto StructLayout = DL.getStructLayout(type);
6204 // Search for the correct offsets if this type was remapped.
6205 std::vector<uint32_t> *offsets = nullptr;
6206 auto iter = RemappedUBOTypeOffsets.find(type);
6207 if (iter != RemappedUBOTypeOffsets.end()) {
6208 offsets = &iter->second;
6209 }
6210 auto ByteOffset =
6211 static_cast<uint32_t>(StructLayout->getElementOffset(member));
6212 if (offsets) {
6213 ByteOffset = (*offsets)[member];
6214 }
6215
6216 return ByteOffset;
6217}
6218
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04006219void SPIRVProducerPass::setVariablePointersCapabilities(
6220 unsigned address_space) {
alan-baker5b86ed72019-02-15 08:26:50 -05006221 if (GetStorageClass(address_space) == spv::StorageClassStorageBuffer) {
6222 setVariablePointersStorageBuffer(true);
6223 } else {
6224 setVariablePointers(true);
6225 }
6226}
6227
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04006228Value *SPIRVProducerPass::GetBasePointer(Value *v) {
alan-baker5b86ed72019-02-15 08:26:50 -05006229 if (auto *gep = dyn_cast<GetElementPtrInst>(v)) {
6230 return GetBasePointer(gep->getPointerOperand());
6231 }
6232
6233 // Conservatively return |v|.
6234 return v;
6235}
6236
6237bool SPIRVProducerPass::sameResource(Value *lhs, Value *rhs) const {
6238 if (auto *lhs_call = dyn_cast<CallInst>(lhs)) {
6239 if (auto *rhs_call = dyn_cast<CallInst>(rhs)) {
6240 if (lhs_call->getCalledFunction()->getName().startswith(
6241 clspv::ResourceAccessorFunction()) &&
6242 rhs_call->getCalledFunction()->getName().startswith(
6243 clspv::ResourceAccessorFunction())) {
6244 // For resource accessors, match descriptor set and binding.
6245 if (lhs_call->getOperand(0) == rhs_call->getOperand(0) &&
6246 lhs_call->getOperand(1) == rhs_call->getOperand(1))
6247 return true;
6248 } else if (lhs_call->getCalledFunction()->getName().startswith(
6249 clspv::WorkgroupAccessorFunction()) &&
6250 rhs_call->getCalledFunction()->getName().startswith(
6251 clspv::WorkgroupAccessorFunction())) {
6252 // For workgroup resources, match spec id.
6253 if (lhs_call->getOperand(0) == rhs_call->getOperand(0))
6254 return true;
6255 }
6256 }
6257 }
6258
6259 return false;
6260}
6261
6262bool SPIRVProducerPass::selectFromSameObject(Instruction *inst) {
6263 assert(inst->getType()->isPointerTy());
6264 assert(GetStorageClass(inst->getType()->getPointerAddressSpace()) ==
6265 spv::StorageClassStorageBuffer);
6266 const bool hack_undef = clspv::Option::HackUndef();
6267 if (auto *select = dyn_cast<SelectInst>(inst)) {
6268 auto *true_base = GetBasePointer(select->getTrueValue());
6269 auto *false_base = GetBasePointer(select->getFalseValue());
6270
6271 if (true_base == false_base)
6272 return true;
6273
6274 // If either the true or false operand is a null, then we satisfy the same
6275 // object constraint.
6276 if (auto *true_cst = dyn_cast<Constant>(true_base)) {
6277 if (true_cst->isNullValue() || (hack_undef && isa<UndefValue>(true_base)))
6278 return true;
6279 }
6280
6281 if (auto *false_cst = dyn_cast<Constant>(false_base)) {
6282 if (false_cst->isNullValue() ||
6283 (hack_undef && isa<UndefValue>(false_base)))
6284 return true;
6285 }
6286
6287 if (sameResource(true_base, false_base))
6288 return true;
6289 } else if (auto *phi = dyn_cast<PHINode>(inst)) {
6290 Value *value = nullptr;
6291 bool ok = true;
6292 for (unsigned i = 0; ok && i != phi->getNumIncomingValues(); ++i) {
6293 auto *base = GetBasePointer(phi->getIncomingValue(i));
6294 // Null values satisfy the constraint of selecting of selecting from the
6295 // same object.
6296 if (!value) {
6297 if (auto *cst = dyn_cast<Constant>(base)) {
6298 if (!cst->isNullValue() && !(hack_undef && isa<UndefValue>(base)))
6299 value = base;
6300 } else {
6301 value = base;
6302 }
6303 } else if (base != value) {
6304 if (auto *base_cst = dyn_cast<Constant>(base)) {
6305 if (base_cst->isNullValue() || (hack_undef && isa<UndefValue>(base)))
6306 continue;
6307 }
6308
6309 if (sameResource(value, base))
6310 continue;
6311
6312 // Values don't represent the same base.
6313 ok = false;
6314 }
6315 }
6316
6317 return ok;
6318 }
6319
6320 // Conservatively return false.
6321 return false;
6322}
alan-bakere9308012019-03-15 10:25:13 -04006323
6324bool SPIRVProducerPass::CalledWithCoherentResource(Argument &Arg) {
6325 if (!Arg.getType()->isPointerTy() ||
6326 Arg.getType()->getPointerAddressSpace() != clspv::AddressSpace::Global) {
6327 // Only SSBOs need to be annotated as coherent.
6328 return false;
6329 }
6330
6331 DenseSet<Value *> visited;
6332 std::vector<Value *> stack;
6333 for (auto *U : Arg.getParent()->users()) {
6334 if (auto *call = dyn_cast<CallInst>(U)) {
6335 stack.push_back(call->getOperand(Arg.getArgNo()));
6336 }
6337 }
6338
6339 while (!stack.empty()) {
6340 Value *v = stack.back();
6341 stack.pop_back();
6342
6343 if (!visited.insert(v).second)
6344 continue;
6345
6346 auto *resource_call = dyn_cast<CallInst>(v);
6347 if (resource_call &&
6348 resource_call->getCalledFunction()->getName().startswith(
6349 clspv::ResourceAccessorFunction())) {
6350 // If this is a resource accessor function, check if the coherent operand
6351 // is set.
6352 const auto coherent =
6353 unsigned(dyn_cast<ConstantInt>(resource_call->getArgOperand(5))
6354 ->getZExtValue());
6355 if (coherent == 1)
6356 return true;
6357 } else if (auto *arg = dyn_cast<Argument>(v)) {
6358 // If this is a function argument, trace through its callers.
alan-bakere98f3f92019-04-08 15:06:36 -04006359 for (auto U : arg->getParent()->users()) {
alan-bakere9308012019-03-15 10:25:13 -04006360 if (auto *call = dyn_cast<CallInst>(U)) {
6361 stack.push_back(call->getOperand(arg->getArgNo()));
6362 }
6363 }
6364 } else if (auto *user = dyn_cast<User>(v)) {
6365 // If this is a user, traverse all operands that could lead to resource
6366 // variables.
6367 for (unsigned i = 0; i != user->getNumOperands(); ++i) {
6368 Value *operand = user->getOperand(i);
6369 if (operand->getType()->isPointerTy() &&
6370 operand->getType()->getPointerAddressSpace() ==
6371 clspv::AddressSpace::Global) {
6372 stack.push_back(operand);
6373 }
6374 }
6375 }
6376 }
6377
6378 // No coherent resource variables encountered.
6379 return false;
6380}
alan-baker06cad652019-12-03 17:56:47 -05006381
6382void SPIRVProducerPass::PopulateStructuredCFGMaps(Module &module) {
6383 // First, track loop merges and continues.
6384 DenseSet<BasicBlock *> LoopMergesAndContinues;
6385 for (auto &F : module) {
6386 if (F.isDeclaration())
6387 continue;
6388
6389 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
6390 const LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>(F).getLoopInfo();
6391 std::deque<BasicBlock *> order;
6392 DenseSet<BasicBlock *> visited;
6393 clspv::ComputeStructuredOrder(&*F.begin(), &DT, LI, &order, &visited);
6394
6395 for (auto BB : order) {
6396 auto terminator = BB->getTerminator();
6397 auto branch = dyn_cast<BranchInst>(terminator);
6398 if (LI.isLoopHeader(BB)) {
6399 auto L = LI.getLoopFor(BB);
6400 BasicBlock *ContinueBB = nullptr;
6401 BasicBlock *MergeBB = nullptr;
6402
6403 MergeBB = L->getExitBlock();
6404 if (!MergeBB) {
6405 // StructurizeCFG pass converts CFG into triangle shape and the cfg
6406 // has regions with single entry/exit. As a result, loop should not
6407 // have multiple exits.
6408 llvm_unreachable("Loop has multiple exits???");
6409 }
6410
6411 if (L->isLoopLatch(BB)) {
6412 ContinueBB = BB;
6413 } else {
6414 // From SPIR-V spec 2.11, Continue Target must dominate that back-edge
6415 // block.
6416 BasicBlock *Header = L->getHeader();
6417 BasicBlock *Latch = L->getLoopLatch();
6418 for (auto *loop_block : L->blocks()) {
6419 if (loop_block == Header) {
6420 continue;
6421 }
6422
6423 // Check whether block dominates block with back-edge.
6424 // The loop latch is the single block with a back-edge. If it was
6425 // possible, StructurizeCFG made the loop conform to this
6426 // requirement, otherwise |Latch| is a nullptr.
6427 if (DT.dominates(loop_block, Latch)) {
6428 ContinueBB = loop_block;
6429 }
6430 }
6431
6432 if (!ContinueBB) {
6433 llvm_unreachable("Wrong continue block from loop");
6434 }
6435 }
6436
6437 // Record the continue and merge blocks.
6438 MergeBlocks[BB] = MergeBB;
6439 ContinueBlocks[BB] = ContinueBB;
6440 LoopMergesAndContinues.insert(MergeBB);
6441 LoopMergesAndContinues.insert(ContinueBB);
6442 } else if (branch && branch->isConditional()) {
6443 auto L = LI.getLoopFor(BB);
6444 bool HasBackedge = false;
6445 while (L && !HasBackedge) {
6446 if (L->isLoopLatch(BB)) {
6447 HasBackedge = true;
6448 }
6449 L = L->getParentLoop();
6450 }
6451
6452 if (!HasBackedge) {
6453 // Only need a merge if the branch doesn't include a loop break or
6454 // continue.
6455 auto true_bb = branch->getSuccessor(0);
6456 auto false_bb = branch->getSuccessor(1);
6457 if (!LoopMergesAndContinues.count(true_bb) &&
6458 !LoopMergesAndContinues.count(false_bb)) {
6459 // StructurizeCFG pass already manipulated CFG. Just use false block
6460 // of branch instruction as merge block.
6461 MergeBlocks[BB] = false_bb;
6462 }
6463 }
6464 }
6465 }
6466 }
6467}