blob: 68124e2095ac64477851259ca09f576996ccefc4 [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-bakerc4579bb2020-04-29 14:15:50 -040060#include "Layout.h"
alan-baker56f7aff2019-05-22 08:06:42 -040061#include "NormalizeGlobalVariable.h"
Diego Novilloa4c44fa2019-04-11 10:56:15 -040062#include "Passes.h"
alan-bakera1be3322020-04-20 12:48:18 -040063#include "SpecConstant.h"
alan-bakerce179f12019-12-06 19:02:22 -050064#include "Types.h"
David Neto48f56a42017-10-06 16:44:25 -040065
David Neto22f144c2017-06-12 14:26:21 -040066#if defined(_MSC_VER)
67#pragma warning(pop)
68#endif
69
70using namespace llvm;
71using namespace clspv;
SJW173c7e92020-03-16 08:44:47 -050072using namespace clspv::Builtins;
David Neto156783e2017-07-05 15:39:41 -040073using namespace mdconst;
David Neto22f144c2017-06-12 14:26:21 -040074
75namespace {
David Netocd8ca5f2017-10-02 23:34:11 -040076
David Neto862b7d82018-06-14 18:48:37 -040077cl::opt<bool> ShowResourceVars("show-rv", cl::init(false), cl::Hidden,
78 cl::desc("Show resource variable creation"));
79
alan-baker5ed87542020-03-23 11:05:22 -040080cl::opt<bool>
81 ShowProducerIR("show-producer-ir", cl::init(false), cl::ReallyHidden,
82 cl::desc("Dump the IR at the start of SPIRVProducer"));
83
David Neto862b7d82018-06-14 18:48:37 -040084// These hacks exist to help transition code generation algorithms
85// without making huge noise in detailed test output.
86const bool Hack_generate_runtime_array_stride_early = true;
87
David Neto3fbb4072017-10-16 11:28:14 -040088// The value of 1/pi. This value is from MSDN
89// https://msdn.microsoft.com/en-us/library/4hwaceh6.aspx
90const double kOneOverPi = 0.318309886183790671538;
91const glsl::ExtInst kGlslExtInstBad = static_cast<glsl::ExtInst>(0);
92
alan-bakerb6b09dc2018-11-08 16:59:28 -050093const char *kCompositeConstructFunctionPrefix = "clspv.composite_construct.";
David Netoab03f432017-11-03 17:00:44 -040094
SJW69939d52020-04-16 07:29:07 -050095// SPIRV Module Sections (per 2.4 of the SPIRV spec)
96// These are used to collect SPIRVInstructions by type on-the-fly.
97enum SPIRVSection {
98 kCapabilities,
99 kExtensions,
100 kImports,
101 kMemoryModel,
102 kEntryPoints,
103 kExecutionModes,
104
105 kDebug,
106 kAnnotations,
107
108 kTypes,
109 kConstants = kTypes,
110 kGlobalVariables,
111
112 kFunctions,
113
114 kSectionCount
115};
116
David Neto22f144c2017-06-12 14:26:21 -0400117enum SPIRVOperandType {
118 NUMBERID,
119 LITERAL_INTEGER,
120 LITERAL_STRING,
121 LITERAL_FLOAT
122};
123
124struct SPIRVOperand {
125 explicit SPIRVOperand(SPIRVOperandType Ty, uint32_t Num)
126 : Type(Ty), LiteralNum(1, Num) {}
127 explicit SPIRVOperand(SPIRVOperandType Ty, const char *Str)
128 : Type(Ty), LiteralStr(Str) {}
129 explicit SPIRVOperand(SPIRVOperandType Ty, StringRef Str)
130 : Type(Ty), LiteralStr(Str) {}
131 explicit SPIRVOperand(SPIRVOperandType Ty, ArrayRef<uint32_t> NumVec)
132 : Type(Ty), LiteralNum(NumVec.begin(), NumVec.end()) {}
133
James Price11010dc2019-12-19 13:53:09 -0500134 SPIRVOperandType getType() const { return Type; };
135 uint32_t getNumID() const { return LiteralNum[0]; };
136 std::string getLiteralStr() const { return LiteralStr; };
137 ArrayRef<uint32_t> getLiteralNum() const { return LiteralNum; };
David Neto22f144c2017-06-12 14:26:21 -0400138
David Neto87846742018-04-11 17:36:22 -0400139 uint32_t GetNumWords() const {
140 switch (Type) {
141 case NUMBERID:
142 return 1;
143 case LITERAL_INTEGER:
144 case LITERAL_FLOAT:
David Netoee2660d2018-06-28 16:31:29 -0400145 return uint32_t(LiteralNum.size());
David Neto87846742018-04-11 17:36:22 -0400146 case LITERAL_STRING:
147 // Account for the terminating null character.
David Netoee2660d2018-06-28 16:31:29 -0400148 return uint32_t((LiteralStr.size() + 4) / 4);
David Neto87846742018-04-11 17:36:22 -0400149 }
150 llvm_unreachable("Unhandled case in SPIRVOperand::GetNumWords()");
151 }
152
David Neto22f144c2017-06-12 14:26:21 -0400153private:
154 SPIRVOperandType Type;
155 std::string LiteralStr;
156 SmallVector<uint32_t, 4> LiteralNum;
157};
158
David Netoc6f3ab22018-04-06 18:02:31 -0400159class SPIRVOperandList {
160public:
David Netoef5ba2b2019-12-20 08:35:54 -0500161 typedef std::unique_ptr<SPIRVOperand> element_type;
162 typedef SmallVector<element_type, 8> container_type;
163 typedef container_type::iterator iterator;
David Netoc6f3ab22018-04-06 18:02:31 -0400164 SPIRVOperandList() {}
alan-bakerb6b09dc2018-11-08 16:59:28 -0500165 SPIRVOperandList(const SPIRVOperandList &other) = delete;
166 SPIRVOperandList(SPIRVOperandList &&other) {
David Netoc6f3ab22018-04-06 18:02:31 -0400167 contents_ = std::move(other.contents_);
168 other.contents_.clear();
169 }
David Netoef5ba2b2019-12-20 08:35:54 -0500170 iterator begin() { return contents_.begin(); }
171 iterator end() { return contents_.end(); }
172 operator ArrayRef<element_type>() { return contents_; }
173 void push_back(element_type op) { contents_.push_back(std::move(op)); }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500174 void clear() { contents_.clear(); }
David Netoc6f3ab22018-04-06 18:02:31 -0400175 size_t size() const { return contents_.size(); }
James Price11010dc2019-12-19 13:53:09 -0500176 const SPIRVOperand *operator[](size_t i) { return contents_[i].get(); }
David Netoc6f3ab22018-04-06 18:02:31 -0400177
David Netoef5ba2b2019-12-20 08:35:54 -0500178 const container_type &getOperands() const { return contents_; }
David Neto87846742018-04-11 17:36:22 -0400179
David Netoc6f3ab22018-04-06 18:02:31 -0400180private:
David Netoef5ba2b2019-12-20 08:35:54 -0500181 container_type contents_;
David Netoc6f3ab22018-04-06 18:02:31 -0400182};
183
James Price11010dc2019-12-19 13:53:09 -0500184SPIRVOperandList &operator<<(SPIRVOperandList &list,
David Netoef5ba2b2019-12-20 08:35:54 -0500185 std::unique_ptr<SPIRVOperand> elem) {
186 list.push_back(std::move(elem));
David Netoc6f3ab22018-04-06 18:02:31 -0400187 return list;
188}
189
David Netoef5ba2b2019-12-20 08:35:54 -0500190std::unique_ptr<SPIRVOperand> MkNum(uint32_t num) {
191 return std::make_unique<SPIRVOperand>(LITERAL_INTEGER, num);
David Netoc6f3ab22018-04-06 18:02:31 -0400192}
David Netoef5ba2b2019-12-20 08:35:54 -0500193std::unique_ptr<SPIRVOperand> MkInteger(ArrayRef<uint32_t> num_vec) {
194 return std::make_unique<SPIRVOperand>(LITERAL_INTEGER, num_vec);
David Neto257c3892018-04-11 13:19:45 -0400195}
David Netoef5ba2b2019-12-20 08:35:54 -0500196std::unique_ptr<SPIRVOperand> MkFloat(ArrayRef<uint32_t> num_vec) {
197 return std::make_unique<SPIRVOperand>(LITERAL_FLOAT, num_vec);
David Neto257c3892018-04-11 13:19:45 -0400198}
David Netoef5ba2b2019-12-20 08:35:54 -0500199std::unique_ptr<SPIRVOperand> MkId(uint32_t id) {
200 return std::make_unique<SPIRVOperand>(NUMBERID, id);
James Price11010dc2019-12-19 13:53:09 -0500201}
David Netoef5ba2b2019-12-20 08:35:54 -0500202std::unique_ptr<SPIRVOperand> MkString(StringRef str) {
203 return std::make_unique<SPIRVOperand>(LITERAL_STRING, str);
David Neto257c3892018-04-11 13:19:45 -0400204}
David Netoc6f3ab22018-04-06 18:02:31 -0400205
David Neto22f144c2017-06-12 14:26:21 -0400206struct SPIRVInstruction {
David Netoef5ba2b2019-12-20 08:35:54 -0500207 // Creates an instruction with an opcode and no result ID, and with the given
208 // operands. This computes its own word count. Takes ownership of the
209 // operands and clears |Ops|.
210 SPIRVInstruction(spv::Op Opc, SPIRVOperandList &Ops)
211 : WordCount(1), Opcode(static_cast<uint16_t>(Opc)), ResultID(0) {
James Price11010dc2019-12-19 13:53:09 -0500212 for (auto &operand : Ops) {
David Netoee2660d2018-06-28 16:31:29 -0400213 WordCount += uint16_t(operand->GetNumWords());
David Neto87846742018-04-11 17:36:22 -0400214 }
David Netoef5ba2b2019-12-20 08:35:54 -0500215 Operands.reserve(Ops.size());
216 for (auto &ptr : Ops) {
217 Operands.emplace_back(std::move(ptr));
218 ptr.reset(nullptr);
David Neto87846742018-04-11 17:36:22 -0400219 }
David Netoef5ba2b2019-12-20 08:35:54 -0500220 Ops.clear();
221 }
222 // Creates an instruction with an opcode and a no-zero result ID, and
223 // with the given operands. This computes its own word count. Takes ownership
224 // of the operands and clears |Ops|.
225 SPIRVInstruction(spv::Op Opc, uint32_t ResID, SPIRVOperandList &Ops)
226 : WordCount(2), Opcode(static_cast<uint16_t>(Opc)), ResultID(ResID) {
James Price11010dc2019-12-19 13:53:09 -0500227 for (auto &operand : Ops) {
David Neto87846742018-04-11 17:36:22 -0400228 WordCount += operand->GetNumWords();
229 }
David Netoef5ba2b2019-12-20 08:35:54 -0500230 Operands.reserve(Ops.size());
231 for (auto &ptr : Ops) {
232 Operands.emplace_back(std::move(ptr));
233 ptr.reset(nullptr);
234 }
235 if (ResID == 0) {
236 llvm_unreachable("Result ID of 0 was provided");
237 }
238 Ops.clear();
David Neto87846742018-04-11 17:36:22 -0400239 }
David Neto22f144c2017-06-12 14:26:21 -0400240
David Netoef5ba2b2019-12-20 08:35:54 -0500241 // Creates an instruction with an opcode and no result ID, and with the single
242 // operand. This computes its own word count.
243 SPIRVInstruction(spv::Op Opc, SPIRVOperandList::element_type operand)
244 : WordCount(1), Opcode(static_cast<uint16_t>(Opc)), ResultID(0) {
245 WordCount += operand->GetNumWords();
246 Operands.emplace_back(std::move(operand));
247 operand.reset(nullptr);
248 }
249 // Creates an instruction with an opcode and a non-zero result ID, and
250 // with the single operand. This computes its own word count.
251 SPIRVInstruction(spv::Op Opc, uint32_t ResID,
252 SPIRVOperandList::element_type operand)
253 : WordCount(2), Opcode(static_cast<uint16_t>(Opc)), ResultID(ResID) {
254 WordCount += operand->GetNumWords();
255 if (ResID == 0) {
256 llvm_unreachable("Result ID of 0 was provided");
257 }
258 Operands.emplace_back(std::move(operand));
259 operand.reset(nullptr);
260 }
261 // Creates an instruction with an opcode and a no-zero result ID, and no
262 // operands.
263 SPIRVInstruction(spv::Op Opc, uint32_t ResID)
264 : WordCount(2), Opcode(static_cast<uint16_t>(Opc)), ResultID(ResID) {
265 if (ResID == 0) {
266 llvm_unreachable("Result ID of 0 was provided");
267 }
268 }
269 // Creates an instruction with an opcode, no result ID, no type ID, and no
270 // operands.
271 SPIRVInstruction(spv::Op Opc)
272 : WordCount(1), Opcode(static_cast<uint16_t>(Opc)), ResultID(0) {}
273
David Netoee2660d2018-06-28 16:31:29 -0400274 uint32_t getWordCount() const { return WordCount; }
David Neto22f144c2017-06-12 14:26:21 -0400275 uint16_t getOpcode() const { return Opcode; }
276 uint32_t getResultID() const { return ResultID; }
David Netoef5ba2b2019-12-20 08:35:54 -0500277 ArrayRef<std::unique_ptr<SPIRVOperand>> getOperands() const {
James Price11010dc2019-12-19 13:53:09 -0500278 return Operands;
279 }
David Neto22f144c2017-06-12 14:26:21 -0400280
281private:
David Netoee2660d2018-06-28 16:31:29 -0400282 uint32_t WordCount; // Check the 16-bit bound at code generation time.
David Neto22f144c2017-06-12 14:26:21 -0400283 uint16_t Opcode;
284 uint32_t ResultID;
David Netoef5ba2b2019-12-20 08:35:54 -0500285 SmallVector<std::unique_ptr<SPIRVOperand>, 4> Operands;
David Neto22f144c2017-06-12 14:26:21 -0400286};
287
288struct SPIRVProducerPass final : public ModulePass {
David Neto22f144c2017-06-12 14:26:21 -0400289 typedef DenseMap<Type *, uint32_t> TypeMapType;
290 typedef UniqueVector<Type *> TypeList;
291 typedef DenseMap<Value *, uint32_t> ValueMapType;
David Netofb9a7972017-08-25 17:08:24 -0400292 typedef UniqueVector<Value *> ValueList;
David Neto22f144c2017-06-12 14:26:21 -0400293 typedef std::vector<std::pair<Value *, uint32_t>> EntryPointVecType;
294 typedef std::list<SPIRVInstruction *> SPIRVInstructionList;
David Neto87846742018-04-11 17:36:22 -0400295 // A vector of tuples, each of which is:
296 // - the LLVM instruction that we will later generate SPIR-V code for
297 // - where the SPIR-V instruction should be inserted
298 // - the result ID of the SPIR-V instruction
David Neto22f144c2017-06-12 14:26:21 -0400299 typedef std::vector<
300 std::tuple<Value *, SPIRVInstructionList::iterator, uint32_t>>
301 DeferredInstVecType;
302 typedef DenseMap<FunctionType *, std::pair<FunctionType *, uint32_t>>
303 GlobalConstFuncMapType;
304
David Neto44795152017-07-13 15:45:28 -0400305 explicit SPIRVProducerPass(
alan-bakerf5e5f692018-11-27 08:33:24 -0500306 raw_pwrite_stream &out,
307 std::vector<clspv::version0::DescriptorMapEntry> *descriptor_map_entries,
alan-baker00e7a582019-06-07 12:54:21 -0400308 ArrayRef<std::pair<unsigned, std::string>> samplerMap,
David Neto44795152017-07-13 15:45:28 -0400309 bool outputCInitList)
David Netoc2c368d2017-06-30 16:50:17 -0400310 : ModulePass(ID), samplerMap(samplerMap), out(out),
David Neto0676e6f2017-07-11 18:47:44 -0400311 binaryTempOut(binaryTempUnderlyingVector), binaryOut(&out),
alan-baker00e7a582019-06-07 12:54:21 -0400312 descriptorMapEntries(descriptor_map_entries),
David Neto0676e6f2017-07-11 18:47:44 -0400313 outputCInitList(outputCInitList), patchBoundOffset(0), nextID(1),
alan-baker5b86ed72019-02-15 08:26:50 -0500314 OpExtInstImportID(0), HasVariablePointersStorageBuffer(false),
315 HasVariablePointers(false), SamplerTy(nullptr), WorkgroupSizeValueID(0),
alan-bakera1be3322020-04-20 12:48:18 -0400316 WorkgroupSizeVarID(0) {}
David Neto22f144c2017-06-12 14:26:21 -0400317
James Price11010dc2019-12-19 13:53:09 -0500318 virtual ~SPIRVProducerPass() {
SJW69939d52020-04-16 07:29:07 -0500319 for (int i = 0; i < kSectionCount; ++i) {
320 for (auto *Inst : SPIRVSections[i]) {
321 delete Inst;
322 }
James Price11010dc2019-12-19 13:53:09 -0500323 }
324 }
325
David Neto22f144c2017-06-12 14:26:21 -0400326 void getAnalysisUsage(AnalysisUsage &AU) const override {
327 AU.addRequired<DominatorTreeWrapperPass>();
328 AU.addRequired<LoopInfoWrapperPass>();
329 }
330
331 virtual bool runOnModule(Module &module) override;
332
333 // output the SPIR-V header block
334 void outputHeader();
335
336 // patch the SPIR-V header block
337 void patchHeader();
338
339 uint32_t lookupType(Type *Ty) {
340 if (Ty->isPointerTy() &&
341 (Ty->getPointerAddressSpace() != AddressSpace::UniformConstant)) {
342 auto PointeeTy = Ty->getPointerElementType();
343 if (PointeeTy->isStructTy() &&
344 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
345 Ty = PointeeTy;
346 }
347 }
348
David Neto862b7d82018-06-14 18:48:37 -0400349 auto where = TypeMap.find(Ty);
350 if (where == TypeMap.end()) {
351 if (Ty) {
352 errs() << "Unhandled type " << *Ty << "\n";
353 } else {
354 errs() << "Unhandled type (null)\n";
355 }
David Netoe439d702018-03-23 13:14:08 -0700356 llvm_unreachable("\nUnhandled type!");
David Neto22f144c2017-06-12 14:26:21 -0400357 }
358
David Neto862b7d82018-06-14 18:48:37 -0400359 return where->second;
David Neto22f144c2017-06-12 14:26:21 -0400360 }
361 TypeMapType &getImageTypeMap() { return ImageTypeMap; }
alan-bakerabd82722019-12-03 17:14:51 -0500362 TypeList &getImageTypeList() { return ImageTypeList; }
David Neto22f144c2017-06-12 14:26:21 -0400363 TypeList &getTypeList() { return Types; };
364 ValueList &getConstantList() { return Constants; };
365 ValueMapType &getValueMap() { return ValueMap; }
366 ValueMapType &getAllocatedValueMap() { return AllocatedValueMap; }
SJW69939d52020-04-16 07:29:07 -0500367 SPIRVInstructionList &getSPIRVInstList(SPIRVSection Section) {
368 return SPIRVSections[Section];
369 };
David Neto22f144c2017-06-12 14:26:21 -0400370 EntryPointVecType &getEntryPointVec() { return EntryPointVec; };
371 DeferredInstVecType &getDeferredInstVec() { return DeferredInstVec; };
372 ValueList &getEntryPointInterfacesVec() { return EntryPointInterfacesVec; };
373 uint32_t &getOpExtInstImportID() { return OpExtInstImportID; };
374 std::vector<uint32_t> &getBuiltinDimVec() { return BuiltinDimensionVec; };
SJW2c317da2020-03-23 07:39:13 -0500375
alan-baker5b86ed72019-02-15 08:26:50 -0500376 bool hasVariablePointersStorageBuffer() {
377 return HasVariablePointersStorageBuffer;
378 }
379 void setVariablePointersStorageBuffer(bool Val) {
380 HasVariablePointersStorageBuffer = Val;
381 }
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400382 bool hasVariablePointers() { return HasVariablePointers; };
David Neto22f144c2017-06-12 14:26:21 -0400383 void setVariablePointers(bool Val) { HasVariablePointers = Val; };
alan-bakerb6b09dc2018-11-08 16:59:28 -0500384 ArrayRef<std::pair<unsigned, std::string>> &getSamplerMap() {
385 return samplerMap;
386 }
David Neto22f144c2017-06-12 14:26:21 -0400387 GlobalConstFuncMapType &getGlobalConstFuncTypeMap() {
388 return GlobalConstFuncTypeMap;
389 }
390 SmallPtrSet<Value *, 16> &getGlobalConstArgSet() {
391 return GlobalConstArgumentSet;
392 }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500393 TypeList &getTypesNeedingArrayStride() { return TypesNeedingArrayStride; }
David Neto22f144c2017-06-12 14:26:21 -0400394
SJW77b87ad2020-04-21 14:37:52 -0500395 void GenerateLLVMIRInfo();
alan-bakerb6b09dc2018-11-08 16:59:28 -0500396 // Populate GlobalConstFuncTypeMap. Also, if module-scope __constant will
397 // *not* be converted to a storage buffer, replace each such global variable
398 // with one in the storage class expecgted by SPIR-V.
SJW77b87ad2020-04-21 14:37:52 -0500399 void FindGlobalConstVars();
David Neto862b7d82018-06-14 18:48:37 -0400400 // Populate ResourceVarInfoList, FunctionToResourceVarsMap, and
401 // ModuleOrderedResourceVars.
SJW77b87ad2020-04-21 14:37:52 -0500402 void FindResourceVars();
403 void FindWorkgroupVars();
404 bool FindExtInst();
David Neto22f144c2017-06-12 14:26:21 -0400405 void FindTypePerGlobalVar(GlobalVariable &GV);
406 void FindTypePerFunc(Function &F);
SJW77b87ad2020-04-21 14:37:52 -0500407 void FindTypesForSamplerMap();
408 void FindTypesForResourceVars();
alan-bakerb6b09dc2018-11-08 16:59:28 -0500409 // Inserts |Ty| and relevant sub-types into the |Types| member, indicating
410 // that |Ty| and its subtypes will need a corresponding SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400411 void FindType(Type *Ty);
412 void FindConstantPerGlobalVar(GlobalVariable &GV);
413 void FindConstantPerFunc(Function &F);
414 void FindConstant(Value *V);
415 void GenerateExtInstImport();
David Neto19a1bad2017-08-25 15:01:41 -0400416 // Generates instructions for SPIR-V types corresponding to the LLVM types
417 // saved in the |Types| member. A type follows its subtypes. IDs are
418 // allocated sequentially starting with the current value of nextID, and
419 // with a type following its subtypes. Also updates nextID to just beyond
420 // the last generated ID.
SJW77b87ad2020-04-21 14:37:52 -0500421 void GenerateSPIRVTypes();
David Neto22f144c2017-06-12 14:26:21 -0400422 void GenerateSPIRVConstants();
SJW77b87ad2020-04-21 14:37:52 -0500423 void GenerateModuleInfo();
424 void GeneratePushConstantDescriptorMapEntries();
425 void GenerateSpecConstantDescriptorMapEntries();
David Neto22f144c2017-06-12 14:26:21 -0400426 void GenerateGlobalVar(GlobalVariable &GV);
SJW77b87ad2020-04-21 14:37:52 -0500427 void GenerateWorkgroupVars();
David Neto862b7d82018-06-14 18:48:37 -0400428 // Generate descriptor map entries for resource variables associated with
429 // arguments to F.
SJW77b87ad2020-04-21 14:37:52 -0500430 void GenerateDescriptorMapInfo(Function &F);
431 void GenerateSamplers();
David Neto862b7d82018-06-14 18:48:37 -0400432 // Generate OpVariables for %clspv.resource.var.* calls.
SJW77b87ad2020-04-21 14:37:52 -0500433 void GenerateResourceVars();
David Neto22f144c2017-06-12 14:26:21 -0400434 void GenerateFuncPrologue(Function &F);
435 void GenerateFuncBody(Function &F);
David Netob6e2e062018-04-25 10:32:06 -0400436 void GenerateEntryPointInitialStores();
David Neto22f144c2017-06-12 14:26:21 -0400437 spv::Op GetSPIRVCmpOpcode(CmpInst *CmpI);
438 spv::Op GetSPIRVCastOpcode(Instruction &I);
439 spv::Op GetSPIRVBinaryOpcode(Instruction &I);
440 void GenerateInstruction(Instruction &I);
441 void GenerateFuncEpilogue();
442 void HandleDeferredInstruction();
SJW77b87ad2020-04-21 14:37:52 -0500443 void HandleDeferredDecorations();
David Neto22f144c2017-06-12 14:26:21 -0400444 bool is4xi8vec(Type *Ty) const;
445 spv::StorageClass GetStorageClass(unsigned AddrSpace) const;
David Neto862b7d82018-06-14 18:48:37 -0400446 spv::StorageClass GetStorageClassForArgKind(clspv::ArgKind arg_kind) const;
David Neto22f144c2017-06-12 14:26:21 -0400447 spv::BuiltIn GetBuiltin(StringRef globalVarName) const;
David Neto3fbb4072017-10-16 11:28:14 -0400448 // Returns the GLSL extended instruction enum that the given function
449 // call maps to. If none, then returns the 0 value, i.e. GLSLstd4580Bad.
David Neto22f144c2017-06-12 14:26:21 -0400450 glsl::ExtInst getExtInstEnum(StringRef Name);
David Neto3fbb4072017-10-16 11:28:14 -0400451 // Returns the GLSL extended instruction enum indirectly used by the given
452 // function. That is, to implement the given function, we use an extended
453 // instruction plus one more instruction. If none, then returns the 0 value,
454 // i.e. GLSLstd4580Bad.
455 glsl::ExtInst getIndirectExtInstEnum(StringRef Name);
456 // Returns the single GLSL extended instruction used directly or
457 // indirectly by the given function call.
458 glsl::ExtInst getDirectOrIndirectExtInstEnum(StringRef Name);
David Neto22f144c2017-06-12 14:26:21 -0400459 void WriteOneWord(uint32_t Word);
460 void WriteResultID(SPIRVInstruction *Inst);
461 void WriteWordCountAndOpcode(SPIRVInstruction *Inst);
David Netoef5ba2b2019-12-20 08:35:54 -0500462 void WriteOperand(const std::unique_ptr<SPIRVOperand> &Op);
David Neto22f144c2017-06-12 14:26:21 -0400463 void WriteSPIRVBinary();
SJW69939d52020-04-16 07:29:07 -0500464 void WriteSPIRVBinary(SPIRVInstructionList &SPIRVInstList);
David Neto22f144c2017-06-12 14:26:21 -0400465
Alan Baker9bf93fb2018-08-28 16:59:26 -0400466 // Returns true if |type| is compatible with OpConstantNull.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500467 bool IsTypeNullable(const Type *type) const;
Alan Baker9bf93fb2018-08-28 16:59:26 -0400468
Alan Bakerfcda9482018-10-02 17:09:59 -0400469 // Populate UBO remapped type maps.
SJW77b87ad2020-04-21 14:37:52 -0500470 void PopulateUBOTypeMaps();
Alan Bakerfcda9482018-10-02 17:09:59 -0400471
alan-baker06cad652019-12-03 17:56:47 -0500472 // Populate the merge and continue block maps.
SJW77b87ad2020-04-21 14:37:52 -0500473 void PopulateStructuredCFGMaps();
alan-baker06cad652019-12-03 17:56:47 -0500474
Alan Bakerfcda9482018-10-02 17:09:59 -0400475 // Wrapped methods of DataLayout accessors. If |type| was remapped for UBOs,
476 // uses the internal map, otherwise it falls back on the data layout.
477 uint64_t GetTypeSizeInBits(Type *type, const DataLayout &DL);
478 uint64_t GetTypeStoreSize(Type *type, const DataLayout &DL);
479 uint64_t GetTypeAllocSize(Type *type, const DataLayout &DL);
Kévin Petitbbbda972020-03-03 19:16:31 +0000480 uint32_t GetExplicitLayoutStructMemberOffset(StructType *type,
481 unsigned member,
482 const DataLayout &DL);
Alan Bakerfcda9482018-10-02 17:09:59 -0400483
alan-baker5b86ed72019-02-15 08:26:50 -0500484 // Returns the base pointer of |v|.
485 Value *GetBasePointer(Value *v);
486
487 // Sets |HasVariablePointersStorageBuffer| or |HasVariablePointers| base on
488 // |address_space|.
489 void setVariablePointersCapabilities(unsigned address_space);
490
491 // Returns true if |lhs| and |rhs| represent the same resource or workgroup
492 // variable.
493 bool sameResource(Value *lhs, Value *rhs) const;
494
495 // Returns true if |inst| is phi or select that selects from the same
496 // structure (or null).
497 bool selectFromSameObject(Instruction *inst);
498
alan-bakere9308012019-03-15 10:25:13 -0400499 // Returns true if |Arg| is called with a coherent resource.
500 bool CalledWithCoherentResource(Argument &Arg);
501
David Neto22f144c2017-06-12 14:26:21 -0400502private:
503 static char ID;
SJW77b87ad2020-04-21 14:37:52 -0500504
505 Module *module;
506
David Neto44795152017-07-13 15:45:28 -0400507 ArrayRef<std::pair<unsigned, std::string>> samplerMap;
David Neto22f144c2017-06-12 14:26:21 -0400508 raw_pwrite_stream &out;
David Neto0676e6f2017-07-11 18:47:44 -0400509
510 // TODO(dneto): Wouldn't it be better to always just emit a binary, and then
511 // convert to other formats on demand?
512
513 // When emitting a C initialization list, the WriteSPIRVBinary method
514 // will actually write its words to this vector via binaryTempOut.
515 SmallVector<char, 100> binaryTempUnderlyingVector;
516 raw_svector_ostream binaryTempOut;
517
518 // Binary output writes to this stream, which might be |out| or
519 // |binaryTempOut|. It's the latter when we really want to write a C
520 // initializer list.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400521 raw_pwrite_stream *binaryOut;
alan-bakerf5e5f692018-11-27 08:33:24 -0500522 std::vector<version0::DescriptorMapEntry> *descriptorMapEntries;
David Neto0676e6f2017-07-11 18:47:44 -0400523 const bool outputCInitList; // If true, output look like {0x7023, ... , 5}
David Neto22f144c2017-06-12 14:26:21 -0400524 uint64_t patchBoundOffset;
525 uint32_t nextID;
526
alan-bakerf67468c2019-11-25 15:51:49 -0500527 // ID for OpTypeInt 32 1.
528 uint32_t int32ID = 0;
529 // ID for OpTypeVector %int 4.
530 uint32_t v4int32ID = 0;
531
David Neto19a1bad2017-08-25 15:01:41 -0400532 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400533 TypeMapType TypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400534 // Maps an LLVM image type to its SPIR-V ID.
David Neto22f144c2017-06-12 14:26:21 -0400535 TypeMapType ImageTypeMap;
alan-bakerabd82722019-12-03 17:14:51 -0500536 // A unique-vector of LLVM image types. This list is used to provide
537 // deterministic traversal of image types.
538 TypeList ImageTypeList;
David Neto19a1bad2017-08-25 15:01:41 -0400539 // A unique-vector of LLVM types that map to a SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400540 TypeList Types;
541 ValueList Constants;
David Neto19a1bad2017-08-25 15:01:41 -0400542 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400543 ValueMapType ValueMap;
544 ValueMapType AllocatedValueMap;
SJW69939d52020-04-16 07:29:07 -0500545 SPIRVInstructionList SPIRVSections[kSectionCount];
David Neto862b7d82018-06-14 18:48:37 -0400546
David Neto22f144c2017-06-12 14:26:21 -0400547 EntryPointVecType EntryPointVec;
548 DeferredInstVecType DeferredInstVec;
549 ValueList EntryPointInterfacesVec;
550 uint32_t OpExtInstImportID;
551 std::vector<uint32_t> BuiltinDimensionVec;
alan-baker5b86ed72019-02-15 08:26:50 -0500552 bool HasVariablePointersStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -0400553 bool HasVariablePointers;
554 Type *SamplerTy;
alan-baker09cb9802019-12-10 13:16:27 -0500555 DenseMap<unsigned, unsigned> SamplerLiteralToIDMap;
David Netoc77d9e22018-03-24 06:30:28 -0700556
557 // If a function F has a pointer-to-__constant parameter, then this variable
David Neto9ed8e2f2018-03-24 06:47:24 -0700558 // will map F's type to (G, index of the parameter), where in a first phase
559 // G is F's type. During FindTypePerFunc, G will be changed to F's type
560 // but replacing the pointer-to-constant parameter with
561 // pointer-to-ModuleScopePrivate.
David Netoc77d9e22018-03-24 06:30:28 -0700562 // TODO(dneto): This doesn't seem general enough? A function might have
563 // more than one such parameter.
David Neto22f144c2017-06-12 14:26:21 -0400564 GlobalConstFuncMapType GlobalConstFuncTypeMap;
565 SmallPtrSet<Value *, 16> GlobalConstArgumentSet;
David Neto1a1a0582017-07-07 12:01:44 -0400566 // An ordered set of pointer types of Base arguments to OpPtrAccessChain,
David Neto85082642018-03-24 06:55:20 -0700567 // or array types, and which point into transparent memory (StorageBuffer
568 // storage class). These will require an ArrayStride decoration.
David Neto1a1a0582017-07-07 12:01:44 -0400569 // See SPV_KHR_variable_pointers rev 13.
David Neto85082642018-03-24 06:55:20 -0700570 TypeList TypesNeedingArrayStride;
David Netoa60b00b2017-09-15 16:34:09 -0400571
572 // This is truly ugly, but works around what look like driver bugs.
573 // For get_local_size, an earlier part of the flow has created a module-scope
574 // variable in Private address space to hold the value for the workgroup
575 // size. Its intializer is a uint3 value marked as builtin WorkgroupSize.
576 // When this is present, save the IDs of the initializer value and variable
577 // in these two variables. We only ever do a vector load from it, and
578 // when we see one of those, substitute just the value of the intializer.
579 // This mimics what Glslang does, and that's what drivers are used to.
David Neto66cfe642018-03-24 06:13:56 -0700580 // TODO(dneto): Remove this once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -0400581 uint32_t WorkgroupSizeValueID;
582 uint32_t WorkgroupSizeVarID;
David Neto26aaf622017-10-23 18:11:53 -0400583
David Neto862b7d82018-06-14 18:48:37 -0400584 // Bookkeeping for mapping kernel arguments to resource variables.
585 struct ResourceVarInfo {
586 ResourceVarInfo(int index_arg, unsigned set_arg, unsigned binding_arg,
alan-bakere9308012019-03-15 10:25:13 -0400587 Function *fn, clspv::ArgKind arg_kind_arg, int coherent_arg)
David Neto862b7d82018-06-14 18:48:37 -0400588 : index(index_arg), descriptor_set(set_arg), binding(binding_arg),
alan-bakere9308012019-03-15 10:25:13 -0400589 var_fn(fn), arg_kind(arg_kind_arg), coherent(coherent_arg),
David Neto862b7d82018-06-14 18:48:37 -0400590 addr_space(fn->getReturnType()->getPointerAddressSpace()) {}
591 const int index; // Index into ResourceVarInfoList
592 const unsigned descriptor_set;
593 const unsigned binding;
594 Function *const var_fn; // The @clspv.resource.var.* function.
595 const clspv::ArgKind arg_kind;
alan-bakere9308012019-03-15 10:25:13 -0400596 const int coherent;
David Neto862b7d82018-06-14 18:48:37 -0400597 const unsigned addr_space; // The LLVM address space
598 // The SPIR-V ID of the OpVariable. Not populated at construction time.
599 uint32_t var_id = 0;
600 };
601 // A list of resource var info. Each one correponds to a module-scope
602 // resource variable we will have to create. Resource var indices are
603 // indices into this vector.
604 SmallVector<std::unique_ptr<ResourceVarInfo>, 8> ResourceVarInfoList;
605 // This is a vector of pointers of all the resource vars, but ordered by
606 // kernel function, and then by argument.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500607 UniqueVector<ResourceVarInfo *> ModuleOrderedResourceVars;
David Neto862b7d82018-06-14 18:48:37 -0400608 // Map a function to the ordered list of resource variables it uses, one for
609 // each argument. If an argument does not use a resource variable, it
610 // will have a null pointer entry.
611 using FunctionToResourceVarsMapType =
612 DenseMap<Function *, SmallVector<ResourceVarInfo *, 8>>;
613 FunctionToResourceVarsMapType FunctionToResourceVarsMap;
614
615 // What LLVM types map to SPIR-V types needing layout? These are the
616 // arrays and structures supporting storage buffers and uniform buffers.
617 TypeList TypesNeedingLayout;
618 // What LLVM struct types map to a SPIR-V struct type with Block decoration?
619 UniqueVector<StructType *> StructTypesNeedingBlock;
620 // For a call that represents a load from an opaque type (samplers, images),
621 // map it to the variable id it should load from.
622 DenseMap<CallInst *, uint32_t> ResourceVarDeferredLoadCalls;
David Neto85082642018-03-24 06:55:20 -0700623
David Netoc6f3ab22018-04-06 18:02:31 -0400624 // An ordered list of the kernel arguments of type pointer-to-local.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500625 using LocalArgList = SmallVector<Argument *, 8>;
David Netoc6f3ab22018-04-06 18:02:31 -0400626 LocalArgList LocalArgs;
627 // Information about a pointer-to-local argument.
628 struct LocalArgInfo {
629 // The SPIR-V ID of the array variable.
630 uint32_t variable_id;
631 // The element type of the
alan-bakerb6b09dc2018-11-08 16:59:28 -0500632 Type *elem_type;
David Netoc6f3ab22018-04-06 18:02:31 -0400633 // The ID of the array type.
634 uint32_t array_size_id;
635 // The ID of the array type.
636 uint32_t array_type_id;
637 // The ID of the pointer to the array type.
638 uint32_t ptr_array_type_id;
David Netoc6f3ab22018-04-06 18:02:31 -0400639 // The specialization constant ID of the array size.
640 int spec_id;
641 };
Alan Baker202c8c72018-08-13 13:47:44 -0400642 // A mapping from Argument to its assigned SpecId.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500643 DenseMap<const Argument *, int> LocalArgSpecIds;
Alan Baker202c8c72018-08-13 13:47:44 -0400644 // A mapping from SpecId to its LocalArgInfo.
645 DenseMap<int, LocalArgInfo> LocalSpecIdInfoMap;
Alan Bakerfcda9482018-10-02 17:09:59 -0400646 // A mapping from a remapped type to its real offsets.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500647 DenseMap<Type *, std::vector<uint32_t>> RemappedUBOTypeOffsets;
Alan Bakerfcda9482018-10-02 17:09:59 -0400648 // A mapping from a remapped type to its real sizes.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500649 DenseMap<Type *, std::tuple<uint64_t, uint64_t, uint64_t>>
650 RemappedUBOTypeSizes;
alan-baker06cad652019-12-03 17:56:47 -0500651
652 // Maps basic block to its merge block.
653 DenseMap<BasicBlock *, BasicBlock *> MergeBlocks;
654 // Maps basic block to its continue block.
655 DenseMap<BasicBlock *, BasicBlock *> ContinueBlocks;
David Neto22f144c2017-06-12 14:26:21 -0400656};
657
658char SPIRVProducerPass::ID;
David Netoc6f3ab22018-04-06 18:02:31 -0400659
alan-bakerb6b09dc2018-11-08 16:59:28 -0500660} // namespace
David Neto22f144c2017-06-12 14:26:21 -0400661
662namespace clspv {
alan-bakerf5e5f692018-11-27 08:33:24 -0500663ModulePass *createSPIRVProducerPass(
664 raw_pwrite_stream &out,
665 std::vector<version0::DescriptorMapEntry> *descriptor_map_entries,
alan-baker00e7a582019-06-07 12:54:21 -0400666 ArrayRef<std::pair<unsigned, std::string>> samplerMap,
alan-bakerf5e5f692018-11-27 08:33:24 -0500667 bool outputCInitList) {
668 return new SPIRVProducerPass(out, descriptor_map_entries, samplerMap,
alan-baker00e7a582019-06-07 12:54:21 -0400669 outputCInitList);
David Neto22f144c2017-06-12 14:26:21 -0400670}
David Netoc2c368d2017-06-30 16:50:17 -0400671} // namespace clspv
David Neto22f144c2017-06-12 14:26:21 -0400672
SJW77b87ad2020-04-21 14:37:52 -0500673bool SPIRVProducerPass::runOnModule(Module &M) {
674 module = &M;
alan-baker5ed87542020-03-23 11:05:22 -0400675 if (ShowProducerIR) {
SJW77b87ad2020-04-21 14:37:52 -0500676 llvm::outs() << *module << "\n";
alan-baker5ed87542020-03-23 11:05:22 -0400677 }
David Neto0676e6f2017-07-11 18:47:44 -0400678 binaryOut = outputCInitList ? &binaryTempOut : &out;
679
SJW77b87ad2020-04-21 14:37:52 -0500680 PopulateUBOTypeMaps();
681 PopulateStructuredCFGMaps();
Alan Bakerfcda9482018-10-02 17:09:59 -0400682
David Neto22f144c2017-06-12 14:26:21 -0400683 // SPIR-V always begins with its header information
684 outputHeader();
685
686 // Gather information from the LLVM IR that we require.
SJW77b87ad2020-04-21 14:37:52 -0500687 GenerateLLVMIRInfo();
David Neto22f144c2017-06-12 14:26:21 -0400688
David Neto22f144c2017-06-12 14:26:21 -0400689 // Collect information on global variables too.
SJW77b87ad2020-04-21 14:37:52 -0500690 for (GlobalVariable &GV : module->globals()) {
David Neto22f144c2017-06-12 14:26:21 -0400691 // If the GV is one of our special __spirv_* variables, remove the
692 // initializer as it was only placed there to force LLVM to not throw the
693 // value away.
Kévin Petitbbbda972020-03-03 19:16:31 +0000694 if (GV.getName().startswith("__spirv_") ||
695 GV.getAddressSpace() == clspv::AddressSpace::PushConstant) {
David Neto22f144c2017-06-12 14:26:21 -0400696 GV.setInitializer(nullptr);
697 }
698
699 // Collect types' information from global variable.
700 FindTypePerGlobalVar(GV);
701
702 // Collect constant information from global variable.
703 FindConstantPerGlobalVar(GV);
704
705 // If the variable is an input, entry points need to know about it.
706 if (AddressSpace::Input == GV.getType()->getPointerAddressSpace()) {
David Netofb9a7972017-08-25 17:08:24 -0400707 getEntryPointInterfacesVec().insert(&GV);
David Neto22f144c2017-06-12 14:26:21 -0400708 }
709 }
710
711 // If there are extended instructions, generate OpExtInstImport.
SJW77b87ad2020-04-21 14:37:52 -0500712 if (FindExtInst()) {
David Neto22f144c2017-06-12 14:26:21 -0400713 GenerateExtInstImport();
714 }
715
716 // Generate SPIRV instructions for types.
SJW77b87ad2020-04-21 14:37:52 -0500717 GenerateSPIRVTypes();
David Neto22f144c2017-06-12 14:26:21 -0400718
719 // Generate SPIRV constants.
720 GenerateSPIRVConstants();
721
alan-baker09cb9802019-12-10 13:16:27 -0500722 // Generate literal samplers if necessary.
SJW77b87ad2020-04-21 14:37:52 -0500723 GenerateSamplers();
David Neto22f144c2017-06-12 14:26:21 -0400724
Kévin Petitbbbda972020-03-03 19:16:31 +0000725 // Generate descriptor map entries for all push constants
SJW77b87ad2020-04-21 14:37:52 -0500726 GeneratePushConstantDescriptorMapEntries();
Kévin Petitbbbda972020-03-03 19:16:31 +0000727
David Neto22f144c2017-06-12 14:26:21 -0400728 // Generate SPIRV variables.
SJW77b87ad2020-04-21 14:37:52 -0500729 for (GlobalVariable &GV : module->globals()) {
David Neto22f144c2017-06-12 14:26:21 -0400730 GenerateGlobalVar(GV);
731 }
SJW77b87ad2020-04-21 14:37:52 -0500732 GenerateResourceVars();
733 GenerateWorkgroupVars();
David Neto22f144c2017-06-12 14:26:21 -0400734
735 // Generate SPIRV instructions for each function.
SJW77b87ad2020-04-21 14:37:52 -0500736 for (Function &F : *module) {
David Neto22f144c2017-06-12 14:26:21 -0400737 if (F.isDeclaration()) {
738 continue;
739 }
740
SJW77b87ad2020-04-21 14:37:52 -0500741 GenerateDescriptorMapInfo(F);
David Neto862b7d82018-06-14 18:48:37 -0400742
David Neto22f144c2017-06-12 14:26:21 -0400743 // Generate Function Prologue.
744 GenerateFuncPrologue(F);
745
746 // Generate SPIRV instructions for function body.
747 GenerateFuncBody(F);
748
749 // Generate Function Epilogue.
750 GenerateFuncEpilogue();
751 }
752
753 HandleDeferredInstruction();
SJW77b87ad2020-04-21 14:37:52 -0500754 HandleDeferredDecorations();
alan-bakera1be3322020-04-20 12:48:18 -0400755
756 // Generate descriptor map entries for module scope specialization constants.
SJW77b87ad2020-04-21 14:37:52 -0500757 GenerateSpecConstantDescriptorMapEntries();
David Neto22f144c2017-06-12 14:26:21 -0400758
759 // Generate SPIRV module information.
SJW77b87ad2020-04-21 14:37:52 -0500760 GenerateModuleInfo();
David Neto22f144c2017-06-12 14:26:21 -0400761
alan-baker00e7a582019-06-07 12:54:21 -0400762 WriteSPIRVBinary();
David Neto22f144c2017-06-12 14:26:21 -0400763
764 // We need to patch the SPIR-V header to set bound correctly.
765 patchHeader();
David Neto0676e6f2017-07-11 18:47:44 -0400766
767 if (outputCInitList) {
768 bool first = true;
David Neto0676e6f2017-07-11 18:47:44 -0400769 std::ostringstream os;
770
David Neto57fb0b92017-08-04 15:35:09 -0400771 auto emit_word = [&os, &first](uint32_t word) {
David Neto0676e6f2017-07-11 18:47:44 -0400772 if (!first)
David Neto57fb0b92017-08-04 15:35:09 -0400773 os << ",\n";
774 os << word;
David Neto0676e6f2017-07-11 18:47:44 -0400775 first = false;
776 };
777
778 os << "{";
David Neto57fb0b92017-08-04 15:35:09 -0400779 const std::string str(binaryTempOut.str());
780 for (unsigned i = 0; i < str.size(); i += 4) {
781 const uint32_t a = static_cast<unsigned char>(str[i]);
782 const uint32_t b = static_cast<unsigned char>(str[i + 1]);
783 const uint32_t c = static_cast<unsigned char>(str[i + 2]);
784 const uint32_t d = static_cast<unsigned char>(str[i + 3]);
785 emit_word(a | (b << 8) | (c << 16) | (d << 24));
David Neto0676e6f2017-07-11 18:47:44 -0400786 }
787 os << "}\n";
788 out << os.str();
789 }
790
David Neto22f144c2017-06-12 14:26:21 -0400791 return false;
792}
793
794void SPIRVProducerPass::outputHeader() {
alan-baker00e7a582019-06-07 12:54:21 -0400795 binaryOut->write(reinterpret_cast<const char *>(&spv::MagicNumber),
796 sizeof(spv::MagicNumber));
alan-bakere0902602020-03-23 08:43:40 -0400797 const uint32_t spv_version = 0x10000; // SPIR-V 1.0
798 binaryOut->write(reinterpret_cast<const char *>(&spv_version),
799 sizeof(spv_version));
David Neto22f144c2017-06-12 14:26:21 -0400800
alan-baker0c18ab02019-06-12 10:23:21 -0400801 // use Google's vendor ID
802 const uint32_t vendor = 21 << 16;
alan-baker00e7a582019-06-07 12:54:21 -0400803 binaryOut->write(reinterpret_cast<const char *>(&vendor), sizeof(vendor));
David Neto22f144c2017-06-12 14:26:21 -0400804
alan-baker00e7a582019-06-07 12:54:21 -0400805 // we record where we need to come back to and patch in the bound value
806 patchBoundOffset = binaryOut->tell();
David Neto22f144c2017-06-12 14:26:21 -0400807
alan-baker00e7a582019-06-07 12:54:21 -0400808 // output a bad bound for now
809 binaryOut->write(reinterpret_cast<const char *>(&nextID), sizeof(nextID));
David Neto22f144c2017-06-12 14:26:21 -0400810
alan-baker00e7a582019-06-07 12:54:21 -0400811 // output the schema (reserved for use and must be 0)
812 const uint32_t schema = 0;
813 binaryOut->write(reinterpret_cast<const char *>(&schema), sizeof(schema));
David Neto22f144c2017-06-12 14:26:21 -0400814}
815
816void SPIRVProducerPass::patchHeader() {
alan-baker00e7a582019-06-07 12:54:21 -0400817 // for a binary we just write the value of nextID over bound
818 binaryOut->pwrite(reinterpret_cast<char *>(&nextID), sizeof(nextID),
819 patchBoundOffset);
David Neto22f144c2017-06-12 14:26:21 -0400820}
821
SJW77b87ad2020-04-21 14:37:52 -0500822void SPIRVProducerPass::GenerateLLVMIRInfo() {
David Neto22f144c2017-06-12 14:26:21 -0400823 // This function generates LLVM IR for function such as global variable for
824 // argument, constant and pointer type for argument access. These information
825 // is artificial one because we need Vulkan SPIR-V output. This function is
826 // executed ahead of FindType and FindConstant.
SJW77b87ad2020-04-21 14:37:52 -0500827 LLVMContext &Context = module->getContext();
David Neto22f144c2017-06-12 14:26:21 -0400828
SJW77b87ad2020-04-21 14:37:52 -0500829 FindGlobalConstVars();
David Neto5c22a252018-03-15 16:07:41 -0400830
SJW77b87ad2020-04-21 14:37:52 -0500831 FindResourceVars();
David Neto22f144c2017-06-12 14:26:21 -0400832
833 bool HasWorkGroupBuiltin = false;
SJW77b87ad2020-04-21 14:37:52 -0500834 for (GlobalVariable &GV : module->globals()) {
David Neto22f144c2017-06-12 14:26:21 -0400835 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
836 if (spv::BuiltInWorkgroupSize == BuiltinType) {
837 HasWorkGroupBuiltin = true;
838 }
839 }
840
SJW77b87ad2020-04-21 14:37:52 -0500841 FindTypesForSamplerMap();
842 FindTypesForResourceVars();
843 FindWorkgroupVars();
David Neto22f144c2017-06-12 14:26:21 -0400844
SJW77b87ad2020-04-21 14:37:52 -0500845 for (Function &F : *module) {
Kévin Petitabef4522019-03-27 13:08:01 +0000846 if (F.isDeclaration()) {
David Neto22f144c2017-06-12 14:26:21 -0400847 continue;
848 }
849
850 for (BasicBlock &BB : F) {
851 for (Instruction &I : BB) {
852 if (I.getOpcode() == Instruction::ZExt ||
853 I.getOpcode() == Instruction::SExt ||
854 I.getOpcode() == Instruction::UIToFP) {
855 // If there is zext with i1 type, it will be changed to OpSelect. The
856 // OpSelect needs constant 0 and 1 so the constants are added here.
857
858 auto OpTy = I.getOperand(0)->getType();
859
Kévin Petit24272b62018-10-18 19:16:12 +0000860 if (OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -0400861 if (I.getOpcode() == Instruction::ZExt) {
David Neto22f144c2017-06-12 14:26:21 -0400862 FindConstant(Constant::getNullValue(I.getType()));
Kévin Petit7bfb8992019-02-26 13:45:08 +0000863 FindConstant(ConstantInt::get(I.getType(), 1));
David Neto22f144c2017-06-12 14:26:21 -0400864 } else if (I.getOpcode() == Instruction::SExt) {
David Neto22f144c2017-06-12 14:26:21 -0400865 FindConstant(Constant::getNullValue(I.getType()));
Kévin Petit7bfb8992019-02-26 13:45:08 +0000866 FindConstant(ConstantInt::getSigned(I.getType(), -1));
David Neto22f144c2017-06-12 14:26:21 -0400867 } else {
868 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
869 FindConstant(ConstantFP::get(Context, APFloat(1.0f)));
870 }
871 }
872 } else if (CallInst *Call = dyn_cast<CallInst>(&I)) {
David Neto862b7d82018-06-14 18:48:37 -0400873 StringRef callee_name = Call->getCalledFunction()->getName();
David Neto22f144c2017-06-12 14:26:21 -0400874
875 // Handle image type specially.
SJW173c7e92020-03-16 08:44:47 -0500876 if (IsImageBuiltin(callee_name)) {
David Neto22f144c2017-06-12 14:26:21 -0400877 TypeMapType &OpImageTypeMap = getImageTypeMap();
878 Type *ImageTy =
879 Call->getArgOperand(0)->getType()->getPointerElementType();
880 OpImageTypeMap[ImageTy] = 0;
alan-bakerabd82722019-12-03 17:14:51 -0500881 getImageTypeList().insert(ImageTy);
alan-baker75090e42020-02-20 11:21:04 -0500882 }
David Neto22f144c2017-06-12 14:26:21 -0400883
SJW173c7e92020-03-16 08:44:47 -0500884 if (IsSampledImageRead(callee_name)) {
alan-bakerf67468c2019-11-25 15:51:49 -0500885 // All sampled reads need a floating point 0 for the Lod operand.
David Neto22f144c2017-06-12 14:26:21 -0400886 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
SJW2c317da2020-03-23 07:39:13 -0500887 } else if (IsUnsampledImageRead(callee_name)) {
alan-baker75090e42020-02-20 11:21:04 -0500888 // All unsampled reads need an integer 0 for the Lod operand.
889 FindConstant(ConstantInt::get(Context, APInt(32, 0)));
SJW2c317da2020-03-23 07:39:13 -0500890 } else if (IsImageQuery(callee_name)) {
alan-bakerce179f12019-12-06 19:02:22 -0500891 Type *ImageTy = Call->getOperand(0)->getType();
892 const uint32_t dim = ImageDimensionality(ImageTy);
alan-baker7150a1d2020-02-25 08:31:06 -0500893 uint32_t components =
894 dim + (clspv::IsArrayImageType(ImageTy) ? 1 : 0);
alan-bakerce179f12019-12-06 19:02:22 -0500895 if (components > 1) {
896 // OpImageQuerySize* return |components| components.
897 FindType(VectorType::get(Type::getInt32Ty(Context), components));
898 if (dim == 3 && IsGetImageDim(callee_name)) {
899 // get_image_dim for 3D images returns an int4.
900 FindType(
901 VectorType::get(Type::getInt32Ty(Context), components + 1));
902 }
903 }
904
SJW173c7e92020-03-16 08:44:47 -0500905 if (IsSampledImageType(ImageTy)) {
alan-bakerce179f12019-12-06 19:02:22 -0500906 // All sampled image queries need a integer 0 for the Lod
907 // operand.
908 FindConstant(ConstantInt::get(Context, APInt(32, 0)));
909 }
David Neto5c22a252018-03-15 16:07:41 -0400910 }
David Neto22f144c2017-06-12 14:26:21 -0400911 }
912 }
913 }
914
Kévin Petitabef4522019-03-27 13:08:01 +0000915 // More things to do on kernel functions
916 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
917 if (const MDNode *MD =
918 dyn_cast<Function>(&F)->getMetadata("reqd_work_group_size")) {
919 // We generate constants if the WorkgroupSize builtin is being used.
920 if (HasWorkGroupBuiltin) {
921 // Collect constant information for work group size.
922 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(0)));
923 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(1)));
924 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(2)));
David Neto22f144c2017-06-12 14:26:21 -0400925 }
926 }
927 }
928
alan-bakerf67468c2019-11-25 15:51:49 -0500929 // TODO(alan-baker): make this better.
SJW77b87ad2020-04-21 14:37:52 -0500930 if (module->getTypeByName("opencl.image1d_ro_t.float") ||
931 module->getTypeByName("opencl.image1d_ro_t.float.sampled") ||
932 module->getTypeByName("opencl.image1d_wo_t.float") ||
933 module->getTypeByName("opencl.image2d_ro_t.float") ||
934 module->getTypeByName("opencl.image2d_ro_t.float.sampled") ||
935 module->getTypeByName("opencl.image2d_wo_t.float") ||
936 module->getTypeByName("opencl.image3d_ro_t.float") ||
937 module->getTypeByName("opencl.image3d_ro_t.float.sampled") ||
938 module->getTypeByName("opencl.image3d_wo_t.float") ||
939 module->getTypeByName("opencl.image1d_array_ro_t.float") ||
940 module->getTypeByName("opencl.image1d_array_ro_t.float.sampled") ||
941 module->getTypeByName("opencl.image1d_array_wo_t.float") ||
942 module->getTypeByName("opencl.image2d_array_ro_t.float") ||
943 module->getTypeByName("opencl.image2d_array_ro_t.float.sampled") ||
944 module->getTypeByName("opencl.image2d_array_wo_t.float")) {
alan-bakerf67468c2019-11-25 15:51:49 -0500945 FindType(Type::getFloatTy(Context));
SJW77b87ad2020-04-21 14:37:52 -0500946 } else if (module->getTypeByName("opencl.image1d_ro_t.uint") ||
947 module->getTypeByName("opencl.image1d_ro_t.uint.sampled") ||
948 module->getTypeByName("opencl.image1d_wo_t.uint") ||
949 module->getTypeByName("opencl.image2d_ro_t.uint") ||
950 module->getTypeByName("opencl.image2d_ro_t.uint.sampled") ||
951 module->getTypeByName("opencl.image2d_wo_t.uint") ||
952 module->getTypeByName("opencl.image3d_ro_t.uint") ||
953 module->getTypeByName("opencl.image3d_ro_t.uint.sampled") ||
954 module->getTypeByName("opencl.image3d_wo_t.uint") ||
955 module->getTypeByName("opencl.image1d_array_ro_t.uint") ||
956 module->getTypeByName(
957 "opencl.image1d_array_ro_t.uint.sampled") ||
958 module->getTypeByName("opencl.image1d_array_wo_t.uint") ||
959 module->getTypeByName("opencl.image2d_array_ro_t.uint") ||
960 module->getTypeByName(
961 "opencl.image2d_array_ro_t.uint.sampled") ||
962 module->getTypeByName("opencl.image2d_array_wo_t.uint")) {
alan-bakerf67468c2019-11-25 15:51:49 -0500963 FindType(Type::getInt32Ty(Context));
SJW77b87ad2020-04-21 14:37:52 -0500964 } else if (module->getTypeByName("opencl.image1d_ro_t.int") ||
965 module->getTypeByName("opencl.image1d_ro_t.int.sampled") ||
966 module->getTypeByName("opencl.image1d_wo_t.int") ||
967 module->getTypeByName("opencl.image2d_ro_t.int") ||
968 module->getTypeByName("opencl.image2d_ro_t.int.sampled") ||
969 module->getTypeByName("opencl.image2d_wo_t.int") ||
970 module->getTypeByName("opencl.image3d_ro_t.int") ||
971 module->getTypeByName("opencl.image3d_ro_t.int.sampled") ||
972 module->getTypeByName("opencl.image3d_wo_t.int") ||
973 module->getTypeByName("opencl.image1d_array_ro_t.int") ||
974 module->getTypeByName("opencl.image1d_array_ro_t.int.sampled") ||
975 module->getTypeByName("opencl.image1d_array_wo_t.int") ||
976 module->getTypeByName("opencl.image2d_array_ro_t.int") ||
977 module->getTypeByName("opencl.image2d_array_ro_t.int.sampled") ||
978 module->getTypeByName("opencl.image2d_array_wo_t.int")) {
alan-bakerf67468c2019-11-25 15:51:49 -0500979 // Nothing for now...
980 } else {
981 // This was likely an UndefValue.
David Neto22f144c2017-06-12 14:26:21 -0400982 FindType(Type::getFloatTy(Context));
983 }
984
985 // Collect types' information from function.
986 FindTypePerFunc(F);
987
988 // Collect constant information from function.
989 FindConstantPerFunc(F);
990 }
991}
992
SJW77b87ad2020-04-21 14:37:52 -0500993void SPIRVProducerPass::FindGlobalConstVars() {
994 clspv::NormalizeGlobalVariables(*module);
995 const DataLayout &DL = module->getDataLayout();
alan-baker56f7aff2019-05-22 08:06:42 -0400996
David Neto862b7d82018-06-14 18:48:37 -0400997 SmallVector<GlobalVariable *, 8> GVList;
998 SmallVector<GlobalVariable *, 8> DeadGVList;
SJW77b87ad2020-04-21 14:37:52 -0500999 for (GlobalVariable &GV : module->globals()) {
David Neto862b7d82018-06-14 18:48:37 -04001000 if (GV.getType()->getAddressSpace() == AddressSpace::Constant) {
1001 if (GV.use_empty()) {
1002 DeadGVList.push_back(&GV);
1003 } else {
1004 GVList.push_back(&GV);
1005 }
1006 }
1007 }
1008
1009 // Remove dead global __constant variables.
1010 for (auto GV : DeadGVList) {
1011 GV->eraseFromParent();
1012 }
1013 DeadGVList.clear();
1014
1015 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
1016 // For now, we only support a single storage buffer.
1017 if (GVList.size() > 0) {
1018 assert(GVList.size() == 1);
1019 const auto *GV = GVList[0];
1020 const auto constants_byte_size =
Alan Bakerfcda9482018-10-02 17:09:59 -04001021 (GetTypeSizeInBits(GV->getInitializer()->getType(), DL)) / 8;
David Neto862b7d82018-06-14 18:48:37 -04001022 const size_t kConstantMaxSize = 65536;
1023 if (constants_byte_size > kConstantMaxSize) {
1024 outs() << "Max __constant capacity of " << kConstantMaxSize
1025 << " bytes exceeded: " << constants_byte_size << " bytes used\n";
1026 llvm_unreachable("Max __constant capacity exceeded");
1027 }
1028 }
1029 } else {
1030 // Change global constant variable's address space to ModuleScopePrivate.
1031 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
1032 for (auto GV : GVList) {
1033 // Create new gv with ModuleScopePrivate address space.
1034 Type *NewGVTy = GV->getType()->getPointerElementType();
1035 GlobalVariable *NewGV = new GlobalVariable(
SJW77b87ad2020-04-21 14:37:52 -05001036 *module, NewGVTy, false, GV->getLinkage(), GV->getInitializer(), "",
David Neto862b7d82018-06-14 18:48:37 -04001037 nullptr, GV->getThreadLocalMode(), AddressSpace::ModuleScopePrivate);
1038 NewGV->takeName(GV);
1039
1040 const SmallVector<User *, 8> GVUsers(GV->user_begin(), GV->user_end());
1041 SmallVector<User *, 8> CandidateUsers;
1042
1043 auto record_called_function_type_as_user =
1044 [&GlobalConstFuncTyMap](Value *gv, CallInst *call) {
1045 // Find argument index.
1046 unsigned index = 0;
1047 for (unsigned i = 0; i < call->getNumArgOperands(); i++) {
1048 if (gv == call->getOperand(i)) {
1049 // TODO(dneto): Should we break here?
1050 index = i;
1051 }
1052 }
1053
1054 // Record function type with global constant.
1055 GlobalConstFuncTyMap[call->getFunctionType()] =
1056 std::make_pair(call->getFunctionType(), index);
1057 };
1058
1059 for (User *GVU : GVUsers) {
1060 if (CallInst *Call = dyn_cast<CallInst>(GVU)) {
1061 record_called_function_type_as_user(GV, Call);
1062 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(GVU)) {
1063 // Check GEP users.
1064 for (User *GEPU : GEP->users()) {
1065 if (CallInst *GEPCall = dyn_cast<CallInst>(GEPU)) {
1066 record_called_function_type_as_user(GEP, GEPCall);
1067 }
1068 }
1069 }
1070
1071 CandidateUsers.push_back(GVU);
1072 }
1073
1074 for (User *U : CandidateUsers) {
1075 // Update users of gv with new gv.
alan-bakered80f572019-02-11 17:28:26 -05001076 if (!isa<Constant>(U)) {
1077 // #254: Can't change operands of a constant, but this shouldn't be
1078 // something that sticks around in the module.
1079 U->replaceUsesOfWith(GV, NewGV);
1080 }
David Neto862b7d82018-06-14 18:48:37 -04001081 }
1082
1083 // Delete original gv.
1084 GV->eraseFromParent();
1085 }
1086 }
1087}
1088
SJW77b87ad2020-04-21 14:37:52 -05001089void SPIRVProducerPass::FindResourceVars() {
David Neto862b7d82018-06-14 18:48:37 -04001090 ResourceVarInfoList.clear();
1091 FunctionToResourceVarsMap.clear();
1092 ModuleOrderedResourceVars.reset();
1093 // Normally, there is one resource variable per clspv.resource.var.*
1094 // function, since that is unique'd by arg type and index. By design,
1095 // we can share these resource variables across kernels because all
1096 // kernels use the same descriptor set.
1097 //
1098 // But if the user requested distinct descriptor sets per kernel, then
1099 // the descriptor allocator has made different (set,binding) pairs for
1100 // the same (type,arg_index) pair. Since we can decorate a resource
1101 // variable with only exactly one DescriptorSet and Binding, we are
1102 // forced in this case to make distinct resource variables whenever
Kévin Petitbbbda972020-03-03 19:16:31 +00001103 // the same clspv.resource.var.X function is seen with disintct
David Neto862b7d82018-06-14 18:48:37 -04001104 // (set,binding) values.
1105 const bool always_distinct_sets =
1106 clspv::Option::DistinctKernelDescriptorSets();
SJW77b87ad2020-04-21 14:37:52 -05001107 for (Function &F : *module) {
David Neto862b7d82018-06-14 18:48:37 -04001108 // Rely on the fact the resource var functions have a stable ordering
1109 // in the module.
Alan Baker202c8c72018-08-13 13:47:44 -04001110 if (F.getName().startswith(clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001111 // Find all calls to this function with distinct set and binding pairs.
1112 // Save them in ResourceVarInfoList.
1113
1114 // Determine uniqueness of the (set,binding) pairs only withing this
1115 // one resource-var builtin function.
1116 using SetAndBinding = std::pair<unsigned, unsigned>;
1117 // Maps set and binding to the resource var info.
1118 DenseMap<SetAndBinding, ResourceVarInfo *> set_and_binding_map;
1119 bool first_use = true;
1120 for (auto &U : F.uses()) {
1121 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
1122 const auto set = unsigned(
1123 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
1124 const auto binding = unsigned(
1125 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
1126 const auto arg_kind = clspv::ArgKind(
1127 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
1128 const auto arg_index = unsigned(
1129 dyn_cast<ConstantInt>(call->getArgOperand(3))->getZExtValue());
alan-bakere9308012019-03-15 10:25:13 -04001130 const auto coherent = unsigned(
1131 dyn_cast<ConstantInt>(call->getArgOperand(5))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04001132
1133 // Find or make the resource var info for this combination.
1134 ResourceVarInfo *rv = nullptr;
1135 if (always_distinct_sets) {
1136 // Make a new resource var any time we see a different
1137 // (set,binding) pair.
1138 SetAndBinding key{set, binding};
1139 auto where = set_and_binding_map.find(key);
1140 if (where == set_and_binding_map.end()) {
1141 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
alan-bakere9308012019-03-15 10:25:13 -04001142 binding, &F, arg_kind, coherent);
David Neto862b7d82018-06-14 18:48:37 -04001143 ResourceVarInfoList.emplace_back(rv);
1144 set_and_binding_map[key] = rv;
1145 } else {
1146 rv = where->second;
1147 }
1148 } else {
1149 // The default is to make exactly one resource for each
1150 // clspv.resource.var.* function.
1151 if (first_use) {
1152 first_use = false;
1153 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
alan-bakere9308012019-03-15 10:25:13 -04001154 binding, &F, arg_kind, coherent);
David Neto862b7d82018-06-14 18:48:37 -04001155 ResourceVarInfoList.emplace_back(rv);
1156 } else {
1157 rv = ResourceVarInfoList.back().get();
1158 }
1159 }
1160
1161 // Now populate FunctionToResourceVarsMap.
1162 auto &mapping =
1163 FunctionToResourceVarsMap[call->getParent()->getParent()];
1164 while (mapping.size() <= arg_index) {
1165 mapping.push_back(nullptr);
1166 }
1167 mapping[arg_index] = rv;
1168 }
1169 }
1170 }
1171 }
1172
1173 // Populate ModuleOrderedResourceVars.
SJW77b87ad2020-04-21 14:37:52 -05001174 for (Function &F : *module) {
David Neto862b7d82018-06-14 18:48:37 -04001175 auto where = FunctionToResourceVarsMap.find(&F);
1176 if (where != FunctionToResourceVarsMap.end()) {
1177 for (auto &rv : where->second) {
1178 if (rv != nullptr) {
1179 ModuleOrderedResourceVars.insert(rv);
1180 }
1181 }
1182 }
1183 }
1184 if (ShowResourceVars) {
1185 for (auto *info : ModuleOrderedResourceVars) {
1186 outs() << "MORV index " << info->index << " (" << info->descriptor_set
1187 << "," << info->binding << ") " << *(info->var_fn->getReturnType())
1188 << "\n";
1189 }
1190 }
1191}
1192
SJW77b87ad2020-04-21 14:37:52 -05001193bool SPIRVProducerPass::FindExtInst() {
1194 LLVMContext &Context = module->getContext();
David Neto22f144c2017-06-12 14:26:21 -04001195 bool HasExtInst = false;
1196
SJW77b87ad2020-04-21 14:37:52 -05001197 for (Function &F : *module) {
David Neto22f144c2017-06-12 14:26:21 -04001198 for (BasicBlock &BB : F) {
1199 for (Instruction &I : BB) {
1200 if (CallInst *Call = dyn_cast<CallInst>(&I)) {
1201 Function *Callee = Call->getCalledFunction();
1202 // Check whether this call is for extend instructions.
David Neto3fbb4072017-10-16 11:28:14 -04001203 auto callee_name = Callee->getName();
1204 const glsl::ExtInst EInst = getExtInstEnum(callee_name);
1205 const glsl::ExtInst IndirectEInst =
1206 getIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04001207
David Neto3fbb4072017-10-16 11:28:14 -04001208 HasExtInst |=
1209 (EInst != kGlslExtInstBad) || (IndirectEInst != kGlslExtInstBad);
1210
1211 if (IndirectEInst) {
1212 // Register extra constants if needed.
1213
1214 // Registers a type and constant for computing the result of the
1215 // given instruction. If the result of the instruction is a vector,
1216 // then make a splat vector constant with the same number of
1217 // elements.
1218 auto register_constant = [this, &I](Constant *constant) {
1219 FindType(constant->getType());
1220 FindConstant(constant);
1221 if (auto *vectorTy = dyn_cast<VectorType>(I.getType())) {
1222 // Register the splat vector of the value with the same
1223 // width as the result of the instruction.
1224 auto *vec_constant = ConstantVector::getSplat(
alan-baker7261e062020-03-15 14:35:48 -04001225 {static_cast<unsigned>(vectorTy->getNumElements()), false},
David Neto3fbb4072017-10-16 11:28:14 -04001226 constant);
1227 FindConstant(vec_constant);
1228 FindType(vec_constant->getType());
1229 }
1230 };
1231 switch (IndirectEInst) {
1232 case glsl::ExtInstFindUMsb:
1233 // clz needs OpExtInst and OpISub with constant 31, or splat
1234 // vector of 31. Add it to the constant list here.
1235 register_constant(
1236 ConstantInt::get(Type::getInt32Ty(Context), 31));
1237 break;
1238 case glsl::ExtInstAcos:
1239 case glsl::ExtInstAsin:
Kévin Petiteb9f90a2018-09-29 12:29:34 +01001240 case glsl::ExtInstAtan:
David Neto3fbb4072017-10-16 11:28:14 -04001241 case glsl::ExtInstAtan2:
1242 // We need 1/pi for acospi, asinpi, atan2pi.
1243 register_constant(
1244 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
1245 break;
1246 default:
1247 assert(false && "internally inconsistent");
1248 }
David Neto22f144c2017-06-12 14:26:21 -04001249 }
1250 }
1251 }
1252 }
1253 }
1254
1255 return HasExtInst;
1256}
1257
1258void SPIRVProducerPass::FindTypePerGlobalVar(GlobalVariable &GV) {
1259 // Investigate global variable's type.
1260 FindType(GV.getType());
1261}
1262
1263void SPIRVProducerPass::FindTypePerFunc(Function &F) {
1264 // Investigate function's type.
1265 FunctionType *FTy = F.getFunctionType();
1266
1267 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
1268 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
David Neto9ed8e2f2018-03-24 06:47:24 -07001269 // Handle a regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04001270 if (GlobalConstFuncTyMap.count(FTy)) {
1271 uint32_t GVCstArgIdx = GlobalConstFuncTypeMap[FTy].second;
1272 SmallVector<Type *, 4> NewFuncParamTys;
1273 for (unsigned i = 0; i < FTy->getNumParams(); i++) {
1274 Type *ParamTy = FTy->getParamType(i);
1275 if (i == GVCstArgIdx) {
1276 Type *EleTy = ParamTy->getPointerElementType();
1277 ParamTy = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1278 }
1279
1280 NewFuncParamTys.push_back(ParamTy);
1281 }
1282
1283 FunctionType *NewFTy =
1284 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1285 GlobalConstFuncTyMap[FTy] = std::make_pair(NewFTy, GVCstArgIdx);
1286 FTy = NewFTy;
1287 }
1288
1289 FindType(FTy);
1290 } else {
1291 // As kernel functions do not have parameters, create new function type and
1292 // add it to type map.
1293 SmallVector<Type *, 4> NewFuncParamTys;
1294 FunctionType *NewFTy =
1295 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1296 FindType(NewFTy);
1297 }
1298
1299 // Investigate instructions' type in function body.
1300 for (BasicBlock &BB : F) {
1301 for (Instruction &I : BB) {
1302 if (isa<ShuffleVectorInst>(I)) {
1303 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1304 // Ignore type for mask of shuffle vector instruction.
1305 if (i == 2) {
1306 continue;
1307 }
1308
1309 Value *Op = I.getOperand(i);
1310 if (!isa<MetadataAsValue>(Op)) {
1311 FindType(Op->getType());
1312 }
1313 }
1314
1315 FindType(I.getType());
1316 continue;
1317 }
1318
David Neto862b7d82018-06-14 18:48:37 -04001319 CallInst *Call = dyn_cast<CallInst>(&I);
1320
1321 if (Call && Call->getCalledFunction()->getName().startswith(
Alan Baker202c8c72018-08-13 13:47:44 -04001322 clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001323 // This is a fake call representing access to a resource variable.
1324 // We handle that elsewhere.
1325 continue;
1326 }
1327
Alan Baker202c8c72018-08-13 13:47:44 -04001328 if (Call && Call->getCalledFunction()->getName().startswith(
1329 clspv::WorkgroupAccessorFunction())) {
1330 // This is a fake call representing access to a workgroup variable.
1331 // We handle that elsewhere.
1332 continue;
1333 }
1334
alan-bakerf083bed2020-01-29 08:15:42 -05001335 // #497: InsertValue and ExtractValue map to OpCompositeInsert and
1336 // OpCompositeExtract which takes literal values for indices. As a result
1337 // don't map the type of indices.
1338 if (I.getOpcode() == Instruction::ExtractValue) {
1339 FindType(I.getOperand(0)->getType());
1340 continue;
1341 }
1342 if (I.getOpcode() == Instruction::InsertValue) {
1343 FindType(I.getOperand(0)->getType());
1344 FindType(I.getOperand(1)->getType());
1345 continue;
1346 }
1347
1348 // #497: InsertElement and ExtractElement map to OpCompositeExtract if
1349 // the index is a constant. In such a case don't map the index type.
1350 if (I.getOpcode() == Instruction::ExtractElement) {
1351 FindType(I.getOperand(0)->getType());
1352 Value *op1 = I.getOperand(1);
1353 if (!isa<Constant>(op1) || isa<GlobalValue>(op1)) {
1354 FindType(op1->getType());
1355 }
1356 continue;
1357 }
1358 if (I.getOpcode() == Instruction::InsertElement) {
1359 FindType(I.getOperand(0)->getType());
1360 FindType(I.getOperand(1)->getType());
1361 Value *op2 = I.getOperand(2);
1362 if (!isa<Constant>(op2) || isa<GlobalValue>(op2)) {
1363 FindType(op2->getType());
1364 }
1365 continue;
1366 }
1367
David Neto22f144c2017-06-12 14:26:21 -04001368 // Work through the operands of the instruction.
1369 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1370 Value *const Op = I.getOperand(i);
1371 // If any of the operands is a constant, find the type!
1372 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1373 FindType(Op->getType());
1374 }
1375 }
1376
1377 for (Use &Op : I.operands()) {
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001378 if (isa<CallInst>(&I)) {
David Neto22f144c2017-06-12 14:26:21 -04001379 // Avoid to check call instruction's type.
1380 break;
1381 }
Alan Baker202c8c72018-08-13 13:47:44 -04001382 if (CallInst *OpCall = dyn_cast<CallInst>(Op)) {
1383 if (OpCall && OpCall->getCalledFunction()->getName().startswith(
1384 clspv::WorkgroupAccessorFunction())) {
1385 // This is a fake call representing access to a workgroup variable.
1386 // We handle that elsewhere.
1387 continue;
1388 }
1389 }
David Neto22f144c2017-06-12 14:26:21 -04001390 if (!isa<MetadataAsValue>(&Op)) {
1391 FindType(Op->getType());
1392 continue;
1393 }
1394 }
1395
David Neto22f144c2017-06-12 14:26:21 -04001396 // We don't want to track the type of this call as we are going to replace
1397 // it.
Kévin Petitdf71de32019-04-09 14:09:50 +01001398 if (Call && (clspv::LiteralSamplerFunction() ==
David Neto22f144c2017-06-12 14:26:21 -04001399 Call->getCalledFunction()->getName())) {
1400 continue;
1401 }
1402
1403 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
1404 // If gep's base operand has ModuleScopePrivate address space, make gep
1405 // return ModuleScopePrivate address space.
1406 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate) {
1407 // Add pointer type with private address space for global constant to
1408 // type list.
1409 Type *EleTy = I.getType()->getPointerElementType();
1410 Type *NewPTy =
1411 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1412
1413 FindType(NewPTy);
1414 continue;
1415 }
1416 }
1417
1418 FindType(I.getType());
1419 }
1420 }
1421}
1422
SJW77b87ad2020-04-21 14:37:52 -05001423void SPIRVProducerPass::FindTypesForSamplerMap() {
David Neto862b7d82018-06-14 18:48:37 -04001424 // If we are using a sampler map, find the type of the sampler.
SJW77b87ad2020-04-21 14:37:52 -05001425 if (module->getFunction(clspv::LiteralSamplerFunction()) ||
David Neto862b7d82018-06-14 18:48:37 -04001426 0 < getSamplerMap().size()) {
SJW77b87ad2020-04-21 14:37:52 -05001427 auto SamplerStructTy = module->getTypeByName("opencl.sampler_t");
David Neto862b7d82018-06-14 18:48:37 -04001428 if (!SamplerStructTy) {
SJW77b87ad2020-04-21 14:37:52 -05001429 SamplerStructTy =
1430 StructType::create(module->getContext(), "opencl.sampler_t");
David Neto862b7d82018-06-14 18:48:37 -04001431 }
1432
1433 SamplerTy = SamplerStructTy->getPointerTo(AddressSpace::UniformConstant);
1434
1435 FindType(SamplerTy);
1436 }
1437}
1438
SJW77b87ad2020-04-21 14:37:52 -05001439void SPIRVProducerPass::FindTypesForResourceVars() {
David Neto862b7d82018-06-14 18:48:37 -04001440 // Record types so they are generated.
1441 TypesNeedingLayout.reset();
1442 StructTypesNeedingBlock.reset();
1443
1444 // To match older clspv codegen, generate the float type first if required
1445 // for images.
1446 for (const auto *info : ModuleOrderedResourceVars) {
1447 if (info->arg_kind == clspv::ArgKind::ReadOnlyImage ||
1448 info->arg_kind == clspv::ArgKind::WriteOnlyImage) {
alan-bakerf67468c2019-11-25 15:51:49 -05001449 if (IsIntImageType(info->var_fn->getReturnType())) {
1450 // Nothing for now...
1451 } else if (IsUintImageType(info->var_fn->getReturnType())) {
SJW77b87ad2020-04-21 14:37:52 -05001452 FindType(Type::getInt32Ty(module->getContext()));
alan-bakerf67468c2019-11-25 15:51:49 -05001453 }
1454
1455 // We need "float" either for the sampled type or for the Lod operand.
SJW77b87ad2020-04-21 14:37:52 -05001456 FindType(Type::getFloatTy(module->getContext()));
David Neto862b7d82018-06-14 18:48:37 -04001457 }
1458 }
1459
1460 for (const auto *info : ModuleOrderedResourceVars) {
1461 Type *type = info->var_fn->getReturnType();
1462
1463 switch (info->arg_kind) {
1464 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04001465 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04001466 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1467 StructTypesNeedingBlock.insert(sty);
1468 } else {
1469 errs() << *type << "\n";
1470 llvm_unreachable("Buffer arguments must map to structures!");
1471 }
1472 break;
1473 case clspv::ArgKind::Pod:
alan-baker9b0ec3c2020-04-06 14:45:34 -04001474 case clspv::ArgKind::PodUBO:
1475 case clspv::ArgKind::PodPushConstant:
David Neto862b7d82018-06-14 18:48:37 -04001476 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1477 StructTypesNeedingBlock.insert(sty);
1478 } else {
1479 errs() << *type << "\n";
1480 llvm_unreachable("POD arguments must map to structures!");
1481 }
1482 break;
1483 case clspv::ArgKind::ReadOnlyImage:
1484 case clspv::ArgKind::WriteOnlyImage:
1485 case clspv::ArgKind::Sampler:
1486 // Sampler and image types map to the pointee type but
1487 // in the uniform constant address space.
1488 type = PointerType::get(type->getPointerElementType(),
1489 clspv::AddressSpace::UniformConstant);
1490 break;
1491 default:
1492 break;
1493 }
1494
1495 // The converted type is the type of the OpVariable we will generate.
1496 // If the pointee type is an array of size zero, FindType will convert it
1497 // to a runtime array.
1498 FindType(type);
1499 }
1500
alan-bakerdcd97412019-09-16 15:32:30 -04001501 // If module constants are clustered in a storage buffer then that struct
1502 // needs layout decorations.
1503 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
SJW77b87ad2020-04-21 14:37:52 -05001504 for (GlobalVariable &GV : module->globals()) {
alan-bakerdcd97412019-09-16 15:32:30 -04001505 PointerType *PTy = cast<PointerType>(GV.getType());
1506 const auto AS = PTy->getAddressSpace();
1507 const bool module_scope_constant_external_init =
1508 (AS == AddressSpace::Constant) && GV.hasInitializer();
1509 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
1510 if (module_scope_constant_external_init &&
1511 spv::BuiltInMax == BuiltinType) {
1512 StructTypesNeedingBlock.insert(
1513 cast<StructType>(PTy->getPointerElementType()));
1514 }
1515 }
1516 }
1517
SJW77b87ad2020-04-21 14:37:52 -05001518 for (const GlobalVariable &GV : module->globals()) {
Kévin Petitbbbda972020-03-03 19:16:31 +00001519 if (GV.getAddressSpace() == clspv::AddressSpace::PushConstant) {
1520 auto Ty = cast<PointerType>(GV.getType())->getPointerElementType();
1521 assert(Ty->isStructTy() && "Push constants have to be structures.");
1522 auto STy = cast<StructType>(Ty);
1523 StructTypesNeedingBlock.insert(STy);
1524 }
1525 }
1526
David Neto862b7d82018-06-14 18:48:37 -04001527 // Traverse the arrays and structures underneath each Block, and
1528 // mark them as needing layout.
1529 std::vector<Type *> work_list(StructTypesNeedingBlock.begin(),
1530 StructTypesNeedingBlock.end());
1531 while (!work_list.empty()) {
1532 Type *type = work_list.back();
1533 work_list.pop_back();
1534 TypesNeedingLayout.insert(type);
1535 switch (type->getTypeID()) {
1536 case Type::ArrayTyID:
1537 work_list.push_back(type->getArrayElementType());
1538 if (!Hack_generate_runtime_array_stride_early) {
1539 // Remember this array type for deferred decoration.
1540 TypesNeedingArrayStride.insert(type);
1541 }
1542 break;
1543 case Type::StructTyID:
1544 for (auto *elem_ty : cast<StructType>(type)->elements()) {
1545 work_list.push_back(elem_ty);
1546 }
1547 default:
1548 // This type and its contained types don't get layout.
1549 break;
1550 }
1551 }
1552}
1553
SJW77b87ad2020-04-21 14:37:52 -05001554void SPIRVProducerPass::FindWorkgroupVars() {
Alan Baker202c8c72018-08-13 13:47:44 -04001555 // The SpecId assignment for pointer-to-local arguments is recorded in
1556 // module-level metadata. Translate that information into local argument
1557 // information.
SJW77b87ad2020-04-21 14:37:52 -05001558 NamedMDNode *nmd = module->getNamedMetadata(clspv::LocalSpecIdMetadataName());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001559 if (!nmd)
1560 return;
Alan Baker202c8c72018-08-13 13:47:44 -04001561 for (auto operand : nmd->operands()) {
1562 MDTuple *tuple = cast<MDTuple>(operand);
1563 ValueAsMetadata *fn_md = cast<ValueAsMetadata>(tuple->getOperand(0));
1564 Function *func = cast<Function>(fn_md->getValue());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001565 ConstantAsMetadata *arg_index_md =
1566 cast<ConstantAsMetadata>(tuple->getOperand(1));
1567 int arg_index = static_cast<int>(
1568 cast<ConstantInt>(arg_index_md->getValue())->getSExtValue());
1569 Argument *arg = &*(func->arg_begin() + arg_index);
Alan Baker202c8c72018-08-13 13:47:44 -04001570
1571 ConstantAsMetadata *spec_id_md =
1572 cast<ConstantAsMetadata>(tuple->getOperand(2));
alan-bakerb6b09dc2018-11-08 16:59:28 -05001573 int spec_id = static_cast<int>(
1574 cast<ConstantInt>(spec_id_md->getValue())->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04001575
Alan Baker202c8c72018-08-13 13:47:44 -04001576 LocalArgSpecIds[arg] = spec_id;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001577 if (LocalSpecIdInfoMap.count(spec_id))
1578 continue;
Alan Baker202c8c72018-08-13 13:47:44 -04001579
1580 // We haven't seen this SpecId yet, so generate the LocalArgInfo for it.
1581 LocalArgInfo info{nextID, arg->getType()->getPointerElementType(),
1582 nextID + 1, nextID + 2,
1583 nextID + 3, spec_id};
1584 LocalSpecIdInfoMap[spec_id] = info;
1585 nextID += 4;
1586
1587 // Ensure the types necessary for this argument get generated.
SJW77b87ad2020-04-21 14:37:52 -05001588 Type *IdxTy = Type::getInt32Ty(module->getContext());
Alan Baker202c8c72018-08-13 13:47:44 -04001589 FindConstant(ConstantInt::get(IdxTy, 0));
1590 FindType(IdxTy);
1591 FindType(arg->getType());
1592 }
1593}
1594
David Neto22f144c2017-06-12 14:26:21 -04001595void SPIRVProducerPass::FindType(Type *Ty) {
1596 TypeList &TyList = getTypeList();
1597
1598 if (0 != TyList.idFor(Ty)) {
1599 return;
1600 }
1601
1602 if (Ty->isPointerTy()) {
1603 auto AddrSpace = Ty->getPointerAddressSpace();
1604 if ((AddressSpace::Constant == AddrSpace) ||
1605 (AddressSpace::Global == AddrSpace)) {
1606 auto PointeeTy = Ty->getPointerElementType();
1607
1608 if (PointeeTy->isStructTy() &&
1609 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1610 FindType(PointeeTy);
1611 auto ActualPointerTy =
1612 PointeeTy->getPointerTo(AddressSpace::UniformConstant);
1613 FindType(ActualPointerTy);
1614 return;
1615 }
1616 }
1617 }
1618
David Neto862b7d82018-06-14 18:48:37 -04001619 // By convention, LLVM array type with 0 elements will map to
1620 // OpTypeRuntimeArray. Otherwise, it will map to OpTypeArray, which
1621 // has a constant number of elements. We need to support type of the
1622 // constant.
1623 if (auto *arrayTy = dyn_cast<ArrayType>(Ty)) {
1624 if (arrayTy->getNumElements() > 0) {
1625 LLVMContext &Context = Ty->getContext();
1626 FindType(Type::getInt32Ty(Context));
1627 }
David Neto22f144c2017-06-12 14:26:21 -04001628 }
1629
1630 for (Type *SubTy : Ty->subtypes()) {
1631 FindType(SubTy);
1632 }
1633
1634 TyList.insert(Ty);
1635}
1636
1637void SPIRVProducerPass::FindConstantPerGlobalVar(GlobalVariable &GV) {
1638 // If the global variable has a (non undef) initializer.
1639 if (GV.hasInitializer() && !isa<UndefValue>(GV.getInitializer())) {
David Neto862b7d82018-06-14 18:48:37 -04001640 // Generate the constant if it's not the initializer to a module scope
1641 // constant that we will expect in a storage buffer.
1642 const bool module_scope_constant_external_init =
1643 (GV.getType()->getPointerAddressSpace() == AddressSpace::Constant) &&
1644 clspv::Option::ModuleConstantsInStorageBuffer();
1645 if (!module_scope_constant_external_init) {
1646 FindConstant(GV.getInitializer());
1647 }
David Neto22f144c2017-06-12 14:26:21 -04001648 }
1649}
1650
1651void SPIRVProducerPass::FindConstantPerFunc(Function &F) {
1652 // Investigate constants in function body.
1653 for (BasicBlock &BB : F) {
1654 for (Instruction &I : BB) {
David Neto862b7d82018-06-14 18:48:37 -04001655 if (auto *call = dyn_cast<CallInst>(&I)) {
1656 auto name = call->getCalledFunction()->getName();
Kévin Petitdf71de32019-04-09 14:09:50 +01001657 if (name == clspv::LiteralSamplerFunction()) {
David Neto862b7d82018-06-14 18:48:37 -04001658 // We've handled these constants elsewhere, so skip it.
1659 continue;
1660 }
Alan Baker202c8c72018-08-13 13:47:44 -04001661 if (name.startswith(clspv::ResourceAccessorFunction())) {
1662 continue;
1663 }
1664 if (name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001665 continue;
1666 }
Kévin Petit617a76d2019-04-04 13:54:16 +01001667 if (name.startswith(clspv::SPIRVOpIntrinsicFunction())) {
1668 // Skip the first operand that has the SPIR-V Opcode
1669 for (unsigned i = 1; i < I.getNumOperands(); i++) {
1670 if (isa<Constant>(I.getOperand(i)) &&
1671 !isa<GlobalValue>(I.getOperand(i))) {
1672 FindConstant(I.getOperand(i));
1673 }
1674 }
1675 continue;
1676 }
David Neto22f144c2017-06-12 14:26:21 -04001677 }
1678
1679 if (isa<AllocaInst>(I)) {
1680 // Alloca instruction has constant for the number of element. Ignore it.
1681 continue;
1682 } else if (isa<ShuffleVectorInst>(I)) {
1683 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1684 // Ignore constant for mask of shuffle vector instruction.
1685 if (i == 2) {
1686 continue;
1687 }
1688
1689 if (isa<Constant>(I.getOperand(i)) &&
1690 !isa<GlobalValue>(I.getOperand(i))) {
1691 FindConstant(I.getOperand(i));
1692 }
1693 }
1694
1695 continue;
1696 } else if (isa<InsertElementInst>(I)) {
1697 // Handle InsertElement with <4 x i8> specially.
1698 Type *CompositeTy = I.getOperand(0)->getType();
1699 if (is4xi8vec(CompositeTy)) {
1700 LLVMContext &Context = CompositeTy->getContext();
1701 if (isa<Constant>(I.getOperand(0))) {
1702 FindConstant(I.getOperand(0));
1703 }
1704
1705 if (isa<Constant>(I.getOperand(1))) {
1706 FindConstant(I.getOperand(1));
1707 }
1708
1709 // Add mask constant 0xFF.
1710 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1711 FindConstant(CstFF);
1712
1713 // Add shift amount constant.
1714 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
1715 uint64_t Idx = CI->getZExtValue();
1716 Constant *CstShiftAmount =
1717 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1718 FindConstant(CstShiftAmount);
1719 }
1720
1721 continue;
1722 }
1723
1724 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1725 // Ignore constant for index of InsertElement instruction.
1726 if (i == 2) {
1727 continue;
1728 }
1729
1730 if (isa<Constant>(I.getOperand(i)) &&
1731 !isa<GlobalValue>(I.getOperand(i))) {
1732 FindConstant(I.getOperand(i));
1733 }
1734 }
1735
1736 continue;
1737 } else if (isa<ExtractElementInst>(I)) {
1738 // Handle ExtractElement with <4 x i8> specially.
1739 Type *CompositeTy = I.getOperand(0)->getType();
1740 if (is4xi8vec(CompositeTy)) {
1741 LLVMContext &Context = CompositeTy->getContext();
1742 if (isa<Constant>(I.getOperand(0))) {
1743 FindConstant(I.getOperand(0));
1744 }
1745
1746 // Add mask constant 0xFF.
1747 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1748 FindConstant(CstFF);
1749
1750 // Add shift amount constant.
1751 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
1752 uint64_t Idx = CI->getZExtValue();
1753 Constant *CstShiftAmount =
1754 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1755 FindConstant(CstShiftAmount);
1756 } else {
1757 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
1758 FindConstant(Cst8);
1759 }
1760
1761 continue;
1762 }
1763
1764 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1765 // Ignore constant for index of ExtractElement instruction.
1766 if (i == 1) {
1767 continue;
1768 }
1769
1770 if (isa<Constant>(I.getOperand(i)) &&
1771 !isa<GlobalValue>(I.getOperand(i))) {
1772 FindConstant(I.getOperand(i));
1773 }
1774 }
1775
1776 continue;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001777 } else if ((Instruction::Xor == I.getOpcode()) &&
1778 I.getType()->isIntegerTy(1)) {
1779 // We special case for Xor where the type is i1 and one of the arguments
1780 // is a constant 1 (true), this is an OpLogicalNot in SPIR-V, and we
1781 // don't need the constant
David Neto22f144c2017-06-12 14:26:21 -04001782 bool foundConstantTrue = false;
1783 for (Use &Op : I.operands()) {
1784 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1785 auto CI = cast<ConstantInt>(Op);
1786
1787 if (CI->isZero() || foundConstantTrue) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05001788 // If we already found the true constant, we might (probably only
1789 // on -O0) have an OpLogicalNot which is taking a constant
1790 // argument, so discover it anyway.
David Neto22f144c2017-06-12 14:26:21 -04001791 FindConstant(Op);
1792 } else {
1793 foundConstantTrue = true;
1794 }
1795 }
1796 }
1797
1798 continue;
David Netod2de94a2017-08-28 17:27:47 -04001799 } else if (isa<TruncInst>(I)) {
alan-bakerb39c8262019-03-08 14:03:37 -05001800 // Special case if i8 is not generally handled.
1801 if (!clspv::Option::Int8Support()) {
1802 // For truncation to i8 we mask against 255.
1803 Type *ToTy = I.getType();
1804 if (8u == ToTy->getPrimitiveSizeInBits()) {
1805 LLVMContext &Context = ToTy->getContext();
1806 Constant *Cst255 =
1807 ConstantInt::get(Type::getInt32Ty(Context), 0xff);
1808 FindConstant(Cst255);
1809 }
David Netod2de94a2017-08-28 17:27:47 -04001810 }
Neil Henning39672102017-09-29 14:33:13 +01001811 } else if (isa<AtomicRMWInst>(I)) {
1812 LLVMContext &Context = I.getContext();
1813
1814 FindConstant(
1815 ConstantInt::get(Type::getInt32Ty(Context), spv::ScopeDevice));
1816 FindConstant(ConstantInt::get(
1817 Type::getInt32Ty(Context),
1818 spv::MemorySemanticsUniformMemoryMask |
1819 spv::MemorySemanticsSequentiallyConsistentMask));
David Neto22f144c2017-06-12 14:26:21 -04001820 }
1821
1822 for (Use &Op : I.operands()) {
1823 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1824 FindConstant(Op);
1825 }
1826 }
1827 }
1828 }
1829}
1830
1831void SPIRVProducerPass::FindConstant(Value *V) {
David Neto22f144c2017-06-12 14:26:21 -04001832 ValueList &CstList = getConstantList();
1833
David Netofb9a7972017-08-25 17:08:24 -04001834 // If V is already tracked, ignore it.
1835 if (0 != CstList.idFor(V)) {
David Neto22f144c2017-06-12 14:26:21 -04001836 return;
1837 }
1838
David Neto862b7d82018-06-14 18:48:37 -04001839 if (isa<GlobalValue>(V) && clspv::Option::ModuleConstantsInStorageBuffer()) {
1840 return;
1841 }
1842
David Neto22f144c2017-06-12 14:26:21 -04001843 Constant *Cst = cast<Constant>(V);
David Neto862b7d82018-06-14 18:48:37 -04001844 Type *CstTy = Cst->getType();
David Neto22f144c2017-06-12 14:26:21 -04001845
1846 // Handle constant with <4 x i8> type specially.
David Neto22f144c2017-06-12 14:26:21 -04001847 if (is4xi8vec(CstTy)) {
1848 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001849 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001850 }
1851 }
1852
1853 if (Cst->getNumOperands()) {
1854 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end(); I != E;
1855 ++I) {
1856 FindConstant(*I);
1857 }
1858
David Netofb9a7972017-08-25 17:08:24 -04001859 CstList.insert(Cst);
David Neto22f144c2017-06-12 14:26:21 -04001860 return;
1861 } else if (const ConstantDataSequential *CDS =
1862 dyn_cast<ConstantDataSequential>(Cst)) {
1863 // Add constants for each element to constant list.
1864 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
1865 Constant *EleCst = CDS->getElementAsConstant(i);
1866 FindConstant(EleCst);
1867 }
1868 }
1869
1870 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001871 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001872 }
1873}
1874
1875spv::StorageClass SPIRVProducerPass::GetStorageClass(unsigned AddrSpace) const {
1876 switch (AddrSpace) {
1877 default:
1878 llvm_unreachable("Unsupported OpenCL address space");
1879 case AddressSpace::Private:
1880 return spv::StorageClassFunction;
1881 case AddressSpace::Global:
David Neto22f144c2017-06-12 14:26:21 -04001882 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001883 case AddressSpace::Constant:
1884 return clspv::Option::ConstantArgsInUniformBuffer()
1885 ? spv::StorageClassUniform
1886 : spv::StorageClassStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -04001887 case AddressSpace::Input:
1888 return spv::StorageClassInput;
1889 case AddressSpace::Local:
1890 return spv::StorageClassWorkgroup;
1891 case AddressSpace::UniformConstant:
1892 return spv::StorageClassUniformConstant;
David Neto9ed8e2f2018-03-24 06:47:24 -07001893 case AddressSpace::Uniform:
David Netoe439d702018-03-23 13:14:08 -07001894 return spv::StorageClassUniform;
David Neto22f144c2017-06-12 14:26:21 -04001895 case AddressSpace::ModuleScopePrivate:
1896 return spv::StorageClassPrivate;
Kévin Petitbbbda972020-03-03 19:16:31 +00001897 case AddressSpace::PushConstant:
1898 return spv::StorageClassPushConstant;
David Neto22f144c2017-06-12 14:26:21 -04001899 }
1900}
1901
David Neto862b7d82018-06-14 18:48:37 -04001902spv::StorageClass
1903SPIRVProducerPass::GetStorageClassForArgKind(clspv::ArgKind arg_kind) const {
1904 switch (arg_kind) {
1905 case clspv::ArgKind::Buffer:
1906 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001907 case clspv::ArgKind::BufferUBO:
1908 return spv::StorageClassUniform;
David Neto862b7d82018-06-14 18:48:37 -04001909 case clspv::ArgKind::Pod:
alan-baker9b0ec3c2020-04-06 14:45:34 -04001910 return spv::StorageClassStorageBuffer;
1911 case clspv::ArgKind::PodUBO:
1912 return spv::StorageClassUniform;
1913 case clspv::ArgKind::PodPushConstant:
1914 return spv::StorageClassPushConstant;
David Neto862b7d82018-06-14 18:48:37 -04001915 case clspv::ArgKind::Local:
1916 return spv::StorageClassWorkgroup;
1917 case clspv::ArgKind::ReadOnlyImage:
1918 case clspv::ArgKind::WriteOnlyImage:
1919 case clspv::ArgKind::Sampler:
1920 return spv::StorageClassUniformConstant;
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001921 default:
1922 llvm_unreachable("Unsupported storage class for argument kind");
David Neto862b7d82018-06-14 18:48:37 -04001923 }
1924}
1925
David Neto22f144c2017-06-12 14:26:21 -04001926spv::BuiltIn SPIRVProducerPass::GetBuiltin(StringRef Name) const {
1927 return StringSwitch<spv::BuiltIn>(Name)
1928 .Case("__spirv_GlobalInvocationId", spv::BuiltInGlobalInvocationId)
1929 .Case("__spirv_LocalInvocationId", spv::BuiltInLocalInvocationId)
1930 .Case("__spirv_WorkgroupSize", spv::BuiltInWorkgroupSize)
1931 .Case("__spirv_NumWorkgroups", spv::BuiltInNumWorkgroups)
1932 .Case("__spirv_WorkgroupId", spv::BuiltInWorkgroupId)
alan-bakerbed3a882020-04-21 14:42:41 -04001933 .Case("__spirv_WorkDim", spv::BuiltInWorkDim)
David Neto22f144c2017-06-12 14:26:21 -04001934 .Default(spv::BuiltInMax);
1935}
1936
1937void SPIRVProducerPass::GenerateExtInstImport() {
SJW69939d52020-04-16 07:29:07 -05001938 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kImports);
David Neto22f144c2017-06-12 14:26:21 -04001939 uint32_t &ExtInstImportID = getOpExtInstImportID();
1940
1941 //
1942 // Generate OpExtInstImport.
1943 //
1944 // Ops[0] ... Ops[n] = Name (Literal String)
David Neto22f144c2017-06-12 14:26:21 -04001945 ExtInstImportID = nextID;
David Neto87846742018-04-11 17:36:22 -04001946 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpExtInstImport, nextID++,
1947 MkString("GLSL.std.450")));
David Neto22f144c2017-06-12 14:26:21 -04001948}
1949
SJW77b87ad2020-04-21 14:37:52 -05001950void SPIRVProducerPass::GenerateSPIRVTypes() {
SJW69939d52020-04-16 07:29:07 -05001951 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kTypes);
David Neto22f144c2017-06-12 14:26:21 -04001952 ValueMapType &VMap = getValueMap();
1953 ValueMapType &AllocatedVMap = getAllocatedValueMap();
SJW77b87ad2020-04-21 14:37:52 -05001954 const auto &DL = module->getDataLayout();
1955 LLVMContext &Context = module->getContext();
David Neto22f144c2017-06-12 14:26:21 -04001956
1957 // Map for OpTypeRuntimeArray. If argument has pointer type, 2 spirv type
1958 // instructions are generated. They are OpTypePointer and OpTypeRuntimeArray.
1959 DenseMap<Type *, uint32_t> OpRuntimeTyMap;
1960
1961 for (Type *Ty : getTypeList()) {
1962 // Update TypeMap with nextID for reference later.
1963 TypeMap[Ty] = nextID;
1964
1965 switch (Ty->getTypeID()) {
1966 default: {
1967 Ty->print(errs());
1968 llvm_unreachable("Unsupported type???");
1969 break;
1970 }
1971 case Type::MetadataTyID:
1972 case Type::LabelTyID: {
1973 // Ignore these types.
1974 break;
1975 }
1976 case Type::PointerTyID: {
1977 PointerType *PTy = cast<PointerType>(Ty);
1978 unsigned AddrSpace = PTy->getAddressSpace();
1979
1980 // For the purposes of our Vulkan SPIR-V type system, constant and global
1981 // are conflated.
1982 bool UseExistingOpTypePointer = false;
1983 if (AddressSpace::Constant == AddrSpace) {
Alan Bakerfcda9482018-10-02 17:09:59 -04001984 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1985 AddrSpace = AddressSpace::Global;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001986 // Check to see if we already created this type (for instance, if we
1987 // had a constant <type>* and a global <type>*, the type would be
1988 // created by one of these types, and shared by both).
Alan Bakerfcda9482018-10-02 17:09:59 -04001989 auto GlobalTy = PTy->getPointerElementType()->getPointerTo(AddrSpace);
1990 if (0 < TypeMap.count(GlobalTy)) {
1991 TypeMap[PTy] = TypeMap[GlobalTy];
1992 UseExistingOpTypePointer = true;
1993 break;
1994 }
David Neto22f144c2017-06-12 14:26:21 -04001995 }
1996 } else if (AddressSpace::Global == AddrSpace) {
Alan Bakerfcda9482018-10-02 17:09:59 -04001997 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1998 AddrSpace = AddressSpace::Constant;
David Neto22f144c2017-06-12 14:26:21 -04001999
alan-bakerb6b09dc2018-11-08 16:59:28 -05002000 // Check to see if we already created this type (for instance, if we
2001 // had a constant <type>* and a global <type>*, the type would be
2002 // created by one of these types, and shared by both).
2003 auto ConstantTy =
2004 PTy->getPointerElementType()->getPointerTo(AddrSpace);
Alan Bakerfcda9482018-10-02 17:09:59 -04002005 if (0 < TypeMap.count(ConstantTy)) {
2006 TypeMap[PTy] = TypeMap[ConstantTy];
2007 UseExistingOpTypePointer = true;
2008 }
David Neto22f144c2017-06-12 14:26:21 -04002009 }
2010 }
2011
David Neto862b7d82018-06-14 18:48:37 -04002012 const bool HasArgUser = true;
David Neto22f144c2017-06-12 14:26:21 -04002013
David Neto862b7d82018-06-14 18:48:37 -04002014 if (HasArgUser && !UseExistingOpTypePointer) {
David Neto22f144c2017-06-12 14:26:21 -04002015 //
2016 // Generate OpTypePointer.
2017 //
2018
2019 // OpTypePointer
2020 // Ops[0] = Storage Class
2021 // Ops[1] = Element Type ID
2022 SPIRVOperandList Ops;
2023
David Neto257c3892018-04-11 13:19:45 -04002024 Ops << MkNum(GetStorageClass(AddrSpace))
2025 << MkId(lookupType(PTy->getElementType()));
David Neto22f144c2017-06-12 14:26:21 -04002026
David Neto87846742018-04-11 17:36:22 -04002027 auto *Inst = new SPIRVInstruction(spv::OpTypePointer, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002028 SPIRVInstList.push_back(Inst);
2029 }
David Neto22f144c2017-06-12 14:26:21 -04002030 break;
2031 }
2032 case Type::StructTyID: {
David Neto22f144c2017-06-12 14:26:21 -04002033 StructType *STy = cast<StructType>(Ty);
2034
2035 // Handle sampler type.
2036 if (STy->isOpaque()) {
2037 if (STy->getName().equals("opencl.sampler_t")) {
2038 //
2039 // Generate OpTypeSampler
2040 //
2041 // Empty Ops.
2042 SPIRVOperandList Ops;
2043
David Neto87846742018-04-11 17:36:22 -04002044 auto *Inst = new SPIRVInstruction(spv::OpTypeSampler, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002045 SPIRVInstList.push_back(Inst);
2046 break;
alan-bakerf906d2b2019-12-10 11:26:23 -05002047 } else if (STy->getName().startswith("opencl.image1d_ro_t") ||
2048 STy->getName().startswith("opencl.image1d_wo_t") ||
alan-baker7150a1d2020-02-25 08:31:06 -05002049 STy->getName().startswith("opencl.image1d_array_ro_t") ||
2050 STy->getName().startswith("opencl.image1d_array_wo_t") ||
alan-bakerf906d2b2019-12-10 11:26:23 -05002051 STy->getName().startswith("opencl.image2d_ro_t") ||
alan-bakerf67468c2019-11-25 15:51:49 -05002052 STy->getName().startswith("opencl.image2d_wo_t") ||
alan-baker7150a1d2020-02-25 08:31:06 -05002053 STy->getName().startswith("opencl.image2d_array_ro_t") ||
2054 STy->getName().startswith("opencl.image2d_array_wo_t") ||
alan-bakerf67468c2019-11-25 15:51:49 -05002055 STy->getName().startswith("opencl.image3d_ro_t") ||
2056 STy->getName().startswith("opencl.image3d_wo_t")) {
David Neto22f144c2017-06-12 14:26:21 -04002057 //
2058 // Generate OpTypeImage
2059 //
2060 // Ops[0] = Sampled Type ID
2061 // Ops[1] = Dim ID
2062 // Ops[2] = Depth (Literal Number)
2063 // Ops[3] = Arrayed (Literal Number)
2064 // Ops[4] = MS (Literal Number)
2065 // Ops[5] = Sampled (Literal Number)
2066 // Ops[6] = Image Format ID
2067 //
2068 SPIRVOperandList Ops;
2069
alan-bakerf67468c2019-11-25 15:51:49 -05002070 uint32_t ImageTyID = nextID++;
2071 uint32_t SampledTyID = 0;
2072 if (STy->getName().contains(".float")) {
2073 SampledTyID = lookupType(Type::getFloatTy(Context));
2074 } else if (STy->getName().contains(".uint")) {
2075 SampledTyID = lookupType(Type::getInt32Ty(Context));
2076 } else if (STy->getName().contains(".int")) {
2077 // Generate a signed 32-bit integer if necessary.
2078 if (int32ID == 0) {
2079 int32ID = nextID++;
2080 SPIRVOperandList intOps;
2081 intOps << MkNum(32);
2082 intOps << MkNum(1);
2083 auto signed_int =
2084 new SPIRVInstruction(spv::OpTypeInt, int32ID, intOps);
2085 SPIRVInstList.push_back(signed_int);
2086 }
2087 SampledTyID = int32ID;
2088
2089 // Generate a vec4 of the signed int if necessary.
2090 if (v4int32ID == 0) {
2091 v4int32ID = nextID++;
2092 SPIRVOperandList vecOps;
2093 vecOps << MkId(int32ID);
2094 vecOps << MkNum(4);
2095 auto int_vec =
2096 new SPIRVInstruction(spv::OpTypeVector, v4int32ID, vecOps);
2097 SPIRVInstList.push_back(int_vec);
2098 }
2099 } else {
2100 // This was likely an UndefValue.
2101 SampledTyID = lookupType(Type::getFloatTy(Context));
2102 }
David Neto257c3892018-04-11 13:19:45 -04002103 Ops << MkId(SampledTyID);
David Neto22f144c2017-06-12 14:26:21 -04002104
2105 spv::Dim DimID = spv::Dim2D;
alan-bakerf906d2b2019-12-10 11:26:23 -05002106 if (STy->getName().startswith("opencl.image1d_ro_t") ||
alan-baker7150a1d2020-02-25 08:31:06 -05002107 STy->getName().startswith("opencl.image1d_wo_t") ||
2108 STy->getName().startswith("opencl.image1d_array_ro_t") ||
2109 STy->getName().startswith("opencl.image1d_array_wo_t")) {
alan-bakerf906d2b2019-12-10 11:26:23 -05002110 DimID = spv::Dim1D;
2111 } else if (STy->getName().startswith("opencl.image3d_ro_t") ||
2112 STy->getName().startswith("opencl.image3d_wo_t")) {
David Neto22f144c2017-06-12 14:26:21 -04002113 DimID = spv::Dim3D;
2114 }
David Neto257c3892018-04-11 13:19:45 -04002115 Ops << MkNum(DimID);
David Neto22f144c2017-06-12 14:26:21 -04002116
2117 // TODO: Set up Depth.
David Neto257c3892018-04-11 13:19:45 -04002118 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04002119
alan-baker7150a1d2020-02-25 08:31:06 -05002120 uint32_t arrayed = STy->getName().contains("_array_") ? 1 : 0;
2121 Ops << MkNum(arrayed);
David Neto22f144c2017-06-12 14:26:21 -04002122
2123 // TODO: Set up MS.
David Neto257c3892018-04-11 13:19:45 -04002124 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04002125
alan-baker7150a1d2020-02-25 08:31:06 -05002126 // Set up Sampled.
David Neto22f144c2017-06-12 14:26:21 -04002127 //
2128 // From Spec
2129 //
2130 // 0 indicates this is only known at run time, not at compile time
2131 // 1 indicates will be used with sampler
2132 // 2 indicates will be used without a sampler (a storage image)
2133 uint32_t Sampled = 1;
alan-bakerf67468c2019-11-25 15:51:49 -05002134 if (!STy->getName().contains(".sampled")) {
David Neto22f144c2017-06-12 14:26:21 -04002135 Sampled = 2;
2136 }
David Neto257c3892018-04-11 13:19:45 -04002137 Ops << MkNum(Sampled);
David Neto22f144c2017-06-12 14:26:21 -04002138
2139 // TODO: Set up Image Format.
David Neto257c3892018-04-11 13:19:45 -04002140 Ops << MkNum(spv::ImageFormatUnknown);
David Neto22f144c2017-06-12 14:26:21 -04002141
alan-bakerf67468c2019-11-25 15:51:49 -05002142 auto *Inst = new SPIRVInstruction(spv::OpTypeImage, ImageTyID, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002143 SPIRVInstList.push_back(Inst);
2144 break;
2145 }
2146 }
2147
2148 //
2149 // Generate OpTypeStruct
2150 //
2151 // Ops[0] ... Ops[n] = Member IDs
2152 SPIRVOperandList Ops;
2153
2154 for (auto *EleTy : STy->elements()) {
David Neto862b7d82018-06-14 18:48:37 -04002155 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04002156 }
2157
David Neto22f144c2017-06-12 14:26:21 -04002158 uint32_t STyID = nextID;
2159
alan-bakerb6b09dc2018-11-08 16:59:28 -05002160 auto *Inst = new SPIRVInstruction(spv::OpTypeStruct, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002161 SPIRVInstList.push_back(Inst);
2162
2163 // Generate OpMemberDecorate.
Kévin Petitbbbda972020-03-03 19:16:31 +00002164 if (TypesNeedingLayout.idFor(STy)) {
2165 for (unsigned MemberIdx = 0; MemberIdx < STy->getNumElements();
2166 MemberIdx++) {
2167 // Ops[0] = Structure Type ID
2168 // Ops[1] = Member Index(Literal Number)
2169 // Ops[2] = Decoration (Offset)
2170 // Ops[3] = Byte Offset (Literal Number)
2171 Ops.clear();
David Netoc463b372017-08-10 15:32:21 -04002172
Kévin Petitbbbda972020-03-03 19:16:31 +00002173 Ops << MkId(STyID) << MkNum(MemberIdx)
2174 << MkNum(spv::DecorationOffset);
David Neto22f144c2017-06-12 14:26:21 -04002175
Kévin Petitbbbda972020-03-03 19:16:31 +00002176 const auto ByteOffset =
2177 GetExplicitLayoutStructMemberOffset(STy, MemberIdx, DL);
David Neto22f144c2017-06-12 14:26:21 -04002178
Kévin Petitbbbda972020-03-03 19:16:31 +00002179 Ops << MkNum(ByteOffset);
2180
2181 auto *DecoInst = new SPIRVInstruction(spv::OpMemberDecorate, Ops);
SJW69939d52020-04-16 07:29:07 -05002182 getSPIRVInstList(kAnnotations).push_back(DecoInst);
Alan Bakerfcda9482018-10-02 17:09:59 -04002183 }
David Neto22f144c2017-06-12 14:26:21 -04002184 }
2185
2186 // Generate OpDecorate.
David Neto862b7d82018-06-14 18:48:37 -04002187 if (StructTypesNeedingBlock.idFor(STy)) {
2188 Ops.clear();
2189 // Use Block decorations with StorageBuffer storage class.
2190 Ops << MkId(STyID) << MkNum(spv::DecorationBlock);
David Neto22f144c2017-06-12 14:26:21 -04002191
David Neto862b7d82018-06-14 18:48:37 -04002192 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
SJW69939d52020-04-16 07:29:07 -05002193 getSPIRVInstList(kAnnotations).push_back(DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04002194 }
2195 break;
2196 }
2197 case Type::IntegerTyID: {
alan-baker0e64a592019-11-18 13:36:25 -05002198 uint32_t BitWidth = static_cast<uint32_t>(Ty->getPrimitiveSizeInBits());
David Neto22f144c2017-06-12 14:26:21 -04002199
2200 if (BitWidth == 1) {
David Netoef5ba2b2019-12-20 08:35:54 -05002201 auto *Inst = new SPIRVInstruction(spv::OpTypeBool, nextID++);
David Neto22f144c2017-06-12 14:26:21 -04002202 SPIRVInstList.push_back(Inst);
2203 } else {
alan-bakerb39c8262019-03-08 14:03:37 -05002204 if (!clspv::Option::Int8Support()) {
2205 // i8 is added to TypeMap as i32.
2206 // No matter what LLVM type is requested first, always alias the
2207 // second one's SPIR-V type to be the same as the one we generated
2208 // first.
2209 unsigned aliasToWidth = 0;
2210 if (BitWidth == 8) {
2211 aliasToWidth = 32;
2212 BitWidth = 32;
2213 } else if (BitWidth == 32) {
2214 aliasToWidth = 8;
2215 }
2216 if (aliasToWidth) {
2217 Type *otherType = Type::getIntNTy(Ty->getContext(), aliasToWidth);
2218 auto where = TypeMap.find(otherType);
2219 if (where == TypeMap.end()) {
2220 // Go ahead and make it, but also map the other type to it.
2221 TypeMap[otherType] = nextID;
2222 } else {
2223 // Alias this SPIR-V type the existing type.
2224 TypeMap[Ty] = where->second;
2225 break;
2226 }
David Neto391aeb12017-08-26 15:51:58 -04002227 }
David Neto22f144c2017-06-12 14:26:21 -04002228 }
2229
David Neto257c3892018-04-11 13:19:45 -04002230 SPIRVOperandList Ops;
2231 Ops << MkNum(BitWidth) << MkNum(0 /* not signed */);
David Neto22f144c2017-06-12 14:26:21 -04002232
2233 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002234 new SPIRVInstruction(spv::OpTypeInt, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002235 }
2236 break;
2237 }
2238 case Type::HalfTyID:
2239 case Type::FloatTyID:
2240 case Type::DoubleTyID: {
alan-baker0e64a592019-11-18 13:36:25 -05002241 uint32_t BitWidth = static_cast<uint32_t>(Ty->getPrimitiveSizeInBits());
James Price11010dc2019-12-19 13:53:09 -05002242 auto WidthOp = MkNum(BitWidth);
David Neto22f144c2017-06-12 14:26:21 -04002243
2244 SPIRVInstList.push_back(
David Netoef5ba2b2019-12-20 08:35:54 -05002245 new SPIRVInstruction(spv::OpTypeFloat, nextID++, std::move(WidthOp)));
David Neto22f144c2017-06-12 14:26:21 -04002246 break;
2247 }
2248 case Type::ArrayTyID: {
David Neto22f144c2017-06-12 14:26:21 -04002249 ArrayType *ArrTy = cast<ArrayType>(Ty);
David Neto862b7d82018-06-14 18:48:37 -04002250 const uint64_t Length = ArrTy->getArrayNumElements();
2251 if (Length == 0) {
2252 // By convention, map it to a RuntimeArray.
David Neto22f144c2017-06-12 14:26:21 -04002253
David Neto862b7d82018-06-14 18:48:37 -04002254 // Only generate the type once.
2255 // TODO(dneto): Can it ever be generated more than once?
2256 // Doesn't LLVM type uniqueness guarantee we'll only see this
2257 // once?
2258 Type *EleTy = ArrTy->getArrayElementType();
2259 if (OpRuntimeTyMap.count(EleTy) == 0) {
2260 uint32_t OpTypeRuntimeArrayID = nextID;
2261 OpRuntimeTyMap[Ty] = nextID;
David Neto22f144c2017-06-12 14:26:21 -04002262
David Neto862b7d82018-06-14 18:48:37 -04002263 //
2264 // Generate OpTypeRuntimeArray.
2265 //
David Neto22f144c2017-06-12 14:26:21 -04002266
David Neto862b7d82018-06-14 18:48:37 -04002267 // OpTypeRuntimeArray
2268 // Ops[0] = Element Type ID
2269 SPIRVOperandList Ops;
2270 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04002271
David Neto862b7d82018-06-14 18:48:37 -04002272 SPIRVInstList.push_back(
2273 new SPIRVInstruction(spv::OpTypeRuntimeArray, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002274
David Neto862b7d82018-06-14 18:48:37 -04002275 if (Hack_generate_runtime_array_stride_early) {
2276 // Generate OpDecorate.
David Neto22f144c2017-06-12 14:26:21 -04002277
David Neto862b7d82018-06-14 18:48:37 -04002278 // Ops[0] = Target ID
2279 // Ops[1] = Decoration (ArrayStride)
2280 // Ops[2] = Stride Number(Literal Number)
2281 Ops.clear();
David Neto85082642018-03-24 06:55:20 -07002282
David Neto862b7d82018-06-14 18:48:37 -04002283 Ops << MkId(OpTypeRuntimeArrayID)
2284 << MkNum(spv::DecorationArrayStride)
Alan Bakerfcda9482018-10-02 17:09:59 -04002285 << MkNum(static_cast<uint32_t>(GetTypeAllocSize(EleTy, DL)));
David Neto22f144c2017-06-12 14:26:21 -04002286
David Neto862b7d82018-06-14 18:48:37 -04002287 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
SJW69939d52020-04-16 07:29:07 -05002288 getSPIRVInstList(kAnnotations).push_back(DecoInst);
David Neto862b7d82018-06-14 18:48:37 -04002289 }
2290 }
David Neto22f144c2017-06-12 14:26:21 -04002291
David Neto862b7d82018-06-14 18:48:37 -04002292 } else {
David Neto22f144c2017-06-12 14:26:21 -04002293
David Neto862b7d82018-06-14 18:48:37 -04002294 //
2295 // Generate OpConstant and OpTypeArray.
2296 //
2297
2298 //
2299 // Generate OpConstant for array length.
2300 //
2301 // Ops[0] = Result Type ID
2302 // Ops[1] .. Ops[n] = Values LiteralNumber
2303 SPIRVOperandList Ops;
2304
2305 Type *LengthTy = Type::getInt32Ty(Context);
2306 uint32_t ResTyID = lookupType(LengthTy);
2307 Ops << MkId(ResTyID);
2308
2309 assert(Length < UINT32_MAX);
2310 Ops << MkNum(static_cast<uint32_t>(Length));
2311
2312 // Add constant for length to constant list.
2313 Constant *CstLength = ConstantInt::get(LengthTy, Length);
2314 AllocatedVMap[CstLength] = nextID;
2315 VMap[CstLength] = nextID;
2316 uint32_t LengthID = nextID;
2317
2318 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
2319 SPIRVInstList.push_back(CstInst);
2320
2321 // Remember to generate ArrayStride later
2322 getTypesNeedingArrayStride().insert(Ty);
2323
2324 //
2325 // Generate OpTypeArray.
2326 //
2327 // Ops[0] = Element Type ID
2328 // Ops[1] = Array Length Constant ID
2329 Ops.clear();
2330
2331 uint32_t EleTyID = lookupType(ArrTy->getElementType());
2332 Ops << MkId(EleTyID) << MkId(LengthID);
2333
2334 // Update TypeMap with nextID.
2335 TypeMap[Ty] = nextID;
2336
2337 auto *ArrayInst = new SPIRVInstruction(spv::OpTypeArray, nextID++, Ops);
2338 SPIRVInstList.push_back(ArrayInst);
2339 }
David Neto22f144c2017-06-12 14:26:21 -04002340 break;
2341 }
James Price59a1c752020-04-23 23:06:16 -04002342 case Type::FixedVectorTyID: {
James Pricecf53df42020-04-20 14:41:24 -04002343 auto VecTy = cast<VectorType>(Ty);
alan-bakerb39c8262019-03-08 14:03:37 -05002344 // <4 x i8> is changed to i32 if i8 is not generally supported.
2345 if (!clspv::Option::Int8Support() &&
James Pricecf53df42020-04-20 14:41:24 -04002346 VecTy->getElementType() == Type::getInt8Ty(Context)) {
2347 if (VecTy->getNumElements() == 4) {
2348 TypeMap[Ty] = lookupType(VecTy->getElementType());
David Neto22f144c2017-06-12 14:26:21 -04002349 break;
2350 } else {
2351 Ty->print(errs());
2352 llvm_unreachable("Support above i8 vector type");
2353 }
2354 }
2355
2356 // Ops[0] = Component Type ID
2357 // Ops[1] = Component Count (Literal Number)
David Neto257c3892018-04-11 13:19:45 -04002358 SPIRVOperandList Ops;
James Pricecf53df42020-04-20 14:41:24 -04002359 Ops << MkId(lookupType(VecTy->getElementType()))
2360 << MkNum(VecTy->getNumElements());
David Neto22f144c2017-06-12 14:26:21 -04002361
alan-bakerb6b09dc2018-11-08 16:59:28 -05002362 SPIRVInstruction *inst =
2363 new SPIRVInstruction(spv::OpTypeVector, nextID++, Ops);
David Netoc6f3ab22018-04-06 18:02:31 -04002364 SPIRVInstList.push_back(inst);
David Neto22f144c2017-06-12 14:26:21 -04002365 break;
2366 }
2367 case Type::VoidTyID: {
David Netoef5ba2b2019-12-20 08:35:54 -05002368 auto *Inst = new SPIRVInstruction(spv::OpTypeVoid, nextID++);
David Neto22f144c2017-06-12 14:26:21 -04002369 SPIRVInstList.push_back(Inst);
2370 break;
2371 }
2372 case Type::FunctionTyID: {
2373 // Generate SPIRV instruction for function type.
2374 FunctionType *FTy = cast<FunctionType>(Ty);
2375
2376 // Ops[0] = Return Type ID
2377 // Ops[1] ... Ops[n] = Parameter Type IDs
2378 SPIRVOperandList Ops;
2379
2380 // Find SPIRV instruction for return type
David Netoc6f3ab22018-04-06 18:02:31 -04002381 Ops << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04002382
2383 // Find SPIRV instructions for parameter types
2384 for (unsigned k = 0; k < FTy->getNumParams(); k++) {
2385 // Find SPIRV instruction for parameter type.
2386 auto ParamTy = FTy->getParamType(k);
2387 if (ParamTy->isPointerTy()) {
2388 auto PointeeTy = ParamTy->getPointerElementType();
2389 if (PointeeTy->isStructTy() &&
2390 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
2391 ParamTy = PointeeTy;
2392 }
2393 }
2394
David Netoc6f3ab22018-04-06 18:02:31 -04002395 Ops << MkId(lookupType(ParamTy));
David Neto22f144c2017-06-12 14:26:21 -04002396 }
2397
David Neto87846742018-04-11 17:36:22 -04002398 auto *Inst = new SPIRVInstruction(spv::OpTypeFunction, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002399 SPIRVInstList.push_back(Inst);
2400 break;
2401 }
2402 }
2403 }
2404
2405 // Generate OpTypeSampledImage.
alan-bakerabd82722019-12-03 17:14:51 -05002406 for (auto &ImgTy : getImageTypeList()) {
David Neto22f144c2017-06-12 14:26:21 -04002407 //
2408 // Generate OpTypeSampledImage.
2409 //
2410 // Ops[0] = Image Type ID
2411 //
2412 SPIRVOperandList Ops;
2413
David Netoc6f3ab22018-04-06 18:02:31 -04002414 Ops << MkId(TypeMap[ImgTy]);
David Neto22f144c2017-06-12 14:26:21 -04002415
alan-bakerabd82722019-12-03 17:14:51 -05002416 // Update the image type map.
2417 getImageTypeMap()[ImgTy] = nextID;
David Neto22f144c2017-06-12 14:26:21 -04002418
David Neto87846742018-04-11 17:36:22 -04002419 auto *Inst = new SPIRVInstruction(spv::OpTypeSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002420 SPIRVInstList.push_back(Inst);
2421 }
David Netoc6f3ab22018-04-06 18:02:31 -04002422
2423 // Generate types for pointer-to-local arguments.
SJW77b87ad2020-04-21 14:37:52 -05002424 for (auto pair : clspv::GetSpecConstants(module)) {
alan-bakera1be3322020-04-20 12:48:18 -04002425 auto kind = pair.first;
2426 auto spec_id = pair.second;
2427
2428 if (kind != SpecConstant::kLocalMemorySize)
2429 continue;
2430
alan-bakerb6b09dc2018-11-08 16:59:28 -05002431 LocalArgInfo &arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04002432
2433 // Generate the spec constant.
2434 SPIRVOperandList Ops;
2435 Ops << MkId(lookupType(Type::getInt32Ty(Context))) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04002436 SPIRVInstList.push_back(
2437 new SPIRVInstruction(spv::OpSpecConstant, arg_info.array_size_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002438
2439 // Generate the array type.
2440 Ops.clear();
2441 // The element type must have been created.
2442 uint32_t elem_ty_id = lookupType(arg_info.elem_type);
2443 assert(elem_ty_id);
2444 Ops << MkId(elem_ty_id) << MkId(arg_info.array_size_id);
2445
2446 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002447 new SPIRVInstruction(spv::OpTypeArray, arg_info.array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002448
2449 Ops.clear();
2450 Ops << MkNum(spv::StorageClassWorkgroup) << MkId(arg_info.array_type_id);
David Neto87846742018-04-11 17:36:22 -04002451 SPIRVInstList.push_back(new SPIRVInstruction(
2452 spv::OpTypePointer, arg_info.ptr_array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002453 }
David Neto22f144c2017-06-12 14:26:21 -04002454}
2455
2456void SPIRVProducerPass::GenerateSPIRVConstants() {
SJW69939d52020-04-16 07:29:07 -05002457 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kConstants);
David Neto22f144c2017-06-12 14:26:21 -04002458 ValueMapType &VMap = getValueMap();
2459 ValueMapType &AllocatedVMap = getAllocatedValueMap();
2460 ValueList &CstList = getConstantList();
David Neto482550a2018-03-24 05:21:07 -07002461 const bool hack_undef = clspv::Option::HackUndef();
David Neto22f144c2017-06-12 14:26:21 -04002462
2463 for (uint32_t i = 0; i < CstList.size(); i++) {
David Netofb9a7972017-08-25 17:08:24 -04002464 // UniqueVector ids are 1-based.
alan-bakerb6b09dc2018-11-08 16:59:28 -05002465 Constant *Cst = cast<Constant>(CstList[i + 1]);
David Neto22f144c2017-06-12 14:26:21 -04002466
2467 // OpTypeArray's constant was already generated.
David Netofb9a7972017-08-25 17:08:24 -04002468 if (AllocatedVMap.find_as(Cst) != AllocatedVMap.end()) {
David Neto22f144c2017-06-12 14:26:21 -04002469 continue;
2470 }
2471
David Netofb9a7972017-08-25 17:08:24 -04002472 // Set ValueMap with nextID for reference later.
David Neto22f144c2017-06-12 14:26:21 -04002473 VMap[Cst] = nextID;
2474
2475 //
2476 // Generate OpConstant.
2477 //
2478
2479 // Ops[0] = Result Type ID
2480 // Ops[1] .. Ops[n] = Values LiteralNumber
2481 SPIRVOperandList Ops;
2482
David Neto257c3892018-04-11 13:19:45 -04002483 Ops << MkId(lookupType(Cst->getType()));
David Neto22f144c2017-06-12 14:26:21 -04002484
2485 std::vector<uint32_t> LiteralNum;
David Neto22f144c2017-06-12 14:26:21 -04002486 spv::Op Opcode = spv::OpNop;
2487
2488 if (isa<UndefValue>(Cst)) {
2489 // Ops[0] = Result Type ID
David Netoc66b3352017-10-20 14:28:46 -04002490 Opcode = spv::OpUndef;
Alan Baker9bf93fb2018-08-28 16:59:26 -04002491 if (hack_undef && IsTypeNullable(Cst->getType())) {
2492 Opcode = spv::OpConstantNull;
David Netoc66b3352017-10-20 14:28:46 -04002493 }
David Neto22f144c2017-06-12 14:26:21 -04002494 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(Cst)) {
2495 unsigned BitWidth = CI->getBitWidth();
2496 if (BitWidth == 1) {
2497 // If the bitwidth of constant is 1, generate OpConstantTrue or
2498 // OpConstantFalse.
2499 if (CI->getZExtValue()) {
2500 // Ops[0] = Result Type ID
2501 Opcode = spv::OpConstantTrue;
2502 } else {
2503 // Ops[0] = Result Type ID
2504 Opcode = spv::OpConstantFalse;
2505 }
David Neto22f144c2017-06-12 14:26:21 -04002506 } else {
2507 auto V = CI->getZExtValue();
2508 LiteralNum.push_back(V & 0xFFFFFFFF);
2509
2510 if (BitWidth > 32) {
2511 LiteralNum.push_back(V >> 32);
2512 }
2513
2514 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002515
David Neto257c3892018-04-11 13:19:45 -04002516 Ops << MkInteger(LiteralNum);
David Neto22f144c2017-06-12 14:26:21 -04002517 }
2518 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Cst)) {
2519 uint64_t FPVal = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
2520 Type *CFPTy = CFP->getType();
2521 if (CFPTy->isFloatTy()) {
2522 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
Kévin Petit02ee34e2019-04-04 19:03:22 +01002523 } else if (CFPTy->isDoubleTy()) {
2524 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
2525 LiteralNum.push_back(FPVal >> 32);
alan-baker089bf932020-01-07 16:35:45 -05002526 } else if (CFPTy->isHalfTy()) {
2527 LiteralNum.push_back(FPVal & 0xFFFF);
David Neto22f144c2017-06-12 14:26:21 -04002528 } else {
2529 CFPTy->print(errs());
2530 llvm_unreachable("Implement this ConstantFP Type");
2531 }
2532
2533 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002534
David Neto257c3892018-04-11 13:19:45 -04002535 Ops << MkFloat(LiteralNum);
David Neto22f144c2017-06-12 14:26:21 -04002536 } else if (isa<ConstantDataSequential>(Cst) &&
2537 cast<ConstantDataSequential>(Cst)->isString()) {
2538 Cst->print(errs());
2539 llvm_unreachable("Implement this Constant");
2540
2541 } else if (const ConstantDataSequential *CDS =
2542 dyn_cast<ConstantDataSequential>(Cst)) {
David Neto49351ac2017-08-26 17:32:20 -04002543 // Let's convert <4 x i8> constant to int constant specially.
2544 // This case occurs when all the values are specified as constant
2545 // ints.
2546 Type *CstTy = Cst->getType();
2547 if (is4xi8vec(CstTy)) {
2548 LLVMContext &Context = CstTy->getContext();
2549
2550 //
2551 // Generate OpConstant with OpTypeInt 32 0.
2552 //
Neil Henning39672102017-09-29 14:33:13 +01002553 uint32_t IntValue = 0;
2554 for (unsigned k = 0; k < 4; k++) {
2555 const uint64_t Val = CDS->getElementAsInteger(k);
David Neto49351ac2017-08-26 17:32:20 -04002556 IntValue = (IntValue << 8) | (Val & 0xffu);
2557 }
2558
2559 Type *i32 = Type::getInt32Ty(Context);
2560 Constant *CstInt = ConstantInt::get(i32, IntValue);
2561 // If this constant is already registered on VMap, use it.
2562 if (VMap.count(CstInt)) {
2563 uint32_t CstID = VMap[CstInt];
2564 VMap[Cst] = CstID;
2565 continue;
2566 }
2567
David Neto257c3892018-04-11 13:19:45 -04002568 Ops << MkNum(IntValue);
David Neto49351ac2017-08-26 17:32:20 -04002569
David Neto87846742018-04-11 17:36:22 -04002570 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto49351ac2017-08-26 17:32:20 -04002571 SPIRVInstList.push_back(CstInst);
2572
2573 continue;
2574 }
2575
2576 // A normal constant-data-sequential case.
David Neto22f144c2017-06-12 14:26:21 -04002577 for (unsigned k = 0; k < CDS->getNumElements(); k++) {
2578 Constant *EleCst = CDS->getElementAsConstant(k);
2579 uint32_t EleCstID = VMap[EleCst];
David Neto257c3892018-04-11 13:19:45 -04002580 Ops << MkId(EleCstID);
David Neto22f144c2017-06-12 14:26:21 -04002581 }
2582
2583 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002584 } else if (const ConstantAggregate *CA = dyn_cast<ConstantAggregate>(Cst)) {
2585 // Let's convert <4 x i8> constant to int constant specially.
David Neto49351ac2017-08-26 17:32:20 -04002586 // This case occurs when at least one of the values is an undef.
David Neto22f144c2017-06-12 14:26:21 -04002587 Type *CstTy = Cst->getType();
2588 if (is4xi8vec(CstTy)) {
2589 LLVMContext &Context = CstTy->getContext();
2590
2591 //
2592 // Generate OpConstant with OpTypeInt 32 0.
2593 //
Neil Henning39672102017-09-29 14:33:13 +01002594 uint32_t IntValue = 0;
David Neto22f144c2017-06-12 14:26:21 -04002595 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end();
2596 I != E; ++I) {
2597 uint64_t Val = 0;
alan-bakerb6b09dc2018-11-08 16:59:28 -05002598 const Value *CV = *I;
Neil Henning39672102017-09-29 14:33:13 +01002599 if (auto *CI2 = dyn_cast<ConstantInt>(CV)) {
2600 Val = CI2->getZExtValue();
David Neto22f144c2017-06-12 14:26:21 -04002601 }
David Neto49351ac2017-08-26 17:32:20 -04002602 IntValue = (IntValue << 8) | (Val & 0xffu);
David Neto22f144c2017-06-12 14:26:21 -04002603 }
2604
David Neto49351ac2017-08-26 17:32:20 -04002605 Type *i32 = Type::getInt32Ty(Context);
2606 Constant *CstInt = ConstantInt::get(i32, IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002607 // If this constant is already registered on VMap, use it.
2608 if (VMap.count(CstInt)) {
2609 uint32_t CstID = VMap[CstInt];
2610 VMap[Cst] = CstID;
David Neto19a1bad2017-08-25 15:01:41 -04002611 continue;
David Neto22f144c2017-06-12 14:26:21 -04002612 }
2613
David Neto257c3892018-04-11 13:19:45 -04002614 Ops << MkNum(IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002615
David Neto87846742018-04-11 17:36:22 -04002616 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002617 SPIRVInstList.push_back(CstInst);
2618
David Neto19a1bad2017-08-25 15:01:41 -04002619 continue;
David Neto22f144c2017-06-12 14:26:21 -04002620 }
2621
2622 // We use a constant composite in SPIR-V for our constant aggregate in
2623 // LLVM.
2624 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002625
2626 for (unsigned k = 0; k < CA->getNumOperands(); k++) {
2627 // Look up the ID of the element of this aggregate (which we will
2628 // previously have created a constant for).
2629 uint32_t ElementConstantID = VMap[CA->getAggregateElement(k)];
2630
2631 // And add an operand to the composite we are constructing
David Neto257c3892018-04-11 13:19:45 -04002632 Ops << MkId(ElementConstantID);
David Neto22f144c2017-06-12 14:26:21 -04002633 }
2634 } else if (Cst->isNullValue()) {
2635 Opcode = spv::OpConstantNull;
David Neto22f144c2017-06-12 14:26:21 -04002636 } else {
2637 Cst->print(errs());
2638 llvm_unreachable("Unsupported Constant???");
2639 }
2640
alan-baker5b86ed72019-02-15 08:26:50 -05002641 if (Opcode == spv::OpConstantNull && Cst->getType()->isPointerTy()) {
2642 // Null pointer requires variable pointers.
2643 setVariablePointersCapabilities(Cst->getType()->getPointerAddressSpace());
2644 }
2645
David Neto87846742018-04-11 17:36:22 -04002646 auto *CstInst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002647 SPIRVInstList.push_back(CstInst);
2648 }
2649}
2650
SJW77b87ad2020-04-21 14:37:52 -05002651void SPIRVProducerPass::GenerateSamplers() {
SJW69939d52020-04-16 07:29:07 -05002652 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kGlobalVariables);
David Neto22f144c2017-06-12 14:26:21 -04002653
alan-bakerb6b09dc2018-11-08 16:59:28 -05002654 auto &sampler_map = getSamplerMap();
alan-baker09cb9802019-12-10 13:16:27 -05002655 SamplerLiteralToIDMap.clear();
David Neto862b7d82018-06-14 18:48:37 -04002656 DenseMap<unsigned, unsigned> SamplerLiteralToDescriptorSetMap;
2657 DenseMap<unsigned, unsigned> SamplerLiteralToBindingMap;
David Neto22f144c2017-06-12 14:26:21 -04002658
David Neto862b7d82018-06-14 18:48:37 -04002659 // We might have samplers in the sampler map that are not used
2660 // in the translation unit. We need to allocate variables
2661 // for them and bindings too.
2662 DenseSet<unsigned> used_bindings;
David Neto22f144c2017-06-12 14:26:21 -04002663
SJW77b87ad2020-04-21 14:37:52 -05002664 auto *var_fn = module->getFunction(clspv::LiteralSamplerFunction());
alan-baker09cb9802019-12-10 13:16:27 -05002665 // Return if there are no literal samplers.
alan-bakerb6b09dc2018-11-08 16:59:28 -05002666 if (!var_fn)
2667 return;
alan-baker09cb9802019-12-10 13:16:27 -05002668
David Neto862b7d82018-06-14 18:48:37 -04002669 for (auto user : var_fn->users()) {
2670 // Populate SamplerLiteralToDescriptorSetMap and
2671 // SamplerLiteralToBindingMap.
2672 //
2673 // Look for calls like
2674 // call %opencl.sampler_t addrspace(2)*
2675 // @clspv.sampler.var.literal(
2676 // i32 descriptor,
2677 // i32 binding,
alan-baker09cb9802019-12-10 13:16:27 -05002678 // i32 (index-into-sampler-map|sampler_mask))
alan-bakerb6b09dc2018-11-08 16:59:28 -05002679 if (auto *call = dyn_cast<CallInst>(user)) {
alan-baker09cb9802019-12-10 13:16:27 -05002680 const auto third_param = static_cast<unsigned>(
alan-bakerb6b09dc2018-11-08 16:59:28 -05002681 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
alan-baker09cb9802019-12-10 13:16:27 -05002682 auto sampler_value = third_param;
2683 if (clspv::Option::UseSamplerMap()) {
2684 if (third_param >= sampler_map.size()) {
2685 errs() << "Out of bounds index to sampler map: " << third_param;
2686 llvm_unreachable("bad sampler init: out of bounds");
2687 }
2688 sampler_value = sampler_map[third_param].first;
David Neto862b7d82018-06-14 18:48:37 -04002689 }
2690
David Neto862b7d82018-06-14 18:48:37 -04002691 const auto descriptor_set = static_cast<unsigned>(
2692 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
2693 const auto binding = static_cast<unsigned>(
2694 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
2695
2696 SamplerLiteralToDescriptorSetMap[sampler_value] = descriptor_set;
2697 SamplerLiteralToBindingMap[sampler_value] = binding;
2698 used_bindings.insert(binding);
2699 }
2700 }
2701
alan-baker09cb9802019-12-10 13:16:27 -05002702 DenseSet<size_t> seen;
2703 for (auto user : var_fn->users()) {
2704 if (!isa<CallInst>(user))
2705 continue;
2706
2707 auto call = cast<CallInst>(user);
2708 const unsigned third_param = static_cast<unsigned>(
2709 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
2710
2711 // Already allocated a variable for this value.
2712 if (!seen.insert(third_param).second)
2713 continue;
2714
2715 auto sampler_value = third_param;
2716 if (clspv::Option::UseSamplerMap()) {
2717 sampler_value = sampler_map[third_param].first;
2718 }
2719
David Neto22f144c2017-06-12 14:26:21 -04002720 // Generate OpVariable.
2721 //
2722 // GIDOps[0] : Result Type ID
2723 // GIDOps[1] : Storage Class
2724 SPIRVOperandList Ops;
2725
David Neto257c3892018-04-11 13:19:45 -04002726 Ops << MkId(lookupType(SamplerTy))
2727 << MkNum(spv::StorageClassUniformConstant);
David Neto22f144c2017-06-12 14:26:21 -04002728
David Neto862b7d82018-06-14 18:48:37 -04002729 auto sampler_var_id = nextID++;
2730 auto *Inst = new SPIRVInstruction(spv::OpVariable, sampler_var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002731 SPIRVInstList.push_back(Inst);
2732
alan-baker09cb9802019-12-10 13:16:27 -05002733 SamplerLiteralToIDMap[sampler_value] = sampler_var_id;
David Neto22f144c2017-06-12 14:26:21 -04002734
David Neto862b7d82018-06-14 18:48:37 -04002735 unsigned descriptor_set;
2736 unsigned binding;
alan-baker09cb9802019-12-10 13:16:27 -05002737 if (SamplerLiteralToBindingMap.find(sampler_value) ==
alan-bakerb6b09dc2018-11-08 16:59:28 -05002738 SamplerLiteralToBindingMap.end()) {
David Neto862b7d82018-06-14 18:48:37 -04002739 // This sampler is not actually used. Find the next one.
2740 for (binding = 0; used_bindings.count(binding); binding++)
2741 ;
2742 descriptor_set = 0; // Literal samplers always use descriptor set 0.
2743 used_bindings.insert(binding);
2744 } else {
alan-baker09cb9802019-12-10 13:16:27 -05002745 descriptor_set = SamplerLiteralToDescriptorSetMap[sampler_value];
2746 binding = SamplerLiteralToBindingMap[sampler_value];
alan-bakercff80152019-06-15 00:38:00 -04002747
alan-baker09cb9802019-12-10 13:16:27 -05002748 version0::DescriptorMapEntry::SamplerData sampler_data = {sampler_value};
alan-bakercff80152019-06-15 00:38:00 -04002749 descriptorMapEntries->emplace_back(std::move(sampler_data),
2750 descriptor_set, binding);
David Neto862b7d82018-06-14 18:48:37 -04002751 }
2752
SJW69939d52020-04-16 07:29:07 -05002753 // Ops[0] = Target ID
2754 // Ops[1] = Decoration (DescriptorSet)
2755 // Ops[2] = LiteralNumber according to Decoration
2756 Ops.clear();
2757
David Neto862b7d82018-06-14 18:48:37 -04002758 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationDescriptorSet)
2759 << MkNum(descriptor_set);
David Neto22f144c2017-06-12 14:26:21 -04002760
David Neto87846742018-04-11 17:36:22 -04002761 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
SJW69939d52020-04-16 07:29:07 -05002762 getSPIRVInstList(kAnnotations).push_back(DescDecoInst);
David Neto22f144c2017-06-12 14:26:21 -04002763
2764 // Ops[0] = Target ID
2765 // Ops[1] = Decoration (Binding)
2766 // Ops[2] = LiteralNumber according to Decoration
2767 Ops.clear();
David Neto862b7d82018-06-14 18:48:37 -04002768 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationBinding)
2769 << MkNum(binding);
David Neto22f144c2017-06-12 14:26:21 -04002770
David Neto87846742018-04-11 17:36:22 -04002771 auto *BindDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
SJW69939d52020-04-16 07:29:07 -05002772 getSPIRVInstList(kAnnotations).push_back(BindDecoInst);
David Neto22f144c2017-06-12 14:26:21 -04002773 }
David Neto862b7d82018-06-14 18:48:37 -04002774}
David Neto22f144c2017-06-12 14:26:21 -04002775
SJW77b87ad2020-04-21 14:37:52 -05002776void SPIRVProducerPass::GenerateResourceVars() {
SJW69939d52020-04-16 07:29:07 -05002777 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kGlobalVariables);
David Neto862b7d82018-06-14 18:48:37 -04002778 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04002779
David Neto862b7d82018-06-14 18:48:37 -04002780 // Generate variables. Make one for each of resource var info object.
2781 for (auto *info : ModuleOrderedResourceVars) {
2782 Type *type = info->var_fn->getReturnType();
2783 // Remap the address space for opaque types.
2784 switch (info->arg_kind) {
2785 case clspv::ArgKind::Sampler:
2786 case clspv::ArgKind::ReadOnlyImage:
2787 case clspv::ArgKind::WriteOnlyImage:
2788 type = PointerType::get(type->getPointerElementType(),
2789 clspv::AddressSpace::UniformConstant);
2790 break;
2791 default:
2792 break;
2793 }
David Neto22f144c2017-06-12 14:26:21 -04002794
David Neto862b7d82018-06-14 18:48:37 -04002795 info->var_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04002796
David Neto862b7d82018-06-14 18:48:37 -04002797 const auto type_id = lookupType(type);
2798 const auto sc = GetStorageClassForArgKind(info->arg_kind);
2799 SPIRVOperandList Ops;
2800 Ops << MkId(type_id) << MkNum(sc);
David Neto22f144c2017-06-12 14:26:21 -04002801
David Neto862b7d82018-06-14 18:48:37 -04002802 auto *Inst = new SPIRVInstruction(spv::OpVariable, info->var_id, Ops);
2803 SPIRVInstList.push_back(Inst);
2804
2805 // Map calls to the variable-builtin-function.
2806 for (auto &U : info->var_fn->uses()) {
2807 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
2808 const auto set = unsigned(
2809 dyn_cast<ConstantInt>(call->getOperand(0))->getZExtValue());
2810 const auto binding = unsigned(
2811 dyn_cast<ConstantInt>(call->getOperand(1))->getZExtValue());
2812 if (set == info->descriptor_set && binding == info->binding) {
2813 switch (info->arg_kind) {
2814 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002815 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002816 case clspv::ArgKind::Pod:
alan-baker9b0ec3c2020-04-06 14:45:34 -04002817 case clspv::ArgKind::PodUBO:
2818 case clspv::ArgKind::PodPushConstant:
David Neto862b7d82018-06-14 18:48:37 -04002819 // The call maps to the variable directly.
2820 VMap[call] = info->var_id;
2821 break;
2822 case clspv::ArgKind::Sampler:
2823 case clspv::ArgKind::ReadOnlyImage:
2824 case clspv::ArgKind::WriteOnlyImage:
2825 // The call maps to a load we generate later.
2826 ResourceVarDeferredLoadCalls[call] = info->var_id;
2827 break;
2828 default:
2829 llvm_unreachable("Unhandled arg kind");
2830 }
2831 }
David Neto22f144c2017-06-12 14:26:21 -04002832 }
David Neto862b7d82018-06-14 18:48:37 -04002833 }
2834 }
David Neto22f144c2017-06-12 14:26:21 -04002835
David Neto862b7d82018-06-14 18:48:37 -04002836 // Generate associated decorations.
SJW69939d52020-04-16 07:29:07 -05002837 SPIRVInstructionList &Annotations = getSPIRVInstList(kAnnotations);
David Neto862b7d82018-06-14 18:48:37 -04002838
2839 SPIRVOperandList Ops;
2840 for (auto *info : ModuleOrderedResourceVars) {
alan-baker9b0ec3c2020-04-06 14:45:34 -04002841 // Push constants don't need descriptor set or binding decorations.
2842 if (info->arg_kind == clspv::ArgKind::PodPushConstant)
2843 continue;
2844
David Neto862b7d82018-06-14 18:48:37 -04002845 // Decorate with DescriptorSet and Binding.
2846 Ops.clear();
2847 Ops << MkId(info->var_id) << MkNum(spv::DecorationDescriptorSet)
2848 << MkNum(info->descriptor_set);
SJW69939d52020-04-16 07:29:07 -05002849 Annotations.push_back(new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto862b7d82018-06-14 18:48:37 -04002850
2851 Ops.clear();
2852 Ops << MkId(info->var_id) << MkNum(spv::DecorationBinding)
2853 << MkNum(info->binding);
SJW69939d52020-04-16 07:29:07 -05002854 Annotations.push_back(new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto862b7d82018-06-14 18:48:37 -04002855
alan-bakere9308012019-03-15 10:25:13 -04002856 if (info->coherent) {
2857 // Decorate with Coherent if required for the variable.
2858 Ops.clear();
2859 Ops << MkId(info->var_id) << MkNum(spv::DecorationCoherent);
SJW69939d52020-04-16 07:29:07 -05002860 Annotations.push_back(new SPIRVInstruction(spv::OpDecorate, Ops));
alan-bakere9308012019-03-15 10:25:13 -04002861 }
2862
David Neto862b7d82018-06-14 18:48:37 -04002863 // Generate NonWritable and NonReadable
2864 switch (info->arg_kind) {
2865 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002866 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002867 if (info->var_fn->getReturnType()->getPointerAddressSpace() ==
2868 clspv::AddressSpace::Constant) {
2869 Ops.clear();
2870 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonWritable);
SJW69939d52020-04-16 07:29:07 -05002871 Annotations.push_back(new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002872 }
David Neto862b7d82018-06-14 18:48:37 -04002873 break;
David Neto862b7d82018-06-14 18:48:37 -04002874 case clspv::ArgKind::WriteOnlyImage:
2875 Ops.clear();
2876 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonReadable);
SJW69939d52020-04-16 07:29:07 -05002877 Annotations.push_back(new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto862b7d82018-06-14 18:48:37 -04002878 break;
2879 default:
2880 break;
David Neto22f144c2017-06-12 14:26:21 -04002881 }
2882 }
2883}
2884
SJW77b87ad2020-04-21 14:37:52 -05002885void SPIRVProducerPass::GeneratePushConstantDescriptorMapEntries() {
Kévin Petitbbbda972020-03-03 19:16:31 +00002886
SJW77b87ad2020-04-21 14:37:52 -05002887 if (auto GV = module->getGlobalVariable(clspv::PushConstantsVariableName())) {
2888 auto const &DL = module->getDataLayout();
Kévin Petitbbbda972020-03-03 19:16:31 +00002889 auto MD = GV->getMetadata(clspv::PushConstantsMetadataName());
2890 auto STy = cast<StructType>(GV->getValueType());
2891
2892 for (unsigned i = 0; i < STy->getNumElements(); i++) {
2893 auto pc = static_cast<clspv::PushConstant>(
2894 mdconst::extract<ConstantInt>(MD->getOperand(i))->getZExtValue());
2895 auto memberType = STy->getElementType(i);
2896 auto offset = GetExplicitLayoutStructMemberOffset(STy, i, DL);
2897 unsigned previousOffset = 0;
2898 if (i > 0) {
2899 previousOffset = GetExplicitLayoutStructMemberOffset(STy, i - 1, DL);
2900 }
2901 auto size = static_cast<uint32_t>(GetTypeSizeInBits(memberType, DL)) / 8;
SJW77b87ad2020-04-21 14:37:52 -05002902 assert(isValidExplicitLayout(*module, STy, i,
2903 spv::StorageClassPushConstant, offset,
2904 previousOffset));
Kévin Petitbbbda972020-03-03 19:16:31 +00002905 version0::DescriptorMapEntry::PushConstantData data = {pc, offset, size};
2906 descriptorMapEntries->emplace_back(std::move(data));
2907 }
2908 }
2909}
2910
SJW77b87ad2020-04-21 14:37:52 -05002911void SPIRVProducerPass::GenerateSpecConstantDescriptorMapEntries() {
2912 for (auto pair : clspv::GetSpecConstants(module)) {
alan-bakera1be3322020-04-20 12:48:18 -04002913 auto kind = pair.first;
2914 auto id = pair.second;
2915
2916 // Local memory size is only used for kernel arguments.
2917 if (kind == SpecConstant::kLocalMemorySize)
2918 continue;
2919
2920 version0::DescriptorMapEntry::SpecConstantData data = {kind, id};
2921 descriptorMapEntries->emplace_back(std::move(data));
2922 }
2923}
2924
David Neto22f144c2017-06-12 14:26:21 -04002925void SPIRVProducerPass::GenerateGlobalVar(GlobalVariable &GV) {
SJW69939d52020-04-16 07:29:07 -05002926 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kGlobalVariables);
David Neto22f144c2017-06-12 14:26:21 -04002927 ValueMapType &VMap = getValueMap();
2928 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
David Neto85082642018-03-24 06:55:20 -07002929 const DataLayout &DL = GV.getParent()->getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04002930
2931 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
2932 Type *Ty = GV.getType();
2933 PointerType *PTy = cast<PointerType>(Ty);
2934
2935 uint32_t InitializerID = 0;
2936
2937 // Workgroup size is handled differently (it goes into a constant)
2938 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2939 std::vector<bool> HasMDVec;
2940 uint32_t PrevXDimCst = 0xFFFFFFFF;
2941 uint32_t PrevYDimCst = 0xFFFFFFFF;
2942 uint32_t PrevZDimCst = 0xFFFFFFFF;
2943 for (Function &Func : *GV.getParent()) {
2944 if (Func.isDeclaration()) {
2945 continue;
2946 }
2947
2948 // We only need to check kernels.
2949 if (Func.getCallingConv() != CallingConv::SPIR_KERNEL) {
2950 continue;
2951 }
2952
2953 if (const MDNode *MD =
2954 dyn_cast<Function>(&Func)->getMetadata("reqd_work_group_size")) {
2955 uint32_t CurXDimCst = static_cast<uint32_t>(
2956 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
2957 uint32_t CurYDimCst = static_cast<uint32_t>(
2958 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
2959 uint32_t CurZDimCst = static_cast<uint32_t>(
2960 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
2961
2962 if (PrevXDimCst == 0xFFFFFFFF && PrevYDimCst == 0xFFFFFFFF &&
2963 PrevZDimCst == 0xFFFFFFFF) {
2964 PrevXDimCst = CurXDimCst;
2965 PrevYDimCst = CurYDimCst;
2966 PrevZDimCst = CurZDimCst;
2967 } else if (CurXDimCst != PrevXDimCst || CurYDimCst != PrevYDimCst ||
2968 CurZDimCst != PrevZDimCst) {
2969 llvm_unreachable(
2970 "reqd_work_group_size must be the same across all kernels");
2971 } else {
2972 continue;
2973 }
2974
2975 //
2976 // Generate OpConstantComposite.
2977 //
2978 // Ops[0] : Result Type ID
2979 // Ops[1] : Constant size for x dimension.
2980 // Ops[2] : Constant size for y dimension.
2981 // Ops[3] : Constant size for z dimension.
2982 SPIRVOperandList Ops;
2983
2984 uint32_t XDimCstID =
2985 VMap[mdconst::extract<ConstantInt>(MD->getOperand(0))];
2986 uint32_t YDimCstID =
2987 VMap[mdconst::extract<ConstantInt>(MD->getOperand(1))];
2988 uint32_t ZDimCstID =
2989 VMap[mdconst::extract<ConstantInt>(MD->getOperand(2))];
2990
2991 InitializerID = nextID;
2992
David Neto257c3892018-04-11 13:19:45 -04002993 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2994 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002995
David Neto87846742018-04-11 17:36:22 -04002996 auto *Inst =
2997 new SPIRVInstruction(spv::OpConstantComposite, nextID++, Ops);
alan-bakera1be3322020-04-20 12:48:18 -04002998 getSPIRVInstList(kConstants).push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04002999
3000 HasMDVec.push_back(true);
3001 } else {
3002 HasMDVec.push_back(false);
3003 }
3004 }
3005
3006 // Check all kernels have same definitions for work_group_size.
3007 bool HasMD = false;
3008 if (!HasMDVec.empty()) {
3009 HasMD = HasMDVec[0];
3010 for (uint32_t i = 1; i < HasMDVec.size(); i++) {
3011 if (HasMD != HasMDVec[i]) {
3012 llvm_unreachable(
3013 "Kernels should have consistent work group size definition");
3014 }
3015 }
3016 }
3017
3018 // If all kernels do not have metadata for reqd_work_group_size, generate
3019 // OpSpecConstants for x/y/z dimension.
Kévin Petit21c23c62020-04-29 01:38:28 +01003020 if (!HasMD || clspv::Option::NonUniformNDRangeSupported()) {
David Neto22f144c2017-06-12 14:26:21 -04003021 //
3022 // Generate OpSpecConstants for x/y/z dimension.
3023 //
3024 // Ops[0] : Result Type ID
3025 // Ops[1] : Constant size for x/y/z dimension (Literal Number).
3026 uint32_t XDimCstID = 0;
3027 uint32_t YDimCstID = 0;
3028 uint32_t ZDimCstID = 0;
3029
alan-bakera1be3322020-04-20 12:48:18 -04003030 // Allocate spec constants for workgroup size.
SJW77b87ad2020-04-21 14:37:52 -05003031 clspv::AddWorkgroupSpecConstants(module);
alan-bakera1be3322020-04-20 12:48:18 -04003032
David Neto22f144c2017-06-12 14:26:21 -04003033 SPIRVOperandList Ops;
James Pricecf53df42020-04-20 14:41:24 -04003034 uint32_t result_type_id = lookupType(
3035 cast<VectorType>(Ty->getPointerElementType())->getElementType());
David Neto22f144c2017-06-12 14:26:21 -04003036
David Neto257c3892018-04-11 13:19:45 -04003037 // X Dimension
3038 Ops << MkId(result_type_id) << MkNum(1);
3039 XDimCstID = nextID++;
alan-bakera1be3322020-04-20 12:48:18 -04003040 getSPIRVInstList(kConstants)
3041 .push_back(new SPIRVInstruction(spv::OpSpecConstant, XDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003042
3043 // Y Dimension
3044 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003045 Ops << MkId(result_type_id) << MkNum(1);
3046 YDimCstID = nextID++;
alan-bakera1be3322020-04-20 12:48:18 -04003047 getSPIRVInstList(kConstants)
3048 .push_back(new SPIRVInstruction(spv::OpSpecConstant, YDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003049
3050 // Z Dimension
3051 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003052 Ops << MkId(result_type_id) << MkNum(1);
3053 ZDimCstID = nextID++;
alan-bakera1be3322020-04-20 12:48:18 -04003054 getSPIRVInstList(kConstants)
3055 .push_back(new SPIRVInstruction(spv::OpSpecConstant, ZDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003056
David Neto257c3892018-04-11 13:19:45 -04003057 BuiltinDimVec.push_back(XDimCstID);
3058 BuiltinDimVec.push_back(YDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04003059 BuiltinDimVec.push_back(ZDimCstID);
3060
David Neto22f144c2017-06-12 14:26:21 -04003061 //
3062 // Generate OpSpecConstantComposite.
3063 //
3064 // Ops[0] : Result Type ID
3065 // Ops[1] : Constant size for x dimension.
3066 // Ops[2] : Constant size for y dimension.
3067 // Ops[3] : Constant size for z dimension.
3068 InitializerID = nextID;
3069
3070 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003071 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
3072 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04003073
David Neto87846742018-04-11 17:36:22 -04003074 auto *Inst =
3075 new SPIRVInstruction(spv::OpSpecConstantComposite, nextID++, Ops);
alan-bakera1be3322020-04-20 12:48:18 -04003076 getSPIRVInstList(kConstants).push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04003077 }
alan-bakerbed3a882020-04-21 14:42:41 -04003078 } else if (BuiltinType == spv::BuiltInWorkDim) {
3079 // 1. Generate a specialization constant with a default of 3.
3080 // 2. Allocate and annotate a SpecId for the constant.
3081 // 3. Use the spec constant as the initializer for the variable.
3082 SPIRVOperandList Ops;
3083
3084 //
3085 // Generate OpSpecConstant.
3086 //
3087 // Ops[0] : Result Type ID
3088 // Ops[1] : Default literal value
3089 InitializerID = nextID++;
3090
3091 Ops << MkId(lookupType(IntegerType::get(GV.getContext(), 32))) << MkNum(3);
3092
3093 auto *Inst = new SPIRVInstruction(spv::OpSpecConstant, InitializerID, Ops);
3094 getSPIRVInstList(kConstants).push_back(Inst);
3095
3096 //
3097 // Generate SpecId decoration.
3098 //
3099 // Ops[0] : target
3100 // Ops[1] : decoration
3101 // Ops[2] : SpecId
Alan Baker75ccc252020-04-21 17:11:52 -04003102 auto spec_id = AllocateSpecConstant(module, SpecConstant::kWorkDim);
alan-bakerbed3a882020-04-21 14:42:41 -04003103 Ops.clear();
3104 Ops << MkId(InitializerID) << MkNum(spv::DecorationSpecId)
3105 << MkNum(spec_id);
3106
3107 Inst = new SPIRVInstruction(spv::OpDecorate, Ops);
3108 getSPIRVInstList(kAnnotations).push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04003109 }
3110
David Neto22f144c2017-06-12 14:26:21 -04003111 VMap[&GV] = nextID;
3112
3113 //
3114 // Generate OpVariable.
3115 //
3116 // GIDOps[0] : Result Type ID
3117 // GIDOps[1] : Storage Class
3118 SPIRVOperandList Ops;
3119
David Neto85082642018-03-24 06:55:20 -07003120 const auto AS = PTy->getAddressSpace();
David Netoc6f3ab22018-04-06 18:02:31 -04003121 Ops << MkId(lookupType(Ty)) << MkNum(GetStorageClass(AS));
David Neto22f144c2017-06-12 14:26:21 -04003122
David Neto85082642018-03-24 06:55:20 -07003123 const bool module_scope_constant_external_init =
David Neto862b7d82018-06-14 18:48:37 -04003124 (AS == AddressSpace::Constant) && GV.hasInitializer() &&
David Neto85082642018-03-24 06:55:20 -07003125 clspv::Option::ModuleConstantsInStorageBuffer();
3126
Kévin Petit23d5f182019-08-13 16:21:29 +01003127 if (GV.hasInitializer()) {
3128 auto GVInit = GV.getInitializer();
3129 if (!isa<UndefValue>(GVInit) && !module_scope_constant_external_init) {
3130 assert(VMap.count(GVInit) == 1);
3131 InitializerID = VMap[GVInit];
David Neto85082642018-03-24 06:55:20 -07003132 }
3133 }
Kévin Petit23d5f182019-08-13 16:21:29 +01003134
3135 if (0 != InitializerID) {
Kévin Petitbbbda972020-03-03 19:16:31 +00003136 // Emit the ID of the initializer as part of the variable definition.
Kévin Petit23d5f182019-08-13 16:21:29 +01003137 Ops << MkId(InitializerID);
3138 }
David Neto85082642018-03-24 06:55:20 -07003139 const uint32_t var_id = nextID++;
3140
David Neto87846742018-04-11 17:36:22 -04003141 auto *Inst = new SPIRVInstruction(spv::OpVariable, var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003142 SPIRVInstList.push_back(Inst);
3143
SJW69939d52020-04-16 07:29:07 -05003144 SPIRVInstructionList &Annotations = getSPIRVInstList(kAnnotations);
alan-bakerbed3a882020-04-21 14:42:41 -04003145 // If we have a builtin (not WorkDim).
3146 if (spv::BuiltInMax != BuiltinType && BuiltinType != spv::BuiltInWorkDim) {
David Neto22f144c2017-06-12 14:26:21 -04003147 //
3148 // Generate OpDecorate.
3149 //
3150 // DOps[0] = Target ID
3151 // DOps[1] = Decoration (Builtin)
3152 // DOps[2] = BuiltIn ID
3153 uint32_t ResultID;
3154
3155 // WorkgroupSize is different, we decorate the constant composite that has
3156 // its value, rather than the variable that we use to access the value.
3157 if (spv::BuiltInWorkgroupSize == BuiltinType) {
3158 ResultID = InitializerID;
David Netoa60b00b2017-09-15 16:34:09 -04003159 // Save both the value and variable IDs for later.
3160 WorkgroupSizeValueID = InitializerID;
3161 WorkgroupSizeVarID = VMap[&GV];
David Neto22f144c2017-06-12 14:26:21 -04003162 } else {
3163 ResultID = VMap[&GV];
3164 }
3165
3166 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04003167 DOps << MkId(ResultID) << MkNum(spv::DecorationBuiltIn)
3168 << MkNum(BuiltinType);
David Neto22f144c2017-06-12 14:26:21 -04003169
David Neto87846742018-04-11 17:36:22 -04003170 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, DOps);
SJW69939d52020-04-16 07:29:07 -05003171 Annotations.push_back(DescDecoInst);
David Neto85082642018-03-24 06:55:20 -07003172 } else if (module_scope_constant_external_init) {
3173 // This module scope constant is initialized from a storage buffer with data
3174 // provided by the host at binding 0 of the next descriptor set.
SJW77b87ad2020-04-21 14:37:52 -05003175 const uint32_t descriptor_set = TakeDescriptorIndex(module);
David Neto85082642018-03-24 06:55:20 -07003176
David Neto862b7d82018-06-14 18:48:37 -04003177 // Emit the intializer to the descriptor map file.
David Neto85082642018-03-24 06:55:20 -07003178 // Use "kind,buffer" to indicate storage buffer. We might want to expand
3179 // that later to other types, like uniform buffer.
alan-bakerf5e5f692018-11-27 08:33:24 -05003180 std::string hexbytes;
3181 llvm::raw_string_ostream str(hexbytes);
3182 clspv::ConstantEmitter(DL, str).Emit(GV.getInitializer());
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003183 version0::DescriptorMapEntry::ConstantData constant_data = {ArgKind::Buffer,
3184 str.str()};
3185 descriptorMapEntries->emplace_back(std::move(constant_data), descriptor_set,
3186 0);
David Neto85082642018-03-24 06:55:20 -07003187
David Neto85082642018-03-24 06:55:20 -07003188 SPIRVOperandList DOps;
David Neto85082642018-03-24 06:55:20 -07003189
3190 // OpDecorate %var DescriptorSet <descriptor_set>
David Neto257c3892018-04-11 13:19:45 -04003191 DOps << MkId(var_id) << MkNum(spv::DecorationDescriptorSet)
3192 << MkNum(descriptor_set);
SJW69939d52020-04-16 07:29:07 -05003193 Annotations.push_back(new SPIRVInstruction(spv::OpDecorate, DOps));
3194
3195 // OpDecorate %var Binding <binding>
3196 DOps.clear();
3197 DOps << MkId(var_id) << MkNum(spv::DecorationBinding) << MkNum(0);
3198 Annotations.push_back(new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto22f144c2017-06-12 14:26:21 -04003199 }
3200}
3201
SJW77b87ad2020-04-21 14:37:52 -05003202void SPIRVProducerPass::GenerateWorkgroupVars() {
SJW69939d52020-04-16 07:29:07 -05003203 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kGlobalVariables);
SJW77b87ad2020-04-21 14:37:52 -05003204 auto spec_constant_md =
3205 module->getNamedMetadata(clspv::SpecConstantMetadataName());
alan-bakera1be3322020-04-20 12:48:18 -04003206 if (!spec_constant_md)
3207 return;
3208
SJW77b87ad2020-04-21 14:37:52 -05003209 for (auto pair : clspv::GetSpecConstants(module)) {
alan-bakera1be3322020-04-20 12:48:18 -04003210 auto kind = pair.first;
3211 auto spec_id = pair.second;
3212
3213 if (kind != SpecConstant::kLocalMemorySize)
3214 continue;
3215
alan-bakerb6b09dc2018-11-08 16:59:28 -05003216 LocalArgInfo &info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04003217
3218 // Generate OpVariable.
3219 //
3220 // GIDOps[0] : Result Type ID
3221 // GIDOps[1] : Storage Class
3222 SPIRVOperandList Ops;
3223 Ops << MkId(info.ptr_array_type_id) << MkNum(spv::StorageClassWorkgroup);
3224
3225 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04003226 new SPIRVInstruction(spv::OpVariable, info.variable_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04003227 }
3228}
3229
SJW77b87ad2020-04-21 14:37:52 -05003230void SPIRVProducerPass::GenerateDescriptorMapInfo(Function &F) {
3231 const auto &DL = module->getDataLayout();
David Netoc5fb5242018-07-30 13:28:31 -04003232 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
3233 return;
3234 }
Kévin Petit717f8572020-04-06 17:31:53 +01003235 // Add entries for each kernel
3236 version0::DescriptorMapEntry::KernelDeclData kernel_decl_data = {
3237 F.getName().str()};
3238 descriptorMapEntries->emplace_back(std::move(kernel_decl_data));
3239
David Neto862b7d82018-06-14 18:48:37 -04003240 // Gather the list of resources that are used by this function's arguments.
3241 auto &resource_var_at_index = FunctionToResourceVarsMap[&F];
3242
David Neto862b7d82018-06-14 18:48:37 -04003243 auto *fty = F.getType()->getPointerElementType();
3244 auto *func_ty = dyn_cast<FunctionType>(fty);
3245
alan-baker038e9242019-04-19 22:14:41 -04003246 // If we've clustered POD arguments, then argument details are in metadata.
David Neto862b7d82018-06-14 18:48:37 -04003247 // If an argument maps to a resource variable, then get descriptor set and
3248 // binding from the resoure variable. Other info comes from the metadata.
3249 const auto *arg_map = F.getMetadata("kernel_arg_map");
3250 if (arg_map) {
3251 for (const auto &arg : arg_map->operands()) {
3252 const MDNode *arg_node = dyn_cast<MDNode>(arg.get());
Kévin PETITa353c832018-03-20 23:21:21 +00003253 assert(arg_node->getNumOperands() == 7);
David Neto862b7d82018-06-14 18:48:37 -04003254 const auto name =
3255 dyn_cast<MDString>(arg_node->getOperand(0))->getString();
3256 const auto old_index =
3257 dyn_extract<ConstantInt>(arg_node->getOperand(1))->getZExtValue();
3258 // Remapped argument index
alan-bakerb6b09dc2018-11-08 16:59:28 -05003259 const size_t new_index = static_cast<size_t>(
3260 dyn_extract<ConstantInt>(arg_node->getOperand(2))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04003261 const auto offset =
3262 dyn_extract<ConstantInt>(arg_node->getOperand(3))->getZExtValue();
Kévin PETITa353c832018-03-20 23:21:21 +00003263 const auto arg_size =
3264 dyn_extract<ConstantInt>(arg_node->getOperand(4))->getZExtValue();
alan-bakerc4579bb2020-04-29 14:15:50 -04003265 const auto argKind = clspv::GetArgKindFromName(
3266 dyn_cast<MDString>(arg_node->getOperand(5))->getString().str());
David Neto862b7d82018-06-14 18:48:37 -04003267 const auto spec_id =
Kévin PETITa353c832018-03-20 23:21:21 +00003268 dyn_extract<ConstantInt>(arg_node->getOperand(6))->getSExtValue();
alan-bakerf5e5f692018-11-27 08:33:24 -05003269
3270 uint32_t descriptor_set = 0;
3271 uint32_t binding = 0;
3272 version0::DescriptorMapEntry::KernelArgData kernel_data = {
alan-baker21574d32020-01-29 16:00:31 -05003273 F.getName().str(), name.str(), static_cast<uint32_t>(old_index),
3274 argKind, static_cast<uint32_t>(spec_id),
alan-bakerf5e5f692018-11-27 08:33:24 -05003275 // This will be set below for pointer-to-local args.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003276 0, static_cast<uint32_t>(offset), static_cast<uint32_t>(arg_size)};
David Neto862b7d82018-06-14 18:48:37 -04003277 if (spec_id > 0) {
alan-bakerf5e5f692018-11-27 08:33:24 -05003278 kernel_data.local_element_size = static_cast<uint32_t>(GetTypeAllocSize(
3279 func_ty->getParamType(unsigned(new_index))->getPointerElementType(),
3280 DL));
David Neto862b7d82018-06-14 18:48:37 -04003281 } else {
3282 auto *info = resource_var_at_index[new_index];
3283 assert(info);
alan-bakerf5e5f692018-11-27 08:33:24 -05003284 descriptor_set = info->descriptor_set;
3285 binding = info->binding;
David Neto862b7d82018-06-14 18:48:37 -04003286 }
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003287 descriptorMapEntries->emplace_back(std::move(kernel_data), descriptor_set,
3288 binding);
David Neto862b7d82018-06-14 18:48:37 -04003289 }
3290 } else {
3291 // There is no argument map.
3292 // Take descriptor info from the resource variable calls.
Kévin PETITa353c832018-03-20 23:21:21 +00003293 // Take argument name and size from the arguments list.
David Neto862b7d82018-06-14 18:48:37 -04003294
3295 SmallVector<Argument *, 4> arguments;
3296 for (auto &arg : F.args()) {
3297 arguments.push_back(&arg);
3298 }
3299
3300 unsigned arg_index = 0;
3301 for (auto *info : resource_var_at_index) {
3302 if (info) {
Kévin PETITa353c832018-03-20 23:21:21 +00003303 auto arg = arguments[arg_index];
alan-bakerb6b09dc2018-11-08 16:59:28 -05003304 unsigned arg_size = 0;
alan-baker9b0ec3c2020-04-06 14:45:34 -04003305 if (info->arg_kind == clspv::ArgKind::Pod ||
3306 info->arg_kind == clspv::ArgKind::PodUBO ||
3307 info->arg_kind == clspv::ArgKind::PodPushConstant) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05003308 arg_size = static_cast<uint32_t>(DL.getTypeStoreSize(arg->getType()));
Kévin PETITa353c832018-03-20 23:21:21 +00003309 }
3310
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003311 // Local pointer arguments are unused in this case. Offset is always
3312 // zero.
alan-bakerf5e5f692018-11-27 08:33:24 -05003313 version0::DescriptorMapEntry::KernelArgData kernel_data = {
alan-baker21574d32020-01-29 16:00:31 -05003314 F.getName().str(),
3315 arg->getName().str(),
3316 arg_index,
alan-bakerc4579bb2020-04-29 14:15:50 -04003317 info->arg_kind,
alan-baker21574d32020-01-29 16:00:31 -05003318 0,
3319 0,
3320 0,
3321 arg_size};
alan-bakerf5e5f692018-11-27 08:33:24 -05003322 descriptorMapEntries->emplace_back(std::move(kernel_data),
3323 info->descriptor_set, info->binding);
David Neto862b7d82018-06-14 18:48:37 -04003324 }
3325 arg_index++;
3326 }
3327 // Generate mappings for pointer-to-local arguments.
3328 for (arg_index = 0; arg_index < arguments.size(); ++arg_index) {
3329 Argument *arg = arguments[arg_index];
Alan Baker202c8c72018-08-13 13:47:44 -04003330 auto where = LocalArgSpecIds.find(arg);
3331 if (where != LocalArgSpecIds.end()) {
3332 auto &local_arg_info = LocalSpecIdInfoMap[where->second];
alan-bakerf5e5f692018-11-27 08:33:24 -05003333 // Pod arguments members are unused in this case.
3334 version0::DescriptorMapEntry::KernelArgData kernel_data = {
alan-baker21574d32020-01-29 16:00:31 -05003335 F.getName().str(),
3336 arg->getName().str(),
alan-bakerf5e5f692018-11-27 08:33:24 -05003337 arg_index,
3338 ArgKind::Local,
3339 static_cast<uint32_t>(local_arg_info.spec_id),
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003340 static_cast<uint32_t>(
3341 GetTypeAllocSize(local_arg_info.elem_type, DL)),
alan-bakerf5e5f692018-11-27 08:33:24 -05003342 0,
3343 0};
3344 // Pointer-to-local arguments do not utilize descriptor set and binding.
3345 descriptorMapEntries->emplace_back(std::move(kernel_data), 0, 0);
David Neto862b7d82018-06-14 18:48:37 -04003346 }
3347 }
3348 }
3349}
3350
David Neto22f144c2017-06-12 14:26:21 -04003351void SPIRVProducerPass::GenerateFuncPrologue(Function &F) {
SJW69939d52020-04-16 07:29:07 -05003352 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kFunctions);
David Neto22f144c2017-06-12 14:26:21 -04003353 ValueMapType &VMap = getValueMap();
3354 EntryPointVecType &EntryPoints = getEntryPointVec();
David Neto22f144c2017-06-12 14:26:21 -04003355 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
3356 auto &GlobalConstArgSet = getGlobalConstArgSet();
3357
3358 FunctionType *FTy = F.getFunctionType();
3359
3360 //
David Neto22f144c2017-06-12 14:26:21 -04003361 // Generate OPFunction.
3362 //
3363
3364 // FOps[0] : Result Type ID
3365 // FOps[1] : Function Control
3366 // FOps[2] : Function Type ID
3367 SPIRVOperandList FOps;
3368
3369 // Find SPIRV instruction for return type.
David Neto257c3892018-04-11 13:19:45 -04003370 FOps << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04003371
3372 // Check function attributes for SPIRV Function Control.
3373 uint32_t FuncControl = spv::FunctionControlMaskNone;
3374 if (F.hasFnAttribute(Attribute::AlwaysInline)) {
3375 FuncControl |= spv::FunctionControlInlineMask;
3376 }
3377 if (F.hasFnAttribute(Attribute::NoInline)) {
3378 FuncControl |= spv::FunctionControlDontInlineMask;
3379 }
3380 // TODO: Check llvm attribute for Function Control Pure.
3381 if (F.hasFnAttribute(Attribute::ReadOnly)) {
3382 FuncControl |= spv::FunctionControlPureMask;
3383 }
3384 // TODO: Check llvm attribute for Function Control Const.
3385 if (F.hasFnAttribute(Attribute::ReadNone)) {
3386 FuncControl |= spv::FunctionControlConstMask;
3387 }
3388
David Neto257c3892018-04-11 13:19:45 -04003389 FOps << MkNum(FuncControl);
David Neto22f144c2017-06-12 14:26:21 -04003390
3391 uint32_t FTyID;
3392 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3393 SmallVector<Type *, 4> NewFuncParamTys;
3394 FunctionType *NewFTy =
3395 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
3396 FTyID = lookupType(NewFTy);
3397 } else {
David Neto9ed8e2f2018-03-24 06:47:24 -07003398 // Handle regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04003399 if (GlobalConstFuncTyMap.count(FTy)) {
3400 FTyID = lookupType(GlobalConstFuncTyMap[FTy].first);
3401 } else {
3402 FTyID = lookupType(FTy);
3403 }
3404 }
3405
David Neto257c3892018-04-11 13:19:45 -04003406 FOps << MkId(FTyID);
David Neto22f144c2017-06-12 14:26:21 -04003407
3408 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3409 EntryPoints.push_back(std::make_pair(&F, nextID));
3410 }
3411
3412 VMap[&F] = nextID;
3413
David Neto482550a2018-03-24 05:21:07 -07003414 if (clspv::Option::ShowIDs()) {
David Netob05675d2018-02-16 12:37:49 -05003415 errs() << "Function " << F.getName() << " is " << nextID << "\n";
3416 }
David Neto22f144c2017-06-12 14:26:21 -04003417 // Generate SPIRV instruction for function.
David Neto87846742018-04-11 17:36:22 -04003418 auto *FuncInst = new SPIRVInstruction(spv::OpFunction, nextID++, FOps);
David Neto22f144c2017-06-12 14:26:21 -04003419 SPIRVInstList.push_back(FuncInst);
3420
3421 //
3422 // Generate OpFunctionParameter for Normal function.
3423 //
3424
3425 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
alan-bakere9308012019-03-15 10:25:13 -04003426
David Neto22f144c2017-06-12 14:26:21 -04003427 // Iterate Argument for name instead of param type from function type.
3428 unsigned ArgIdx = 0;
3429 for (Argument &Arg : F.args()) {
alan-bakere9308012019-03-15 10:25:13 -04003430 uint32_t param_id = nextID++;
3431 VMap[&Arg] = param_id;
3432
3433 if (CalledWithCoherentResource(Arg)) {
3434 // If the arg is passed a coherent resource ever, then decorate this
3435 // parameter with Coherent too.
3436 SPIRVOperandList decoration_ops;
3437 decoration_ops << MkId(param_id) << MkNum(spv::DecorationCoherent);
SJW69939d52020-04-16 07:29:07 -05003438 getSPIRVInstList(kAnnotations)
3439 .push_back(new SPIRVInstruction(spv::OpDecorate, decoration_ops));
alan-bakere9308012019-03-15 10:25:13 -04003440 }
David Neto22f144c2017-06-12 14:26:21 -04003441
3442 // ParamOps[0] : Result Type ID
3443 SPIRVOperandList ParamOps;
3444
3445 // Find SPIRV instruction for parameter type.
3446 uint32_t ParamTyID = lookupType(Arg.getType());
3447 if (PointerType *PTy = dyn_cast<PointerType>(Arg.getType())) {
3448 if (GlobalConstFuncTyMap.count(FTy)) {
3449 if (ArgIdx == GlobalConstFuncTyMap[FTy].second) {
3450 Type *EleTy = PTy->getPointerElementType();
3451 Type *ArgTy =
3452 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
3453 ParamTyID = lookupType(ArgTy);
3454 GlobalConstArgSet.insert(&Arg);
3455 }
3456 }
3457 }
David Neto257c3892018-04-11 13:19:45 -04003458 ParamOps << MkId(ParamTyID);
David Neto22f144c2017-06-12 14:26:21 -04003459
3460 // Generate SPIRV instruction for parameter.
David Neto87846742018-04-11 17:36:22 -04003461 auto *ParamInst =
alan-bakere9308012019-03-15 10:25:13 -04003462 new SPIRVInstruction(spv::OpFunctionParameter, param_id, ParamOps);
David Neto22f144c2017-06-12 14:26:21 -04003463 SPIRVInstList.push_back(ParamInst);
3464
3465 ArgIdx++;
3466 }
3467 }
3468}
3469
SJW77b87ad2020-04-21 14:37:52 -05003470void SPIRVProducerPass::GenerateModuleInfo() {
David Neto22f144c2017-06-12 14:26:21 -04003471 EntryPointVecType &EntryPoints = getEntryPointVec();
3472 ValueMapType &VMap = getValueMap();
3473 ValueList &EntryPointInterfaces = getEntryPointInterfacesVec();
David Neto22f144c2017-06-12 14:26:21 -04003474 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
3475
SJW69939d52020-04-16 07:29:07 -05003476 SPIRVInstructionList &SPIRVCapabilities = getSPIRVInstList(kCapabilities);
David Neto22f144c2017-06-12 14:26:21 -04003477 //
3478 // Generate OpCapability
3479 //
3480 // TODO: Which llvm information is mapped to SPIRV Capapbility?
3481
3482 // Ops[0] = Capability
3483 SPIRVOperandList Ops;
3484
David Neto87846742018-04-11 17:36:22 -04003485 auto *CapInst =
David Netoef5ba2b2019-12-20 08:35:54 -05003486 new SPIRVInstruction(spv::OpCapability, MkNum(spv::CapabilityShader));
SJW69939d52020-04-16 07:29:07 -05003487 SPIRVCapabilities.push_back(CapInst);
David Neto22f144c2017-06-12 14:26:21 -04003488
alan-bakerf906d2b2019-12-10 11:26:23 -05003489 bool write_without_format = false;
3490 bool sampled_1d = false;
3491 bool image_1d = false;
David Neto22f144c2017-06-12 14:26:21 -04003492 for (Type *Ty : getTypeList()) {
alan-bakerb39c8262019-03-08 14:03:37 -05003493 if (clspv::Option::Int8Support() && Ty->isIntegerTy(8)) {
3494 // Generate OpCapability for i8 type.
SJW69939d52020-04-16 07:29:07 -05003495 SPIRVCapabilities.push_back(
David Netoef5ba2b2019-12-20 08:35:54 -05003496 new SPIRVInstruction(spv::OpCapability, MkNum(spv::CapabilityInt8)));
alan-bakerb39c8262019-03-08 14:03:37 -05003497 } else if (Ty->isIntegerTy(16)) {
David Neto22f144c2017-06-12 14:26:21 -04003498 // Generate OpCapability for i16 type.
SJW69939d52020-04-16 07:29:07 -05003499 SPIRVCapabilities.push_back(
David Netoef5ba2b2019-12-20 08:35:54 -05003500 new SPIRVInstruction(spv::OpCapability, MkNum(spv::CapabilityInt16)));
David Neto22f144c2017-06-12 14:26:21 -04003501 } else if (Ty->isIntegerTy(64)) {
3502 // Generate OpCapability for i64 type.
SJW69939d52020-04-16 07:29:07 -05003503 SPIRVCapabilities.push_back(
David Netoef5ba2b2019-12-20 08:35:54 -05003504 new SPIRVInstruction(spv::OpCapability, MkNum(spv::CapabilityInt64)));
David Neto22f144c2017-06-12 14:26:21 -04003505 } else if (Ty->isHalfTy()) {
3506 // Generate OpCapability for half type.
SJW69939d52020-04-16 07:29:07 -05003507 SPIRVCapabilities.push_back(new SPIRVInstruction(
3508 spv::OpCapability, MkNum(spv::CapabilityFloat16)));
David Neto22f144c2017-06-12 14:26:21 -04003509 } else if (Ty->isDoubleTy()) {
3510 // Generate OpCapability for double type.
SJW69939d52020-04-16 07:29:07 -05003511 SPIRVCapabilities.push_back(new SPIRVInstruction(
3512 spv::OpCapability, MkNum(spv::CapabilityFloat64)));
David Neto22f144c2017-06-12 14:26:21 -04003513 } else if (auto *STy = dyn_cast<StructType>(Ty)) {
3514 if (STy->isOpaque()) {
alan-bakerf906d2b2019-12-10 11:26:23 -05003515 if (STy->getName().startswith("opencl.image1d_wo_t") ||
alan-baker7150a1d2020-02-25 08:31:06 -05003516 STy->getName().startswith("opencl.image1d_array_wo_t") ||
alan-bakerf906d2b2019-12-10 11:26:23 -05003517 STy->getName().startswith("opencl.image2d_wo_t") ||
alan-baker7150a1d2020-02-25 08:31:06 -05003518 STy->getName().startswith("opencl.image2d_array_wo_t") ||
alan-bakerf67468c2019-11-25 15:51:49 -05003519 STy->getName().startswith("opencl.image3d_wo_t")) {
alan-bakerf906d2b2019-12-10 11:26:23 -05003520 write_without_format = true;
3521 }
3522 if (STy->getName().startswith("opencl.image1d_ro_t") ||
alan-baker7150a1d2020-02-25 08:31:06 -05003523 STy->getName().startswith("opencl.image1d_wo_t") ||
3524 STy->getName().startswith("opencl.image1d_array_ro_t") ||
3525 STy->getName().startswith("opencl.image1d_array_wo_t")) {
alan-bakerf906d2b2019-12-10 11:26:23 -05003526 if (STy->getName().contains(".sampled"))
3527 sampled_1d = true;
3528 else
3529 image_1d = true;
David Neto22f144c2017-06-12 14:26:21 -04003530 }
3531 }
3532 }
3533 }
3534
alan-bakerf906d2b2019-12-10 11:26:23 -05003535 if (write_without_format) {
3536 // Generate OpCapability for write only image type.
SJW69939d52020-04-16 07:29:07 -05003537 SPIRVCapabilities.push_back(new SPIRVInstruction(
3538 spv::OpCapability,
3539 {MkNum(spv::CapabilityStorageImageWriteWithoutFormat)}));
alan-bakerf906d2b2019-12-10 11:26:23 -05003540 }
3541 if (image_1d) {
3542 // Generate OpCapability for unsampled 1D image type.
SJW69939d52020-04-16 07:29:07 -05003543 SPIRVCapabilities.push_back(new SPIRVInstruction(
3544 spv::OpCapability, {MkNum(spv::CapabilityImage1D)}));
alan-bakerf906d2b2019-12-10 11:26:23 -05003545 } else if (sampled_1d) {
3546 // Generate OpCapability for sampled 1D image type.
SJW69939d52020-04-16 07:29:07 -05003547 SPIRVCapabilities.push_back(new SPIRVInstruction(
3548 spv::OpCapability, {MkNum(spv::CapabilitySampled1D)}));
alan-bakerf906d2b2019-12-10 11:26:23 -05003549 }
3550
David Neto5c22a252018-03-15 16:07:41 -04003551 { // OpCapability ImageQuery
3552 bool hasImageQuery = false;
SJW77b87ad2020-04-21 14:37:52 -05003553 for (const auto &SymVal : module->getValueSymbolTable()) {
alan-bakerf67468c2019-11-25 15:51:49 -05003554 if (auto F = dyn_cast<Function>(SymVal.getValue())) {
SJW173c7e92020-03-16 08:44:47 -05003555 if (IsImageQuery(F)) {
alan-bakerf67468c2019-11-25 15:51:49 -05003556 hasImageQuery = true;
3557 break;
3558 }
David Neto5c22a252018-03-15 16:07:41 -04003559 }
3560 }
alan-bakerf67468c2019-11-25 15:51:49 -05003561
David Neto5c22a252018-03-15 16:07:41 -04003562 if (hasImageQuery) {
SJW69939d52020-04-16 07:29:07 -05003563 SPIRVCapabilities.push_back(new SPIRVInstruction(
3564 spv::OpCapability, {MkNum(spv::CapabilityImageQuery)}));
David Neto5c22a252018-03-15 16:07:41 -04003565 }
3566 }
3567
David Neto22f144c2017-06-12 14:26:21 -04003568 if (hasVariablePointers()) {
3569 //
David Neto22f144c2017-06-12 14:26:21 -04003570 // Generate OpCapability.
3571 //
3572 // Ops[0] = Capability
3573 //
3574 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003575 Ops << MkNum(spv::CapabilityVariablePointers);
David Neto22f144c2017-06-12 14:26:21 -04003576
SJW69939d52020-04-16 07:29:07 -05003577 SPIRVCapabilities.push_back(new SPIRVInstruction(spv::OpCapability, Ops));
alan-baker5b86ed72019-02-15 08:26:50 -05003578 } else if (hasVariablePointersStorageBuffer()) {
3579 //
3580 // Generate OpCapability.
3581 //
3582 // Ops[0] = Capability
3583 //
3584 Ops.clear();
3585 Ops << MkNum(spv::CapabilityVariablePointersStorageBuffer);
David Neto22f144c2017-06-12 14:26:21 -04003586
SJW69939d52020-04-16 07:29:07 -05003587 SPIRVCapabilities.push_back(new SPIRVInstruction(spv::OpCapability, Ops));
alan-baker5b86ed72019-02-15 08:26:50 -05003588 }
3589
SJW69939d52020-04-16 07:29:07 -05003590 SPIRVInstructionList &SPIRVExtensions = getSPIRVInstList(kExtensions);
alan-baker5b86ed72019-02-15 08:26:50 -05003591 // Always add the storage buffer extension
3592 {
David Neto22f144c2017-06-12 14:26:21 -04003593 //
3594 // Generate OpExtension.
3595 //
3596 // Ops[0] = Name (Literal String)
3597 //
alan-baker5b86ed72019-02-15 08:26:50 -05003598 auto *ExtensionInst = new SPIRVInstruction(
3599 spv::OpExtension, {MkString("SPV_KHR_storage_buffer_storage_class")});
SJW69939d52020-04-16 07:29:07 -05003600 SPIRVExtensions.push_back(ExtensionInst);
alan-baker5b86ed72019-02-15 08:26:50 -05003601 }
David Neto22f144c2017-06-12 14:26:21 -04003602
alan-baker5b86ed72019-02-15 08:26:50 -05003603 if (hasVariablePointers() || hasVariablePointersStorageBuffer()) {
3604 //
3605 // Generate OpExtension.
3606 //
3607 // Ops[0] = Name (Literal String)
3608 //
3609 auto *ExtensionInst = new SPIRVInstruction(
3610 spv::OpExtension, {MkString("SPV_KHR_variable_pointers")});
SJW69939d52020-04-16 07:29:07 -05003611 SPIRVExtensions.push_back(ExtensionInst);
David Neto22f144c2017-06-12 14:26:21 -04003612 }
3613
3614 //
3615 // Generate OpMemoryModel
3616 //
3617 // Memory model for Vulkan will always be GLSL450.
3618
3619 // Ops[0] = Addressing Model
3620 // Ops[1] = Memory Model
3621 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003622 Ops << MkNum(spv::AddressingModelLogical) << MkNum(spv::MemoryModelGLSL450);
David Neto22f144c2017-06-12 14:26:21 -04003623
David Neto87846742018-04-11 17:36:22 -04003624 auto *MemModelInst = new SPIRVInstruction(spv::OpMemoryModel, Ops);
SJW69939d52020-04-16 07:29:07 -05003625 getSPIRVInstList(kMemoryModel).push_back(MemModelInst);
David Neto22f144c2017-06-12 14:26:21 -04003626
SJW69939d52020-04-16 07:29:07 -05003627 SPIRVInstructionList &SPIRVEntryPoints = getSPIRVInstList(kEntryPoints);
David Neto22f144c2017-06-12 14:26:21 -04003628 //
3629 // Generate OpEntryPoint
3630 //
3631 for (auto EntryPoint : EntryPoints) {
3632 // Ops[0] = Execution Model
3633 // Ops[1] = EntryPoint ID
3634 // Ops[2] = Name (Literal String)
3635 // ...
3636 //
3637 // TODO: Do we need to consider Interface ID for forward references???
3638 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05003639 const StringRef &name = EntryPoint.first->getName();
David Neto257c3892018-04-11 13:19:45 -04003640 Ops << MkNum(spv::ExecutionModelGLCompute) << MkId(EntryPoint.second)
3641 << MkString(name);
David Neto22f144c2017-06-12 14:26:21 -04003642
David Neto22f144c2017-06-12 14:26:21 -04003643 for (Value *Interface : EntryPointInterfaces) {
David Neto257c3892018-04-11 13:19:45 -04003644 Ops << MkId(VMap[Interface]);
David Neto22f144c2017-06-12 14:26:21 -04003645 }
3646
David Neto87846742018-04-11 17:36:22 -04003647 auto *EntryPointInst = new SPIRVInstruction(spv::OpEntryPoint, Ops);
SJW69939d52020-04-16 07:29:07 -05003648 SPIRVEntryPoints.push_back(EntryPointInst);
David Neto22f144c2017-06-12 14:26:21 -04003649 }
3650
SJW69939d52020-04-16 07:29:07 -05003651 SPIRVInstructionList &SPIRVExecutionModes = getSPIRVInstList(kExecutionModes);
David Neto22f144c2017-06-12 14:26:21 -04003652 for (auto EntryPoint : EntryPoints) {
Kévin Petit21c23c62020-04-29 01:38:28 +01003653 const MDNode *MD = dyn_cast<Function>(EntryPoint.first)
3654 ->getMetadata("reqd_work_group_size");
3655 if ((MD != nullptr) && !clspv::Option::NonUniformNDRangeSupported()) {
David Neto22f144c2017-06-12 14:26:21 -04003656
3657 if (!BuiltinDimVec.empty()) {
3658 llvm_unreachable(
3659 "Kernels should have consistent work group size definition");
3660 }
3661
3662 //
3663 // Generate OpExecutionMode
3664 //
3665
3666 // Ops[0] = Entry Point ID
3667 // Ops[1] = Execution Mode
3668 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
3669 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05003670 Ops << MkId(EntryPoint.second) << MkNum(spv::ExecutionModeLocalSize);
David Neto22f144c2017-06-12 14:26:21 -04003671
3672 uint32_t XDim = static_cast<uint32_t>(
3673 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
3674 uint32_t YDim = static_cast<uint32_t>(
3675 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
3676 uint32_t ZDim = static_cast<uint32_t>(
3677 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
3678
David Neto257c3892018-04-11 13:19:45 -04003679 Ops << MkNum(XDim) << MkNum(YDim) << MkNum(ZDim);
David Neto22f144c2017-06-12 14:26:21 -04003680
David Neto87846742018-04-11 17:36:22 -04003681 auto *ExecModeInst = new SPIRVInstruction(spv::OpExecutionMode, Ops);
SJW69939d52020-04-16 07:29:07 -05003682 SPIRVExecutionModes.push_back(ExecModeInst);
David Neto22f144c2017-06-12 14:26:21 -04003683 }
3684 }
3685
3686 //
3687 // Generate OpSource.
3688 //
3689 // Ops[0] = SourceLanguage ID
3690 // Ops[1] = Version (LiteralNum)
3691 //
3692 Ops.clear();
Kévin Petitf0515712020-01-07 18:29:20 +00003693 switch (clspv::Option::Language()) {
3694 case clspv::Option::SourceLanguage::OpenCL_C_10:
3695 Ops << MkNum(spv::SourceLanguageOpenCL_C) << MkNum(100);
3696 break;
3697 case clspv::Option::SourceLanguage::OpenCL_C_11:
3698 Ops << MkNum(spv::SourceLanguageOpenCL_C) << MkNum(110);
3699 break;
3700 case clspv::Option::SourceLanguage::OpenCL_C_12:
Kévin Petit0fc88042019-04-09 23:25:02 +01003701 Ops << MkNum(spv::SourceLanguageOpenCL_C) << MkNum(120);
Kévin Petitf0515712020-01-07 18:29:20 +00003702 break;
3703 case clspv::Option::SourceLanguage::OpenCL_C_20:
3704 Ops << MkNum(spv::SourceLanguageOpenCL_C) << MkNum(200);
3705 break;
3706 case clspv::Option::SourceLanguage::OpenCL_CPP:
3707 Ops << MkNum(spv::SourceLanguageOpenCL_CPP) << MkNum(100);
3708 break;
3709 default:
3710 Ops << MkNum(spv::SourceLanguageUnknown) << MkNum(0);
3711 break;
Kévin Petit0fc88042019-04-09 23:25:02 +01003712 }
David Neto22f144c2017-06-12 14:26:21 -04003713
David Neto87846742018-04-11 17:36:22 -04003714 auto *OpenSourceInst = new SPIRVInstruction(spv::OpSource, Ops);
SJW69939d52020-04-16 07:29:07 -05003715 getSPIRVInstList(kDebug).push_back(OpenSourceInst);
David Neto22f144c2017-06-12 14:26:21 -04003716
3717 if (!BuiltinDimVec.empty()) {
SJW69939d52020-04-16 07:29:07 -05003718 SPIRVInstructionList &SPIRVAnnotations = getSPIRVInstList(kAnnotations);
David Neto22f144c2017-06-12 14:26:21 -04003719 //
3720 // Generate OpDecorates for x/y/z dimension.
3721 //
3722 // Ops[0] = Target ID
3723 // Ops[1] = Decoration (SpecId)
David Neto257c3892018-04-11 13:19:45 -04003724 // Ops[2] = Specialization Constant ID (Literal Number)
David Neto22f144c2017-06-12 14:26:21 -04003725
3726 // X Dimension
3727 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003728 Ops << MkId(BuiltinDimVec[0]) << MkNum(spv::DecorationSpecId) << MkNum(0);
SJW69939d52020-04-16 07:29:07 -05003729 SPIRVAnnotations.push_back(new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003730
3731 // Y Dimension
3732 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003733 Ops << MkId(BuiltinDimVec[1]) << MkNum(spv::DecorationSpecId) << MkNum(1);
SJW69939d52020-04-16 07:29:07 -05003734 SPIRVAnnotations.push_back(new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003735
3736 // Z Dimension
3737 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003738 Ops << MkId(BuiltinDimVec[2]) << MkNum(spv::DecorationSpecId) << MkNum(2);
SJW69939d52020-04-16 07:29:07 -05003739 SPIRVAnnotations.push_back(new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003740 }
3741}
3742
David Netob6e2e062018-04-25 10:32:06 -04003743void SPIRVProducerPass::GenerateEntryPointInitialStores() {
3744 // Work around a driver bug. Initializers on Private variables might not
3745 // work. So the start of the kernel should store the initializer value to the
3746 // variables. Yes, *every* entry point pays this cost if *any* entry point
3747 // uses this builtin. At this point I judge this to be an acceptable tradeoff
3748 // of complexity vs. runtime, for a broken driver.
alan-bakerb6b09dc2018-11-08 16:59:28 -05003749 // TODO(dneto): Remove this at some point once fixed drivers are widely
3750 // available.
David Netob6e2e062018-04-25 10:32:06 -04003751 if (WorkgroupSizeVarID) {
3752 assert(WorkgroupSizeValueID);
3753
3754 SPIRVOperandList Ops;
3755 Ops << MkId(WorkgroupSizeVarID) << MkId(WorkgroupSizeValueID);
3756
3757 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
SJW69939d52020-04-16 07:29:07 -05003758 getSPIRVInstList(kFunctions).push_back(Inst);
David Netob6e2e062018-04-25 10:32:06 -04003759 }
3760}
3761
David Neto22f144c2017-06-12 14:26:21 -04003762void SPIRVProducerPass::GenerateFuncBody(Function &F) {
SJW69939d52020-04-16 07:29:07 -05003763 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kFunctions);
David Neto22f144c2017-06-12 14:26:21 -04003764 ValueMapType &VMap = getValueMap();
3765
David Netob6e2e062018-04-25 10:32:06 -04003766 const bool IsKernel = F.getCallingConv() == CallingConv::SPIR_KERNEL;
David Neto22f144c2017-06-12 14:26:21 -04003767
3768 for (BasicBlock &BB : F) {
3769 // Register BasicBlock to ValueMap.
3770 VMap[&BB] = nextID;
3771
3772 //
3773 // Generate OpLabel for Basic Block.
3774 //
3775 SPIRVOperandList Ops;
David Neto87846742018-04-11 17:36:22 -04003776 auto *Inst = new SPIRVInstruction(spv::OpLabel, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003777 SPIRVInstList.push_back(Inst);
3778
David Neto6dcd4712017-06-23 11:06:47 -04003779 // OpVariable instructions must come first.
3780 for (Instruction &I : BB) {
alan-baker5b86ed72019-02-15 08:26:50 -05003781 if (auto *alloca = dyn_cast<AllocaInst>(&I)) {
3782 // Allocating a pointer requires variable pointers.
3783 if (alloca->getAllocatedType()->isPointerTy()) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003784 setVariablePointersCapabilities(
3785 alloca->getAllocatedType()->getPointerAddressSpace());
alan-baker5b86ed72019-02-15 08:26:50 -05003786 }
David Neto6dcd4712017-06-23 11:06:47 -04003787 GenerateInstruction(I);
3788 }
3789 }
3790
David Neto22f144c2017-06-12 14:26:21 -04003791 if (&BB == &F.getEntryBlock() && IsKernel) {
David Netob6e2e062018-04-25 10:32:06 -04003792 if (clspv::Option::HackInitializers()) {
3793 GenerateEntryPointInitialStores();
3794 }
David Neto22f144c2017-06-12 14:26:21 -04003795 }
3796
3797 for (Instruction &I : BB) {
David Neto6dcd4712017-06-23 11:06:47 -04003798 if (!isa<AllocaInst>(I)) {
3799 GenerateInstruction(I);
3800 }
David Neto22f144c2017-06-12 14:26:21 -04003801 }
3802 }
3803}
3804
3805spv::Op SPIRVProducerPass::GetSPIRVCmpOpcode(CmpInst *I) {
3806 const std::map<CmpInst::Predicate, spv::Op> Map = {
3807 {CmpInst::ICMP_EQ, spv::OpIEqual},
3808 {CmpInst::ICMP_NE, spv::OpINotEqual},
3809 {CmpInst::ICMP_UGT, spv::OpUGreaterThan},
3810 {CmpInst::ICMP_UGE, spv::OpUGreaterThanEqual},
3811 {CmpInst::ICMP_ULT, spv::OpULessThan},
3812 {CmpInst::ICMP_ULE, spv::OpULessThanEqual},
3813 {CmpInst::ICMP_SGT, spv::OpSGreaterThan},
3814 {CmpInst::ICMP_SGE, spv::OpSGreaterThanEqual},
3815 {CmpInst::ICMP_SLT, spv::OpSLessThan},
3816 {CmpInst::ICMP_SLE, spv::OpSLessThanEqual},
3817 {CmpInst::FCMP_OEQ, spv::OpFOrdEqual},
3818 {CmpInst::FCMP_OGT, spv::OpFOrdGreaterThan},
3819 {CmpInst::FCMP_OGE, spv::OpFOrdGreaterThanEqual},
3820 {CmpInst::FCMP_OLT, spv::OpFOrdLessThan},
3821 {CmpInst::FCMP_OLE, spv::OpFOrdLessThanEqual},
3822 {CmpInst::FCMP_ONE, spv::OpFOrdNotEqual},
3823 {CmpInst::FCMP_UEQ, spv::OpFUnordEqual},
3824 {CmpInst::FCMP_UGT, spv::OpFUnordGreaterThan},
3825 {CmpInst::FCMP_UGE, spv::OpFUnordGreaterThanEqual},
3826 {CmpInst::FCMP_ULT, spv::OpFUnordLessThan},
3827 {CmpInst::FCMP_ULE, spv::OpFUnordLessThanEqual},
3828 {CmpInst::FCMP_UNE, spv::OpFUnordNotEqual}};
3829
3830 assert(0 != Map.count(I->getPredicate()));
3831
3832 return Map.at(I->getPredicate());
3833}
3834
3835spv::Op SPIRVProducerPass::GetSPIRVCastOpcode(Instruction &I) {
3836 const std::map<unsigned, spv::Op> Map{
3837 {Instruction::Trunc, spv::OpUConvert},
3838 {Instruction::ZExt, spv::OpUConvert},
3839 {Instruction::SExt, spv::OpSConvert},
3840 {Instruction::FPToUI, spv::OpConvertFToU},
3841 {Instruction::FPToSI, spv::OpConvertFToS},
3842 {Instruction::UIToFP, spv::OpConvertUToF},
3843 {Instruction::SIToFP, spv::OpConvertSToF},
3844 {Instruction::FPTrunc, spv::OpFConvert},
3845 {Instruction::FPExt, spv::OpFConvert},
3846 {Instruction::BitCast, spv::OpBitcast}};
3847
3848 assert(0 != Map.count(I.getOpcode()));
3849
3850 return Map.at(I.getOpcode());
3851}
3852
3853spv::Op SPIRVProducerPass::GetSPIRVBinaryOpcode(Instruction &I) {
Kévin Petit24272b62018-10-18 19:16:12 +00003854 if (I.getType()->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003855 switch (I.getOpcode()) {
3856 default:
3857 break;
3858 case Instruction::Or:
3859 return spv::OpLogicalOr;
3860 case Instruction::And:
3861 return spv::OpLogicalAnd;
3862 case Instruction::Xor:
3863 return spv::OpLogicalNotEqual;
3864 }
3865 }
3866
alan-bakerb6b09dc2018-11-08 16:59:28 -05003867 const std::map<unsigned, spv::Op> Map{
David Neto22f144c2017-06-12 14:26:21 -04003868 {Instruction::Add, spv::OpIAdd},
3869 {Instruction::FAdd, spv::OpFAdd},
3870 {Instruction::Sub, spv::OpISub},
3871 {Instruction::FSub, spv::OpFSub},
3872 {Instruction::Mul, spv::OpIMul},
3873 {Instruction::FMul, spv::OpFMul},
3874 {Instruction::UDiv, spv::OpUDiv},
3875 {Instruction::SDiv, spv::OpSDiv},
3876 {Instruction::FDiv, spv::OpFDiv},
3877 {Instruction::URem, spv::OpUMod},
3878 {Instruction::SRem, spv::OpSRem},
3879 {Instruction::FRem, spv::OpFRem},
3880 {Instruction::Or, spv::OpBitwiseOr},
3881 {Instruction::Xor, spv::OpBitwiseXor},
3882 {Instruction::And, spv::OpBitwiseAnd},
3883 {Instruction::Shl, spv::OpShiftLeftLogical},
3884 {Instruction::LShr, spv::OpShiftRightLogical},
3885 {Instruction::AShr, spv::OpShiftRightArithmetic}};
3886
3887 assert(0 != Map.count(I.getOpcode()));
3888
3889 return Map.at(I.getOpcode());
3890}
3891
3892void SPIRVProducerPass::GenerateInstruction(Instruction &I) {
SJW69939d52020-04-16 07:29:07 -05003893 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kFunctions);
David Neto22f144c2017-06-12 14:26:21 -04003894 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04003895 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
3896 LLVMContext &Context = I.getParent()->getParent()->getParent()->getContext();
3897
3898 // Register Instruction to ValueMap.
3899 if (0 == VMap[&I]) {
3900 VMap[&I] = nextID;
3901 }
3902
3903 switch (I.getOpcode()) {
3904 default: {
3905 if (Instruction::isCast(I.getOpcode())) {
3906 //
3907 // Generate SPIRV instructions for cast operators.
3908 //
3909
David Netod2de94a2017-08-28 17:27:47 -04003910 auto Ty = I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003911 auto OpTy = I.getOperand(0)->getType();
David Netod2de94a2017-08-28 17:27:47 -04003912 auto toI8 = Ty == Type::getInt8Ty(Context);
3913 auto fromI32 = OpTy == Type::getInt32Ty(Context);
David Neto22f144c2017-06-12 14:26:21 -04003914 // Handle zext, sext and uitofp with i1 type specially.
3915 if ((I.getOpcode() == Instruction::ZExt ||
3916 I.getOpcode() == Instruction::SExt ||
3917 I.getOpcode() == Instruction::UIToFP) &&
alan-bakerb6b09dc2018-11-08 16:59:28 -05003918 OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003919 //
3920 // Generate OpSelect.
3921 //
3922
3923 // Ops[0] = Result Type ID
3924 // Ops[1] = Condition ID
3925 // Ops[2] = True Constant ID
3926 // Ops[3] = False Constant ID
3927 SPIRVOperandList Ops;
3928
David Neto257c3892018-04-11 13:19:45 -04003929 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003930
David Neto22f144c2017-06-12 14:26:21 -04003931 uint32_t CondID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003932 Ops << MkId(CondID);
David Neto22f144c2017-06-12 14:26:21 -04003933
3934 uint32_t TrueID = 0;
3935 if (I.getOpcode() == Instruction::ZExt) {
Kévin Petit7bfb8992019-02-26 13:45:08 +00003936 TrueID = VMap[ConstantInt::get(I.getType(), 1)];
David Neto22f144c2017-06-12 14:26:21 -04003937 } else if (I.getOpcode() == Instruction::SExt) {
Kévin Petit7bfb8992019-02-26 13:45:08 +00003938 TrueID = VMap[ConstantInt::getSigned(I.getType(), -1)];
David Neto22f144c2017-06-12 14:26:21 -04003939 } else {
3940 TrueID = VMap[ConstantFP::get(Context, APFloat(1.0f))];
3941 }
David Neto257c3892018-04-11 13:19:45 -04003942 Ops << MkId(TrueID);
David Neto22f144c2017-06-12 14:26:21 -04003943
3944 uint32_t FalseID = 0;
3945 if (I.getOpcode() == Instruction::ZExt) {
3946 FalseID = VMap[Constant::getNullValue(I.getType())];
3947 } else if (I.getOpcode() == Instruction::SExt) {
3948 FalseID = VMap[Constant::getNullValue(I.getType())];
3949 } else {
3950 FalseID = VMap[ConstantFP::get(Context, APFloat(0.0f))];
3951 }
David Neto257c3892018-04-11 13:19:45 -04003952 Ops << MkId(FalseID);
David Neto22f144c2017-06-12 14:26:21 -04003953
David Neto87846742018-04-11 17:36:22 -04003954 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003955 SPIRVInstList.push_back(Inst);
alan-bakerb39c8262019-03-08 14:03:37 -05003956 } else if (!clspv::Option::Int8Support() &&
3957 I.getOpcode() == Instruction::Trunc && fromI32 && toI8) {
David Netod2de94a2017-08-28 17:27:47 -04003958 // The SPIR-V target type is a 32-bit int. Keep only the bottom
3959 // 8 bits.
3960 // Before:
3961 // %result = trunc i32 %a to i8
3962 // After
3963 // %result = OpBitwiseAnd %uint %a %uint_255
3964
3965 SPIRVOperandList Ops;
3966
David Neto257c3892018-04-11 13:19:45 -04003967 Ops << MkId(lookupType(OpTy)) << MkId(VMap[I.getOperand(0)]);
David Netod2de94a2017-08-28 17:27:47 -04003968
3969 Type *UintTy = Type::getInt32Ty(Context);
3970 uint32_t MaskID = VMap[ConstantInt::get(UintTy, 255)];
David Neto257c3892018-04-11 13:19:45 -04003971 Ops << MkId(MaskID);
David Netod2de94a2017-08-28 17:27:47 -04003972
David Neto87846742018-04-11 17:36:22 -04003973 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Netod2de94a2017-08-28 17:27:47 -04003974 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04003975 } else {
3976 // Ops[0] = Result Type ID
3977 // Ops[1] = Source Value ID
3978 SPIRVOperandList Ops;
3979
David Neto257c3892018-04-11 13:19:45 -04003980 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003981
David Neto87846742018-04-11 17:36:22 -04003982 auto *Inst = new SPIRVInstruction(GetSPIRVCastOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003983 SPIRVInstList.push_back(Inst);
3984 }
3985 } else if (isa<BinaryOperator>(I)) {
3986 //
3987 // Generate SPIRV instructions for binary operators.
3988 //
3989
3990 // Handle xor with i1 type specially.
3991 if (I.getOpcode() == Instruction::Xor &&
3992 I.getType() == Type::getInt1Ty(Context) &&
Kévin Petit24272b62018-10-18 19:16:12 +00003993 ((isa<ConstantInt>(I.getOperand(0)) &&
3994 !cast<ConstantInt>(I.getOperand(0))->isZero()) ||
3995 (isa<ConstantInt>(I.getOperand(1)) &&
3996 !cast<ConstantInt>(I.getOperand(1))->isZero()))) {
David Neto22f144c2017-06-12 14:26:21 -04003997 //
3998 // Generate OpLogicalNot.
3999 //
4000 // Ops[0] = Result Type ID
4001 // Ops[1] = Operand
4002 SPIRVOperandList Ops;
4003
David Neto257c3892018-04-11 13:19:45 -04004004 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004005
4006 Value *CondV = I.getOperand(0);
4007 if (isa<Constant>(I.getOperand(0))) {
4008 CondV = I.getOperand(1);
4009 }
David Neto257c3892018-04-11 13:19:45 -04004010 Ops << MkId(VMap[CondV]);
David Neto22f144c2017-06-12 14:26:21 -04004011
David Neto87846742018-04-11 17:36:22 -04004012 auto *Inst = new SPIRVInstruction(spv::OpLogicalNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004013 SPIRVInstList.push_back(Inst);
4014 } else {
4015 // Ops[0] = Result Type ID
4016 // Ops[1] = Operand 0
4017 // Ops[2] = Operand 1
4018 SPIRVOperandList Ops;
4019
David Neto257c3892018-04-11 13:19:45 -04004020 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
4021 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004022
David Neto87846742018-04-11 17:36:22 -04004023 auto *Inst =
4024 new SPIRVInstruction(GetSPIRVBinaryOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004025 SPIRVInstList.push_back(Inst);
4026 }
alan-bakerc9c55ae2019-12-02 16:01:27 -05004027 } else if (I.getOpcode() == Instruction::FNeg) {
4028 // The only unary operator.
4029 //
4030 // Ops[0] = Result Type ID
4031 // Ops[1] = Operand 0
4032 SPIRVOperandList ops;
4033
4034 ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
4035 auto *Inst = new SPIRVInstruction(spv::OpFNegate, nextID++, ops);
4036 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04004037 } else {
4038 I.print(errs());
4039 llvm_unreachable("Unsupported instruction???");
4040 }
4041 break;
4042 }
4043 case Instruction::GetElementPtr: {
4044 auto &GlobalConstArgSet = getGlobalConstArgSet();
4045
4046 //
4047 // Generate OpAccessChain.
4048 //
4049 GetElementPtrInst *GEP = cast<GetElementPtrInst>(&I);
4050
4051 //
4052 // Generate OpAccessChain.
4053 //
4054
4055 // Ops[0] = Result Type ID
4056 // Ops[1] = Base ID
4057 // Ops[2] ... Ops[n] = Indexes ID
4058 SPIRVOperandList Ops;
4059
alan-bakerb6b09dc2018-11-08 16:59:28 -05004060 PointerType *ResultType = cast<PointerType>(GEP->getType());
David Neto22f144c2017-06-12 14:26:21 -04004061 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate ||
4062 GlobalConstArgSet.count(GEP->getPointerOperand())) {
4063 // Use pointer type with private address space for global constant.
4064 Type *EleTy = I.getType()->getPointerElementType();
David Neto1a1a0582017-07-07 12:01:44 -04004065 ResultType = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
David Neto22f144c2017-06-12 14:26:21 -04004066 }
David Neto257c3892018-04-11 13:19:45 -04004067
4068 Ops << MkId(lookupType(ResultType));
David Neto22f144c2017-06-12 14:26:21 -04004069
David Neto862b7d82018-06-14 18:48:37 -04004070 // Generate the base pointer.
4071 Ops << MkId(VMap[GEP->getPointerOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04004072
David Neto862b7d82018-06-14 18:48:37 -04004073 // TODO(dneto): Simplify the following?
David Neto22f144c2017-06-12 14:26:21 -04004074
4075 //
4076 // Follows below rules for gep.
4077 //
David Neto862b7d82018-06-14 18:48:37 -04004078 // 1. If gep's first index is 0 generate OpAccessChain and ignore gep's
4079 // first index.
David Neto22f144c2017-06-12 14:26:21 -04004080 // 2. If gep's first index is not 0, generate OpPtrAccessChain and use gep's
4081 // first index.
4082 // 3. If gep's first index is not constant, generate OpPtrAccessChain and
4083 // use gep's first index.
4084 // 4. If it is not above case 1, 2 and 3, generate OpAccessChain and use
4085 // gep's first index.
4086 //
4087 spv::Op Opcode = spv::OpAccessChain;
4088 unsigned offset = 0;
4089 if (ConstantInt *CstInt = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
David Neto862b7d82018-06-14 18:48:37 -04004090 if (CstInt->getZExtValue() == 0) {
David Neto22f144c2017-06-12 14:26:21 -04004091 offset = 1;
David Neto862b7d82018-06-14 18:48:37 -04004092 } else if (CstInt->getZExtValue() != 0) {
David Neto22f144c2017-06-12 14:26:21 -04004093 Opcode = spv::OpPtrAccessChain;
David Neto22f144c2017-06-12 14:26:21 -04004094 }
David Neto862b7d82018-06-14 18:48:37 -04004095 } else {
David Neto22f144c2017-06-12 14:26:21 -04004096 Opcode = spv::OpPtrAccessChain;
David Neto1a1a0582017-07-07 12:01:44 -04004097 }
4098
4099 if (Opcode == spv::OpPtrAccessChain) {
David Neto1a1a0582017-07-07 12:01:44 -04004100 // Do we need to generate ArrayStride? Check against the GEP result type
4101 // rather than the pointer type of the base because when indexing into
4102 // an OpenCL program-scope constant, we'll swap out the LLVM base pointer
4103 // for something else in the SPIR-V.
4104 // E.g. see test/PointerAccessChain/pointer_index_is_constant_1.cl
alan-baker5b86ed72019-02-15 08:26:50 -05004105 auto address_space = ResultType->getAddressSpace();
4106 setVariablePointersCapabilities(address_space);
4107 switch (GetStorageClass(address_space)) {
Alan Bakerfcda9482018-10-02 17:09:59 -04004108 case spv::StorageClassStorageBuffer:
4109 case spv::StorageClassUniform:
David Neto1a1a0582017-07-07 12:01:44 -04004110 // Save the need to generate an ArrayStride decoration. But defer
4111 // generation until later, so we only make one decoration.
David Neto85082642018-03-24 06:55:20 -07004112 getTypesNeedingArrayStride().insert(ResultType);
Alan Bakerfcda9482018-10-02 17:09:59 -04004113 break;
4114 default:
4115 break;
David Neto1a1a0582017-07-07 12:01:44 -04004116 }
David Neto22f144c2017-06-12 14:26:21 -04004117 }
4118
4119 for (auto II = GEP->idx_begin() + offset; II != GEP->idx_end(); II++) {
David Neto257c3892018-04-11 13:19:45 -04004120 Ops << MkId(VMap[*II]);
David Neto22f144c2017-06-12 14:26:21 -04004121 }
4122
David Neto87846742018-04-11 17:36:22 -04004123 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004124 SPIRVInstList.push_back(Inst);
4125 break;
4126 }
4127 case Instruction::ExtractValue: {
4128 ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
4129 // Ops[0] = Result Type ID
4130 // Ops[1] = Composite ID
4131 // Ops[2] ... Ops[n] = Indexes (Literal Number)
4132 SPIRVOperandList Ops;
4133
David Neto257c3892018-04-11 13:19:45 -04004134 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004135
4136 uint32_t CompositeID = VMap[EVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04004137 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04004138
4139 for (auto &Index : EVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04004140 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04004141 }
4142
David Neto87846742018-04-11 17:36:22 -04004143 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004144 SPIRVInstList.push_back(Inst);
4145 break;
4146 }
4147 case Instruction::InsertValue: {
4148 InsertValueInst *IVI = cast<InsertValueInst>(&I);
4149 // Ops[0] = Result Type ID
4150 // Ops[1] = Object ID
4151 // Ops[2] = Composite ID
4152 // Ops[3] ... Ops[n] = Indexes (Literal Number)
4153 SPIRVOperandList Ops;
4154
4155 uint32_t ResTyID = lookupType(I.getType());
David Neto257c3892018-04-11 13:19:45 -04004156 Ops << MkId(ResTyID);
David Neto22f144c2017-06-12 14:26:21 -04004157
4158 uint32_t ObjectID = VMap[IVI->getInsertedValueOperand()];
David Neto257c3892018-04-11 13:19:45 -04004159 Ops << MkId(ObjectID);
David Neto22f144c2017-06-12 14:26:21 -04004160
4161 uint32_t CompositeID = VMap[IVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04004162 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04004163
4164 for (auto &Index : IVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04004165 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04004166 }
4167
David Neto87846742018-04-11 17:36:22 -04004168 auto *Inst = new SPIRVInstruction(spv::OpCompositeInsert, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004169 SPIRVInstList.push_back(Inst);
4170 break;
4171 }
4172 case Instruction::Select: {
4173 //
4174 // Generate OpSelect.
4175 //
4176
4177 // Ops[0] = Result Type ID
4178 // Ops[1] = Condition ID
4179 // Ops[2] = True Constant ID
4180 // Ops[3] = False Constant ID
4181 SPIRVOperandList Ops;
4182
4183 // Find SPIRV instruction for parameter type.
4184 auto Ty = I.getType();
4185 if (Ty->isPointerTy()) {
4186 auto PointeeTy = Ty->getPointerElementType();
4187 if (PointeeTy->isStructTy() &&
4188 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
4189 Ty = PointeeTy;
alan-baker5b86ed72019-02-15 08:26:50 -05004190 } else {
4191 // Selecting between pointers requires variable pointers.
4192 setVariablePointersCapabilities(Ty->getPointerAddressSpace());
4193 if (!hasVariablePointers() && !selectFromSameObject(&I)) {
4194 setVariablePointers(true);
4195 }
David Neto22f144c2017-06-12 14:26:21 -04004196 }
4197 }
4198
David Neto257c3892018-04-11 13:19:45 -04004199 Ops << MkId(lookupType(Ty)) << MkId(VMap[I.getOperand(0)])
4200 << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004201
David Neto87846742018-04-11 17:36:22 -04004202 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004203 SPIRVInstList.push_back(Inst);
4204 break;
4205 }
4206 case Instruction::ExtractElement: {
4207 // Handle <4 x i8> type manually.
4208 Type *CompositeTy = I.getOperand(0)->getType();
4209 if (is4xi8vec(CompositeTy)) {
4210 //
4211 // Generate OpShiftRightLogical and OpBitwiseAnd for extractelement with
4212 // <4 x i8>.
4213 //
4214
4215 //
4216 // Generate OpShiftRightLogical
4217 //
4218 // Ops[0] = Result Type ID
4219 // Ops[1] = Operand 0
4220 // Ops[2] = Operand 1
4221 //
4222 SPIRVOperandList Ops;
4223
David Neto257c3892018-04-11 13:19:45 -04004224 Ops << MkId(lookupType(CompositeTy));
David Neto22f144c2017-06-12 14:26:21 -04004225
4226 uint32_t Op0ID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04004227 Ops << MkId(Op0ID);
David Neto22f144c2017-06-12 14:26:21 -04004228
4229 uint32_t Op1ID = 0;
4230 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
4231 // Handle constant index.
4232 uint64_t Idx = CI->getZExtValue();
4233 Value *ShiftAmount =
4234 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
4235 Op1ID = VMap[ShiftAmount];
4236 } else {
4237 // Handle variable index.
4238 SPIRVOperandList TmpOps;
4239
David Neto257c3892018-04-11 13:19:45 -04004240 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
4241 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004242
4243 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04004244 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04004245
4246 Op1ID = nextID;
4247
David Neto87846742018-04-11 17:36:22 -04004248 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04004249 SPIRVInstList.push_back(TmpInst);
4250 }
David Neto257c3892018-04-11 13:19:45 -04004251 Ops << MkId(Op1ID);
David Neto22f144c2017-06-12 14:26:21 -04004252
4253 uint32_t ShiftID = nextID;
4254
David Neto87846742018-04-11 17:36:22 -04004255 auto *Inst =
4256 new SPIRVInstruction(spv::OpShiftRightLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004257 SPIRVInstList.push_back(Inst);
4258
4259 //
4260 // Generate OpBitwiseAnd
4261 //
4262 // Ops[0] = Result Type ID
4263 // Ops[1] = Operand 0
4264 // Ops[2] = Operand 1
4265 //
4266 Ops.clear();
4267
David Neto257c3892018-04-11 13:19:45 -04004268 Ops << MkId(lookupType(CompositeTy)) << MkId(ShiftID);
David Neto22f144c2017-06-12 14:26:21 -04004269
4270 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
David Neto257c3892018-04-11 13:19:45 -04004271 Ops << MkId(VMap[CstFF]);
David Neto22f144c2017-06-12 14:26:21 -04004272
David Neto9b2d6252017-09-06 15:47:37 -04004273 // Reset mapping for this value to the result of the bitwise and.
4274 VMap[&I] = nextID;
4275
David Neto87846742018-04-11 17:36:22 -04004276 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004277 SPIRVInstList.push_back(Inst);
4278 break;
4279 }
4280
4281 // Ops[0] = Result Type ID
4282 // Ops[1] = Composite ID
4283 // Ops[2] ... Ops[n] = Indexes (Literal Number)
4284 SPIRVOperandList Ops;
4285
David Neto257c3892018-04-11 13:19:45 -04004286 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004287
4288 spv::Op Opcode = spv::OpCompositeExtract;
4289 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
David Neto257c3892018-04-11 13:19:45 -04004290 Ops << MkNum(static_cast<uint32_t>(CI->getZExtValue()));
David Neto22f144c2017-06-12 14:26:21 -04004291 } else {
David Neto257c3892018-04-11 13:19:45 -04004292 Ops << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004293 Opcode = spv::OpVectorExtractDynamic;
4294 }
4295
David Neto87846742018-04-11 17:36:22 -04004296 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004297 SPIRVInstList.push_back(Inst);
4298 break;
4299 }
4300 case Instruction::InsertElement: {
4301 // Handle <4 x i8> type manually.
4302 Type *CompositeTy = I.getOperand(0)->getType();
4303 if (is4xi8vec(CompositeTy)) {
4304 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
4305 uint32_t CstFFID = VMap[CstFF];
4306
4307 uint32_t ShiftAmountID = 0;
4308 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
4309 // Handle constant index.
4310 uint64_t Idx = CI->getZExtValue();
4311 Value *ShiftAmount =
4312 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
4313 ShiftAmountID = VMap[ShiftAmount];
4314 } else {
4315 // Handle variable index.
4316 SPIRVOperandList TmpOps;
4317
David Neto257c3892018-04-11 13:19:45 -04004318 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
4319 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004320
4321 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04004322 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04004323
4324 ShiftAmountID = nextID;
4325
David Neto87846742018-04-11 17:36:22 -04004326 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04004327 SPIRVInstList.push_back(TmpInst);
4328 }
4329
4330 //
4331 // Generate mask operations.
4332 //
4333
4334 // ShiftLeft mask according to index of insertelement.
4335 SPIRVOperandList Ops;
4336
David Neto257c3892018-04-11 13:19:45 -04004337 const uint32_t ResTyID = lookupType(CompositeTy);
4338 Ops << MkId(ResTyID) << MkId(CstFFID) << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04004339
4340 uint32_t MaskID = nextID;
4341
David Neto87846742018-04-11 17:36:22 -04004342 auto *Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004343 SPIRVInstList.push_back(Inst);
4344
4345 // Inverse mask.
4346 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004347 Ops << MkId(ResTyID) << MkId(MaskID);
David Neto22f144c2017-06-12 14:26:21 -04004348
4349 uint32_t InvMaskID = nextID;
4350
David Neto87846742018-04-11 17:36:22 -04004351 Inst = new SPIRVInstruction(spv::OpNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004352 SPIRVInstList.push_back(Inst);
4353
4354 // Apply mask.
4355 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004356 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(0)]) << MkId(InvMaskID);
David Neto22f144c2017-06-12 14:26:21 -04004357
4358 uint32_t OrgValID = nextID;
4359
David Neto87846742018-04-11 17:36:22 -04004360 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004361 SPIRVInstList.push_back(Inst);
4362
4363 // Create correct value according to index of insertelement.
4364 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05004365 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(1)])
4366 << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04004367
4368 uint32_t InsertValID = nextID;
4369
David Neto87846742018-04-11 17:36:22 -04004370 Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004371 SPIRVInstList.push_back(Inst);
4372
4373 // Insert value to original value.
4374 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004375 Ops << MkId(ResTyID) << MkId(OrgValID) << MkId(InsertValID);
David Neto22f144c2017-06-12 14:26:21 -04004376
David Netoa394f392017-08-26 20:45:29 -04004377 VMap[&I] = nextID;
4378
David Neto87846742018-04-11 17:36:22 -04004379 Inst = new SPIRVInstruction(spv::OpBitwiseOr, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004380 SPIRVInstList.push_back(Inst);
4381
4382 break;
4383 }
4384
David Neto22f144c2017-06-12 14:26:21 -04004385 SPIRVOperandList Ops;
4386
James Priced26efea2018-06-09 23:28:32 +01004387 // Ops[0] = Result Type ID
4388 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004389
4390 spv::Op Opcode = spv::OpCompositeInsert;
4391 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
David Neto257c3892018-04-11 13:19:45 -04004392 const auto value = CI->getZExtValue();
4393 assert(value <= UINT32_MAX);
James Priced26efea2018-06-09 23:28:32 +01004394 // Ops[1] = Object ID
4395 // Ops[2] = Composite ID
4396 // Ops[3] ... Ops[n] = Indexes (Literal Number)
alan-bakerb6b09dc2018-11-08 16:59:28 -05004397 Ops << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(0)])
James Priced26efea2018-06-09 23:28:32 +01004398 << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004399 } else {
James Priced26efea2018-06-09 23:28:32 +01004400 // Ops[1] = Composite ID
4401 // Ops[2] = Object ID
4402 // Ops[3] ... Ops[n] = Indexes (Literal Number)
alan-bakerb6b09dc2018-11-08 16:59:28 -05004403 Ops << MkId(VMap[I.getOperand(0)]) << MkId(VMap[I.getOperand(1)])
James Priced26efea2018-06-09 23:28:32 +01004404 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004405 Opcode = spv::OpVectorInsertDynamic;
4406 }
4407
David Neto87846742018-04-11 17:36:22 -04004408 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004409 SPIRVInstList.push_back(Inst);
4410 break;
4411 }
4412 case Instruction::ShuffleVector: {
4413 // Ops[0] = Result Type ID
4414 // Ops[1] = Vector 1 ID
4415 // Ops[2] = Vector 2 ID
4416 // Ops[3] ... Ops[n] = Components (Literal Number)
4417 SPIRVOperandList Ops;
4418
David Neto257c3892018-04-11 13:19:45 -04004419 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
4420 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004421
alan-bakerc9666712020-04-01 16:31:21 -04004422 auto shuffle = cast<ShuffleVectorInst>(&I);
4423 SmallVector<int, 4> mask;
4424 shuffle->getShuffleMask(mask);
4425 for (auto i : mask) {
4426 if (i == UndefMaskElem) {
4427 if (clspv::Option::HackUndef())
4428 // Use 0 instead of undef.
David Neto257c3892018-04-11 13:19:45 -04004429 Ops << MkNum(0);
alan-bakerc9666712020-04-01 16:31:21 -04004430 else
4431 // Undef for shuffle in SPIR-V.
4432 Ops << MkNum(0xffffffff);
David Neto22f144c2017-06-12 14:26:21 -04004433 } else {
alan-bakerc9666712020-04-01 16:31:21 -04004434 Ops << MkNum(i);
David Neto22f144c2017-06-12 14:26:21 -04004435 }
4436 }
4437
David Neto87846742018-04-11 17:36:22 -04004438 auto *Inst = new SPIRVInstruction(spv::OpVectorShuffle, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004439 SPIRVInstList.push_back(Inst);
4440 break;
4441 }
4442 case Instruction::ICmp:
4443 case Instruction::FCmp: {
4444 CmpInst *CmpI = cast<CmpInst>(&I);
4445
David Netod4ca2e62017-07-06 18:47:35 -04004446 // Pointer equality is invalid.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004447 Type *ArgTy = CmpI->getOperand(0)->getType();
David Netod4ca2e62017-07-06 18:47:35 -04004448 if (isa<PointerType>(ArgTy)) {
4449 CmpI->print(errs());
alan-baker21574d32020-01-29 16:00:31 -05004450 std::string name = I.getParent()->getParent()->getName().str();
David Netod4ca2e62017-07-06 18:47:35 -04004451 errs()
4452 << "\nPointer equality test is not supported by SPIR-V for Vulkan, "
4453 << "in function " << name << "\n";
4454 llvm_unreachable("Pointer equality check is invalid");
4455 break;
4456 }
4457
David Neto257c3892018-04-11 13:19:45 -04004458 // Ops[0] = Result Type ID
4459 // Ops[1] = Operand 1 ID
4460 // Ops[2] = Operand 2 ID
4461 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04004462
David Neto257c3892018-04-11 13:19:45 -04004463 Ops << MkId(lookupType(CmpI->getType())) << MkId(VMap[CmpI->getOperand(0)])
4464 << MkId(VMap[CmpI->getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004465
4466 spv::Op Opcode = GetSPIRVCmpOpcode(CmpI);
David Neto87846742018-04-11 17:36:22 -04004467 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004468 SPIRVInstList.push_back(Inst);
4469 break;
4470 }
4471 case Instruction::Br: {
4472 // Branch instrucion is deferred because it needs label's ID. Record slot's
4473 // location on SPIRVInstructionList.
4474 DeferredInsts.push_back(
4475 std::make_tuple(&I, --SPIRVInstList.end(), 0 /* No id */));
4476 break;
4477 }
4478 case Instruction::Switch: {
4479 I.print(errs());
4480 llvm_unreachable("Unsupported instruction???");
4481 break;
4482 }
4483 case Instruction::IndirectBr: {
4484 I.print(errs());
4485 llvm_unreachable("Unsupported instruction???");
4486 break;
4487 }
4488 case Instruction::PHI: {
4489 // Branch instrucion is deferred because it needs label's ID. Record slot's
4490 // location on SPIRVInstructionList.
4491 DeferredInsts.push_back(
4492 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4493 break;
4494 }
4495 case Instruction::Alloca: {
4496 //
4497 // Generate OpVariable.
4498 //
4499 // Ops[0] : Result Type ID
4500 // Ops[1] : Storage Class
4501 SPIRVOperandList Ops;
4502
David Neto257c3892018-04-11 13:19:45 -04004503 Ops << MkId(lookupType(I.getType())) << MkNum(spv::StorageClassFunction);
David Neto22f144c2017-06-12 14:26:21 -04004504
David Neto87846742018-04-11 17:36:22 -04004505 auto *Inst = new SPIRVInstruction(spv::OpVariable, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004506 SPIRVInstList.push_back(Inst);
4507 break;
4508 }
4509 case Instruction::Load: {
4510 LoadInst *LD = cast<LoadInst>(&I);
4511 //
4512 // Generate OpLoad.
4513 //
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04004514
alan-baker5b86ed72019-02-15 08:26:50 -05004515 if (LD->getType()->isPointerTy()) {
4516 // Loading a pointer requires variable pointers.
4517 setVariablePointersCapabilities(LD->getType()->getPointerAddressSpace());
4518 }
David Neto22f144c2017-06-12 14:26:21 -04004519
David Neto0a2f98d2017-09-15 19:38:40 -04004520 uint32_t ResTyID = lookupType(LD->getType());
David Netoa60b00b2017-09-15 16:34:09 -04004521 uint32_t PointerID = VMap[LD->getPointerOperand()];
4522
4523 // This is a hack to work around what looks like a driver bug.
4524 // When we're loading from the special variable holding the WorkgroupSize
David Neto0a2f98d2017-09-15 19:38:40 -04004525 // builtin value, use an OpBitWiseAnd of the value's ID rather than
4526 // generating a load.
David Neto66cfe642018-03-24 06:13:56 -07004527 // TODO(dneto): Remove this awful hack once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -04004528 if (PointerID == WorkgroupSizeVarID) {
David Neto0a2f98d2017-09-15 19:38:40 -04004529 // Generate a bitwise-and of the original value with itself.
4530 // We should have been able to get away with just an OpCopyObject,
4531 // but we need something more complex to get past certain driver bugs.
4532 // This is ridiculous, but necessary.
4533 // TODO(dneto): Revisit this once drivers fix their bugs.
4534
4535 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004536 Ops << MkId(ResTyID) << MkId(WorkgroupSizeValueID)
4537 << MkId(WorkgroupSizeValueID);
David Neto0a2f98d2017-09-15 19:38:40 -04004538
David Neto87846742018-04-11 17:36:22 -04004539 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto0a2f98d2017-09-15 19:38:40 -04004540 SPIRVInstList.push_back(Inst);
David Netoa60b00b2017-09-15 16:34:09 -04004541 break;
4542 }
4543
4544 // This is the normal path. Generate a load.
4545
David Neto22f144c2017-06-12 14:26:21 -04004546 // Ops[0] = Result Type ID
4547 // Ops[1] = Pointer ID
4548 // Ops[2] ... Ops[n] = Optional Memory Access
4549 //
4550 // TODO: Do we need to implement Optional Memory Access???
David Neto0a2f98d2017-09-15 19:38:40 -04004551
David Neto22f144c2017-06-12 14:26:21 -04004552 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004553 Ops << MkId(ResTyID) << MkId(PointerID);
David Neto22f144c2017-06-12 14:26:21 -04004554
David Neto87846742018-04-11 17:36:22 -04004555 auto *Inst = new SPIRVInstruction(spv::OpLoad, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004556 SPIRVInstList.push_back(Inst);
4557 break;
4558 }
4559 case Instruction::Store: {
4560 StoreInst *ST = cast<StoreInst>(&I);
4561 //
4562 // Generate OpStore.
4563 //
4564
alan-baker5b86ed72019-02-15 08:26:50 -05004565 if (ST->getValueOperand()->getType()->isPointerTy()) {
4566 // Storing a pointer requires variable pointers.
4567 setVariablePointersCapabilities(
4568 ST->getValueOperand()->getType()->getPointerAddressSpace());
4569 }
4570
David Neto22f144c2017-06-12 14:26:21 -04004571 // Ops[0] = Pointer ID
4572 // Ops[1] = Object ID
4573 // Ops[2] ... Ops[n] = Optional Memory Access (later???)
4574 //
4575 // TODO: Do we need to implement Optional Memory Access???
David Neto257c3892018-04-11 13:19:45 -04004576 SPIRVOperandList Ops;
4577 Ops << MkId(VMap[ST->getPointerOperand()])
4578 << MkId(VMap[ST->getValueOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04004579
David Neto87846742018-04-11 17:36:22 -04004580 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004581 SPIRVInstList.push_back(Inst);
4582 break;
4583 }
4584 case Instruction::AtomicCmpXchg: {
4585 I.print(errs());
4586 llvm_unreachable("Unsupported instruction???");
4587 break;
4588 }
4589 case Instruction::AtomicRMW: {
Neil Henning39672102017-09-29 14:33:13 +01004590 AtomicRMWInst *AtomicRMW = dyn_cast<AtomicRMWInst>(&I);
4591
4592 spv::Op opcode;
4593
4594 switch (AtomicRMW->getOperation()) {
4595 default:
4596 I.print(errs());
4597 llvm_unreachable("Unsupported instruction???");
4598 case llvm::AtomicRMWInst::Add:
4599 opcode = spv::OpAtomicIAdd;
4600 break;
4601 case llvm::AtomicRMWInst::Sub:
4602 opcode = spv::OpAtomicISub;
4603 break;
4604 case llvm::AtomicRMWInst::Xchg:
4605 opcode = spv::OpAtomicExchange;
4606 break;
4607 case llvm::AtomicRMWInst::Min:
4608 opcode = spv::OpAtomicSMin;
4609 break;
4610 case llvm::AtomicRMWInst::Max:
4611 opcode = spv::OpAtomicSMax;
4612 break;
4613 case llvm::AtomicRMWInst::UMin:
4614 opcode = spv::OpAtomicUMin;
4615 break;
4616 case llvm::AtomicRMWInst::UMax:
4617 opcode = spv::OpAtomicUMax;
4618 break;
4619 case llvm::AtomicRMWInst::And:
4620 opcode = spv::OpAtomicAnd;
4621 break;
4622 case llvm::AtomicRMWInst::Or:
4623 opcode = spv::OpAtomicOr;
4624 break;
4625 case llvm::AtomicRMWInst::Xor:
4626 opcode = spv::OpAtomicXor;
4627 break;
4628 }
4629
4630 //
4631 // Generate OpAtomic*.
4632 //
4633 SPIRVOperandList Ops;
4634
David Neto257c3892018-04-11 13:19:45 -04004635 Ops << MkId(lookupType(I.getType()))
4636 << MkId(VMap[AtomicRMW->getPointerOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004637
4638 auto IntTy = Type::getInt32Ty(I.getContext());
Neil Henning39672102017-09-29 14:33:13 +01004639 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
David Neto257c3892018-04-11 13:19:45 -04004640 Ops << MkId(VMap[ConstantScopeDevice]);
Neil Henning39672102017-09-29 14:33:13 +01004641
4642 const auto ConstantMemorySemantics = ConstantInt::get(
4643 IntTy, spv::MemorySemanticsUniformMemoryMask |
4644 spv::MemorySemanticsSequentiallyConsistentMask);
David Neto257c3892018-04-11 13:19:45 -04004645 Ops << MkId(VMap[ConstantMemorySemantics]);
Neil Henning39672102017-09-29 14:33:13 +01004646
David Neto257c3892018-04-11 13:19:45 -04004647 Ops << MkId(VMap[AtomicRMW->getValOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004648
4649 VMap[&I] = nextID;
4650
David Neto87846742018-04-11 17:36:22 -04004651 auto *Inst = new SPIRVInstruction(opcode, nextID++, Ops);
Neil Henning39672102017-09-29 14:33:13 +01004652 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04004653 break;
4654 }
4655 case Instruction::Fence: {
4656 I.print(errs());
4657 llvm_unreachable("Unsupported instruction???");
4658 break;
4659 }
4660 case Instruction::Call: {
4661 CallInst *Call = dyn_cast<CallInst>(&I);
4662 Function *Callee = Call->getCalledFunction();
4663
Alan Baker202c8c72018-08-13 13:47:44 -04004664 if (Callee->getName().startswith(clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04004665 if (ResourceVarDeferredLoadCalls.count(Call) && Call->hasNUsesOrMore(1)) {
4666 // Generate an OpLoad
4667 SPIRVOperandList Ops;
4668 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004669
David Neto862b7d82018-06-14 18:48:37 -04004670 Ops << MkId(lookupType(Call->getType()->getPointerElementType()))
4671 << MkId(ResourceVarDeferredLoadCalls[Call]);
4672
4673 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
4674 SPIRVInstList.push_back(Inst);
4675 VMap[Call] = load_id;
4676 break;
4677
4678 } else {
4679 // This maps to an OpVariable we've already generated.
4680 // No code is generated for the call.
4681 }
4682 break;
alan-bakerb6b09dc2018-11-08 16:59:28 -05004683 } else if (Callee->getName().startswith(
4684 clspv::WorkgroupAccessorFunction())) {
Alan Baker202c8c72018-08-13 13:47:44 -04004685 // Don't codegen an instruction here, but instead map this call directly
4686 // to the workgroup variable id.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004687 int spec_id = static_cast<int>(
4688 cast<ConstantInt>(Call->getOperand(0))->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04004689 const auto &info = LocalSpecIdInfoMap[spec_id];
4690 VMap[Call] = info.variable_id;
4691 break;
David Neto862b7d82018-06-14 18:48:37 -04004692 }
4693
4694 // Sampler initializers become a load of the corresponding sampler.
4695
Kévin Petitdf71de32019-04-09 14:09:50 +01004696 if (Callee->getName().equals(clspv::LiteralSamplerFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04004697 // Map this to a load from the variable.
alan-baker09cb9802019-12-10 13:16:27 -05004698 const auto third_param = static_cast<unsigned>(
4699 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue());
4700 auto sampler_value = third_param;
4701 if (clspv::Option::UseSamplerMap()) {
4702 sampler_value = getSamplerMap()[third_param].first;
4703 }
David Neto862b7d82018-06-14 18:48:37 -04004704
4705 // Generate an OpLoad
David Neto22f144c2017-06-12 14:26:21 -04004706 SPIRVOperandList Ops;
David Neto862b7d82018-06-14 18:48:37 -04004707 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004708
David Neto257c3892018-04-11 13:19:45 -04004709 Ops << MkId(lookupType(SamplerTy->getPointerElementType()))
alan-baker09cb9802019-12-10 13:16:27 -05004710 << MkId(SamplerLiteralToIDMap[sampler_value]);
David Neto22f144c2017-06-12 14:26:21 -04004711
David Neto862b7d82018-06-14 18:48:37 -04004712 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004713 SPIRVInstList.push_back(Inst);
David Neto862b7d82018-06-14 18:48:37 -04004714 VMap[Call] = load_id;
David Neto22f144c2017-06-12 14:26:21 -04004715 break;
4716 }
4717
Kévin Petit349c9502019-03-28 17:24:14 +00004718 // Handle SPIR-V intrinsics
Kévin Petit9b340262019-06-19 18:31:11 +01004719 spv::Op opcode = StringSwitch<spv::Op>(Callee->getName())
4720 .Case("spirv.atomic_xor", spv::OpAtomicXor)
4721 .Default(spv::OpNop);
David Neto22f144c2017-06-12 14:26:21 -04004722
Kévin Petit617a76d2019-04-04 13:54:16 +01004723 // If the switch above didn't have an entry maybe the intrinsic
4724 // is using the name mangling logic.
4725 bool usesMangler = false;
4726 if (opcode == spv::OpNop) {
4727 if (Callee->getName().startswith(clspv::SPIRVOpIntrinsicFunction())) {
4728 auto OpCst = cast<ConstantInt>(Call->getOperand(0));
4729 opcode = static_cast<spv::Op>(OpCst->getZExtValue());
4730 usesMangler = true;
4731 }
4732 }
4733
Kévin Petit349c9502019-03-28 17:24:14 +00004734 if (opcode != spv::OpNop) {
4735
David Neto22f144c2017-06-12 14:26:21 -04004736 SPIRVOperandList Ops;
4737
Kévin Petit349c9502019-03-28 17:24:14 +00004738 if (!I.getType()->isVoidTy()) {
4739 Ops << MkId(lookupType(I.getType()));
4740 }
David Neto22f144c2017-06-12 14:26:21 -04004741
Kévin Petit617a76d2019-04-04 13:54:16 +01004742 unsigned firstOperand = usesMangler ? 1 : 0;
4743 for (unsigned i = firstOperand; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004744 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004745 }
4746
Kévin Petit349c9502019-03-28 17:24:14 +00004747 if (!I.getType()->isVoidTy()) {
4748 VMap[&I] = nextID;
Kévin Petit8a560882019-03-21 15:24:34 +00004749 }
4750
Kévin Petit349c9502019-03-28 17:24:14 +00004751 SPIRVInstruction *Inst;
4752 if (!I.getType()->isVoidTy()) {
4753 Inst = new SPIRVInstruction(opcode, nextID++, Ops);
4754 } else {
4755 Inst = new SPIRVInstruction(opcode, Ops);
4756 }
Kévin Petit8a560882019-03-21 15:24:34 +00004757 SPIRVInstList.push_back(Inst);
4758 break;
4759 }
4760
David Neto22f144c2017-06-12 14:26:21 -04004761 // spirv.copy_memory.* intrinsics become OpMemoryMemory's.
4762 if (Callee->getName().startswith("spirv.copy_memory")) {
4763 //
4764 // Generate OpCopyMemory.
4765 //
4766
4767 // Ops[0] = Dst ID
4768 // Ops[1] = Src ID
4769 // Ops[2] = Memory Access
4770 // Ops[3] = Alignment
4771
4772 auto IsVolatile =
4773 dyn_cast<ConstantInt>(Call->getArgOperand(3))->getZExtValue() != 0;
4774
4775 auto VolatileMemoryAccess = (IsVolatile) ? spv::MemoryAccessVolatileMask
4776 : spv::MemoryAccessMaskNone;
4777
4778 auto MemoryAccess = VolatileMemoryAccess | spv::MemoryAccessAlignedMask;
4779
4780 auto Alignment =
4781 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4782
David Neto257c3892018-04-11 13:19:45 -04004783 SPIRVOperandList Ops;
4784 Ops << MkId(VMap[Call->getArgOperand(0)])
4785 << MkId(VMap[Call->getArgOperand(1)]) << MkNum(MemoryAccess)
4786 << MkNum(static_cast<uint32_t>(Alignment));
David Neto22f144c2017-06-12 14:26:21 -04004787
David Neto87846742018-04-11 17:36:22 -04004788 auto *Inst = new SPIRVInstruction(spv::OpCopyMemory, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004789
4790 SPIRVInstList.push_back(Inst);
4791
4792 break;
4793 }
4794
SJW2c317da2020-03-23 07:39:13 -05004795 // read_image is converted to OpSampledImage and OpImageSampleExplicitLod.
4796 // Additionally, OpTypeSampledImage is generated.
SJW173c7e92020-03-16 08:44:47 -05004797 if (IsSampledImageRead(Callee)) {
David Neto22f144c2017-06-12 14:26:21 -04004798 //
4799 // Generate OpSampledImage.
4800 //
4801 // Ops[0] = Result Type ID
4802 // Ops[1] = Image ID
4803 // Ops[2] = Sampler ID
4804 //
4805 SPIRVOperandList Ops;
4806
4807 Value *Image = Call->getArgOperand(0);
4808 Value *Sampler = Call->getArgOperand(1);
4809 Value *Coordinate = Call->getArgOperand(2);
4810
4811 TypeMapType &OpImageTypeMap = getImageTypeMap();
4812 Type *ImageTy = Image->getType()->getPointerElementType();
4813 uint32_t ImageTyID = OpImageTypeMap[ImageTy];
David Neto22f144c2017-06-12 14:26:21 -04004814 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004815 uint32_t SamplerID = VMap[Sampler];
David Neto257c3892018-04-11 13:19:45 -04004816
4817 Ops << MkId(ImageTyID) << MkId(ImageID) << MkId(SamplerID);
David Neto22f144c2017-06-12 14:26:21 -04004818
4819 uint32_t SampledImageID = nextID;
4820
David Neto87846742018-04-11 17:36:22 -04004821 auto *Inst = new SPIRVInstruction(spv::OpSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004822 SPIRVInstList.push_back(Inst);
4823
4824 //
4825 // Generate OpImageSampleExplicitLod.
4826 //
4827 // Ops[0] = Result Type ID
4828 // Ops[1] = Sampled Image ID
4829 // Ops[2] = Coordinate ID
4830 // Ops[3] = Image Operands Type ID
4831 // Ops[4] ... Ops[n] = Operands ID
4832 //
4833 Ops.clear();
4834
alan-bakerf67468c2019-11-25 15:51:49 -05004835 const bool is_int_image = IsIntImageType(Image->getType());
4836 uint32_t result_type = 0;
4837 if (is_int_image) {
4838 result_type = v4int32ID;
4839 } else {
4840 result_type = lookupType(Call->getType());
4841 }
4842
4843 Ops << MkId(result_type) << MkId(SampledImageID) << MkId(VMap[Coordinate])
4844 << MkNum(spv::ImageOperandsLodMask);
David Neto22f144c2017-06-12 14:26:21 -04004845
4846 Constant *CstFP0 = ConstantFP::get(Context, APFloat(0.0f));
David Neto257c3892018-04-11 13:19:45 -04004847 Ops << MkId(VMap[CstFP0]);
David Neto22f144c2017-06-12 14:26:21 -04004848
alan-bakerf67468c2019-11-25 15:51:49 -05004849 uint32_t final_id = nextID++;
4850 VMap[&I] = final_id;
David Neto22f144c2017-06-12 14:26:21 -04004851
alan-bakerf67468c2019-11-25 15:51:49 -05004852 uint32_t image_id = final_id;
4853 if (is_int_image) {
4854 // Int image requires a bitcast from v4int to v4uint.
4855 image_id = nextID++;
4856 }
4857
4858 Inst = new SPIRVInstruction(spv::OpImageSampleExplicitLod, image_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004859 SPIRVInstList.push_back(Inst);
alan-bakerf67468c2019-11-25 15:51:49 -05004860
4861 if (is_int_image) {
4862 // Generate the bitcast.
4863 Ops.clear();
4864 Ops << MkId(lookupType(Call->getType())) << MkId(image_id);
4865 Inst = new SPIRVInstruction(spv::OpBitcast, final_id, Ops);
4866 SPIRVInstList.push_back(Inst);
4867 }
David Neto22f144c2017-06-12 14:26:21 -04004868 break;
4869 }
4870
alan-baker75090e42020-02-20 11:21:04 -05004871 // read_image (without a sampler) is mapped to OpImageFetch.
SJW173c7e92020-03-16 08:44:47 -05004872 if (IsUnsampledImageRead(Callee)) {
alan-baker75090e42020-02-20 11:21:04 -05004873 Value *Image = Call->getArgOperand(0);
4874 Value *Coordinate = Call->getArgOperand(1);
4875
4876 //
4877 // Generate OpImageFetch
4878 //
4879 // Ops[0] = Result Type ID
4880 // Ops[1] = Image ID
4881 // Ops[2] = Coordinate ID
4882 // Ops[3] = Lod
4883 // Ops[4] = 0
4884 //
4885 SPIRVOperandList Ops;
4886
4887 const bool is_int_image = IsIntImageType(Image->getType());
4888 uint32_t result_type = 0;
4889 if (is_int_image) {
4890 result_type = v4int32ID;
4891 } else {
4892 result_type = lookupType(Call->getType());
4893 }
4894
4895 Ops << MkId(result_type) << MkId(VMap[Image]) << MkId(VMap[Coordinate])
4896 << MkNum(spv::ImageOperandsLodMask);
4897
4898 Constant *CstInt0 = ConstantInt::get(Context, APInt(32, 0));
4899 Ops << MkId(VMap[CstInt0]);
4900
4901 uint32_t final_id = nextID++;
4902 VMap[&I] = final_id;
4903
4904 uint32_t image_id = final_id;
4905 if (is_int_image) {
4906 // Int image requires a bitcast from v4int to v4uint.
4907 image_id = nextID++;
4908 }
4909
4910 auto *Inst = new SPIRVInstruction(spv::OpImageFetch, image_id, Ops);
4911 SPIRVInstList.push_back(Inst);
4912
4913 if (is_int_image) {
4914 // Generate the bitcast.
4915 Ops.clear();
4916 Ops << MkId(lookupType(Call->getType())) << MkId(image_id);
4917 Inst = new SPIRVInstruction(spv::OpBitcast, final_id, Ops);
4918 SPIRVInstList.push_back(Inst);
4919 }
4920 break;
4921 }
4922
alan-bakerf67468c2019-11-25 15:51:49 -05004923 // write_image is mapped to OpImageWrite.
SJW173c7e92020-03-16 08:44:47 -05004924 if (IsImageWrite(Callee)) {
David Neto22f144c2017-06-12 14:26:21 -04004925 //
4926 // Generate OpImageWrite.
4927 //
4928 // Ops[0] = Image ID
4929 // Ops[1] = Coordinate ID
4930 // Ops[2] = Texel ID
4931 // Ops[3] = (Optional) Image Operands Type (Literal Number)
4932 // Ops[4] ... Ops[n] = (Optional) Operands ID
4933 //
4934 SPIRVOperandList Ops;
4935
4936 Value *Image = Call->getArgOperand(0);
4937 Value *Coordinate = Call->getArgOperand(1);
4938 Value *Texel = Call->getArgOperand(2);
4939
4940 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004941 uint32_t CoordinateID = VMap[Coordinate];
David Neto22f144c2017-06-12 14:26:21 -04004942 uint32_t TexelID = VMap[Texel];
alan-bakerf67468c2019-11-25 15:51:49 -05004943
4944 const bool is_int_image = IsIntImageType(Image->getType());
4945 if (is_int_image) {
4946 // Generate a bitcast to v4int and use it as the texel value.
4947 uint32_t castID = nextID++;
4948 Ops << MkId(v4int32ID) << MkId(TexelID);
4949 auto cast = new SPIRVInstruction(spv::OpBitcast, castID, Ops);
4950 SPIRVInstList.push_back(cast);
4951 Ops.clear();
4952 TexelID = castID;
4953 }
David Neto257c3892018-04-11 13:19:45 -04004954 Ops << MkId(ImageID) << MkId(CoordinateID) << MkId(TexelID);
David Neto22f144c2017-06-12 14:26:21 -04004955
David Neto87846742018-04-11 17:36:22 -04004956 auto *Inst = new SPIRVInstruction(spv::OpImageWrite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004957 SPIRVInstList.push_back(Inst);
4958 break;
4959 }
4960
alan-bakerce179f12019-12-06 19:02:22 -05004961 // get_image_* is mapped to OpImageQuerySize or OpImageQuerySizeLod
SJW173c7e92020-03-16 08:44:47 -05004962 if (IsImageQuery(Callee)) {
David Neto5c22a252018-03-15 16:07:41 -04004963 //
alan-bakerce179f12019-12-06 19:02:22 -05004964 // Generate OpImageQuerySize[Lod]
David Neto5c22a252018-03-15 16:07:41 -04004965 //
4966 // Ops[0] = Image ID
4967 //
alan-bakerce179f12019-12-06 19:02:22 -05004968 // Result type has components equal to the dimensionality of the image,
4969 // plus 1 if the image is arrayed.
4970 //
alan-bakerf906d2b2019-12-10 11:26:23 -05004971 // %sizes = OpImageQuerySize[Lod] %uint[2|3|4] %im [%uint_0]
David Neto5c22a252018-03-15 16:07:41 -04004972 SPIRVOperandList Ops;
4973
4974 // Implement:
alan-bakerce179f12019-12-06 19:02:22 -05004975 // %sizes = OpImageQuerySize[Lod] %uint[2|3|4] %im [%uint_0]
4976 uint32_t SizesTypeID = 0;
4977
David Neto5c22a252018-03-15 16:07:41 -04004978 Value *Image = Call->getArgOperand(0);
alan-bakerce179f12019-12-06 19:02:22 -05004979 const uint32_t dim = ImageDimensionality(Image->getType());
alan-baker7150a1d2020-02-25 08:31:06 -05004980 const uint32_t components =
4981 dim + (IsArrayImageType(Image->getType()) ? 1 : 0);
alan-bakerce179f12019-12-06 19:02:22 -05004982 if (components == 1) {
alan-bakerce179f12019-12-06 19:02:22 -05004983 SizesTypeID = TypeMap[Type::getInt32Ty(Context)];
4984 } else {
alan-baker7150a1d2020-02-25 08:31:06 -05004985 SizesTypeID =
4986 TypeMap[VectorType::get(Type::getInt32Ty(Context), components)];
alan-bakerce179f12019-12-06 19:02:22 -05004987 }
David Neto5c22a252018-03-15 16:07:41 -04004988 uint32_t ImageID = VMap[Image];
David Neto257c3892018-04-11 13:19:45 -04004989 Ops << MkId(SizesTypeID) << MkId(ImageID);
alan-bakerce179f12019-12-06 19:02:22 -05004990 spv::Op query_opcode = spv::OpImageQuerySize;
SJW173c7e92020-03-16 08:44:47 -05004991 if (IsSampledImageType(Image->getType())) {
alan-bakerce179f12019-12-06 19:02:22 -05004992 query_opcode = spv::OpImageQuerySizeLod;
4993 // Need explicit 0 for Lod operand.
4994 Constant *CstInt0 = ConstantInt::get(Context, APInt(32, 0));
4995 Ops << MkId(VMap[CstInt0]);
4996 }
David Neto5c22a252018-03-15 16:07:41 -04004997
4998 uint32_t SizesID = nextID++;
alan-bakerce179f12019-12-06 19:02:22 -05004999 auto *QueryInst = new SPIRVInstruction(query_opcode, SizesID, Ops);
David Neto5c22a252018-03-15 16:07:41 -04005000 SPIRVInstList.push_back(QueryInst);
5001
alan-bakerce179f12019-12-06 19:02:22 -05005002 // May require an extra instruction to create the appropriate result of
5003 // the builtin function.
SJW173c7e92020-03-16 08:44:47 -05005004 if (IsGetImageDim(Callee)) {
alan-bakerce179f12019-12-06 19:02:22 -05005005 if (dim == 3) {
5006 // get_image_dim returns an int4 for 3D images.
5007 //
5008 // Reset value map entry since we generated an intermediate
5009 // instruction.
5010 VMap[&I] = nextID;
David Neto5c22a252018-03-15 16:07:41 -04005011
alan-bakerce179f12019-12-06 19:02:22 -05005012 // Implement:
5013 // %result = OpCompositeConstruct %uint4 %sizes %uint_0
5014 Ops.clear();
5015 Ops << MkId(lookupType(VectorType::get(Type::getInt32Ty(Context), 4)))
5016 << MkId(SizesID);
David Neto5c22a252018-03-15 16:07:41 -04005017
alan-bakerce179f12019-12-06 19:02:22 -05005018 Constant *CstInt0 = ConstantInt::get(Context, APInt(32, 0));
5019 Ops << MkId(VMap[CstInt0]);
David Neto5c22a252018-03-15 16:07:41 -04005020
alan-bakerce179f12019-12-06 19:02:22 -05005021 auto *Inst =
5022 new SPIRVInstruction(spv::OpCompositeConstruct, nextID++, Ops);
5023 SPIRVInstList.push_back(Inst);
5024 } else if (dim != components) {
5025 // get_image_dim return an int2 regardless of the arrayedness of the
5026 // image. If the image is arrayed an element must be dropped from the
5027 // query result.
5028 //
5029 // Reset value map entry since we generated an intermediate
5030 // instruction.
5031 VMap[&I] = nextID;
5032
5033 // Implement:
5034 // %result = OpVectorShuffle %uint2 %sizes %sizes 0 1
5035 Ops.clear();
5036 Ops << MkId(lookupType(VectorType::get(Type::getInt32Ty(Context), 2)))
5037 << MkId(SizesID) << MkId(SizesID) << MkNum(0) << MkNum(1);
5038
5039 auto *Inst =
5040 new SPIRVInstruction(spv::OpVectorShuffle, nextID++, Ops);
5041 SPIRVInstList.push_back(Inst);
5042 }
5043 } else if (components > 1) {
5044 // Reset value map entry since we generated an intermediate instruction.
5045 VMap[&I] = nextID;
5046
5047 // Implement:
5048 // %result = OpCompositeExtract %uint %sizes <component number>
5049 Ops.clear();
5050 Ops << MkId(TypeMap[I.getType()]) << MkId(SizesID);
5051
5052 uint32_t component = 0;
5053 if (IsGetImageHeight(Callee))
5054 component = 1;
5055 else if (IsGetImageDepth(Callee))
5056 component = 2;
5057 Ops << MkNum(component);
5058
5059 auto *Inst =
5060 new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
5061 SPIRVInstList.push_back(Inst);
5062 }
David Neto5c22a252018-03-15 16:07:41 -04005063 break;
5064 }
5065
David Neto22f144c2017-06-12 14:26:21 -04005066 // Call instrucion is deferred because it needs function's ID. Record
5067 // slot's location on SPIRVInstructionList.
5068 DeferredInsts.push_back(
5069 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
5070
David Neto3fbb4072017-10-16 11:28:14 -04005071 // Check whether the implementation of this call uses an extended
5072 // instruction plus one more value-producing instruction. If so, then
5073 // reserve the id for the extra value-producing slot.
5074 glsl::ExtInst EInst = getIndirectExtInstEnum(Callee->getName());
5075 if (EInst != kGlslExtInstBad) {
5076 // Reserve a spot for the extra value.
David Neto4d02a532017-09-17 12:57:44 -04005077 // Increase nextID.
David Neto22f144c2017-06-12 14:26:21 -04005078 VMap[&I] = nextID;
5079 nextID++;
5080 }
5081 break;
5082 }
5083 case Instruction::Ret: {
5084 unsigned NumOps = I.getNumOperands();
5085 if (NumOps == 0) {
5086 //
5087 // Generate OpReturn.
5088 //
David Netoef5ba2b2019-12-20 08:35:54 -05005089 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpReturn));
David Neto22f144c2017-06-12 14:26:21 -04005090 } else {
5091 //
5092 // Generate OpReturnValue.
5093 //
5094
5095 // Ops[0] = Return Value ID
5096 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04005097
5098 Ops << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04005099
David Neto87846742018-04-11 17:36:22 -04005100 auto *Inst = new SPIRVInstruction(spv::OpReturnValue, Ops);
David Neto22f144c2017-06-12 14:26:21 -04005101 SPIRVInstList.push_back(Inst);
5102 break;
5103 }
5104 break;
5105 }
5106 }
5107}
5108
5109void SPIRVProducerPass::GenerateFuncEpilogue() {
SJW69939d52020-04-16 07:29:07 -05005110 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kFunctions);
David Neto22f144c2017-06-12 14:26:21 -04005111
5112 //
5113 // Generate OpFunctionEnd
5114 //
5115
David Netoef5ba2b2019-12-20 08:35:54 -05005116 auto *Inst = new SPIRVInstruction(spv::OpFunctionEnd);
David Neto22f144c2017-06-12 14:26:21 -04005117 SPIRVInstList.push_back(Inst);
5118}
5119
5120bool SPIRVProducerPass::is4xi8vec(Type *Ty) const {
alan-bakerb39c8262019-03-08 14:03:37 -05005121 // Don't specialize <4 x i8> if i8 is generally supported.
5122 if (clspv::Option::Int8Support())
5123 return false;
5124
David Neto22f144c2017-06-12 14:26:21 -04005125 LLVMContext &Context = Ty->getContext();
James Pricecf53df42020-04-20 14:41:24 -04005126 if (auto VecTy = dyn_cast<VectorType>(Ty)) {
5127 if (VecTy->getElementType() == Type::getInt8Ty(Context) &&
5128 VecTy->getNumElements() == 4) {
David Neto22f144c2017-06-12 14:26:21 -04005129 return true;
5130 }
5131 }
5132
5133 return false;
5134}
5135
5136void SPIRVProducerPass::HandleDeferredInstruction() {
SJW69939d52020-04-16 07:29:07 -05005137 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kFunctions);
David Neto22f144c2017-06-12 14:26:21 -04005138 ValueMapType &VMap = getValueMap();
5139 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
5140
5141 for (auto DeferredInst = DeferredInsts.rbegin();
5142 DeferredInst != DeferredInsts.rend(); ++DeferredInst) {
5143 Value *Inst = std::get<0>(*DeferredInst);
5144 SPIRVInstructionList::iterator InsertPoint = ++std::get<1>(*DeferredInst);
5145 if (InsertPoint != SPIRVInstList.end()) {
5146 while ((*InsertPoint)->getOpcode() == spv::OpPhi) {
5147 ++InsertPoint;
5148 }
5149 }
5150
5151 if (BranchInst *Br = dyn_cast<BranchInst>(Inst)) {
alan-baker06cad652019-12-03 17:56:47 -05005152 // Check whether this branch needs to be preceeded by merge instruction.
David Neto22f144c2017-06-12 14:26:21 -04005153 BasicBlock *BrBB = Br->getParent();
alan-baker06cad652019-12-03 17:56:47 -05005154 if (ContinueBlocks.count(BrBB)) {
David Neto22f144c2017-06-12 14:26:21 -04005155 //
5156 // Generate OpLoopMerge.
5157 //
5158 // Ops[0] = Merge Block ID
5159 // Ops[1] = Continue Target ID
5160 // Ops[2] = Selection Control
5161 SPIRVOperandList Ops;
5162
alan-baker06cad652019-12-03 17:56:47 -05005163 auto MergeBB = MergeBlocks[BrBB];
5164 auto ContinueBB = ContinueBlocks[BrBB];
David Neto22f144c2017-06-12 14:26:21 -04005165 uint32_t MergeBBID = VMap[MergeBB];
David Neto22f144c2017-06-12 14:26:21 -04005166 uint32_t ContinueBBID = VMap[ContinueBB];
David Neto257c3892018-04-11 13:19:45 -04005167 Ops << MkId(MergeBBID) << MkId(ContinueBBID)
alan-baker06cad652019-12-03 17:56:47 -05005168 << MkNum(spv::LoopControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04005169
David Neto87846742018-04-11 17:36:22 -04005170 auto *MergeInst = new SPIRVInstruction(spv::OpLoopMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04005171 SPIRVInstList.insert(InsertPoint, MergeInst);
alan-baker06cad652019-12-03 17:56:47 -05005172 } else if (MergeBlocks.count(BrBB)) {
5173 //
5174 // Generate OpSelectionMerge.
5175 //
5176 // Ops[0] = Merge Block ID
5177 // Ops[1] = Selection Control
5178 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04005179
alan-baker06cad652019-12-03 17:56:47 -05005180 auto MergeBB = MergeBlocks[BrBB];
5181 uint32_t MergeBBID = VMap[MergeBB];
5182 Ops << MkId(MergeBBID) << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04005183
alan-baker06cad652019-12-03 17:56:47 -05005184 auto *MergeInst = new SPIRVInstruction(spv::OpSelectionMerge, Ops);
5185 SPIRVInstList.insert(InsertPoint, MergeInst);
David Neto22f144c2017-06-12 14:26:21 -04005186 }
5187
5188 if (Br->isConditional()) {
5189 //
5190 // Generate OpBranchConditional.
5191 //
5192 // Ops[0] = Condition ID
5193 // Ops[1] = True Label ID
5194 // Ops[2] = False Label ID
5195 // Ops[3] ... Ops[n] = Branch weights (Literal Number)
5196 SPIRVOperandList Ops;
5197
5198 uint32_t CondID = VMap[Br->getCondition()];
David Neto22f144c2017-06-12 14:26:21 -04005199 uint32_t TrueBBID = VMap[Br->getSuccessor(0)];
David Neto22f144c2017-06-12 14:26:21 -04005200 uint32_t FalseBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04005201
5202 Ops << MkId(CondID) << MkId(TrueBBID) << MkId(FalseBBID);
David Neto22f144c2017-06-12 14:26:21 -04005203
David Neto87846742018-04-11 17:36:22 -04005204 auto *BrInst = new SPIRVInstruction(spv::OpBranchConditional, Ops);
David Neto22f144c2017-06-12 14:26:21 -04005205 SPIRVInstList.insert(InsertPoint, BrInst);
5206 } else {
5207 //
5208 // Generate OpBranch.
5209 //
5210 // Ops[0] = Target Label ID
5211 SPIRVOperandList Ops;
5212
5213 uint32_t TargetID = VMap[Br->getSuccessor(0)];
David Neto257c3892018-04-11 13:19:45 -04005214 Ops << MkId(TargetID);
David Neto22f144c2017-06-12 14:26:21 -04005215
David Neto87846742018-04-11 17:36:22 -04005216 SPIRVInstList.insert(InsertPoint,
5217 new SPIRVInstruction(spv::OpBranch, Ops));
David Neto22f144c2017-06-12 14:26:21 -04005218 }
5219 } else if (PHINode *PHI = dyn_cast<PHINode>(Inst)) {
alan-baker5ed87542020-03-23 11:05:22 -04005220 if (PHI->getType()->isPointerTy() && !IsSamplerType(PHI->getType()) &&
5221 !IsImageType(PHI->getType())) {
alan-baker5b86ed72019-02-15 08:26:50 -05005222 // OpPhi on pointers requires variable pointers.
5223 setVariablePointersCapabilities(
5224 PHI->getType()->getPointerAddressSpace());
5225 if (!hasVariablePointers() && !selectFromSameObject(PHI)) {
5226 setVariablePointers(true);
5227 }
5228 }
5229
David Neto22f144c2017-06-12 14:26:21 -04005230 //
5231 // Generate OpPhi.
5232 //
5233 // Ops[0] = Result Type ID
5234 // Ops[1] ... Ops[n] = (Variable ID, Parent ID) pairs
5235 SPIRVOperandList Ops;
5236
David Neto257c3892018-04-11 13:19:45 -04005237 Ops << MkId(lookupType(PHI->getType()));
David Neto22f144c2017-06-12 14:26:21 -04005238
David Neto22f144c2017-06-12 14:26:21 -04005239 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
5240 uint32_t VarID = VMap[PHI->getIncomingValue(i)];
David Neto22f144c2017-06-12 14:26:21 -04005241 uint32_t ParentID = VMap[PHI->getIncomingBlock(i)];
David Neto257c3892018-04-11 13:19:45 -04005242 Ops << MkId(VarID) << MkId(ParentID);
David Neto22f144c2017-06-12 14:26:21 -04005243 }
5244
5245 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005246 InsertPoint,
5247 new SPIRVInstruction(spv::OpPhi, std::get<2>(*DeferredInst), Ops));
David Neto22f144c2017-06-12 14:26:21 -04005248 } else if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
5249 Function *Callee = Call->getCalledFunction();
SJW2c317da2020-03-23 07:39:13 -05005250 LLVMContext &Context = Callee->getContext();
5251 auto IntTy = Type::getInt32Ty(Context);
5252 auto callee_code = Builtins::Lookup(Callee);
David Neto3fbb4072017-10-16 11:28:14 -04005253 auto callee_name = Callee->getName();
5254 glsl::ExtInst EInst = getDirectOrIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04005255
5256 if (EInst) {
5257 uint32_t &ExtInstImportID = getOpExtInstImportID();
5258
5259 //
5260 // Generate OpExtInst.
5261 //
5262
5263 // Ops[0] = Result Type ID
5264 // Ops[1] = Set ID (OpExtInstImport ID)
5265 // Ops[2] = Instruction Number (Literal Number)
5266 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
5267 SPIRVOperandList Ops;
5268
David Neto862b7d82018-06-14 18:48:37 -04005269 Ops << MkId(lookupType(Call->getType())) << MkId(ExtInstImportID)
5270 << MkNum(EInst);
David Neto22f144c2017-06-12 14:26:21 -04005271
David Neto22f144c2017-06-12 14:26:21 -04005272 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5273 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
David Neto257c3892018-04-11 13:19:45 -04005274 Ops << MkId(VMap[Call->getOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04005275 }
5276
David Neto87846742018-04-11 17:36:22 -04005277 auto *ExtInst = new SPIRVInstruction(spv::OpExtInst,
5278 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04005279 SPIRVInstList.insert(InsertPoint, ExtInst);
5280
David Neto3fbb4072017-10-16 11:28:14 -04005281 const auto IndirectExtInst = getIndirectExtInstEnum(callee_name);
5282 if (IndirectExtInst != kGlslExtInstBad) {
5283 // Generate one more instruction that uses the result of the extended
5284 // instruction. Its result id is one more than the id of the
5285 // extended instruction.
David Neto3fbb4072017-10-16 11:28:14 -04005286 auto generate_extra_inst = [this, &Context, &Call, &DeferredInst,
5287 &VMap, &SPIRVInstList, &InsertPoint](
5288 spv::Op opcode, Constant *constant) {
5289 //
5290 // Generate instruction like:
5291 // result = opcode constant <extinst-result>
5292 //
5293 // Ops[0] = Result Type ID
5294 // Ops[1] = Operand 0 ;; the constant, suitably splatted
5295 // Ops[2] = Operand 1 ;; the result of the extended instruction
5296 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04005297
David Neto3fbb4072017-10-16 11:28:14 -04005298 Type *resultTy = Call->getType();
David Neto257c3892018-04-11 13:19:45 -04005299 Ops << MkId(lookupType(resultTy));
David Neto3fbb4072017-10-16 11:28:14 -04005300
5301 if (auto *vectorTy = dyn_cast<VectorType>(resultTy)) {
5302 constant = ConstantVector::getSplat(
alan-baker7261e062020-03-15 14:35:48 -04005303 {static_cast<unsigned>(vectorTy->getNumElements()), false},
5304 constant);
David Neto3fbb4072017-10-16 11:28:14 -04005305 }
David Neto257c3892018-04-11 13:19:45 -04005306 Ops << MkId(VMap[constant]) << MkId(std::get<2>(*DeferredInst));
David Neto3fbb4072017-10-16 11:28:14 -04005307
5308 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005309 InsertPoint, new SPIRVInstruction(
5310 opcode, std::get<2>(*DeferredInst) + 1, Ops));
David Neto3fbb4072017-10-16 11:28:14 -04005311 };
5312
5313 switch (IndirectExtInst) {
5314 case glsl::ExtInstFindUMsb: // Implementing clz
SJW2c317da2020-03-23 07:39:13 -05005315 generate_extra_inst(spv::OpISub, ConstantInt::get(IntTy, 31));
David Neto3fbb4072017-10-16 11:28:14 -04005316 break;
5317 case glsl::ExtInstAcos: // Implementing acospi
5318 case glsl::ExtInstAsin: // Implementing asinpi
Kévin Petiteb9f90a2018-09-29 12:29:34 +01005319 case glsl::ExtInstAtan: // Implementing atanpi
David Neto3fbb4072017-10-16 11:28:14 -04005320 case glsl::ExtInstAtan2: // Implementing atan2pi
5321 generate_extra_inst(
5322 spv::OpFMul,
5323 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
5324 break;
5325
5326 default:
5327 assert(false && "internally inconsistent");
David Neto4d02a532017-09-17 12:57:44 -04005328 }
David Neto22f144c2017-06-12 14:26:21 -04005329 }
David Neto3fbb4072017-10-16 11:28:14 -04005330
SJW2c317da2020-03-23 07:39:13 -05005331 } else if (callee_code == Builtins::kPopcount) {
David Neto22f144c2017-06-12 14:26:21 -04005332 //
5333 // Generate OpBitCount
5334 //
5335 // Ops[0] = Result Type ID
5336 // Ops[1] = Base ID
David Neto257c3892018-04-11 13:19:45 -04005337 SPIRVOperandList Ops;
5338 Ops << MkId(lookupType(Call->getType()))
5339 << MkId(VMap[Call->getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04005340
5341 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005342 InsertPoint, new SPIRVInstruction(spv::OpBitCount,
David Neto22f144c2017-06-12 14:26:21 -04005343 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005344
David Neto862b7d82018-06-14 18:48:37 -04005345 } else if (callee_name.startswith(kCompositeConstructFunctionPrefix)) {
David Netoab03f432017-11-03 17:00:44 -04005346
5347 // Generate an OpCompositeConstruct
5348 SPIRVOperandList Ops;
5349
5350 // The result type.
David Neto257c3892018-04-11 13:19:45 -04005351 Ops << MkId(lookupType(Call->getType()));
David Netoab03f432017-11-03 17:00:44 -04005352
5353 for (Use &use : Call->arg_operands()) {
David Neto257c3892018-04-11 13:19:45 -04005354 Ops << MkId(VMap[use.get()]);
David Netoab03f432017-11-03 17:00:44 -04005355 }
5356
5357 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005358 InsertPoint, new SPIRVInstruction(spv::OpCompositeConstruct,
5359 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005360
Alan Baker202c8c72018-08-13 13:47:44 -04005361 } else if (callee_name.startswith(clspv::ResourceAccessorFunction())) {
5362
5363 // We have already mapped the call's result value to an ID.
5364 // Don't generate any code now.
5365
5366 } else if (callee_name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04005367
5368 // We have already mapped the call's result value to an ID.
5369 // Don't generate any code now.
5370
David Neto22f144c2017-06-12 14:26:21 -04005371 } else {
alan-baker5b86ed72019-02-15 08:26:50 -05005372 if (Call->getType()->isPointerTy()) {
5373 // Functions returning pointers require variable pointers.
5374 setVariablePointersCapabilities(
5375 Call->getType()->getPointerAddressSpace());
5376 }
5377
David Neto22f144c2017-06-12 14:26:21 -04005378 //
5379 // Generate OpFunctionCall.
5380 //
5381
5382 // Ops[0] = Result Type ID
5383 // Ops[1] = Callee Function ID
5384 // Ops[2] ... Ops[n] = Argument 0, ... , Argument n
5385 SPIRVOperandList Ops;
5386
David Neto862b7d82018-06-14 18:48:37 -04005387 Ops << MkId(lookupType(Call->getType()));
David Neto22f144c2017-06-12 14:26:21 -04005388
5389 uint32_t CalleeID = VMap[Callee];
David Neto43568eb2017-10-13 18:25:25 -04005390 if (CalleeID == 0) {
5391 errs() << "Can't translate function call. Missing builtin? "
David Neto862b7d82018-06-14 18:48:37 -04005392 << callee_name << " in: " << *Call << "\n";
David Neto43568eb2017-10-13 18:25:25 -04005393 // TODO(dneto): Can we error out? Enabling this llvm_unreachable
5394 // causes an infinite loop. Instead, go ahead and generate
5395 // the bad function call. A validator will catch the 0-Id.
5396 // llvm_unreachable("Can't translate function call");
5397 }
David Neto22f144c2017-06-12 14:26:21 -04005398
David Neto257c3892018-04-11 13:19:45 -04005399 Ops << MkId(CalleeID);
David Neto22f144c2017-06-12 14:26:21 -04005400
David Neto22f144c2017-06-12 14:26:21 -04005401 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5402 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
alan-baker5b86ed72019-02-15 08:26:50 -05005403 auto *operand = Call->getOperand(i);
alan-bakerd4d50652019-12-03 17:17:15 -05005404 auto *operand_type = operand->getType();
5405 // Images and samplers can be passed as function parameters without
5406 // variable pointers.
5407 if (operand_type->isPointerTy() && !IsImageType(operand_type) &&
5408 !IsSamplerType(operand_type)) {
alan-baker5b86ed72019-02-15 08:26:50 -05005409 auto sc =
5410 GetStorageClass(operand->getType()->getPointerAddressSpace());
5411 if (sc == spv::StorageClassStorageBuffer) {
5412 // Passing SSBO by reference requires variable pointers storage
5413 // buffer.
5414 setVariablePointersStorageBuffer(true);
5415 } else if (sc == spv::StorageClassWorkgroup) {
5416 // Workgroup references require variable pointers if they are not
5417 // memory object declarations.
5418 if (auto *operand_call = dyn_cast<CallInst>(operand)) {
5419 // Workgroup accessor represents a variable reference.
5420 if (!operand_call->getCalledFunction()->getName().startswith(
5421 clspv::WorkgroupAccessorFunction()))
5422 setVariablePointers(true);
5423 } else {
5424 // Arguments are function parameters.
5425 if (!isa<Argument>(operand))
5426 setVariablePointers(true);
5427 }
5428 }
5429 }
5430 Ops << MkId(VMap[operand]);
David Neto22f144c2017-06-12 14:26:21 -04005431 }
5432
David Neto87846742018-04-11 17:36:22 -04005433 auto *CallInst = new SPIRVInstruction(spv::OpFunctionCall,
5434 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04005435 SPIRVInstList.insert(InsertPoint, CallInst);
5436 }
5437 }
5438 }
5439}
5440
SJW77b87ad2020-04-21 14:37:52 -05005441void SPIRVProducerPass::HandleDeferredDecorations() {
5442 const auto &DL = module->getDataLayout();
Alan Baker202c8c72018-08-13 13:47:44 -04005443 if (getTypesNeedingArrayStride().empty() && LocalArgSpecIds.empty()) {
David Neto1a1a0582017-07-07 12:01:44 -04005444 return;
David Netoc6f3ab22018-04-06 18:02:31 -04005445 }
David Neto1a1a0582017-07-07 12:01:44 -04005446
SJW69939d52020-04-16 07:29:07 -05005447 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kAnnotations);
David Neto1a1a0582017-07-07 12:01:44 -04005448
David Netoc6f3ab22018-04-06 18:02:31 -04005449 // Insert ArrayStride decorations on pointer types, due to OpPtrAccessChain
5450 // instructions we generated earlier.
David Neto85082642018-03-24 06:55:20 -07005451 for (auto *type : getTypesNeedingArrayStride()) {
5452 Type *elemTy = nullptr;
5453 if (auto *ptrTy = dyn_cast<PointerType>(type)) {
5454 elemTy = ptrTy->getElementType();
alan-bakerb6b09dc2018-11-08 16:59:28 -05005455 } else if (auto *arrayTy = dyn_cast<ArrayType>(type)) {
alan-baker8eb435a2020-04-08 00:42:06 -04005456 elemTy = arrayTy->getElementType();
5457 } else if (auto *vecTy = dyn_cast<VectorType>(type)) {
5458 elemTy = vecTy->getElementType();
David Neto85082642018-03-24 06:55:20 -07005459 } else {
5460 errs() << "Unhandled strided type " << *type << "\n";
5461 llvm_unreachable("Unhandled strided type");
5462 }
David Neto1a1a0582017-07-07 12:01:44 -04005463
5464 // Ops[0] = Target ID
5465 // Ops[1] = Decoration (ArrayStride)
5466 // Ops[2] = Stride number (Literal Number)
5467 SPIRVOperandList Ops;
5468
David Neto85082642018-03-24 06:55:20 -07005469 // Same as DL.getIndexedOffsetInType( elemTy, { 1 } );
Alan Bakerfcda9482018-10-02 17:09:59 -04005470 const uint32_t stride = static_cast<uint32_t>(GetTypeAllocSize(elemTy, DL));
David Neto257c3892018-04-11 13:19:45 -04005471
5472 Ops << MkId(lookupType(type)) << MkNum(spv::DecorationArrayStride)
5473 << MkNum(stride);
David Neto1a1a0582017-07-07 12:01:44 -04005474
David Neto87846742018-04-11 17:36:22 -04005475 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
SJW69939d52020-04-16 07:29:07 -05005476 SPIRVInstList.push_back(DecoInst);
David Neto1a1a0582017-07-07 12:01:44 -04005477 }
David Netoc6f3ab22018-04-06 18:02:31 -04005478
5479 // Emit SpecId decorations targeting the array size value.
SJW77b87ad2020-04-21 14:37:52 -05005480 for (auto pair : clspv::GetSpecConstants(module)) {
alan-bakera1be3322020-04-20 12:48:18 -04005481 auto kind = pair.first;
5482 auto spec_id = pair.second;
5483
5484 if (kind != SpecConstant::kLocalMemorySize)
5485 continue;
5486
alan-bakerb6b09dc2018-11-08 16:59:28 -05005487 LocalArgInfo &arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04005488 SPIRVOperandList Ops;
5489 Ops << MkId(arg_info.array_size_id) << MkNum(spv::DecorationSpecId)
5490 << MkNum(arg_info.spec_id);
SJW69939d52020-04-16 07:29:07 -05005491 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpDecorate, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04005492 }
David Neto1a1a0582017-07-07 12:01:44 -04005493}
5494
David Neto22f144c2017-06-12 14:26:21 -04005495glsl::ExtInst SPIRVProducerPass::getExtInstEnum(StringRef Name) {
SJW2c317da2020-03-23 07:39:13 -05005496
5497 const auto &fi = Builtins::Lookup(Name);
5498 switch (fi) {
5499 case Builtins::kClamp: {
5500 auto param_type = fi.getParameter(0);
5501 if (param_type.type_id == Type::FloatTyID) {
5502 return glsl::ExtInst::ExtInstFClamp;
5503 }
5504 return param_type.is_signed ? glsl::ExtInst::ExtInstSClamp
5505 : glsl::ExtInst::ExtInstUClamp;
5506 }
5507 case Builtins::kMax: {
5508 auto param_type = fi.getParameter(0);
5509 if (param_type.type_id == Type::FloatTyID) {
5510 return glsl::ExtInst::ExtInstFMax;
5511 }
5512 return param_type.is_signed ? glsl::ExtInst::ExtInstSMax
5513 : glsl::ExtInst::ExtInstUMax;
5514 }
5515 case Builtins::kMin: {
5516 auto param_type = fi.getParameter(0);
5517 if (param_type.type_id == Type::FloatTyID) {
5518 return glsl::ExtInst::ExtInstFMin;
5519 }
5520 return param_type.is_signed ? glsl::ExtInst::ExtInstSMin
5521 : glsl::ExtInst::ExtInstUMin;
5522 }
5523 case Builtins::kAbs:
5524 return glsl::ExtInst::ExtInstSAbs;
5525 case Builtins::kFmax:
5526 return glsl::ExtInst::ExtInstFMax;
5527 case Builtins::kFmin:
5528 return glsl::ExtInst::ExtInstFMin;
5529 case Builtins::kDegrees:
5530 return glsl::ExtInst::ExtInstDegrees;
5531 case Builtins::kRadians:
5532 return glsl::ExtInst::ExtInstRadians;
5533 case Builtins::kMix:
5534 return glsl::ExtInst::ExtInstFMix;
5535 case Builtins::kAcos:
5536 case Builtins::kAcospi:
5537 return glsl::ExtInst::ExtInstAcos;
5538 case Builtins::kAcosh:
5539 return glsl::ExtInst::ExtInstAcosh;
5540 case Builtins::kAsin:
5541 case Builtins::kAsinpi:
5542 return glsl::ExtInst::ExtInstAsin;
5543 case Builtins::kAsinh:
5544 return glsl::ExtInst::ExtInstAsinh;
5545 case Builtins::kAtan:
5546 case Builtins::kAtanpi:
5547 return glsl::ExtInst::ExtInstAtan;
5548 case Builtins::kAtanh:
5549 return glsl::ExtInst::ExtInstAtanh;
5550 case Builtins::kAtan2:
5551 case Builtins::kAtan2pi:
5552 return glsl::ExtInst::ExtInstAtan2;
5553 case Builtins::kCeil:
5554 return glsl::ExtInst::ExtInstCeil;
5555 case Builtins::kSin:
5556 case Builtins::kHalfSin:
5557 case Builtins::kNativeSin:
5558 return glsl::ExtInst::ExtInstSin;
5559 case Builtins::kSinh:
5560 return glsl::ExtInst::ExtInstSinh;
5561 case Builtins::kCos:
5562 case Builtins::kHalfCos:
5563 case Builtins::kNativeCos:
5564 return glsl::ExtInst::ExtInstCos;
5565 case Builtins::kCosh:
5566 return glsl::ExtInst::ExtInstCosh;
5567 case Builtins::kTan:
5568 case Builtins::kHalfTan:
5569 case Builtins::kNativeTan:
5570 return glsl::ExtInst::ExtInstTan;
5571 case Builtins::kTanh:
5572 return glsl::ExtInst::ExtInstTanh;
5573 case Builtins::kExp:
5574 case Builtins::kHalfExp:
5575 case Builtins::kNativeExp:
5576 return glsl::ExtInst::ExtInstExp;
5577 case Builtins::kExp2:
5578 case Builtins::kHalfExp2:
5579 case Builtins::kNativeExp2:
5580 return glsl::ExtInst::ExtInstExp2;
5581 case Builtins::kLog:
5582 case Builtins::kHalfLog:
5583 case Builtins::kNativeLog:
5584 return glsl::ExtInst::ExtInstLog;
5585 case Builtins::kLog2:
5586 case Builtins::kHalfLog2:
5587 case Builtins::kNativeLog2:
5588 return glsl::ExtInst::ExtInstLog2;
5589 case Builtins::kFabs:
5590 return glsl::ExtInst::ExtInstFAbs;
5591 case Builtins::kFma:
5592 return glsl::ExtInst::ExtInstFma;
5593 case Builtins::kFloor:
5594 return glsl::ExtInst::ExtInstFloor;
5595 case Builtins::kLdexp:
5596 return glsl::ExtInst::ExtInstLdexp;
5597 case Builtins::kPow:
5598 case Builtins::kPowr:
5599 case Builtins::kHalfPowr:
5600 case Builtins::kNativePowr:
5601 return glsl::ExtInst::ExtInstPow;
5602 case Builtins::kRound:
5603 return glsl::ExtInst::ExtInstRound;
5604 case Builtins::kSqrt:
5605 case Builtins::kHalfSqrt:
5606 case Builtins::kNativeSqrt:
5607 return glsl::ExtInst::ExtInstSqrt;
5608 case Builtins::kRsqrt:
5609 case Builtins::kHalfRsqrt:
5610 case Builtins::kNativeRsqrt:
5611 return glsl::ExtInst::ExtInstInverseSqrt;
5612 case Builtins::kTrunc:
5613 return glsl::ExtInst::ExtInstTrunc;
5614 case Builtins::kFrexp:
5615 return glsl::ExtInst::ExtInstFrexp;
5616 case Builtins::kFract:
5617 return glsl::ExtInst::ExtInstFract;
5618 case Builtins::kSign:
5619 return glsl::ExtInst::ExtInstFSign;
5620 case Builtins::kLength:
5621 case Builtins::kFastLength:
5622 return glsl::ExtInst::ExtInstLength;
5623 case Builtins::kDistance:
5624 case Builtins::kFastDistance:
5625 return glsl::ExtInst::ExtInstDistance;
5626 case Builtins::kStep:
5627 return glsl::ExtInst::ExtInstStep;
5628 case Builtins::kSmoothstep:
5629 return glsl::ExtInst::ExtInstSmoothStep;
5630 case Builtins::kCross:
5631 return glsl::ExtInst::ExtInstCross;
5632 case Builtins::kNormalize:
5633 case Builtins::kFastNormalize:
5634 return glsl::ExtInst::ExtInstNormalize;
5635 default:
5636 break;
5637 }
5638
David Neto22f144c2017-06-12 14:26:21 -04005639 return StringSwitch<glsl::ExtInst>(Name)
David Neto22f144c2017-06-12 14:26:21 -04005640 .StartsWith("llvm.fmuladd.", glsl::ExtInst::ExtInstFma)
5641 .Case("spirv.unpack.v2f16", glsl::ExtInst::ExtInstUnpackHalf2x16)
5642 .Case("spirv.pack.v2f16", glsl::ExtInst::ExtInstPackHalf2x16)
David Neto3fbb4072017-10-16 11:28:14 -04005643 .Default(kGlslExtInstBad);
5644}
5645
5646glsl::ExtInst SPIRVProducerPass::getIndirectExtInstEnum(StringRef Name) {
SJW2c317da2020-03-23 07:39:13 -05005647 switch (Builtins::Lookup(Name)) {
5648 case Builtins::kClz:
5649 return glsl::ExtInst::ExtInstFindUMsb;
5650 case Builtins::kAcospi:
5651 return glsl::ExtInst::ExtInstAcos;
5652 case Builtins::kAsinpi:
5653 return glsl::ExtInst::ExtInstAsin;
5654 case Builtins::kAtanpi:
5655 return glsl::ExtInst::ExtInstAtan;
5656 case Builtins::kAtan2pi:
5657 return glsl::ExtInst::ExtInstAtan2;
5658 default:
5659 break;
5660 }
5661 return kGlslExtInstBad;
David Neto3fbb4072017-10-16 11:28:14 -04005662}
5663
alan-bakerb6b09dc2018-11-08 16:59:28 -05005664glsl::ExtInst
5665SPIRVProducerPass::getDirectOrIndirectExtInstEnum(StringRef Name) {
David Neto3fbb4072017-10-16 11:28:14 -04005666 auto direct = getExtInstEnum(Name);
5667 if (direct != kGlslExtInstBad)
5668 return direct;
5669 return getIndirectExtInstEnum(Name);
David Neto22f144c2017-06-12 14:26:21 -04005670}
5671
David Neto22f144c2017-06-12 14:26:21 -04005672void SPIRVProducerPass::WriteOneWord(uint32_t Word) {
David Neto0676e6f2017-07-11 18:47:44 -04005673 binaryOut->write(reinterpret_cast<const char *>(&Word), sizeof(uint32_t));
David Neto22f144c2017-06-12 14:26:21 -04005674}
5675
5676void SPIRVProducerPass::WriteResultID(SPIRVInstruction *Inst) {
5677 WriteOneWord(Inst->getResultID());
5678}
5679
5680void SPIRVProducerPass::WriteWordCountAndOpcode(SPIRVInstruction *Inst) {
5681 // High 16 bit : Word Count
5682 // Low 16 bit : Opcode
5683 uint32_t Word = Inst->getOpcode();
David Netoee2660d2018-06-28 16:31:29 -04005684 const uint32_t count = Inst->getWordCount();
5685 if (count > 65535) {
5686 errs() << "Word count limit of 65535 exceeded: " << count << "\n";
5687 llvm_unreachable("Word count too high");
5688 }
David Neto22f144c2017-06-12 14:26:21 -04005689 Word |= Inst->getWordCount() << 16;
5690 WriteOneWord(Word);
5691}
5692
David Netoef5ba2b2019-12-20 08:35:54 -05005693void SPIRVProducerPass::WriteOperand(const std::unique_ptr<SPIRVOperand> &Op) {
David Neto22f144c2017-06-12 14:26:21 -04005694 SPIRVOperandType OpTy = Op->getType();
5695 switch (OpTy) {
5696 default: {
5697 llvm_unreachable("Unsupported SPIRV Operand Type???");
5698 break;
5699 }
5700 case SPIRVOperandType::NUMBERID: {
5701 WriteOneWord(Op->getNumID());
5702 break;
5703 }
5704 case SPIRVOperandType::LITERAL_STRING: {
5705 std::string Str = Op->getLiteralStr();
5706 const char *Data = Str.c_str();
5707 size_t WordSize = Str.size() / 4;
5708 for (unsigned Idx = 0; Idx < WordSize; Idx++) {
5709 WriteOneWord(*reinterpret_cast<const uint32_t *>(&Data[4 * Idx]));
5710 }
5711
5712 uint32_t Remainder = Str.size() % 4;
5713 uint32_t LastWord = 0;
5714 if (Remainder) {
5715 for (unsigned Idx = 0; Idx < Remainder; Idx++) {
5716 LastWord |= Data[4 * WordSize + Idx] << 8 * Idx;
5717 }
5718 }
5719
5720 WriteOneWord(LastWord);
5721 break;
5722 }
5723 case SPIRVOperandType::LITERAL_INTEGER:
5724 case SPIRVOperandType::LITERAL_FLOAT: {
5725 auto LiteralNum = Op->getLiteralNum();
5726 // TODO: Handle LiteranNum carefully.
5727 for (auto Word : LiteralNum) {
5728 WriteOneWord(Word);
5729 }
5730 break;
5731 }
5732 }
5733}
5734
5735void SPIRVProducerPass::WriteSPIRVBinary() {
SJW69939d52020-04-16 07:29:07 -05005736 for (int i = 0; i < kSectionCount; ++i) {
5737 WriteSPIRVBinary(SPIRVSections[i]);
5738 }
5739}
5740
5741void SPIRVProducerPass::WriteSPIRVBinary(SPIRVInstructionList &SPIRVInstList) {
David Neto22f144c2017-06-12 14:26:21 -04005742
5743 for (auto Inst : SPIRVInstList) {
David Netoef5ba2b2019-12-20 08:35:54 -05005744 const auto &Ops = Inst->getOperands();
David Neto22f144c2017-06-12 14:26:21 -04005745 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5746
5747 switch (Opcode) {
5748 default: {
David Neto5c22a252018-03-15 16:07:41 -04005749 errs() << "Unsupported SPIR-V instruction opcode " << int(Opcode) << "\n";
David Neto22f144c2017-06-12 14:26:21 -04005750 llvm_unreachable("Unsupported SPIRV instruction");
5751 break;
5752 }
5753 case spv::OpCapability:
5754 case spv::OpExtension:
5755 case spv::OpMemoryModel:
5756 case spv::OpEntryPoint:
5757 case spv::OpExecutionMode:
5758 case spv::OpSource:
5759 case spv::OpDecorate:
5760 case spv::OpMemberDecorate:
5761 case spv::OpBranch:
5762 case spv::OpBranchConditional:
5763 case spv::OpSelectionMerge:
5764 case spv::OpLoopMerge:
5765 case spv::OpStore:
5766 case spv::OpImageWrite:
5767 case spv::OpReturnValue:
5768 case spv::OpControlBarrier:
5769 case spv::OpMemoryBarrier:
5770 case spv::OpReturn:
5771 case spv::OpFunctionEnd:
5772 case spv::OpCopyMemory: {
5773 WriteWordCountAndOpcode(Inst);
5774 for (uint32_t i = 0; i < Ops.size(); i++) {
5775 WriteOperand(Ops[i]);
5776 }
5777 break;
5778 }
5779 case spv::OpTypeBool:
5780 case spv::OpTypeVoid:
5781 case spv::OpTypeSampler:
5782 case spv::OpLabel:
5783 case spv::OpExtInstImport:
5784 case spv::OpTypePointer:
5785 case spv::OpTypeRuntimeArray:
5786 case spv::OpTypeStruct:
5787 case spv::OpTypeImage:
5788 case spv::OpTypeSampledImage:
5789 case spv::OpTypeInt:
5790 case spv::OpTypeFloat:
5791 case spv::OpTypeArray:
5792 case spv::OpTypeVector:
5793 case spv::OpTypeFunction: {
5794 WriteWordCountAndOpcode(Inst);
5795 WriteResultID(Inst);
5796 for (uint32_t i = 0; i < Ops.size(); i++) {
5797 WriteOperand(Ops[i]);
5798 }
5799 break;
5800 }
5801 case spv::OpFunction:
5802 case spv::OpFunctionParameter:
5803 case spv::OpAccessChain:
5804 case spv::OpPtrAccessChain:
5805 case spv::OpInBoundsAccessChain:
5806 case spv::OpUConvert:
5807 case spv::OpSConvert:
5808 case spv::OpConvertFToU:
5809 case spv::OpConvertFToS:
5810 case spv::OpConvertUToF:
5811 case spv::OpConvertSToF:
5812 case spv::OpFConvert:
5813 case spv::OpConvertPtrToU:
5814 case spv::OpConvertUToPtr:
5815 case spv::OpBitcast:
alan-bakerc9c55ae2019-12-02 16:01:27 -05005816 case spv::OpFNegate:
David Neto22f144c2017-06-12 14:26:21 -04005817 case spv::OpIAdd:
5818 case spv::OpFAdd:
5819 case spv::OpISub:
5820 case spv::OpFSub:
5821 case spv::OpIMul:
5822 case spv::OpFMul:
5823 case spv::OpUDiv:
5824 case spv::OpSDiv:
5825 case spv::OpFDiv:
5826 case spv::OpUMod:
5827 case spv::OpSRem:
5828 case spv::OpFRem:
Kévin Petit8a560882019-03-21 15:24:34 +00005829 case spv::OpUMulExtended:
5830 case spv::OpSMulExtended:
David Neto22f144c2017-06-12 14:26:21 -04005831 case spv::OpBitwiseOr:
5832 case spv::OpBitwiseXor:
5833 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04005834 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04005835 case spv::OpShiftLeftLogical:
5836 case spv::OpShiftRightLogical:
5837 case spv::OpShiftRightArithmetic:
5838 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04005839 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04005840 case spv::OpCompositeExtract:
5841 case spv::OpVectorExtractDynamic:
5842 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04005843 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04005844 case spv::OpVectorInsertDynamic:
5845 case spv::OpVectorShuffle:
5846 case spv::OpIEqual:
5847 case spv::OpINotEqual:
5848 case spv::OpUGreaterThan:
5849 case spv::OpUGreaterThanEqual:
5850 case spv::OpULessThan:
5851 case spv::OpULessThanEqual:
5852 case spv::OpSGreaterThan:
5853 case spv::OpSGreaterThanEqual:
5854 case spv::OpSLessThan:
5855 case spv::OpSLessThanEqual:
5856 case spv::OpFOrdEqual:
5857 case spv::OpFOrdGreaterThan:
5858 case spv::OpFOrdGreaterThanEqual:
5859 case spv::OpFOrdLessThan:
5860 case spv::OpFOrdLessThanEqual:
5861 case spv::OpFOrdNotEqual:
5862 case spv::OpFUnordEqual:
5863 case spv::OpFUnordGreaterThan:
5864 case spv::OpFUnordGreaterThanEqual:
5865 case spv::OpFUnordLessThan:
5866 case spv::OpFUnordLessThanEqual:
5867 case spv::OpFUnordNotEqual:
5868 case spv::OpExtInst:
5869 case spv::OpIsInf:
5870 case spv::OpIsNan:
5871 case spv::OpAny:
5872 case spv::OpAll:
5873 case spv::OpUndef:
5874 case spv::OpConstantNull:
5875 case spv::OpLogicalOr:
5876 case spv::OpLogicalAnd:
5877 case spv::OpLogicalNot:
5878 case spv::OpLogicalNotEqual:
5879 case spv::OpConstantComposite:
5880 case spv::OpSpecConstantComposite:
5881 case spv::OpConstantTrue:
5882 case spv::OpConstantFalse:
5883 case spv::OpConstant:
5884 case spv::OpSpecConstant:
5885 case spv::OpVariable:
5886 case spv::OpFunctionCall:
5887 case spv::OpSampledImage:
alan-baker75090e42020-02-20 11:21:04 -05005888 case spv::OpImageFetch:
David Neto22f144c2017-06-12 14:26:21 -04005889 case spv::OpImageSampleExplicitLod:
David Neto5c22a252018-03-15 16:07:41 -04005890 case spv::OpImageQuerySize:
alan-bakerce179f12019-12-06 19:02:22 -05005891 case spv::OpImageQuerySizeLod:
David Neto22f144c2017-06-12 14:26:21 -04005892 case spv::OpSelect:
5893 case spv::OpPhi:
5894 case spv::OpLoad:
5895 case spv::OpAtomicIAdd:
5896 case spv::OpAtomicISub:
5897 case spv::OpAtomicExchange:
5898 case spv::OpAtomicIIncrement:
5899 case spv::OpAtomicIDecrement:
5900 case spv::OpAtomicCompareExchange:
5901 case spv::OpAtomicUMin:
5902 case spv::OpAtomicSMin:
5903 case spv::OpAtomicUMax:
5904 case spv::OpAtomicSMax:
5905 case spv::OpAtomicAnd:
5906 case spv::OpAtomicOr:
5907 case spv::OpAtomicXor:
5908 case spv::OpDot: {
5909 WriteWordCountAndOpcode(Inst);
5910 WriteOperand(Ops[0]);
5911 WriteResultID(Inst);
5912 for (uint32_t i = 1; i < Ops.size(); i++) {
5913 WriteOperand(Ops[i]);
5914 }
5915 break;
5916 }
5917 }
5918 }
5919}
Alan Baker9bf93fb2018-08-28 16:59:26 -04005920
alan-bakerb6b09dc2018-11-08 16:59:28 -05005921bool SPIRVProducerPass::IsTypeNullable(const Type *type) const {
Alan Baker9bf93fb2018-08-28 16:59:26 -04005922 switch (type->getTypeID()) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05005923 case Type::HalfTyID:
5924 case Type::FloatTyID:
5925 case Type::DoubleTyID:
5926 case Type::IntegerTyID:
James Price59a1c752020-04-23 23:06:16 -04005927 case Type::FixedVectorTyID:
alan-bakerb6b09dc2018-11-08 16:59:28 -05005928 return true;
5929 case Type::PointerTyID: {
5930 const PointerType *pointer_type = cast<PointerType>(type);
5931 if (pointer_type->getPointerAddressSpace() !=
5932 AddressSpace::UniformConstant) {
5933 auto pointee_type = pointer_type->getPointerElementType();
5934 if (pointee_type->isStructTy() &&
5935 cast<StructType>(pointee_type)->isOpaque()) {
5936 // Images and samplers are not nullable.
5937 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04005938 }
Alan Baker9bf93fb2018-08-28 16:59:26 -04005939 }
alan-bakerb6b09dc2018-11-08 16:59:28 -05005940 return true;
5941 }
5942 case Type::ArrayTyID:
alan-baker8eb435a2020-04-08 00:42:06 -04005943 return IsTypeNullable(type->getArrayElementType());
alan-bakerb6b09dc2018-11-08 16:59:28 -05005944 case Type::StructTyID: {
5945 const StructType *struct_type = cast<StructType>(type);
5946 // Images and samplers are not nullable.
5947 if (struct_type->isOpaque())
Alan Baker9bf93fb2018-08-28 16:59:26 -04005948 return false;
alan-bakerb6b09dc2018-11-08 16:59:28 -05005949 for (const auto element : struct_type->elements()) {
5950 if (!IsTypeNullable(element))
5951 return false;
5952 }
5953 return true;
5954 }
5955 default:
5956 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04005957 }
5958}
Alan Bakerfcda9482018-10-02 17:09:59 -04005959
SJW77b87ad2020-04-21 14:37:52 -05005960void SPIRVProducerPass::PopulateUBOTypeMaps() {
Alan Bakerfcda9482018-10-02 17:09:59 -04005961 if (auto *offsets_md =
SJW77b87ad2020-04-21 14:37:52 -05005962 module->getNamedMetadata(clspv::RemappedTypeOffsetMetadataName())) {
Alan Bakerfcda9482018-10-02 17:09:59 -04005963 // Metdata is stored as key-value pair operands. The first element of each
5964 // operand is the type and the second is a vector of offsets.
5965 for (const auto *operand : offsets_md->operands()) {
5966 const auto *pair = cast<MDTuple>(operand);
5967 auto *type =
5968 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
5969 const auto *offset_vector = cast<MDTuple>(pair->getOperand(1));
5970 std::vector<uint32_t> offsets;
5971 for (const Metadata *offset_md : offset_vector->operands()) {
5972 const auto *constant_md = cast<ConstantAsMetadata>(offset_md);
alan-bakerb6b09dc2018-11-08 16:59:28 -05005973 offsets.push_back(static_cast<uint32_t>(
5974 cast<ConstantInt>(constant_md->getValue())->getZExtValue()));
Alan Bakerfcda9482018-10-02 17:09:59 -04005975 }
5976 RemappedUBOTypeOffsets.insert(std::make_pair(type, offsets));
5977 }
5978 }
5979
5980 if (auto *sizes_md =
SJW77b87ad2020-04-21 14:37:52 -05005981 module->getNamedMetadata(clspv::RemappedTypeSizesMetadataName())) {
Alan Bakerfcda9482018-10-02 17:09:59 -04005982 // Metadata is stored as key-value pair operands. The first element of each
5983 // operand is the type and the second is a triple of sizes: type size in
5984 // bits, store size and alloc size.
5985 for (const auto *operand : sizes_md->operands()) {
5986 const auto *pair = cast<MDTuple>(operand);
5987 auto *type =
5988 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
5989 const auto *size_triple = cast<MDTuple>(pair->getOperand(1));
5990 uint64_t type_size_in_bits =
5991 cast<ConstantInt>(
5992 cast<ConstantAsMetadata>(size_triple->getOperand(0))->getValue())
5993 ->getZExtValue();
5994 uint64_t type_store_size =
5995 cast<ConstantInt>(
5996 cast<ConstantAsMetadata>(size_triple->getOperand(1))->getValue())
5997 ->getZExtValue();
5998 uint64_t type_alloc_size =
5999 cast<ConstantInt>(
6000 cast<ConstantAsMetadata>(size_triple->getOperand(2))->getValue())
6001 ->getZExtValue();
6002 RemappedUBOTypeSizes.insert(std::make_pair(
6003 type, std::make_tuple(type_size_in_bits, type_store_size,
6004 type_alloc_size)));
6005 }
6006 }
6007}
6008
6009uint64_t SPIRVProducerPass::GetTypeSizeInBits(Type *type,
6010 const DataLayout &DL) {
6011 auto iter = RemappedUBOTypeSizes.find(type);
6012 if (iter != RemappedUBOTypeSizes.end()) {
6013 return std::get<0>(iter->second);
6014 }
6015
6016 return DL.getTypeSizeInBits(type);
6017}
6018
6019uint64_t SPIRVProducerPass::GetTypeStoreSize(Type *type, const DataLayout &DL) {
6020 auto iter = RemappedUBOTypeSizes.find(type);
6021 if (iter != RemappedUBOTypeSizes.end()) {
6022 return std::get<1>(iter->second);
6023 }
6024
6025 return DL.getTypeStoreSize(type);
6026}
6027
6028uint64_t SPIRVProducerPass::GetTypeAllocSize(Type *type, const DataLayout &DL) {
6029 auto iter = RemappedUBOTypeSizes.find(type);
6030 if (iter != RemappedUBOTypeSizes.end()) {
6031 return std::get<2>(iter->second);
6032 }
6033
6034 return DL.getTypeAllocSize(type);
6035}
alan-baker5b86ed72019-02-15 08:26:50 -05006036
Kévin Petitbbbda972020-03-03 19:16:31 +00006037uint32_t SPIRVProducerPass::GetExplicitLayoutStructMemberOffset(
6038 StructType *type, unsigned member, const DataLayout &DL) {
6039 const auto StructLayout = DL.getStructLayout(type);
6040 // Search for the correct offsets if this type was remapped.
6041 std::vector<uint32_t> *offsets = nullptr;
6042 auto iter = RemappedUBOTypeOffsets.find(type);
6043 if (iter != RemappedUBOTypeOffsets.end()) {
6044 offsets = &iter->second;
6045 }
6046 auto ByteOffset =
6047 static_cast<uint32_t>(StructLayout->getElementOffset(member));
6048 if (offsets) {
6049 ByteOffset = (*offsets)[member];
6050 }
6051
6052 return ByteOffset;
6053}
6054
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04006055void SPIRVProducerPass::setVariablePointersCapabilities(
6056 unsigned address_space) {
alan-baker5b86ed72019-02-15 08:26:50 -05006057 if (GetStorageClass(address_space) == spv::StorageClassStorageBuffer) {
6058 setVariablePointersStorageBuffer(true);
6059 } else {
6060 setVariablePointers(true);
6061 }
6062}
6063
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04006064Value *SPIRVProducerPass::GetBasePointer(Value *v) {
alan-baker5b86ed72019-02-15 08:26:50 -05006065 if (auto *gep = dyn_cast<GetElementPtrInst>(v)) {
6066 return GetBasePointer(gep->getPointerOperand());
6067 }
6068
6069 // Conservatively return |v|.
6070 return v;
6071}
6072
6073bool SPIRVProducerPass::sameResource(Value *lhs, Value *rhs) const {
6074 if (auto *lhs_call = dyn_cast<CallInst>(lhs)) {
6075 if (auto *rhs_call = dyn_cast<CallInst>(rhs)) {
6076 if (lhs_call->getCalledFunction()->getName().startswith(
6077 clspv::ResourceAccessorFunction()) &&
6078 rhs_call->getCalledFunction()->getName().startswith(
6079 clspv::ResourceAccessorFunction())) {
6080 // For resource accessors, match descriptor set and binding.
6081 if (lhs_call->getOperand(0) == rhs_call->getOperand(0) &&
6082 lhs_call->getOperand(1) == rhs_call->getOperand(1))
6083 return true;
6084 } else if (lhs_call->getCalledFunction()->getName().startswith(
6085 clspv::WorkgroupAccessorFunction()) &&
6086 rhs_call->getCalledFunction()->getName().startswith(
6087 clspv::WorkgroupAccessorFunction())) {
6088 // For workgroup resources, match spec id.
6089 if (lhs_call->getOperand(0) == rhs_call->getOperand(0))
6090 return true;
6091 }
6092 }
6093 }
6094
6095 return false;
6096}
6097
6098bool SPIRVProducerPass::selectFromSameObject(Instruction *inst) {
6099 assert(inst->getType()->isPointerTy());
6100 assert(GetStorageClass(inst->getType()->getPointerAddressSpace()) ==
6101 spv::StorageClassStorageBuffer);
6102 const bool hack_undef = clspv::Option::HackUndef();
6103 if (auto *select = dyn_cast<SelectInst>(inst)) {
6104 auto *true_base = GetBasePointer(select->getTrueValue());
6105 auto *false_base = GetBasePointer(select->getFalseValue());
6106
6107 if (true_base == false_base)
6108 return true;
6109
6110 // If either the true or false operand is a null, then we satisfy the same
6111 // object constraint.
6112 if (auto *true_cst = dyn_cast<Constant>(true_base)) {
6113 if (true_cst->isNullValue() || (hack_undef && isa<UndefValue>(true_base)))
6114 return true;
6115 }
6116
6117 if (auto *false_cst = dyn_cast<Constant>(false_base)) {
6118 if (false_cst->isNullValue() ||
6119 (hack_undef && isa<UndefValue>(false_base)))
6120 return true;
6121 }
6122
6123 if (sameResource(true_base, false_base))
6124 return true;
6125 } else if (auto *phi = dyn_cast<PHINode>(inst)) {
6126 Value *value = nullptr;
6127 bool ok = true;
6128 for (unsigned i = 0; ok && i != phi->getNumIncomingValues(); ++i) {
6129 auto *base = GetBasePointer(phi->getIncomingValue(i));
6130 // Null values satisfy the constraint of selecting of selecting from the
6131 // same object.
6132 if (!value) {
6133 if (auto *cst = dyn_cast<Constant>(base)) {
6134 if (!cst->isNullValue() && !(hack_undef && isa<UndefValue>(base)))
6135 value = base;
6136 } else {
6137 value = base;
6138 }
6139 } else if (base != value) {
6140 if (auto *base_cst = dyn_cast<Constant>(base)) {
6141 if (base_cst->isNullValue() || (hack_undef && isa<UndefValue>(base)))
6142 continue;
6143 }
6144
6145 if (sameResource(value, base))
6146 continue;
6147
6148 // Values don't represent the same base.
6149 ok = false;
6150 }
6151 }
6152
6153 return ok;
6154 }
6155
6156 // Conservatively return false.
6157 return false;
6158}
alan-bakere9308012019-03-15 10:25:13 -04006159
6160bool SPIRVProducerPass::CalledWithCoherentResource(Argument &Arg) {
6161 if (!Arg.getType()->isPointerTy() ||
6162 Arg.getType()->getPointerAddressSpace() != clspv::AddressSpace::Global) {
6163 // Only SSBOs need to be annotated as coherent.
6164 return false;
6165 }
6166
6167 DenseSet<Value *> visited;
6168 std::vector<Value *> stack;
6169 for (auto *U : Arg.getParent()->users()) {
6170 if (auto *call = dyn_cast<CallInst>(U)) {
6171 stack.push_back(call->getOperand(Arg.getArgNo()));
6172 }
6173 }
6174
6175 while (!stack.empty()) {
6176 Value *v = stack.back();
6177 stack.pop_back();
6178
6179 if (!visited.insert(v).second)
6180 continue;
6181
6182 auto *resource_call = dyn_cast<CallInst>(v);
6183 if (resource_call &&
6184 resource_call->getCalledFunction()->getName().startswith(
6185 clspv::ResourceAccessorFunction())) {
6186 // If this is a resource accessor function, check if the coherent operand
6187 // is set.
6188 const auto coherent =
6189 unsigned(dyn_cast<ConstantInt>(resource_call->getArgOperand(5))
6190 ->getZExtValue());
6191 if (coherent == 1)
6192 return true;
6193 } else if (auto *arg = dyn_cast<Argument>(v)) {
6194 // If this is a function argument, trace through its callers.
alan-bakere98f3f92019-04-08 15:06:36 -04006195 for (auto U : arg->getParent()->users()) {
alan-bakere9308012019-03-15 10:25:13 -04006196 if (auto *call = dyn_cast<CallInst>(U)) {
6197 stack.push_back(call->getOperand(arg->getArgNo()));
6198 }
6199 }
6200 } else if (auto *user = dyn_cast<User>(v)) {
6201 // If this is a user, traverse all operands that could lead to resource
6202 // variables.
6203 for (unsigned i = 0; i != user->getNumOperands(); ++i) {
6204 Value *operand = user->getOperand(i);
6205 if (operand->getType()->isPointerTy() &&
6206 operand->getType()->getPointerAddressSpace() ==
6207 clspv::AddressSpace::Global) {
6208 stack.push_back(operand);
6209 }
6210 }
6211 }
6212 }
6213
6214 // No coherent resource variables encountered.
6215 return false;
6216}
alan-baker06cad652019-12-03 17:56:47 -05006217
SJW77b87ad2020-04-21 14:37:52 -05006218void SPIRVProducerPass::PopulateStructuredCFGMaps() {
alan-baker06cad652019-12-03 17:56:47 -05006219 // First, track loop merges and continues.
6220 DenseSet<BasicBlock *> LoopMergesAndContinues;
SJW77b87ad2020-04-21 14:37:52 -05006221 for (auto &F : *module) {
alan-baker06cad652019-12-03 17:56:47 -05006222 if (F.isDeclaration())
6223 continue;
6224
6225 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
6226 const LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>(F).getLoopInfo();
6227 std::deque<BasicBlock *> order;
6228 DenseSet<BasicBlock *> visited;
6229 clspv::ComputeStructuredOrder(&*F.begin(), &DT, LI, &order, &visited);
6230
6231 for (auto BB : order) {
6232 auto terminator = BB->getTerminator();
6233 auto branch = dyn_cast<BranchInst>(terminator);
6234 if (LI.isLoopHeader(BB)) {
6235 auto L = LI.getLoopFor(BB);
6236 BasicBlock *ContinueBB = nullptr;
6237 BasicBlock *MergeBB = nullptr;
6238
6239 MergeBB = L->getExitBlock();
6240 if (!MergeBB) {
6241 // StructurizeCFG pass converts CFG into triangle shape and the cfg
6242 // has regions with single entry/exit. As a result, loop should not
6243 // have multiple exits.
6244 llvm_unreachable("Loop has multiple exits???");
6245 }
6246
6247 if (L->isLoopLatch(BB)) {
6248 ContinueBB = BB;
6249 } else {
6250 // From SPIR-V spec 2.11, Continue Target must dominate that back-edge
6251 // block.
6252 BasicBlock *Header = L->getHeader();
6253 BasicBlock *Latch = L->getLoopLatch();
6254 for (auto *loop_block : L->blocks()) {
6255 if (loop_block == Header) {
6256 continue;
6257 }
6258
6259 // Check whether block dominates block with back-edge.
6260 // The loop latch is the single block with a back-edge. If it was
6261 // possible, StructurizeCFG made the loop conform to this
6262 // requirement, otherwise |Latch| is a nullptr.
6263 if (DT.dominates(loop_block, Latch)) {
6264 ContinueBB = loop_block;
6265 }
6266 }
6267
6268 if (!ContinueBB) {
6269 llvm_unreachable("Wrong continue block from loop");
6270 }
6271 }
6272
6273 // Record the continue and merge blocks.
6274 MergeBlocks[BB] = MergeBB;
6275 ContinueBlocks[BB] = ContinueBB;
6276 LoopMergesAndContinues.insert(MergeBB);
6277 LoopMergesAndContinues.insert(ContinueBB);
6278 } else if (branch && branch->isConditional()) {
6279 auto L = LI.getLoopFor(BB);
6280 bool HasBackedge = false;
6281 while (L && !HasBackedge) {
6282 if (L->isLoopLatch(BB)) {
6283 HasBackedge = true;
6284 }
6285 L = L->getParentLoop();
6286 }
6287
6288 if (!HasBackedge) {
6289 // Only need a merge if the branch doesn't include a loop break or
6290 // continue.
6291 auto true_bb = branch->getSuccessor(0);
6292 auto false_bb = branch->getSuccessor(1);
6293 if (!LoopMergesAndContinues.count(true_bb) &&
6294 !LoopMergesAndContinues.count(false_bb)) {
6295 // StructurizeCFG pass already manipulated CFG. Just use false block
6296 // of branch instruction as merge block.
6297 MergeBlocks[BB] = false_bb;
6298 }
6299 }
6300 }
6301 }
6302 }
6303}