blob: fbb00910aa4b8b2e3bce4bb8c155e3f19cf65dd7 [file] [log] [blame]
David Neto22f144c2017-06-12 14:26:21 -04001// Copyright 2017 The Clspv Authors. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#ifdef _MSC_VER
16#pragma warning(push, 0)
17#endif
18
David Neto156783e2017-07-05 15:39:41 -040019#include <cassert>
David Neto257c3892018-04-11 13:19:45 -040020#include <cstring>
David Neto118188e2018-08-24 11:27:54 -040021#include <iomanip>
22#include <list>
David Neto862b7d82018-06-14 18:48:37 -040023#include <memory>
David Neto118188e2018-08-24 11:27:54 -040024#include <set>
25#include <sstream>
26#include <string>
27#include <tuple>
28#include <unordered_set>
29#include <utility>
David Neto862b7d82018-06-14 18:48:37 -040030
David Neto118188e2018-08-24 11:27:54 -040031#include "llvm/ADT/StringSwitch.h"
32#include "llvm/ADT/UniqueVector.h"
33#include "llvm/Analysis/LoopInfo.h"
34#include "llvm/IR/Constants.h"
35#include "llvm/IR/Dominators.h"
36#include "llvm/IR/Instructions.h"
37#include "llvm/IR/Metadata.h"
38#include "llvm/IR/Module.h"
alan-bakerf67468c2019-11-25 15:51:49 -050039#include "llvm/IR/ValueSymbolTable.h"
David Neto118188e2018-08-24 11:27:54 -040040#include "llvm/Pass.h"
41#include "llvm/Support/CommandLine.h"
Kévin Petitbbbda972020-03-03 19:16:31 +000042#include "llvm/Support/MathExtras.h"
David Neto118188e2018-08-24 11:27:54 -040043#include "llvm/Support/raw_ostream.h"
44#include "llvm/Transforms/Utils/Cloning.h"
David Neto22f144c2017-06-12 14:26:21 -040045
alan-bakere0902602020-03-23 08:43:40 -040046#include "spirv/unified1/spirv.hpp"
David Neto118188e2018-08-24 11:27:54 -040047
David Neto85082642018-03-24 06:55:20 -070048#include "clspv/AddressSpace.h"
alan-bakerf5e5f692018-11-27 08:33:24 -050049#include "clspv/DescriptorMap.h"
David Neto118188e2018-08-24 11:27:54 -040050#include "clspv/Option.h"
David Neto85082642018-03-24 06:55:20 -070051#include "clspv/spirv_c_strings.hpp"
52#include "clspv/spirv_glsl.hpp"
David Neto22f144c2017-06-12 14:26:21 -040053
David Neto4feb7a42017-10-06 17:29:42 -040054#include "ArgKind.h"
alan-bakerf67468c2019-11-25 15:51:49 -050055#include "Builtins.h"
alan-baker06cad652019-12-03 17:56:47 -050056#include "ComputeStructuredOrder.h"
David Neto85082642018-03-24 06:55:20 -070057#include "ConstantEmitter.h"
Alan Baker202c8c72018-08-13 13:47:44 -040058#include "Constants.h"
David Neto78383442018-06-15 20:31:56 -040059#include "DescriptorCounter.h"
alan-baker56f7aff2019-05-22 08:06:42 -040060#include "NormalizeGlobalVariable.h"
Diego Novilloa4c44fa2019-04-11 10:56:15 -040061#include "Passes.h"
alan-bakerce179f12019-12-06 19:02:22 -050062#include "Types.h"
David Neto48f56a42017-10-06 16:44:25 -040063
David Neto22f144c2017-06-12 14:26:21 -040064#if defined(_MSC_VER)
65#pragma warning(pop)
66#endif
67
68using namespace llvm;
69using namespace clspv;
SJW173c7e92020-03-16 08:44:47 -050070using namespace clspv::Builtins;
David Neto156783e2017-07-05 15:39:41 -040071using namespace mdconst;
David Neto22f144c2017-06-12 14:26:21 -040072
73namespace {
David Netocd8ca5f2017-10-02 23:34:11 -040074
David Neto862b7d82018-06-14 18:48:37 -040075cl::opt<bool> ShowResourceVars("show-rv", cl::init(false), cl::Hidden,
76 cl::desc("Show resource variable creation"));
77
alan-baker5ed87542020-03-23 11:05:22 -040078cl::opt<bool>
79 ShowProducerIR("show-producer-ir", cl::init(false), cl::ReallyHidden,
80 cl::desc("Dump the IR at the start of SPIRVProducer"));
81
David Neto862b7d82018-06-14 18:48:37 -040082// These hacks exist to help transition code generation algorithms
83// without making huge noise in detailed test output.
84const bool Hack_generate_runtime_array_stride_early = true;
85
David Neto3fbb4072017-10-16 11:28:14 -040086// The value of 1/pi. This value is from MSDN
87// https://msdn.microsoft.com/en-us/library/4hwaceh6.aspx
88const double kOneOverPi = 0.318309886183790671538;
89const glsl::ExtInst kGlslExtInstBad = static_cast<glsl::ExtInst>(0);
90
alan-bakerb6b09dc2018-11-08 16:59:28 -050091const char *kCompositeConstructFunctionPrefix = "clspv.composite_construct.";
David Netoab03f432017-11-03 17:00:44 -040092
David Neto22f144c2017-06-12 14:26:21 -040093enum SPIRVOperandType {
94 NUMBERID,
95 LITERAL_INTEGER,
96 LITERAL_STRING,
97 LITERAL_FLOAT
98};
99
100struct SPIRVOperand {
101 explicit SPIRVOperand(SPIRVOperandType Ty, uint32_t Num)
102 : Type(Ty), LiteralNum(1, Num) {}
103 explicit SPIRVOperand(SPIRVOperandType Ty, const char *Str)
104 : Type(Ty), LiteralStr(Str) {}
105 explicit SPIRVOperand(SPIRVOperandType Ty, StringRef Str)
106 : Type(Ty), LiteralStr(Str) {}
107 explicit SPIRVOperand(SPIRVOperandType Ty, ArrayRef<uint32_t> NumVec)
108 : Type(Ty), LiteralNum(NumVec.begin(), NumVec.end()) {}
109
James Price11010dc2019-12-19 13:53:09 -0500110 SPIRVOperandType getType() const { return Type; };
111 uint32_t getNumID() const { return LiteralNum[0]; };
112 std::string getLiteralStr() const { return LiteralStr; };
113 ArrayRef<uint32_t> getLiteralNum() const { return LiteralNum; };
David Neto22f144c2017-06-12 14:26:21 -0400114
David Neto87846742018-04-11 17:36:22 -0400115 uint32_t GetNumWords() const {
116 switch (Type) {
117 case NUMBERID:
118 return 1;
119 case LITERAL_INTEGER:
120 case LITERAL_FLOAT:
David Netoee2660d2018-06-28 16:31:29 -0400121 return uint32_t(LiteralNum.size());
David Neto87846742018-04-11 17:36:22 -0400122 case LITERAL_STRING:
123 // Account for the terminating null character.
David Netoee2660d2018-06-28 16:31:29 -0400124 return uint32_t((LiteralStr.size() + 4) / 4);
David Neto87846742018-04-11 17:36:22 -0400125 }
126 llvm_unreachable("Unhandled case in SPIRVOperand::GetNumWords()");
127 }
128
David Neto22f144c2017-06-12 14:26:21 -0400129private:
130 SPIRVOperandType Type;
131 std::string LiteralStr;
132 SmallVector<uint32_t, 4> LiteralNum;
133};
134
David Netoc6f3ab22018-04-06 18:02:31 -0400135class SPIRVOperandList {
136public:
David Netoef5ba2b2019-12-20 08:35:54 -0500137 typedef std::unique_ptr<SPIRVOperand> element_type;
138 typedef SmallVector<element_type, 8> container_type;
139 typedef container_type::iterator iterator;
David Netoc6f3ab22018-04-06 18:02:31 -0400140 SPIRVOperandList() {}
alan-bakerb6b09dc2018-11-08 16:59:28 -0500141 SPIRVOperandList(const SPIRVOperandList &other) = delete;
142 SPIRVOperandList(SPIRVOperandList &&other) {
David Netoc6f3ab22018-04-06 18:02:31 -0400143 contents_ = std::move(other.contents_);
144 other.contents_.clear();
145 }
David Netoef5ba2b2019-12-20 08:35:54 -0500146 iterator begin() { return contents_.begin(); }
147 iterator end() { return contents_.end(); }
148 operator ArrayRef<element_type>() { return contents_; }
149 void push_back(element_type op) { contents_.push_back(std::move(op)); }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500150 void clear() { contents_.clear(); }
David Netoc6f3ab22018-04-06 18:02:31 -0400151 size_t size() const { return contents_.size(); }
James Price11010dc2019-12-19 13:53:09 -0500152 const SPIRVOperand *operator[](size_t i) { return contents_[i].get(); }
David Netoc6f3ab22018-04-06 18:02:31 -0400153
David Netoef5ba2b2019-12-20 08:35:54 -0500154 const container_type &getOperands() const { return contents_; }
David Neto87846742018-04-11 17:36:22 -0400155
David Netoc6f3ab22018-04-06 18:02:31 -0400156private:
David Netoef5ba2b2019-12-20 08:35:54 -0500157 container_type contents_;
David Netoc6f3ab22018-04-06 18:02:31 -0400158};
159
James Price11010dc2019-12-19 13:53:09 -0500160SPIRVOperandList &operator<<(SPIRVOperandList &list,
David Netoef5ba2b2019-12-20 08:35:54 -0500161 std::unique_ptr<SPIRVOperand> elem) {
162 list.push_back(std::move(elem));
David Netoc6f3ab22018-04-06 18:02:31 -0400163 return list;
164}
165
David Netoef5ba2b2019-12-20 08:35:54 -0500166std::unique_ptr<SPIRVOperand> MkNum(uint32_t num) {
167 return std::make_unique<SPIRVOperand>(LITERAL_INTEGER, num);
David Netoc6f3ab22018-04-06 18:02:31 -0400168}
David Netoef5ba2b2019-12-20 08:35:54 -0500169std::unique_ptr<SPIRVOperand> MkInteger(ArrayRef<uint32_t> num_vec) {
170 return std::make_unique<SPIRVOperand>(LITERAL_INTEGER, num_vec);
David Neto257c3892018-04-11 13:19:45 -0400171}
David Netoef5ba2b2019-12-20 08:35:54 -0500172std::unique_ptr<SPIRVOperand> MkFloat(ArrayRef<uint32_t> num_vec) {
173 return std::make_unique<SPIRVOperand>(LITERAL_FLOAT, num_vec);
David Neto257c3892018-04-11 13:19:45 -0400174}
David Netoef5ba2b2019-12-20 08:35:54 -0500175std::unique_ptr<SPIRVOperand> MkId(uint32_t id) {
176 return std::make_unique<SPIRVOperand>(NUMBERID, id);
James Price11010dc2019-12-19 13:53:09 -0500177}
David Netoef5ba2b2019-12-20 08:35:54 -0500178std::unique_ptr<SPIRVOperand> MkString(StringRef str) {
179 return std::make_unique<SPIRVOperand>(LITERAL_STRING, str);
David Neto257c3892018-04-11 13:19:45 -0400180}
David Netoc6f3ab22018-04-06 18:02:31 -0400181
David Neto22f144c2017-06-12 14:26:21 -0400182struct SPIRVInstruction {
David Netoef5ba2b2019-12-20 08:35:54 -0500183 // Creates an instruction with an opcode and no result ID, and with the given
184 // operands. This computes its own word count. Takes ownership of the
185 // operands and clears |Ops|.
186 SPIRVInstruction(spv::Op Opc, SPIRVOperandList &Ops)
187 : WordCount(1), Opcode(static_cast<uint16_t>(Opc)), ResultID(0) {
James Price11010dc2019-12-19 13:53:09 -0500188 for (auto &operand : Ops) {
David Netoee2660d2018-06-28 16:31:29 -0400189 WordCount += uint16_t(operand->GetNumWords());
David Neto87846742018-04-11 17:36:22 -0400190 }
David Netoef5ba2b2019-12-20 08:35:54 -0500191 Operands.reserve(Ops.size());
192 for (auto &ptr : Ops) {
193 Operands.emplace_back(std::move(ptr));
194 ptr.reset(nullptr);
David Neto87846742018-04-11 17:36:22 -0400195 }
David Netoef5ba2b2019-12-20 08:35:54 -0500196 Ops.clear();
197 }
198 // Creates an instruction with an opcode and a no-zero result ID, and
199 // with the given operands. This computes its own word count. Takes ownership
200 // of the operands and clears |Ops|.
201 SPIRVInstruction(spv::Op Opc, uint32_t ResID, SPIRVOperandList &Ops)
202 : WordCount(2), Opcode(static_cast<uint16_t>(Opc)), ResultID(ResID) {
James Price11010dc2019-12-19 13:53:09 -0500203 for (auto &operand : Ops) {
David Neto87846742018-04-11 17:36:22 -0400204 WordCount += operand->GetNumWords();
205 }
David Netoef5ba2b2019-12-20 08:35:54 -0500206 Operands.reserve(Ops.size());
207 for (auto &ptr : Ops) {
208 Operands.emplace_back(std::move(ptr));
209 ptr.reset(nullptr);
210 }
211 if (ResID == 0) {
212 llvm_unreachable("Result ID of 0 was provided");
213 }
214 Ops.clear();
David Neto87846742018-04-11 17:36:22 -0400215 }
David Neto22f144c2017-06-12 14:26:21 -0400216
David Netoef5ba2b2019-12-20 08:35:54 -0500217 // Creates an instruction with an opcode and no result ID, and with the single
218 // operand. This computes its own word count.
219 SPIRVInstruction(spv::Op Opc, SPIRVOperandList::element_type operand)
220 : WordCount(1), Opcode(static_cast<uint16_t>(Opc)), ResultID(0) {
221 WordCount += operand->GetNumWords();
222 Operands.emplace_back(std::move(operand));
223 operand.reset(nullptr);
224 }
225 // Creates an instruction with an opcode and a non-zero result ID, and
226 // with the single operand. This computes its own word count.
227 SPIRVInstruction(spv::Op Opc, uint32_t ResID,
228 SPIRVOperandList::element_type operand)
229 : WordCount(2), Opcode(static_cast<uint16_t>(Opc)), ResultID(ResID) {
230 WordCount += operand->GetNumWords();
231 if (ResID == 0) {
232 llvm_unreachable("Result ID of 0 was provided");
233 }
234 Operands.emplace_back(std::move(operand));
235 operand.reset(nullptr);
236 }
237 // Creates an instruction with an opcode and a no-zero result ID, and no
238 // operands.
239 SPIRVInstruction(spv::Op Opc, uint32_t ResID)
240 : WordCount(2), Opcode(static_cast<uint16_t>(Opc)), ResultID(ResID) {
241 if (ResID == 0) {
242 llvm_unreachable("Result ID of 0 was provided");
243 }
244 }
245 // Creates an instruction with an opcode, no result ID, no type ID, and no
246 // operands.
247 SPIRVInstruction(spv::Op Opc)
248 : WordCount(1), Opcode(static_cast<uint16_t>(Opc)), ResultID(0) {}
249
David Netoee2660d2018-06-28 16:31:29 -0400250 uint32_t getWordCount() const { return WordCount; }
David Neto22f144c2017-06-12 14:26:21 -0400251 uint16_t getOpcode() const { return Opcode; }
252 uint32_t getResultID() const { return ResultID; }
David Netoef5ba2b2019-12-20 08:35:54 -0500253 ArrayRef<std::unique_ptr<SPIRVOperand>> getOperands() const {
James Price11010dc2019-12-19 13:53:09 -0500254 return Operands;
255 }
David Neto22f144c2017-06-12 14:26:21 -0400256
257private:
David Netoee2660d2018-06-28 16:31:29 -0400258 uint32_t WordCount; // Check the 16-bit bound at code generation time.
David Neto22f144c2017-06-12 14:26:21 -0400259 uint16_t Opcode;
260 uint32_t ResultID;
David Netoef5ba2b2019-12-20 08:35:54 -0500261 SmallVector<std::unique_ptr<SPIRVOperand>, 4> Operands;
David Neto22f144c2017-06-12 14:26:21 -0400262};
263
264struct SPIRVProducerPass final : public ModulePass {
David Neto22f144c2017-06-12 14:26:21 -0400265 typedef DenseMap<Type *, uint32_t> TypeMapType;
266 typedef UniqueVector<Type *> TypeList;
267 typedef DenseMap<Value *, uint32_t> ValueMapType;
David Netofb9a7972017-08-25 17:08:24 -0400268 typedef UniqueVector<Value *> ValueList;
David Neto22f144c2017-06-12 14:26:21 -0400269 typedef std::vector<std::pair<Value *, uint32_t>> EntryPointVecType;
270 typedef std::list<SPIRVInstruction *> SPIRVInstructionList;
David Neto87846742018-04-11 17:36:22 -0400271 // A vector of tuples, each of which is:
272 // - the LLVM instruction that we will later generate SPIR-V code for
273 // - where the SPIR-V instruction should be inserted
274 // - the result ID of the SPIR-V instruction
David Neto22f144c2017-06-12 14:26:21 -0400275 typedef std::vector<
276 std::tuple<Value *, SPIRVInstructionList::iterator, uint32_t>>
277 DeferredInstVecType;
278 typedef DenseMap<FunctionType *, std::pair<FunctionType *, uint32_t>>
279 GlobalConstFuncMapType;
280
David Neto44795152017-07-13 15:45:28 -0400281 explicit SPIRVProducerPass(
alan-bakerf5e5f692018-11-27 08:33:24 -0500282 raw_pwrite_stream &out,
283 std::vector<clspv::version0::DescriptorMapEntry> *descriptor_map_entries,
alan-baker00e7a582019-06-07 12:54:21 -0400284 ArrayRef<std::pair<unsigned, std::string>> samplerMap,
David Neto44795152017-07-13 15:45:28 -0400285 bool outputCInitList)
David Netoc2c368d2017-06-30 16:50:17 -0400286 : ModulePass(ID), samplerMap(samplerMap), out(out),
David Neto0676e6f2017-07-11 18:47:44 -0400287 binaryTempOut(binaryTempUnderlyingVector), binaryOut(&out),
alan-baker00e7a582019-06-07 12:54:21 -0400288 descriptorMapEntries(descriptor_map_entries),
David Neto0676e6f2017-07-11 18:47:44 -0400289 outputCInitList(outputCInitList), patchBoundOffset(0), nextID(1),
alan-baker5b86ed72019-02-15 08:26:50 -0500290 OpExtInstImportID(0), HasVariablePointersStorageBuffer(false),
291 HasVariablePointers(false), SamplerTy(nullptr), WorkgroupSizeValueID(0),
Kévin Petit89a525c2019-06-15 08:13:07 +0100292 WorkgroupSizeVarID(0), max_local_spec_id_(0) {}
David Neto22f144c2017-06-12 14:26:21 -0400293
James Price11010dc2019-12-19 13:53:09 -0500294 virtual ~SPIRVProducerPass() {
295 for (auto *Inst : SPIRVInsts) {
296 delete Inst;
297 }
298 }
299
David Neto22f144c2017-06-12 14:26:21 -0400300 void getAnalysisUsage(AnalysisUsage &AU) const override {
301 AU.addRequired<DominatorTreeWrapperPass>();
302 AU.addRequired<LoopInfoWrapperPass>();
303 }
304
305 virtual bool runOnModule(Module &module) override;
306
307 // output the SPIR-V header block
308 void outputHeader();
309
310 // patch the SPIR-V header block
311 void patchHeader();
312
313 uint32_t lookupType(Type *Ty) {
314 if (Ty->isPointerTy() &&
315 (Ty->getPointerAddressSpace() != AddressSpace::UniformConstant)) {
316 auto PointeeTy = Ty->getPointerElementType();
317 if (PointeeTy->isStructTy() &&
318 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
319 Ty = PointeeTy;
320 }
321 }
322
David Neto862b7d82018-06-14 18:48:37 -0400323 auto where = TypeMap.find(Ty);
324 if (where == TypeMap.end()) {
325 if (Ty) {
326 errs() << "Unhandled type " << *Ty << "\n";
327 } else {
328 errs() << "Unhandled type (null)\n";
329 }
David Netoe439d702018-03-23 13:14:08 -0700330 llvm_unreachable("\nUnhandled type!");
David Neto22f144c2017-06-12 14:26:21 -0400331 }
332
David Neto862b7d82018-06-14 18:48:37 -0400333 return where->second;
David Neto22f144c2017-06-12 14:26:21 -0400334 }
335 TypeMapType &getImageTypeMap() { return ImageTypeMap; }
alan-bakerabd82722019-12-03 17:14:51 -0500336 TypeList &getImageTypeList() { return ImageTypeList; }
David Neto22f144c2017-06-12 14:26:21 -0400337 TypeList &getTypeList() { return Types; };
338 ValueList &getConstantList() { return Constants; };
339 ValueMapType &getValueMap() { return ValueMap; }
340 ValueMapType &getAllocatedValueMap() { return AllocatedValueMap; }
341 SPIRVInstructionList &getSPIRVInstList() { return SPIRVInsts; };
David Neto22f144c2017-06-12 14:26:21 -0400342 EntryPointVecType &getEntryPointVec() { return EntryPointVec; };
343 DeferredInstVecType &getDeferredInstVec() { return DeferredInstVec; };
344 ValueList &getEntryPointInterfacesVec() { return EntryPointInterfacesVec; };
345 uint32_t &getOpExtInstImportID() { return OpExtInstImportID; };
346 std::vector<uint32_t> &getBuiltinDimVec() { return BuiltinDimensionVec; };
SJW2c317da2020-03-23 07:39:13 -0500347
alan-baker5b86ed72019-02-15 08:26:50 -0500348 bool hasVariablePointersStorageBuffer() {
349 return HasVariablePointersStorageBuffer;
350 }
351 void setVariablePointersStorageBuffer(bool Val) {
352 HasVariablePointersStorageBuffer = Val;
353 }
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400354 bool hasVariablePointers() { return HasVariablePointers; };
David Neto22f144c2017-06-12 14:26:21 -0400355 void setVariablePointers(bool Val) { HasVariablePointers = Val; };
alan-bakerb6b09dc2018-11-08 16:59:28 -0500356 ArrayRef<std::pair<unsigned, std::string>> &getSamplerMap() {
357 return samplerMap;
358 }
David Neto22f144c2017-06-12 14:26:21 -0400359 GlobalConstFuncMapType &getGlobalConstFuncTypeMap() {
360 return GlobalConstFuncTypeMap;
361 }
362 SmallPtrSet<Value *, 16> &getGlobalConstArgSet() {
363 return GlobalConstArgumentSet;
364 }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500365 TypeList &getTypesNeedingArrayStride() { return TypesNeedingArrayStride; }
David Neto22f144c2017-06-12 14:26:21 -0400366
David Netoc6f3ab22018-04-06 18:02:31 -0400367 void GenerateLLVMIRInfo(Module &M, const DataLayout &DL);
alan-bakerb6b09dc2018-11-08 16:59:28 -0500368 // Populate GlobalConstFuncTypeMap. Also, if module-scope __constant will
369 // *not* be converted to a storage buffer, replace each such global variable
370 // with one in the storage class expecgted by SPIR-V.
David Neto862b7d82018-06-14 18:48:37 -0400371 void FindGlobalConstVars(Module &M, const DataLayout &DL);
372 // Populate ResourceVarInfoList, FunctionToResourceVarsMap, and
373 // ModuleOrderedResourceVars.
374 void FindResourceVars(Module &M, const DataLayout &DL);
Alan Baker202c8c72018-08-13 13:47:44 -0400375 void FindWorkgroupVars(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400376 bool FindExtInst(Module &M);
377 void FindTypePerGlobalVar(GlobalVariable &GV);
378 void FindTypePerFunc(Function &F);
David Neto862b7d82018-06-14 18:48:37 -0400379 void FindTypesForSamplerMap(Module &M);
380 void FindTypesForResourceVars(Module &M);
alan-bakerb6b09dc2018-11-08 16:59:28 -0500381 // Inserts |Ty| and relevant sub-types into the |Types| member, indicating
382 // that |Ty| and its subtypes will need a corresponding SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400383 void FindType(Type *Ty);
384 void FindConstantPerGlobalVar(GlobalVariable &GV);
385 void FindConstantPerFunc(Function &F);
386 void FindConstant(Value *V);
387 void GenerateExtInstImport();
David Neto19a1bad2017-08-25 15:01:41 -0400388 // Generates instructions for SPIR-V types corresponding to the LLVM types
389 // saved in the |Types| member. A type follows its subtypes. IDs are
390 // allocated sequentially starting with the current value of nextID, and
391 // with a type following its subtypes. Also updates nextID to just beyond
392 // the last generated ID.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500393 void GenerateSPIRVTypes(LLVMContext &context, Module &module);
David Neto22f144c2017-06-12 14:26:21 -0400394 void GenerateSPIRVConstants();
David Neto5c22a252018-03-15 16:07:41 -0400395 void GenerateModuleInfo(Module &M);
Kévin Petitbbbda972020-03-03 19:16:31 +0000396 void GeneratePushConstantDescriptormapEntries(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400397 void GenerateGlobalVar(GlobalVariable &GV);
David Netoc6f3ab22018-04-06 18:02:31 -0400398 void GenerateWorkgroupVars();
David Neto862b7d82018-06-14 18:48:37 -0400399 // Generate descriptor map entries for resource variables associated with
400 // arguments to F.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500401 void GenerateDescriptorMapInfo(const DataLayout &DL, Function &F);
David Neto22f144c2017-06-12 14:26:21 -0400402 void GenerateSamplers(Module &M);
David Neto862b7d82018-06-14 18:48:37 -0400403 // Generate OpVariables for %clspv.resource.var.* calls.
404 void GenerateResourceVars(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400405 void GenerateFuncPrologue(Function &F);
406 void GenerateFuncBody(Function &F);
David Netob6e2e062018-04-25 10:32:06 -0400407 void GenerateEntryPointInitialStores();
David Neto22f144c2017-06-12 14:26:21 -0400408 spv::Op GetSPIRVCmpOpcode(CmpInst *CmpI);
409 spv::Op GetSPIRVCastOpcode(Instruction &I);
410 spv::Op GetSPIRVBinaryOpcode(Instruction &I);
411 void GenerateInstruction(Instruction &I);
412 void GenerateFuncEpilogue();
413 void HandleDeferredInstruction();
alan-bakerb6b09dc2018-11-08 16:59:28 -0500414 void HandleDeferredDecorations(const DataLayout &DL);
David Neto22f144c2017-06-12 14:26:21 -0400415 bool is4xi8vec(Type *Ty) const;
416 spv::StorageClass GetStorageClass(unsigned AddrSpace) const;
David Neto862b7d82018-06-14 18:48:37 -0400417 spv::StorageClass GetStorageClassForArgKind(clspv::ArgKind arg_kind) const;
David Neto22f144c2017-06-12 14:26:21 -0400418 spv::BuiltIn GetBuiltin(StringRef globalVarName) const;
David Neto3fbb4072017-10-16 11:28:14 -0400419 // Returns the GLSL extended instruction enum that the given function
420 // call maps to. If none, then returns the 0 value, i.e. GLSLstd4580Bad.
David Neto22f144c2017-06-12 14:26:21 -0400421 glsl::ExtInst getExtInstEnum(StringRef Name);
David Neto3fbb4072017-10-16 11:28:14 -0400422 // Returns the GLSL extended instruction enum indirectly used by the given
423 // function. That is, to implement the given function, we use an extended
424 // instruction plus one more instruction. If none, then returns the 0 value,
425 // i.e. GLSLstd4580Bad.
426 glsl::ExtInst getIndirectExtInstEnum(StringRef Name);
427 // Returns the single GLSL extended instruction used directly or
428 // indirectly by the given function call.
429 glsl::ExtInst getDirectOrIndirectExtInstEnum(StringRef Name);
David Neto22f144c2017-06-12 14:26:21 -0400430 void WriteOneWord(uint32_t Word);
431 void WriteResultID(SPIRVInstruction *Inst);
432 void WriteWordCountAndOpcode(SPIRVInstruction *Inst);
David Netoef5ba2b2019-12-20 08:35:54 -0500433 void WriteOperand(const std::unique_ptr<SPIRVOperand> &Op);
David Neto22f144c2017-06-12 14:26:21 -0400434 void WriteSPIRVBinary();
435
Alan Baker9bf93fb2018-08-28 16:59:26 -0400436 // Returns true if |type| is compatible with OpConstantNull.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500437 bool IsTypeNullable(const Type *type) const;
Alan Baker9bf93fb2018-08-28 16:59:26 -0400438
Alan Bakerfcda9482018-10-02 17:09:59 -0400439 // Populate UBO remapped type maps.
440 void PopulateUBOTypeMaps(Module &module);
441
alan-baker06cad652019-12-03 17:56:47 -0500442 // Populate the merge and continue block maps.
443 void PopulateStructuredCFGMaps(Module &module);
444
Alan Bakerfcda9482018-10-02 17:09:59 -0400445 // Wrapped methods of DataLayout accessors. If |type| was remapped for UBOs,
446 // uses the internal map, otherwise it falls back on the data layout.
447 uint64_t GetTypeSizeInBits(Type *type, const DataLayout &DL);
448 uint64_t GetTypeStoreSize(Type *type, const DataLayout &DL);
449 uint64_t GetTypeAllocSize(Type *type, const DataLayout &DL);
Kévin Petitbbbda972020-03-03 19:16:31 +0000450 uint32_t GetExplicitLayoutStructMemberOffset(StructType *type,
451 unsigned member,
452 const DataLayout &DL);
Alan Bakerfcda9482018-10-02 17:09:59 -0400453
alan-baker5b86ed72019-02-15 08:26:50 -0500454 // Returns the base pointer of |v|.
455 Value *GetBasePointer(Value *v);
456
457 // Sets |HasVariablePointersStorageBuffer| or |HasVariablePointers| base on
458 // |address_space|.
459 void setVariablePointersCapabilities(unsigned address_space);
460
461 // Returns true if |lhs| and |rhs| represent the same resource or workgroup
462 // variable.
463 bool sameResource(Value *lhs, Value *rhs) const;
464
465 // Returns true if |inst| is phi or select that selects from the same
466 // structure (or null).
467 bool selectFromSameObject(Instruction *inst);
468
alan-bakere9308012019-03-15 10:25:13 -0400469 // Returns true if |Arg| is called with a coherent resource.
470 bool CalledWithCoherentResource(Argument &Arg);
471
David Neto22f144c2017-06-12 14:26:21 -0400472private:
473 static char ID;
David Neto44795152017-07-13 15:45:28 -0400474 ArrayRef<std::pair<unsigned, std::string>> samplerMap;
David Neto22f144c2017-06-12 14:26:21 -0400475 raw_pwrite_stream &out;
David Neto0676e6f2017-07-11 18:47:44 -0400476
477 // TODO(dneto): Wouldn't it be better to always just emit a binary, and then
478 // convert to other formats on demand?
479
480 // When emitting a C initialization list, the WriteSPIRVBinary method
481 // will actually write its words to this vector via binaryTempOut.
482 SmallVector<char, 100> binaryTempUnderlyingVector;
483 raw_svector_ostream binaryTempOut;
484
485 // Binary output writes to this stream, which might be |out| or
486 // |binaryTempOut|. It's the latter when we really want to write a C
487 // initializer list.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400488 raw_pwrite_stream *binaryOut;
alan-bakerf5e5f692018-11-27 08:33:24 -0500489 std::vector<version0::DescriptorMapEntry> *descriptorMapEntries;
David Neto0676e6f2017-07-11 18:47:44 -0400490 const bool outputCInitList; // If true, output look like {0x7023, ... , 5}
David Neto22f144c2017-06-12 14:26:21 -0400491 uint64_t patchBoundOffset;
492 uint32_t nextID;
493
alan-bakerf67468c2019-11-25 15:51:49 -0500494 // ID for OpTypeInt 32 1.
495 uint32_t int32ID = 0;
496 // ID for OpTypeVector %int 4.
497 uint32_t v4int32ID = 0;
498
David Neto19a1bad2017-08-25 15:01:41 -0400499 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400500 TypeMapType TypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400501 // Maps an LLVM image type to its SPIR-V ID.
David Neto22f144c2017-06-12 14:26:21 -0400502 TypeMapType ImageTypeMap;
alan-bakerabd82722019-12-03 17:14:51 -0500503 // A unique-vector of LLVM image types. This list is used to provide
504 // deterministic traversal of image types.
505 TypeList ImageTypeList;
David Neto19a1bad2017-08-25 15:01:41 -0400506 // A unique-vector of LLVM types that map to a SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400507 TypeList Types;
508 ValueList Constants;
David Neto19a1bad2017-08-25 15:01:41 -0400509 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400510 ValueMapType ValueMap;
511 ValueMapType AllocatedValueMap;
512 SPIRVInstructionList SPIRVInsts;
David Neto862b7d82018-06-14 18:48:37 -0400513
David Neto22f144c2017-06-12 14:26:21 -0400514 EntryPointVecType EntryPointVec;
515 DeferredInstVecType DeferredInstVec;
516 ValueList EntryPointInterfacesVec;
517 uint32_t OpExtInstImportID;
518 std::vector<uint32_t> BuiltinDimensionVec;
alan-baker5b86ed72019-02-15 08:26:50 -0500519 bool HasVariablePointersStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -0400520 bool HasVariablePointers;
521 Type *SamplerTy;
alan-baker09cb9802019-12-10 13:16:27 -0500522 DenseMap<unsigned, unsigned> SamplerLiteralToIDMap;
David Netoc77d9e22018-03-24 06:30:28 -0700523
524 // If a function F has a pointer-to-__constant parameter, then this variable
David Neto9ed8e2f2018-03-24 06:47:24 -0700525 // will map F's type to (G, index of the parameter), where in a first phase
526 // G is F's type. During FindTypePerFunc, G will be changed to F's type
527 // but replacing the pointer-to-constant parameter with
528 // pointer-to-ModuleScopePrivate.
David Netoc77d9e22018-03-24 06:30:28 -0700529 // TODO(dneto): This doesn't seem general enough? A function might have
530 // more than one such parameter.
David Neto22f144c2017-06-12 14:26:21 -0400531 GlobalConstFuncMapType GlobalConstFuncTypeMap;
532 SmallPtrSet<Value *, 16> GlobalConstArgumentSet;
David Neto1a1a0582017-07-07 12:01:44 -0400533 // An ordered set of pointer types of Base arguments to OpPtrAccessChain,
David Neto85082642018-03-24 06:55:20 -0700534 // or array types, and which point into transparent memory (StorageBuffer
535 // storage class). These will require an ArrayStride decoration.
David Neto1a1a0582017-07-07 12:01:44 -0400536 // See SPV_KHR_variable_pointers rev 13.
David Neto85082642018-03-24 06:55:20 -0700537 TypeList TypesNeedingArrayStride;
David Netoa60b00b2017-09-15 16:34:09 -0400538
539 // This is truly ugly, but works around what look like driver bugs.
540 // For get_local_size, an earlier part of the flow has created a module-scope
541 // variable in Private address space to hold the value for the workgroup
542 // size. Its intializer is a uint3 value marked as builtin WorkgroupSize.
543 // When this is present, save the IDs of the initializer value and variable
544 // in these two variables. We only ever do a vector load from it, and
545 // when we see one of those, substitute just the value of the intializer.
546 // This mimics what Glslang does, and that's what drivers are used to.
David Neto66cfe642018-03-24 06:13:56 -0700547 // TODO(dneto): Remove this once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -0400548 uint32_t WorkgroupSizeValueID;
549 uint32_t WorkgroupSizeVarID;
David Neto26aaf622017-10-23 18:11:53 -0400550
David Neto862b7d82018-06-14 18:48:37 -0400551 // Bookkeeping for mapping kernel arguments to resource variables.
552 struct ResourceVarInfo {
553 ResourceVarInfo(int index_arg, unsigned set_arg, unsigned binding_arg,
alan-bakere9308012019-03-15 10:25:13 -0400554 Function *fn, clspv::ArgKind arg_kind_arg, int coherent_arg)
David Neto862b7d82018-06-14 18:48:37 -0400555 : index(index_arg), descriptor_set(set_arg), binding(binding_arg),
alan-bakere9308012019-03-15 10:25:13 -0400556 var_fn(fn), arg_kind(arg_kind_arg), coherent(coherent_arg),
David Neto862b7d82018-06-14 18:48:37 -0400557 addr_space(fn->getReturnType()->getPointerAddressSpace()) {}
558 const int index; // Index into ResourceVarInfoList
559 const unsigned descriptor_set;
560 const unsigned binding;
561 Function *const var_fn; // The @clspv.resource.var.* function.
562 const clspv::ArgKind arg_kind;
alan-bakere9308012019-03-15 10:25:13 -0400563 const int coherent;
David Neto862b7d82018-06-14 18:48:37 -0400564 const unsigned addr_space; // The LLVM address space
565 // The SPIR-V ID of the OpVariable. Not populated at construction time.
566 uint32_t var_id = 0;
567 };
568 // A list of resource var info. Each one correponds to a module-scope
569 // resource variable we will have to create. Resource var indices are
570 // indices into this vector.
571 SmallVector<std::unique_ptr<ResourceVarInfo>, 8> ResourceVarInfoList;
572 // This is a vector of pointers of all the resource vars, but ordered by
573 // kernel function, and then by argument.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500574 UniqueVector<ResourceVarInfo *> ModuleOrderedResourceVars;
David Neto862b7d82018-06-14 18:48:37 -0400575 // Map a function to the ordered list of resource variables it uses, one for
576 // each argument. If an argument does not use a resource variable, it
577 // will have a null pointer entry.
578 using FunctionToResourceVarsMapType =
579 DenseMap<Function *, SmallVector<ResourceVarInfo *, 8>>;
580 FunctionToResourceVarsMapType FunctionToResourceVarsMap;
581
582 // What LLVM types map to SPIR-V types needing layout? These are the
583 // arrays and structures supporting storage buffers and uniform buffers.
584 TypeList TypesNeedingLayout;
585 // What LLVM struct types map to a SPIR-V struct type with Block decoration?
586 UniqueVector<StructType *> StructTypesNeedingBlock;
587 // For a call that represents a load from an opaque type (samplers, images),
588 // map it to the variable id it should load from.
589 DenseMap<CallInst *, uint32_t> ResourceVarDeferredLoadCalls;
David Neto85082642018-03-24 06:55:20 -0700590
Alan Baker202c8c72018-08-13 13:47:44 -0400591 // One larger than the maximum used SpecId for pointer-to-local arguments.
592 int max_local_spec_id_;
David Netoc6f3ab22018-04-06 18:02:31 -0400593 // An ordered list of the kernel arguments of type pointer-to-local.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500594 using LocalArgList = SmallVector<Argument *, 8>;
David Netoc6f3ab22018-04-06 18:02:31 -0400595 LocalArgList LocalArgs;
596 // Information about a pointer-to-local argument.
597 struct LocalArgInfo {
598 // The SPIR-V ID of the array variable.
599 uint32_t variable_id;
600 // The element type of the
alan-bakerb6b09dc2018-11-08 16:59:28 -0500601 Type *elem_type;
David Netoc6f3ab22018-04-06 18:02:31 -0400602 // The ID of the array type.
603 uint32_t array_size_id;
604 // The ID of the array type.
605 uint32_t array_type_id;
606 // The ID of the pointer to the array type.
607 uint32_t ptr_array_type_id;
David Netoc6f3ab22018-04-06 18:02:31 -0400608 // The specialization constant ID of the array size.
609 int spec_id;
610 };
Alan Baker202c8c72018-08-13 13:47:44 -0400611 // A mapping from Argument to its assigned SpecId.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500612 DenseMap<const Argument *, int> LocalArgSpecIds;
Alan Baker202c8c72018-08-13 13:47:44 -0400613 // A mapping from SpecId to its LocalArgInfo.
614 DenseMap<int, LocalArgInfo> LocalSpecIdInfoMap;
Alan Bakerfcda9482018-10-02 17:09:59 -0400615 // A mapping from a remapped type to its real offsets.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500616 DenseMap<Type *, std::vector<uint32_t>> RemappedUBOTypeOffsets;
Alan Bakerfcda9482018-10-02 17:09:59 -0400617 // A mapping from a remapped type to its real sizes.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500618 DenseMap<Type *, std::tuple<uint64_t, uint64_t, uint64_t>>
619 RemappedUBOTypeSizes;
alan-baker06cad652019-12-03 17:56:47 -0500620
621 // Maps basic block to its merge block.
622 DenseMap<BasicBlock *, BasicBlock *> MergeBlocks;
623 // Maps basic block to its continue block.
624 DenseMap<BasicBlock *, BasicBlock *> ContinueBlocks;
David Neto22f144c2017-06-12 14:26:21 -0400625};
626
627char SPIRVProducerPass::ID;
David Netoc6f3ab22018-04-06 18:02:31 -0400628
alan-bakerb6b09dc2018-11-08 16:59:28 -0500629} // namespace
David Neto22f144c2017-06-12 14:26:21 -0400630
631namespace clspv {
alan-bakerf5e5f692018-11-27 08:33:24 -0500632ModulePass *createSPIRVProducerPass(
633 raw_pwrite_stream &out,
634 std::vector<version0::DescriptorMapEntry> *descriptor_map_entries,
alan-baker00e7a582019-06-07 12:54:21 -0400635 ArrayRef<std::pair<unsigned, std::string>> samplerMap,
alan-bakerf5e5f692018-11-27 08:33:24 -0500636 bool outputCInitList) {
637 return new SPIRVProducerPass(out, descriptor_map_entries, samplerMap,
alan-baker00e7a582019-06-07 12:54:21 -0400638 outputCInitList);
David Neto22f144c2017-06-12 14:26:21 -0400639}
David Netoc2c368d2017-06-30 16:50:17 -0400640} // namespace clspv
David Neto22f144c2017-06-12 14:26:21 -0400641
642bool SPIRVProducerPass::runOnModule(Module &module) {
alan-baker5ed87542020-03-23 11:05:22 -0400643 if (ShowProducerIR) {
644 llvm::outs() << module << "\n";
645 }
David Neto0676e6f2017-07-11 18:47:44 -0400646 binaryOut = outputCInitList ? &binaryTempOut : &out;
647
Alan Bakerfcda9482018-10-02 17:09:59 -0400648 PopulateUBOTypeMaps(module);
alan-baker06cad652019-12-03 17:56:47 -0500649 PopulateStructuredCFGMaps(module);
Alan Bakerfcda9482018-10-02 17:09:59 -0400650
David Neto22f144c2017-06-12 14:26:21 -0400651 // SPIR-V always begins with its header information
652 outputHeader();
653
David Netoc6f3ab22018-04-06 18:02:31 -0400654 const DataLayout &DL = module.getDataLayout();
655
David Neto22f144c2017-06-12 14:26:21 -0400656 // Gather information from the LLVM IR that we require.
David Netoc6f3ab22018-04-06 18:02:31 -0400657 GenerateLLVMIRInfo(module, DL);
David Neto22f144c2017-06-12 14:26:21 -0400658
David Neto22f144c2017-06-12 14:26:21 -0400659 // Collect information on global variables too.
660 for (GlobalVariable &GV : module.globals()) {
661 // If the GV is one of our special __spirv_* variables, remove the
662 // initializer as it was only placed there to force LLVM to not throw the
663 // value away.
Kévin Petitbbbda972020-03-03 19:16:31 +0000664 if (GV.getName().startswith("__spirv_") ||
665 GV.getAddressSpace() == clspv::AddressSpace::PushConstant) {
David Neto22f144c2017-06-12 14:26:21 -0400666 GV.setInitializer(nullptr);
667 }
668
669 // Collect types' information from global variable.
670 FindTypePerGlobalVar(GV);
671
672 // Collect constant information from global variable.
673 FindConstantPerGlobalVar(GV);
674
675 // If the variable is an input, entry points need to know about it.
676 if (AddressSpace::Input == GV.getType()->getPointerAddressSpace()) {
David Netofb9a7972017-08-25 17:08:24 -0400677 getEntryPointInterfacesVec().insert(&GV);
David Neto22f144c2017-06-12 14:26:21 -0400678 }
679 }
680
681 // If there are extended instructions, generate OpExtInstImport.
682 if (FindExtInst(module)) {
683 GenerateExtInstImport();
684 }
685
686 // Generate SPIRV instructions for types.
Alan Bakerfcda9482018-10-02 17:09:59 -0400687 GenerateSPIRVTypes(module.getContext(), module);
David Neto22f144c2017-06-12 14:26:21 -0400688
689 // Generate SPIRV constants.
690 GenerateSPIRVConstants();
691
alan-baker09cb9802019-12-10 13:16:27 -0500692 // Generate literal samplers if necessary.
693 GenerateSamplers(module);
David Neto22f144c2017-06-12 14:26:21 -0400694
Kévin Petitbbbda972020-03-03 19:16:31 +0000695 // Generate descriptor map entries for all push constants
696 GeneratePushConstantDescriptormapEntries(module);
697
David Neto22f144c2017-06-12 14:26:21 -0400698 // Generate SPIRV variables.
699 for (GlobalVariable &GV : module.globals()) {
700 GenerateGlobalVar(GV);
701 }
David Neto862b7d82018-06-14 18:48:37 -0400702 GenerateResourceVars(module);
David Netoc6f3ab22018-04-06 18:02:31 -0400703 GenerateWorkgroupVars();
David Neto22f144c2017-06-12 14:26:21 -0400704
705 // Generate SPIRV instructions for each function.
706 for (Function &F : module) {
707 if (F.isDeclaration()) {
708 continue;
709 }
710
David Neto862b7d82018-06-14 18:48:37 -0400711 GenerateDescriptorMapInfo(DL, F);
712
David Neto22f144c2017-06-12 14:26:21 -0400713 // Generate Function Prologue.
714 GenerateFuncPrologue(F);
715
716 // Generate SPIRV instructions for function body.
717 GenerateFuncBody(F);
718
719 // Generate Function Epilogue.
720 GenerateFuncEpilogue();
721 }
722
723 HandleDeferredInstruction();
David Neto1a1a0582017-07-07 12:01:44 -0400724 HandleDeferredDecorations(DL);
David Neto22f144c2017-06-12 14:26:21 -0400725
726 // Generate SPIRV module information.
David Neto5c22a252018-03-15 16:07:41 -0400727 GenerateModuleInfo(module);
David Neto22f144c2017-06-12 14:26:21 -0400728
alan-baker00e7a582019-06-07 12:54:21 -0400729 WriteSPIRVBinary();
David Neto22f144c2017-06-12 14:26:21 -0400730
731 // We need to patch the SPIR-V header to set bound correctly.
732 patchHeader();
David Neto0676e6f2017-07-11 18:47:44 -0400733
734 if (outputCInitList) {
735 bool first = true;
David Neto0676e6f2017-07-11 18:47:44 -0400736 std::ostringstream os;
737
David Neto57fb0b92017-08-04 15:35:09 -0400738 auto emit_word = [&os, &first](uint32_t word) {
David Neto0676e6f2017-07-11 18:47:44 -0400739 if (!first)
David Neto57fb0b92017-08-04 15:35:09 -0400740 os << ",\n";
741 os << word;
David Neto0676e6f2017-07-11 18:47:44 -0400742 first = false;
743 };
744
745 os << "{";
David Neto57fb0b92017-08-04 15:35:09 -0400746 const std::string str(binaryTempOut.str());
747 for (unsigned i = 0; i < str.size(); i += 4) {
748 const uint32_t a = static_cast<unsigned char>(str[i]);
749 const uint32_t b = static_cast<unsigned char>(str[i + 1]);
750 const uint32_t c = static_cast<unsigned char>(str[i + 2]);
751 const uint32_t d = static_cast<unsigned char>(str[i + 3]);
752 emit_word(a | (b << 8) | (c << 16) | (d << 24));
David Neto0676e6f2017-07-11 18:47:44 -0400753 }
754 os << "}\n";
755 out << os.str();
756 }
757
David Neto22f144c2017-06-12 14:26:21 -0400758 return false;
759}
760
761void SPIRVProducerPass::outputHeader() {
alan-baker00e7a582019-06-07 12:54:21 -0400762 binaryOut->write(reinterpret_cast<const char *>(&spv::MagicNumber),
763 sizeof(spv::MagicNumber));
alan-bakere0902602020-03-23 08:43:40 -0400764 const uint32_t spv_version = 0x10000; // SPIR-V 1.0
765 binaryOut->write(reinterpret_cast<const char *>(&spv_version),
766 sizeof(spv_version));
David Neto22f144c2017-06-12 14:26:21 -0400767
alan-baker0c18ab02019-06-12 10:23:21 -0400768 // use Google's vendor ID
769 const uint32_t vendor = 21 << 16;
alan-baker00e7a582019-06-07 12:54:21 -0400770 binaryOut->write(reinterpret_cast<const char *>(&vendor), sizeof(vendor));
David Neto22f144c2017-06-12 14:26:21 -0400771
alan-baker00e7a582019-06-07 12:54:21 -0400772 // we record where we need to come back to and patch in the bound value
773 patchBoundOffset = binaryOut->tell();
David Neto22f144c2017-06-12 14:26:21 -0400774
alan-baker00e7a582019-06-07 12:54:21 -0400775 // output a bad bound for now
776 binaryOut->write(reinterpret_cast<const char *>(&nextID), sizeof(nextID));
David Neto22f144c2017-06-12 14:26:21 -0400777
alan-baker00e7a582019-06-07 12:54:21 -0400778 // output the schema (reserved for use and must be 0)
779 const uint32_t schema = 0;
780 binaryOut->write(reinterpret_cast<const char *>(&schema), sizeof(schema));
David Neto22f144c2017-06-12 14:26:21 -0400781}
782
783void SPIRVProducerPass::patchHeader() {
alan-baker00e7a582019-06-07 12:54:21 -0400784 // for a binary we just write the value of nextID over bound
785 binaryOut->pwrite(reinterpret_cast<char *>(&nextID), sizeof(nextID),
786 patchBoundOffset);
David Neto22f144c2017-06-12 14:26:21 -0400787}
788
David Netoc6f3ab22018-04-06 18:02:31 -0400789void SPIRVProducerPass::GenerateLLVMIRInfo(Module &M, const DataLayout &DL) {
David Neto22f144c2017-06-12 14:26:21 -0400790 // This function generates LLVM IR for function such as global variable for
791 // argument, constant and pointer type for argument access. These information
792 // is artificial one because we need Vulkan SPIR-V output. This function is
793 // executed ahead of FindType and FindConstant.
David Neto22f144c2017-06-12 14:26:21 -0400794 LLVMContext &Context = M.getContext();
795
David Neto862b7d82018-06-14 18:48:37 -0400796 FindGlobalConstVars(M, DL);
David Neto5c22a252018-03-15 16:07:41 -0400797
David Neto862b7d82018-06-14 18:48:37 -0400798 FindResourceVars(M, DL);
David Neto22f144c2017-06-12 14:26:21 -0400799
800 bool HasWorkGroupBuiltin = false;
801 for (GlobalVariable &GV : M.globals()) {
802 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
803 if (spv::BuiltInWorkgroupSize == BuiltinType) {
804 HasWorkGroupBuiltin = true;
805 }
806 }
807
David Neto862b7d82018-06-14 18:48:37 -0400808 FindTypesForSamplerMap(M);
809 FindTypesForResourceVars(M);
Alan Baker202c8c72018-08-13 13:47:44 -0400810 FindWorkgroupVars(M);
David Neto22f144c2017-06-12 14:26:21 -0400811
812 for (Function &F : M) {
Kévin Petitabef4522019-03-27 13:08:01 +0000813 if (F.isDeclaration()) {
David Neto22f144c2017-06-12 14:26:21 -0400814 continue;
815 }
816
817 for (BasicBlock &BB : F) {
818 for (Instruction &I : BB) {
819 if (I.getOpcode() == Instruction::ZExt ||
820 I.getOpcode() == Instruction::SExt ||
821 I.getOpcode() == Instruction::UIToFP) {
822 // If there is zext with i1 type, it will be changed to OpSelect. The
823 // OpSelect needs constant 0 and 1 so the constants are added here.
824
825 auto OpTy = I.getOperand(0)->getType();
826
Kévin Petit24272b62018-10-18 19:16:12 +0000827 if (OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -0400828 if (I.getOpcode() == Instruction::ZExt) {
David Neto22f144c2017-06-12 14:26:21 -0400829 FindConstant(Constant::getNullValue(I.getType()));
Kévin Petit7bfb8992019-02-26 13:45:08 +0000830 FindConstant(ConstantInt::get(I.getType(), 1));
David Neto22f144c2017-06-12 14:26:21 -0400831 } else if (I.getOpcode() == Instruction::SExt) {
David Neto22f144c2017-06-12 14:26:21 -0400832 FindConstant(Constant::getNullValue(I.getType()));
Kévin Petit7bfb8992019-02-26 13:45:08 +0000833 FindConstant(ConstantInt::getSigned(I.getType(), -1));
David Neto22f144c2017-06-12 14:26:21 -0400834 } else {
835 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
836 FindConstant(ConstantFP::get(Context, APFloat(1.0f)));
837 }
838 }
839 } else if (CallInst *Call = dyn_cast<CallInst>(&I)) {
David Neto862b7d82018-06-14 18:48:37 -0400840 StringRef callee_name = Call->getCalledFunction()->getName();
David Neto22f144c2017-06-12 14:26:21 -0400841
842 // Handle image type specially.
SJW173c7e92020-03-16 08:44:47 -0500843 if (IsImageBuiltin(callee_name)) {
David Neto22f144c2017-06-12 14:26:21 -0400844 TypeMapType &OpImageTypeMap = getImageTypeMap();
845 Type *ImageTy =
846 Call->getArgOperand(0)->getType()->getPointerElementType();
847 OpImageTypeMap[ImageTy] = 0;
alan-bakerabd82722019-12-03 17:14:51 -0500848 getImageTypeList().insert(ImageTy);
alan-baker75090e42020-02-20 11:21:04 -0500849 }
David Neto22f144c2017-06-12 14:26:21 -0400850
SJW173c7e92020-03-16 08:44:47 -0500851 if (IsSampledImageRead(callee_name)) {
alan-bakerf67468c2019-11-25 15:51:49 -0500852 // All sampled reads need a floating point 0 for the Lod operand.
David Neto22f144c2017-06-12 14:26:21 -0400853 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
SJW2c317da2020-03-23 07:39:13 -0500854 } else if (IsUnsampledImageRead(callee_name)) {
alan-baker75090e42020-02-20 11:21:04 -0500855 // All unsampled reads need an integer 0 for the Lod operand.
856 FindConstant(ConstantInt::get(Context, APInt(32, 0)));
SJW2c317da2020-03-23 07:39:13 -0500857 } else if (IsImageQuery(callee_name)) {
alan-bakerce179f12019-12-06 19:02:22 -0500858 Type *ImageTy = Call->getOperand(0)->getType();
859 const uint32_t dim = ImageDimensionality(ImageTy);
alan-baker7150a1d2020-02-25 08:31:06 -0500860 uint32_t components =
861 dim + (clspv::IsArrayImageType(ImageTy) ? 1 : 0);
alan-bakerce179f12019-12-06 19:02:22 -0500862 if (components > 1) {
863 // OpImageQuerySize* return |components| components.
864 FindType(VectorType::get(Type::getInt32Ty(Context), components));
865 if (dim == 3 && IsGetImageDim(callee_name)) {
866 // get_image_dim for 3D images returns an int4.
867 FindType(
868 VectorType::get(Type::getInt32Ty(Context), components + 1));
869 }
870 }
871
SJW173c7e92020-03-16 08:44:47 -0500872 if (IsSampledImageType(ImageTy)) {
alan-bakerce179f12019-12-06 19:02:22 -0500873 // All sampled image queries need a integer 0 for the Lod
874 // operand.
875 FindConstant(ConstantInt::get(Context, APInt(32, 0)));
876 }
David Neto5c22a252018-03-15 16:07:41 -0400877 }
David Neto22f144c2017-06-12 14:26:21 -0400878 }
879 }
880 }
881
Kévin Petitabef4522019-03-27 13:08:01 +0000882 // More things to do on kernel functions
883 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
884 if (const MDNode *MD =
885 dyn_cast<Function>(&F)->getMetadata("reqd_work_group_size")) {
886 // We generate constants if the WorkgroupSize builtin is being used.
887 if (HasWorkGroupBuiltin) {
888 // Collect constant information for work group size.
889 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(0)));
890 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(1)));
891 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(2)));
David Neto22f144c2017-06-12 14:26:21 -0400892 }
893 }
894 }
895
alan-bakerf67468c2019-11-25 15:51:49 -0500896 // TODO(alan-baker): make this better.
alan-bakerf906d2b2019-12-10 11:26:23 -0500897 if (M.getTypeByName("opencl.image1d_ro_t.float") ||
898 M.getTypeByName("opencl.image1d_ro_t.float.sampled") ||
899 M.getTypeByName("opencl.image1d_wo_t.float") ||
900 M.getTypeByName("opencl.image2d_ro_t.float") ||
alan-bakerf67468c2019-11-25 15:51:49 -0500901 M.getTypeByName("opencl.image2d_ro_t.float.sampled") ||
902 M.getTypeByName("opencl.image2d_wo_t.float") ||
903 M.getTypeByName("opencl.image3d_ro_t.float") ||
904 M.getTypeByName("opencl.image3d_ro_t.float.sampled") ||
alan-baker7150a1d2020-02-25 08:31:06 -0500905 M.getTypeByName("opencl.image3d_wo_t.float") ||
906 M.getTypeByName("opencl.image1d_array_ro_t.float") ||
907 M.getTypeByName("opencl.image1d_array_ro_t.float.sampled") ||
908 M.getTypeByName("opencl.image1d_array_wo_t.float") ||
909 M.getTypeByName("opencl.image2d_array_ro_t.float") ||
910 M.getTypeByName("opencl.image2d_array_ro_t.float.sampled") ||
911 M.getTypeByName("opencl.image2d_array_wo_t.float")) {
alan-bakerf67468c2019-11-25 15:51:49 -0500912 FindType(Type::getFloatTy(Context));
alan-bakerf906d2b2019-12-10 11:26:23 -0500913 } else if (M.getTypeByName("opencl.image1d_ro_t.uint") ||
914 M.getTypeByName("opencl.image1d_ro_t.uint.sampled") ||
915 M.getTypeByName("opencl.image1d_wo_t.uint") ||
916 M.getTypeByName("opencl.image2d_ro_t.uint") ||
alan-bakerf67468c2019-11-25 15:51:49 -0500917 M.getTypeByName("opencl.image2d_ro_t.uint.sampled") ||
918 M.getTypeByName("opencl.image2d_wo_t.uint") ||
919 M.getTypeByName("opencl.image3d_ro_t.uint") ||
920 M.getTypeByName("opencl.image3d_ro_t.uint.sampled") ||
alan-baker7150a1d2020-02-25 08:31:06 -0500921 M.getTypeByName("opencl.image3d_wo_t.uint") ||
922 M.getTypeByName("opencl.image1d_array_ro_t.uint") ||
923 M.getTypeByName("opencl.image1d_array_ro_t.uint.sampled") ||
924 M.getTypeByName("opencl.image1d_array_wo_t.uint") ||
925 M.getTypeByName("opencl.image2d_array_ro_t.uint") ||
926 M.getTypeByName("opencl.image2d_array_ro_t.uint.sampled") ||
927 M.getTypeByName("opencl.image2d_array_wo_t.uint")) {
alan-bakerf67468c2019-11-25 15:51:49 -0500928 FindType(Type::getInt32Ty(Context));
alan-bakerf906d2b2019-12-10 11:26:23 -0500929 } else if (M.getTypeByName("opencl.image1d_ro_t.int") ||
930 M.getTypeByName("opencl.image1d_ro_t.int.sampled") ||
931 M.getTypeByName("opencl.image1d_wo_t.int") ||
932 M.getTypeByName("opencl.image2d_ro_t.int") ||
alan-bakerf67468c2019-11-25 15:51:49 -0500933 M.getTypeByName("opencl.image2d_ro_t.int.sampled") ||
934 M.getTypeByName("opencl.image2d_wo_t.int") ||
935 M.getTypeByName("opencl.image3d_ro_t.int") ||
936 M.getTypeByName("opencl.image3d_ro_t.int.sampled") ||
alan-baker7150a1d2020-02-25 08:31:06 -0500937 M.getTypeByName("opencl.image3d_wo_t.int") ||
938 M.getTypeByName("opencl.image1d_array_ro_t.int") ||
939 M.getTypeByName("opencl.image1d_array_ro_t.int.sampled") ||
940 M.getTypeByName("opencl.image1d_array_wo_t.int") ||
941 M.getTypeByName("opencl.image2d_array_ro_t.int") ||
942 M.getTypeByName("opencl.image2d_array_ro_t.int.sampled") ||
943 M.getTypeByName("opencl.image2d_array_wo_t.int")) {
alan-bakerf67468c2019-11-25 15:51:49 -0500944 // Nothing for now...
945 } else {
946 // This was likely an UndefValue.
David Neto22f144c2017-06-12 14:26:21 -0400947 FindType(Type::getFloatTy(Context));
948 }
949
950 // Collect types' information from function.
951 FindTypePerFunc(F);
952
953 // Collect constant information from function.
954 FindConstantPerFunc(F);
955 }
956}
957
David Neto862b7d82018-06-14 18:48:37 -0400958void SPIRVProducerPass::FindGlobalConstVars(Module &M, const DataLayout &DL) {
alan-baker56f7aff2019-05-22 08:06:42 -0400959 clspv::NormalizeGlobalVariables(M);
960
David Neto862b7d82018-06-14 18:48:37 -0400961 SmallVector<GlobalVariable *, 8> GVList;
962 SmallVector<GlobalVariable *, 8> DeadGVList;
963 for (GlobalVariable &GV : M.globals()) {
964 if (GV.getType()->getAddressSpace() == AddressSpace::Constant) {
965 if (GV.use_empty()) {
966 DeadGVList.push_back(&GV);
967 } else {
968 GVList.push_back(&GV);
969 }
970 }
971 }
972
973 // Remove dead global __constant variables.
974 for (auto GV : DeadGVList) {
975 GV->eraseFromParent();
976 }
977 DeadGVList.clear();
978
979 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
980 // For now, we only support a single storage buffer.
981 if (GVList.size() > 0) {
982 assert(GVList.size() == 1);
983 const auto *GV = GVList[0];
984 const auto constants_byte_size =
Alan Bakerfcda9482018-10-02 17:09:59 -0400985 (GetTypeSizeInBits(GV->getInitializer()->getType(), DL)) / 8;
David Neto862b7d82018-06-14 18:48:37 -0400986 const size_t kConstantMaxSize = 65536;
987 if (constants_byte_size > kConstantMaxSize) {
988 outs() << "Max __constant capacity of " << kConstantMaxSize
989 << " bytes exceeded: " << constants_byte_size << " bytes used\n";
990 llvm_unreachable("Max __constant capacity exceeded");
991 }
992 }
993 } else {
994 // Change global constant variable's address space to ModuleScopePrivate.
995 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
996 for (auto GV : GVList) {
997 // Create new gv with ModuleScopePrivate address space.
998 Type *NewGVTy = GV->getType()->getPointerElementType();
999 GlobalVariable *NewGV = new GlobalVariable(
1000 M, NewGVTy, false, GV->getLinkage(), GV->getInitializer(), "",
1001 nullptr, GV->getThreadLocalMode(), AddressSpace::ModuleScopePrivate);
1002 NewGV->takeName(GV);
1003
1004 const SmallVector<User *, 8> GVUsers(GV->user_begin(), GV->user_end());
1005 SmallVector<User *, 8> CandidateUsers;
1006
1007 auto record_called_function_type_as_user =
1008 [&GlobalConstFuncTyMap](Value *gv, CallInst *call) {
1009 // Find argument index.
1010 unsigned index = 0;
1011 for (unsigned i = 0; i < call->getNumArgOperands(); i++) {
1012 if (gv == call->getOperand(i)) {
1013 // TODO(dneto): Should we break here?
1014 index = i;
1015 }
1016 }
1017
1018 // Record function type with global constant.
1019 GlobalConstFuncTyMap[call->getFunctionType()] =
1020 std::make_pair(call->getFunctionType(), index);
1021 };
1022
1023 for (User *GVU : GVUsers) {
1024 if (CallInst *Call = dyn_cast<CallInst>(GVU)) {
1025 record_called_function_type_as_user(GV, Call);
1026 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(GVU)) {
1027 // Check GEP users.
1028 for (User *GEPU : GEP->users()) {
1029 if (CallInst *GEPCall = dyn_cast<CallInst>(GEPU)) {
1030 record_called_function_type_as_user(GEP, GEPCall);
1031 }
1032 }
1033 }
1034
1035 CandidateUsers.push_back(GVU);
1036 }
1037
1038 for (User *U : CandidateUsers) {
1039 // Update users of gv with new gv.
alan-bakered80f572019-02-11 17:28:26 -05001040 if (!isa<Constant>(U)) {
1041 // #254: Can't change operands of a constant, but this shouldn't be
1042 // something that sticks around in the module.
1043 U->replaceUsesOfWith(GV, NewGV);
1044 }
David Neto862b7d82018-06-14 18:48:37 -04001045 }
1046
1047 // Delete original gv.
1048 GV->eraseFromParent();
1049 }
1050 }
1051}
1052
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001053void SPIRVProducerPass::FindResourceVars(Module &M, const DataLayout &) {
David Neto862b7d82018-06-14 18:48:37 -04001054 ResourceVarInfoList.clear();
1055 FunctionToResourceVarsMap.clear();
1056 ModuleOrderedResourceVars.reset();
1057 // Normally, there is one resource variable per clspv.resource.var.*
1058 // function, since that is unique'd by arg type and index. By design,
1059 // we can share these resource variables across kernels because all
1060 // kernels use the same descriptor set.
1061 //
1062 // But if the user requested distinct descriptor sets per kernel, then
1063 // the descriptor allocator has made different (set,binding) pairs for
1064 // the same (type,arg_index) pair. Since we can decorate a resource
1065 // variable with only exactly one DescriptorSet and Binding, we are
1066 // forced in this case to make distinct resource variables whenever
Kévin Petitbbbda972020-03-03 19:16:31 +00001067 // the same clspv.resource.var.X function is seen with disintct
David Neto862b7d82018-06-14 18:48:37 -04001068 // (set,binding) values.
1069 const bool always_distinct_sets =
1070 clspv::Option::DistinctKernelDescriptorSets();
1071 for (Function &F : M) {
1072 // Rely on the fact the resource var functions have a stable ordering
1073 // in the module.
Alan Baker202c8c72018-08-13 13:47:44 -04001074 if (F.getName().startswith(clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001075 // Find all calls to this function with distinct set and binding pairs.
1076 // Save them in ResourceVarInfoList.
1077
1078 // Determine uniqueness of the (set,binding) pairs only withing this
1079 // one resource-var builtin function.
1080 using SetAndBinding = std::pair<unsigned, unsigned>;
1081 // Maps set and binding to the resource var info.
1082 DenseMap<SetAndBinding, ResourceVarInfo *> set_and_binding_map;
1083 bool first_use = true;
1084 for (auto &U : F.uses()) {
1085 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
1086 const auto set = unsigned(
1087 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
1088 const auto binding = unsigned(
1089 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
1090 const auto arg_kind = clspv::ArgKind(
1091 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
1092 const auto arg_index = unsigned(
1093 dyn_cast<ConstantInt>(call->getArgOperand(3))->getZExtValue());
alan-bakere9308012019-03-15 10:25:13 -04001094 const auto coherent = unsigned(
1095 dyn_cast<ConstantInt>(call->getArgOperand(5))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04001096
1097 // Find or make the resource var info for this combination.
1098 ResourceVarInfo *rv = nullptr;
1099 if (always_distinct_sets) {
1100 // Make a new resource var any time we see a different
1101 // (set,binding) pair.
1102 SetAndBinding key{set, binding};
1103 auto where = set_and_binding_map.find(key);
1104 if (where == set_and_binding_map.end()) {
1105 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
alan-bakere9308012019-03-15 10:25:13 -04001106 binding, &F, arg_kind, coherent);
David Neto862b7d82018-06-14 18:48:37 -04001107 ResourceVarInfoList.emplace_back(rv);
1108 set_and_binding_map[key] = rv;
1109 } else {
1110 rv = where->second;
1111 }
1112 } else {
1113 // The default is to make exactly one resource for each
1114 // clspv.resource.var.* function.
1115 if (first_use) {
1116 first_use = false;
1117 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
alan-bakere9308012019-03-15 10:25:13 -04001118 binding, &F, arg_kind, coherent);
David Neto862b7d82018-06-14 18:48:37 -04001119 ResourceVarInfoList.emplace_back(rv);
1120 } else {
1121 rv = ResourceVarInfoList.back().get();
1122 }
1123 }
1124
1125 // Now populate FunctionToResourceVarsMap.
1126 auto &mapping =
1127 FunctionToResourceVarsMap[call->getParent()->getParent()];
1128 while (mapping.size() <= arg_index) {
1129 mapping.push_back(nullptr);
1130 }
1131 mapping[arg_index] = rv;
1132 }
1133 }
1134 }
1135 }
1136
1137 // Populate ModuleOrderedResourceVars.
1138 for (Function &F : M) {
1139 auto where = FunctionToResourceVarsMap.find(&F);
1140 if (where != FunctionToResourceVarsMap.end()) {
1141 for (auto &rv : where->second) {
1142 if (rv != nullptr) {
1143 ModuleOrderedResourceVars.insert(rv);
1144 }
1145 }
1146 }
1147 }
1148 if (ShowResourceVars) {
1149 for (auto *info : ModuleOrderedResourceVars) {
1150 outs() << "MORV index " << info->index << " (" << info->descriptor_set
1151 << "," << info->binding << ") " << *(info->var_fn->getReturnType())
1152 << "\n";
1153 }
1154 }
1155}
1156
David Neto22f144c2017-06-12 14:26:21 -04001157bool SPIRVProducerPass::FindExtInst(Module &M) {
1158 LLVMContext &Context = M.getContext();
1159 bool HasExtInst = false;
1160
1161 for (Function &F : M) {
1162 for (BasicBlock &BB : F) {
1163 for (Instruction &I : BB) {
1164 if (CallInst *Call = dyn_cast<CallInst>(&I)) {
1165 Function *Callee = Call->getCalledFunction();
1166 // Check whether this call is for extend instructions.
David Neto3fbb4072017-10-16 11:28:14 -04001167 auto callee_name = Callee->getName();
1168 const glsl::ExtInst EInst = getExtInstEnum(callee_name);
1169 const glsl::ExtInst IndirectEInst =
1170 getIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04001171
David Neto3fbb4072017-10-16 11:28:14 -04001172 HasExtInst |=
1173 (EInst != kGlslExtInstBad) || (IndirectEInst != kGlslExtInstBad);
1174
1175 if (IndirectEInst) {
1176 // Register extra constants if needed.
1177
1178 // Registers a type and constant for computing the result of the
1179 // given instruction. If the result of the instruction is a vector,
1180 // then make a splat vector constant with the same number of
1181 // elements.
1182 auto register_constant = [this, &I](Constant *constant) {
1183 FindType(constant->getType());
1184 FindConstant(constant);
1185 if (auto *vectorTy = dyn_cast<VectorType>(I.getType())) {
1186 // Register the splat vector of the value with the same
1187 // width as the result of the instruction.
1188 auto *vec_constant = ConstantVector::getSplat(
alan-baker7261e062020-03-15 14:35:48 -04001189 {static_cast<unsigned>(vectorTy->getNumElements()), false},
David Neto3fbb4072017-10-16 11:28:14 -04001190 constant);
1191 FindConstant(vec_constant);
1192 FindType(vec_constant->getType());
1193 }
1194 };
1195 switch (IndirectEInst) {
1196 case glsl::ExtInstFindUMsb:
1197 // clz needs OpExtInst and OpISub with constant 31, or splat
1198 // vector of 31. Add it to the constant list here.
1199 register_constant(
1200 ConstantInt::get(Type::getInt32Ty(Context), 31));
1201 break;
1202 case glsl::ExtInstAcos:
1203 case glsl::ExtInstAsin:
Kévin Petiteb9f90a2018-09-29 12:29:34 +01001204 case glsl::ExtInstAtan:
David Neto3fbb4072017-10-16 11:28:14 -04001205 case glsl::ExtInstAtan2:
1206 // We need 1/pi for acospi, asinpi, atan2pi.
1207 register_constant(
1208 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
1209 break;
1210 default:
1211 assert(false && "internally inconsistent");
1212 }
David Neto22f144c2017-06-12 14:26:21 -04001213 }
1214 }
1215 }
1216 }
1217 }
1218
1219 return HasExtInst;
1220}
1221
1222void SPIRVProducerPass::FindTypePerGlobalVar(GlobalVariable &GV) {
1223 // Investigate global variable's type.
1224 FindType(GV.getType());
1225}
1226
1227void SPIRVProducerPass::FindTypePerFunc(Function &F) {
1228 // Investigate function's type.
1229 FunctionType *FTy = F.getFunctionType();
1230
1231 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
1232 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
David Neto9ed8e2f2018-03-24 06:47:24 -07001233 // Handle a regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04001234 if (GlobalConstFuncTyMap.count(FTy)) {
1235 uint32_t GVCstArgIdx = GlobalConstFuncTypeMap[FTy].second;
1236 SmallVector<Type *, 4> NewFuncParamTys;
1237 for (unsigned i = 0; i < FTy->getNumParams(); i++) {
1238 Type *ParamTy = FTy->getParamType(i);
1239 if (i == GVCstArgIdx) {
1240 Type *EleTy = ParamTy->getPointerElementType();
1241 ParamTy = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1242 }
1243
1244 NewFuncParamTys.push_back(ParamTy);
1245 }
1246
1247 FunctionType *NewFTy =
1248 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1249 GlobalConstFuncTyMap[FTy] = std::make_pair(NewFTy, GVCstArgIdx);
1250 FTy = NewFTy;
1251 }
1252
1253 FindType(FTy);
1254 } else {
1255 // As kernel functions do not have parameters, create new function type and
1256 // add it to type map.
1257 SmallVector<Type *, 4> NewFuncParamTys;
1258 FunctionType *NewFTy =
1259 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1260 FindType(NewFTy);
1261 }
1262
1263 // Investigate instructions' type in function body.
1264 for (BasicBlock &BB : F) {
1265 for (Instruction &I : BB) {
1266 if (isa<ShuffleVectorInst>(I)) {
1267 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1268 // Ignore type for mask of shuffle vector instruction.
1269 if (i == 2) {
1270 continue;
1271 }
1272
1273 Value *Op = I.getOperand(i);
1274 if (!isa<MetadataAsValue>(Op)) {
1275 FindType(Op->getType());
1276 }
1277 }
1278
1279 FindType(I.getType());
1280 continue;
1281 }
1282
David Neto862b7d82018-06-14 18:48:37 -04001283 CallInst *Call = dyn_cast<CallInst>(&I);
1284
1285 if (Call && Call->getCalledFunction()->getName().startswith(
Alan Baker202c8c72018-08-13 13:47:44 -04001286 clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001287 // This is a fake call representing access to a resource variable.
1288 // We handle that elsewhere.
1289 continue;
1290 }
1291
Alan Baker202c8c72018-08-13 13:47:44 -04001292 if (Call && Call->getCalledFunction()->getName().startswith(
1293 clspv::WorkgroupAccessorFunction())) {
1294 // This is a fake call representing access to a workgroup variable.
1295 // We handle that elsewhere.
1296 continue;
1297 }
1298
alan-bakerf083bed2020-01-29 08:15:42 -05001299 // #497: InsertValue and ExtractValue map to OpCompositeInsert and
1300 // OpCompositeExtract which takes literal values for indices. As a result
1301 // don't map the type of indices.
1302 if (I.getOpcode() == Instruction::ExtractValue) {
1303 FindType(I.getOperand(0)->getType());
1304 continue;
1305 }
1306 if (I.getOpcode() == Instruction::InsertValue) {
1307 FindType(I.getOperand(0)->getType());
1308 FindType(I.getOperand(1)->getType());
1309 continue;
1310 }
1311
1312 // #497: InsertElement and ExtractElement map to OpCompositeExtract if
1313 // the index is a constant. In such a case don't map the index type.
1314 if (I.getOpcode() == Instruction::ExtractElement) {
1315 FindType(I.getOperand(0)->getType());
1316 Value *op1 = I.getOperand(1);
1317 if (!isa<Constant>(op1) || isa<GlobalValue>(op1)) {
1318 FindType(op1->getType());
1319 }
1320 continue;
1321 }
1322 if (I.getOpcode() == Instruction::InsertElement) {
1323 FindType(I.getOperand(0)->getType());
1324 FindType(I.getOperand(1)->getType());
1325 Value *op2 = I.getOperand(2);
1326 if (!isa<Constant>(op2) || isa<GlobalValue>(op2)) {
1327 FindType(op2->getType());
1328 }
1329 continue;
1330 }
1331
David Neto22f144c2017-06-12 14:26:21 -04001332 // Work through the operands of the instruction.
1333 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1334 Value *const Op = I.getOperand(i);
1335 // If any of the operands is a constant, find the type!
1336 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1337 FindType(Op->getType());
1338 }
1339 }
1340
1341 for (Use &Op : I.operands()) {
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001342 if (isa<CallInst>(&I)) {
David Neto22f144c2017-06-12 14:26:21 -04001343 // Avoid to check call instruction's type.
1344 break;
1345 }
Alan Baker202c8c72018-08-13 13:47:44 -04001346 if (CallInst *OpCall = dyn_cast<CallInst>(Op)) {
1347 if (OpCall && OpCall->getCalledFunction()->getName().startswith(
1348 clspv::WorkgroupAccessorFunction())) {
1349 // This is a fake call representing access to a workgroup variable.
1350 // We handle that elsewhere.
1351 continue;
1352 }
1353 }
David Neto22f144c2017-06-12 14:26:21 -04001354 if (!isa<MetadataAsValue>(&Op)) {
1355 FindType(Op->getType());
1356 continue;
1357 }
1358 }
1359
David Neto22f144c2017-06-12 14:26:21 -04001360 // We don't want to track the type of this call as we are going to replace
1361 // it.
Kévin Petitdf71de32019-04-09 14:09:50 +01001362 if (Call && (clspv::LiteralSamplerFunction() ==
David Neto22f144c2017-06-12 14:26:21 -04001363 Call->getCalledFunction()->getName())) {
1364 continue;
1365 }
1366
1367 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
1368 // If gep's base operand has ModuleScopePrivate address space, make gep
1369 // return ModuleScopePrivate address space.
1370 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate) {
1371 // Add pointer type with private address space for global constant to
1372 // type list.
1373 Type *EleTy = I.getType()->getPointerElementType();
1374 Type *NewPTy =
1375 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1376
1377 FindType(NewPTy);
1378 continue;
1379 }
1380 }
1381
1382 FindType(I.getType());
1383 }
1384 }
1385}
1386
David Neto862b7d82018-06-14 18:48:37 -04001387void SPIRVProducerPass::FindTypesForSamplerMap(Module &M) {
1388 // If we are using a sampler map, find the type of the sampler.
Kévin Petitdf71de32019-04-09 14:09:50 +01001389 if (M.getFunction(clspv::LiteralSamplerFunction()) ||
David Neto862b7d82018-06-14 18:48:37 -04001390 0 < getSamplerMap().size()) {
1391 auto SamplerStructTy = M.getTypeByName("opencl.sampler_t");
1392 if (!SamplerStructTy) {
1393 SamplerStructTy = StructType::create(M.getContext(), "opencl.sampler_t");
1394 }
1395
1396 SamplerTy = SamplerStructTy->getPointerTo(AddressSpace::UniformConstant);
1397
1398 FindType(SamplerTy);
1399 }
1400}
1401
1402void SPIRVProducerPass::FindTypesForResourceVars(Module &M) {
1403 // Record types so they are generated.
1404 TypesNeedingLayout.reset();
1405 StructTypesNeedingBlock.reset();
1406
1407 // To match older clspv codegen, generate the float type first if required
1408 // for images.
1409 for (const auto *info : ModuleOrderedResourceVars) {
1410 if (info->arg_kind == clspv::ArgKind::ReadOnlyImage ||
1411 info->arg_kind == clspv::ArgKind::WriteOnlyImage) {
alan-bakerf67468c2019-11-25 15:51:49 -05001412 if (IsIntImageType(info->var_fn->getReturnType())) {
1413 // Nothing for now...
1414 } else if (IsUintImageType(info->var_fn->getReturnType())) {
1415 FindType(Type::getInt32Ty(M.getContext()));
1416 }
1417
1418 // We need "float" either for the sampled type or for the Lod operand.
David Neto862b7d82018-06-14 18:48:37 -04001419 FindType(Type::getFloatTy(M.getContext()));
David Neto862b7d82018-06-14 18:48:37 -04001420 }
1421 }
1422
1423 for (const auto *info : ModuleOrderedResourceVars) {
1424 Type *type = info->var_fn->getReturnType();
1425
1426 switch (info->arg_kind) {
1427 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04001428 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04001429 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1430 StructTypesNeedingBlock.insert(sty);
1431 } else {
1432 errs() << *type << "\n";
1433 llvm_unreachable("Buffer arguments must map to structures!");
1434 }
1435 break;
1436 case clspv::ArgKind::Pod:
1437 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1438 StructTypesNeedingBlock.insert(sty);
1439 } else {
1440 errs() << *type << "\n";
1441 llvm_unreachable("POD arguments must map to structures!");
1442 }
1443 break;
1444 case clspv::ArgKind::ReadOnlyImage:
1445 case clspv::ArgKind::WriteOnlyImage:
1446 case clspv::ArgKind::Sampler:
1447 // Sampler and image types map to the pointee type but
1448 // in the uniform constant address space.
1449 type = PointerType::get(type->getPointerElementType(),
1450 clspv::AddressSpace::UniformConstant);
1451 break;
1452 default:
1453 break;
1454 }
1455
1456 // The converted type is the type of the OpVariable we will generate.
1457 // If the pointee type is an array of size zero, FindType will convert it
1458 // to a runtime array.
1459 FindType(type);
1460 }
1461
alan-bakerdcd97412019-09-16 15:32:30 -04001462 // If module constants are clustered in a storage buffer then that struct
1463 // needs layout decorations.
1464 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
1465 for (GlobalVariable &GV : M.globals()) {
1466 PointerType *PTy = cast<PointerType>(GV.getType());
1467 const auto AS = PTy->getAddressSpace();
1468 const bool module_scope_constant_external_init =
1469 (AS == AddressSpace::Constant) && GV.hasInitializer();
1470 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
1471 if (module_scope_constant_external_init &&
1472 spv::BuiltInMax == BuiltinType) {
1473 StructTypesNeedingBlock.insert(
1474 cast<StructType>(PTy->getPointerElementType()));
1475 }
1476 }
1477 }
1478
Kévin Petitbbbda972020-03-03 19:16:31 +00001479 for (const GlobalVariable &GV : M.globals()) {
1480 if (GV.getAddressSpace() == clspv::AddressSpace::PushConstant) {
1481 auto Ty = cast<PointerType>(GV.getType())->getPointerElementType();
1482 assert(Ty->isStructTy() && "Push constants have to be structures.");
1483 auto STy = cast<StructType>(Ty);
1484 StructTypesNeedingBlock.insert(STy);
1485 }
1486 }
1487
David Neto862b7d82018-06-14 18:48:37 -04001488 // Traverse the arrays and structures underneath each Block, and
1489 // mark them as needing layout.
1490 std::vector<Type *> work_list(StructTypesNeedingBlock.begin(),
1491 StructTypesNeedingBlock.end());
1492 while (!work_list.empty()) {
1493 Type *type = work_list.back();
1494 work_list.pop_back();
1495 TypesNeedingLayout.insert(type);
1496 switch (type->getTypeID()) {
1497 case Type::ArrayTyID:
1498 work_list.push_back(type->getArrayElementType());
1499 if (!Hack_generate_runtime_array_stride_early) {
1500 // Remember this array type for deferred decoration.
1501 TypesNeedingArrayStride.insert(type);
1502 }
1503 break;
1504 case Type::StructTyID:
1505 for (auto *elem_ty : cast<StructType>(type)->elements()) {
1506 work_list.push_back(elem_ty);
1507 }
1508 default:
1509 // This type and its contained types don't get layout.
1510 break;
1511 }
1512 }
1513}
1514
Alan Baker202c8c72018-08-13 13:47:44 -04001515void SPIRVProducerPass::FindWorkgroupVars(Module &M) {
1516 // The SpecId assignment for pointer-to-local arguments is recorded in
1517 // module-level metadata. Translate that information into local argument
1518 // information.
1519 NamedMDNode *nmd = M.getNamedMetadata(clspv::LocalSpecIdMetadataName());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001520 if (!nmd)
1521 return;
Alan Baker202c8c72018-08-13 13:47:44 -04001522 for (auto operand : nmd->operands()) {
1523 MDTuple *tuple = cast<MDTuple>(operand);
1524 ValueAsMetadata *fn_md = cast<ValueAsMetadata>(tuple->getOperand(0));
1525 Function *func = cast<Function>(fn_md->getValue());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001526 ConstantAsMetadata *arg_index_md =
1527 cast<ConstantAsMetadata>(tuple->getOperand(1));
1528 int arg_index = static_cast<int>(
1529 cast<ConstantInt>(arg_index_md->getValue())->getSExtValue());
1530 Argument *arg = &*(func->arg_begin() + arg_index);
Alan Baker202c8c72018-08-13 13:47:44 -04001531
1532 ConstantAsMetadata *spec_id_md =
1533 cast<ConstantAsMetadata>(tuple->getOperand(2));
alan-bakerb6b09dc2018-11-08 16:59:28 -05001534 int spec_id = static_cast<int>(
1535 cast<ConstantInt>(spec_id_md->getValue())->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04001536
1537 max_local_spec_id_ = std::max(max_local_spec_id_, spec_id + 1);
1538 LocalArgSpecIds[arg] = spec_id;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001539 if (LocalSpecIdInfoMap.count(spec_id))
1540 continue;
Alan Baker202c8c72018-08-13 13:47:44 -04001541
1542 // We haven't seen this SpecId yet, so generate the LocalArgInfo for it.
1543 LocalArgInfo info{nextID, arg->getType()->getPointerElementType(),
1544 nextID + 1, nextID + 2,
1545 nextID + 3, spec_id};
1546 LocalSpecIdInfoMap[spec_id] = info;
1547 nextID += 4;
1548
1549 // Ensure the types necessary for this argument get generated.
1550 Type *IdxTy = Type::getInt32Ty(M.getContext());
1551 FindConstant(ConstantInt::get(IdxTy, 0));
1552 FindType(IdxTy);
1553 FindType(arg->getType());
1554 }
1555}
1556
David Neto22f144c2017-06-12 14:26:21 -04001557void SPIRVProducerPass::FindType(Type *Ty) {
1558 TypeList &TyList = getTypeList();
1559
1560 if (0 != TyList.idFor(Ty)) {
1561 return;
1562 }
1563
1564 if (Ty->isPointerTy()) {
1565 auto AddrSpace = Ty->getPointerAddressSpace();
1566 if ((AddressSpace::Constant == AddrSpace) ||
1567 (AddressSpace::Global == AddrSpace)) {
1568 auto PointeeTy = Ty->getPointerElementType();
1569
1570 if (PointeeTy->isStructTy() &&
1571 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1572 FindType(PointeeTy);
1573 auto ActualPointerTy =
1574 PointeeTy->getPointerTo(AddressSpace::UniformConstant);
1575 FindType(ActualPointerTy);
1576 return;
1577 }
1578 }
1579 }
1580
David Neto862b7d82018-06-14 18:48:37 -04001581 // By convention, LLVM array type with 0 elements will map to
1582 // OpTypeRuntimeArray. Otherwise, it will map to OpTypeArray, which
1583 // has a constant number of elements. We need to support type of the
1584 // constant.
1585 if (auto *arrayTy = dyn_cast<ArrayType>(Ty)) {
1586 if (arrayTy->getNumElements() > 0) {
1587 LLVMContext &Context = Ty->getContext();
1588 FindType(Type::getInt32Ty(Context));
1589 }
David Neto22f144c2017-06-12 14:26:21 -04001590 }
1591
1592 for (Type *SubTy : Ty->subtypes()) {
1593 FindType(SubTy);
1594 }
1595
1596 TyList.insert(Ty);
1597}
1598
1599void SPIRVProducerPass::FindConstantPerGlobalVar(GlobalVariable &GV) {
1600 // If the global variable has a (non undef) initializer.
1601 if (GV.hasInitializer() && !isa<UndefValue>(GV.getInitializer())) {
David Neto862b7d82018-06-14 18:48:37 -04001602 // Generate the constant if it's not the initializer to a module scope
1603 // constant that we will expect in a storage buffer.
1604 const bool module_scope_constant_external_init =
1605 (GV.getType()->getPointerAddressSpace() == AddressSpace::Constant) &&
1606 clspv::Option::ModuleConstantsInStorageBuffer();
1607 if (!module_scope_constant_external_init) {
1608 FindConstant(GV.getInitializer());
1609 }
David Neto22f144c2017-06-12 14:26:21 -04001610 }
1611}
1612
1613void SPIRVProducerPass::FindConstantPerFunc(Function &F) {
1614 // Investigate constants in function body.
1615 for (BasicBlock &BB : F) {
1616 for (Instruction &I : BB) {
David Neto862b7d82018-06-14 18:48:37 -04001617 if (auto *call = dyn_cast<CallInst>(&I)) {
1618 auto name = call->getCalledFunction()->getName();
Kévin Petitdf71de32019-04-09 14:09:50 +01001619 if (name == clspv::LiteralSamplerFunction()) {
David Neto862b7d82018-06-14 18:48:37 -04001620 // We've handled these constants elsewhere, so skip it.
1621 continue;
1622 }
Alan Baker202c8c72018-08-13 13:47:44 -04001623 if (name.startswith(clspv::ResourceAccessorFunction())) {
1624 continue;
1625 }
1626 if (name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001627 continue;
1628 }
Kévin Petit617a76d2019-04-04 13:54:16 +01001629 if (name.startswith(clspv::SPIRVOpIntrinsicFunction())) {
1630 // Skip the first operand that has the SPIR-V Opcode
1631 for (unsigned i = 1; i < I.getNumOperands(); i++) {
1632 if (isa<Constant>(I.getOperand(i)) &&
1633 !isa<GlobalValue>(I.getOperand(i))) {
1634 FindConstant(I.getOperand(i));
1635 }
1636 }
1637 continue;
1638 }
David Neto22f144c2017-06-12 14:26:21 -04001639 }
1640
1641 if (isa<AllocaInst>(I)) {
1642 // Alloca instruction has constant for the number of element. Ignore it.
1643 continue;
1644 } else if (isa<ShuffleVectorInst>(I)) {
1645 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1646 // Ignore constant for mask of shuffle vector instruction.
1647 if (i == 2) {
1648 continue;
1649 }
1650
1651 if (isa<Constant>(I.getOperand(i)) &&
1652 !isa<GlobalValue>(I.getOperand(i))) {
1653 FindConstant(I.getOperand(i));
1654 }
1655 }
1656
1657 continue;
1658 } else if (isa<InsertElementInst>(I)) {
1659 // Handle InsertElement with <4 x i8> specially.
1660 Type *CompositeTy = I.getOperand(0)->getType();
1661 if (is4xi8vec(CompositeTy)) {
1662 LLVMContext &Context = CompositeTy->getContext();
1663 if (isa<Constant>(I.getOperand(0))) {
1664 FindConstant(I.getOperand(0));
1665 }
1666
1667 if (isa<Constant>(I.getOperand(1))) {
1668 FindConstant(I.getOperand(1));
1669 }
1670
1671 // Add mask constant 0xFF.
1672 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1673 FindConstant(CstFF);
1674
1675 // Add shift amount constant.
1676 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
1677 uint64_t Idx = CI->getZExtValue();
1678 Constant *CstShiftAmount =
1679 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1680 FindConstant(CstShiftAmount);
1681 }
1682
1683 continue;
1684 }
1685
1686 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1687 // Ignore constant for index of InsertElement instruction.
1688 if (i == 2) {
1689 continue;
1690 }
1691
1692 if (isa<Constant>(I.getOperand(i)) &&
1693 !isa<GlobalValue>(I.getOperand(i))) {
1694 FindConstant(I.getOperand(i));
1695 }
1696 }
1697
1698 continue;
1699 } else if (isa<ExtractElementInst>(I)) {
1700 // Handle ExtractElement with <4 x i8> specially.
1701 Type *CompositeTy = I.getOperand(0)->getType();
1702 if (is4xi8vec(CompositeTy)) {
1703 LLVMContext &Context = CompositeTy->getContext();
1704 if (isa<Constant>(I.getOperand(0))) {
1705 FindConstant(I.getOperand(0));
1706 }
1707
1708 // Add mask constant 0xFF.
1709 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1710 FindConstant(CstFF);
1711
1712 // Add shift amount constant.
1713 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
1714 uint64_t Idx = CI->getZExtValue();
1715 Constant *CstShiftAmount =
1716 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1717 FindConstant(CstShiftAmount);
1718 } else {
1719 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
1720 FindConstant(Cst8);
1721 }
1722
1723 continue;
1724 }
1725
1726 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1727 // Ignore constant for index of ExtractElement instruction.
1728 if (i == 1) {
1729 continue;
1730 }
1731
1732 if (isa<Constant>(I.getOperand(i)) &&
1733 !isa<GlobalValue>(I.getOperand(i))) {
1734 FindConstant(I.getOperand(i));
1735 }
1736 }
1737
1738 continue;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001739 } else if ((Instruction::Xor == I.getOpcode()) &&
1740 I.getType()->isIntegerTy(1)) {
1741 // We special case for Xor where the type is i1 and one of the arguments
1742 // is a constant 1 (true), this is an OpLogicalNot in SPIR-V, and we
1743 // don't need the constant
David Neto22f144c2017-06-12 14:26:21 -04001744 bool foundConstantTrue = false;
1745 for (Use &Op : I.operands()) {
1746 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1747 auto CI = cast<ConstantInt>(Op);
1748
1749 if (CI->isZero() || foundConstantTrue) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05001750 // If we already found the true constant, we might (probably only
1751 // on -O0) have an OpLogicalNot which is taking a constant
1752 // argument, so discover it anyway.
David Neto22f144c2017-06-12 14:26:21 -04001753 FindConstant(Op);
1754 } else {
1755 foundConstantTrue = true;
1756 }
1757 }
1758 }
1759
1760 continue;
David Netod2de94a2017-08-28 17:27:47 -04001761 } else if (isa<TruncInst>(I)) {
alan-bakerb39c8262019-03-08 14:03:37 -05001762 // Special case if i8 is not generally handled.
1763 if (!clspv::Option::Int8Support()) {
1764 // For truncation to i8 we mask against 255.
1765 Type *ToTy = I.getType();
1766 if (8u == ToTy->getPrimitiveSizeInBits()) {
1767 LLVMContext &Context = ToTy->getContext();
1768 Constant *Cst255 =
1769 ConstantInt::get(Type::getInt32Ty(Context), 0xff);
1770 FindConstant(Cst255);
1771 }
David Netod2de94a2017-08-28 17:27:47 -04001772 }
Neil Henning39672102017-09-29 14:33:13 +01001773 } else if (isa<AtomicRMWInst>(I)) {
1774 LLVMContext &Context = I.getContext();
1775
1776 FindConstant(
1777 ConstantInt::get(Type::getInt32Ty(Context), spv::ScopeDevice));
1778 FindConstant(ConstantInt::get(
1779 Type::getInt32Ty(Context),
1780 spv::MemorySemanticsUniformMemoryMask |
1781 spv::MemorySemanticsSequentiallyConsistentMask));
David Neto22f144c2017-06-12 14:26:21 -04001782 }
1783
1784 for (Use &Op : I.operands()) {
1785 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1786 FindConstant(Op);
1787 }
1788 }
1789 }
1790 }
1791}
1792
1793void SPIRVProducerPass::FindConstant(Value *V) {
David Neto22f144c2017-06-12 14:26:21 -04001794 ValueList &CstList = getConstantList();
1795
David Netofb9a7972017-08-25 17:08:24 -04001796 // If V is already tracked, ignore it.
1797 if (0 != CstList.idFor(V)) {
David Neto22f144c2017-06-12 14:26:21 -04001798 return;
1799 }
1800
David Neto862b7d82018-06-14 18:48:37 -04001801 if (isa<GlobalValue>(V) && clspv::Option::ModuleConstantsInStorageBuffer()) {
1802 return;
1803 }
1804
David Neto22f144c2017-06-12 14:26:21 -04001805 Constant *Cst = cast<Constant>(V);
David Neto862b7d82018-06-14 18:48:37 -04001806 Type *CstTy = Cst->getType();
David Neto22f144c2017-06-12 14:26:21 -04001807
1808 // Handle constant with <4 x i8> type specially.
David Neto22f144c2017-06-12 14:26:21 -04001809 if (is4xi8vec(CstTy)) {
1810 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001811 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001812 }
1813 }
1814
1815 if (Cst->getNumOperands()) {
1816 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end(); I != E;
1817 ++I) {
1818 FindConstant(*I);
1819 }
1820
David Netofb9a7972017-08-25 17:08:24 -04001821 CstList.insert(Cst);
David Neto22f144c2017-06-12 14:26:21 -04001822 return;
1823 } else if (const ConstantDataSequential *CDS =
1824 dyn_cast<ConstantDataSequential>(Cst)) {
1825 // Add constants for each element to constant list.
1826 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
1827 Constant *EleCst = CDS->getElementAsConstant(i);
1828 FindConstant(EleCst);
1829 }
1830 }
1831
1832 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001833 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001834 }
1835}
1836
1837spv::StorageClass SPIRVProducerPass::GetStorageClass(unsigned AddrSpace) const {
1838 switch (AddrSpace) {
1839 default:
1840 llvm_unreachable("Unsupported OpenCL address space");
1841 case AddressSpace::Private:
1842 return spv::StorageClassFunction;
1843 case AddressSpace::Global:
David Neto22f144c2017-06-12 14:26:21 -04001844 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001845 case AddressSpace::Constant:
1846 return clspv::Option::ConstantArgsInUniformBuffer()
1847 ? spv::StorageClassUniform
1848 : spv::StorageClassStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -04001849 case AddressSpace::Input:
1850 return spv::StorageClassInput;
1851 case AddressSpace::Local:
1852 return spv::StorageClassWorkgroup;
1853 case AddressSpace::UniformConstant:
1854 return spv::StorageClassUniformConstant;
David Neto9ed8e2f2018-03-24 06:47:24 -07001855 case AddressSpace::Uniform:
David Netoe439d702018-03-23 13:14:08 -07001856 return spv::StorageClassUniform;
David Neto22f144c2017-06-12 14:26:21 -04001857 case AddressSpace::ModuleScopePrivate:
1858 return spv::StorageClassPrivate;
Kévin Petitbbbda972020-03-03 19:16:31 +00001859 case AddressSpace::PushConstant:
1860 return spv::StorageClassPushConstant;
David Neto22f144c2017-06-12 14:26:21 -04001861 }
1862}
1863
David Neto862b7d82018-06-14 18:48:37 -04001864spv::StorageClass
1865SPIRVProducerPass::GetStorageClassForArgKind(clspv::ArgKind arg_kind) const {
1866 switch (arg_kind) {
1867 case clspv::ArgKind::Buffer:
1868 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001869 case clspv::ArgKind::BufferUBO:
1870 return spv::StorageClassUniform;
David Neto862b7d82018-06-14 18:48:37 -04001871 case clspv::ArgKind::Pod:
1872 return clspv::Option::PodArgsInUniformBuffer()
1873 ? spv::StorageClassUniform
1874 : spv::StorageClassStorageBuffer;
1875 case clspv::ArgKind::Local:
1876 return spv::StorageClassWorkgroup;
1877 case clspv::ArgKind::ReadOnlyImage:
1878 case clspv::ArgKind::WriteOnlyImage:
1879 case clspv::ArgKind::Sampler:
1880 return spv::StorageClassUniformConstant;
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001881 default:
1882 llvm_unreachable("Unsupported storage class for argument kind");
David Neto862b7d82018-06-14 18:48:37 -04001883 }
1884}
1885
David Neto22f144c2017-06-12 14:26:21 -04001886spv::BuiltIn SPIRVProducerPass::GetBuiltin(StringRef Name) const {
1887 return StringSwitch<spv::BuiltIn>(Name)
1888 .Case("__spirv_GlobalInvocationId", spv::BuiltInGlobalInvocationId)
1889 .Case("__spirv_LocalInvocationId", spv::BuiltInLocalInvocationId)
1890 .Case("__spirv_WorkgroupSize", spv::BuiltInWorkgroupSize)
1891 .Case("__spirv_NumWorkgroups", spv::BuiltInNumWorkgroups)
1892 .Case("__spirv_WorkgroupId", spv::BuiltInWorkgroupId)
1893 .Default(spv::BuiltInMax);
1894}
1895
1896void SPIRVProducerPass::GenerateExtInstImport() {
1897 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1898 uint32_t &ExtInstImportID = getOpExtInstImportID();
1899
1900 //
1901 // Generate OpExtInstImport.
1902 //
1903 // Ops[0] ... Ops[n] = Name (Literal String)
David Neto22f144c2017-06-12 14:26:21 -04001904 ExtInstImportID = nextID;
David Neto87846742018-04-11 17:36:22 -04001905 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpExtInstImport, nextID++,
1906 MkString("GLSL.std.450")));
David Neto22f144c2017-06-12 14:26:21 -04001907}
1908
alan-bakerb6b09dc2018-11-08 16:59:28 -05001909void SPIRVProducerPass::GenerateSPIRVTypes(LLVMContext &Context,
1910 Module &module) {
David Neto22f144c2017-06-12 14:26:21 -04001911 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1912 ValueMapType &VMap = getValueMap();
1913 ValueMapType &AllocatedVMap = getAllocatedValueMap();
Alan Bakerfcda9482018-10-02 17:09:59 -04001914 const auto &DL = module.getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04001915
1916 // Map for OpTypeRuntimeArray. If argument has pointer type, 2 spirv type
1917 // instructions are generated. They are OpTypePointer and OpTypeRuntimeArray.
1918 DenseMap<Type *, uint32_t> OpRuntimeTyMap;
1919
1920 for (Type *Ty : getTypeList()) {
1921 // Update TypeMap with nextID for reference later.
1922 TypeMap[Ty] = nextID;
1923
1924 switch (Ty->getTypeID()) {
1925 default: {
1926 Ty->print(errs());
1927 llvm_unreachable("Unsupported type???");
1928 break;
1929 }
1930 case Type::MetadataTyID:
1931 case Type::LabelTyID: {
1932 // Ignore these types.
1933 break;
1934 }
1935 case Type::PointerTyID: {
1936 PointerType *PTy = cast<PointerType>(Ty);
1937 unsigned AddrSpace = PTy->getAddressSpace();
1938
1939 // For the purposes of our Vulkan SPIR-V type system, constant and global
1940 // are conflated.
1941 bool UseExistingOpTypePointer = false;
1942 if (AddressSpace::Constant == AddrSpace) {
Alan Bakerfcda9482018-10-02 17:09:59 -04001943 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1944 AddrSpace = AddressSpace::Global;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001945 // Check to see if we already created this type (for instance, if we
1946 // had a constant <type>* and a global <type>*, the type would be
1947 // created by one of these types, and shared by both).
Alan Bakerfcda9482018-10-02 17:09:59 -04001948 auto GlobalTy = PTy->getPointerElementType()->getPointerTo(AddrSpace);
1949 if (0 < TypeMap.count(GlobalTy)) {
1950 TypeMap[PTy] = TypeMap[GlobalTy];
1951 UseExistingOpTypePointer = true;
1952 break;
1953 }
David Neto22f144c2017-06-12 14:26:21 -04001954 }
1955 } else if (AddressSpace::Global == AddrSpace) {
Alan Bakerfcda9482018-10-02 17:09:59 -04001956 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1957 AddrSpace = AddressSpace::Constant;
David Neto22f144c2017-06-12 14:26:21 -04001958
alan-bakerb6b09dc2018-11-08 16:59:28 -05001959 // Check to see if we already created this type (for instance, if we
1960 // had a constant <type>* and a global <type>*, the type would be
1961 // created by one of these types, and shared by both).
1962 auto ConstantTy =
1963 PTy->getPointerElementType()->getPointerTo(AddrSpace);
Alan Bakerfcda9482018-10-02 17:09:59 -04001964 if (0 < TypeMap.count(ConstantTy)) {
1965 TypeMap[PTy] = TypeMap[ConstantTy];
1966 UseExistingOpTypePointer = true;
1967 }
David Neto22f144c2017-06-12 14:26:21 -04001968 }
1969 }
1970
David Neto862b7d82018-06-14 18:48:37 -04001971 const bool HasArgUser = true;
David Neto22f144c2017-06-12 14:26:21 -04001972
David Neto862b7d82018-06-14 18:48:37 -04001973 if (HasArgUser && !UseExistingOpTypePointer) {
David Neto22f144c2017-06-12 14:26:21 -04001974 //
1975 // Generate OpTypePointer.
1976 //
1977
1978 // OpTypePointer
1979 // Ops[0] = Storage Class
1980 // Ops[1] = Element Type ID
1981 SPIRVOperandList Ops;
1982
David Neto257c3892018-04-11 13:19:45 -04001983 Ops << MkNum(GetStorageClass(AddrSpace))
1984 << MkId(lookupType(PTy->getElementType()));
David Neto22f144c2017-06-12 14:26:21 -04001985
David Neto87846742018-04-11 17:36:22 -04001986 auto *Inst = new SPIRVInstruction(spv::OpTypePointer, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001987 SPIRVInstList.push_back(Inst);
1988 }
David Neto22f144c2017-06-12 14:26:21 -04001989 break;
1990 }
1991 case Type::StructTyID: {
David Neto22f144c2017-06-12 14:26:21 -04001992 StructType *STy = cast<StructType>(Ty);
1993
1994 // Handle sampler type.
1995 if (STy->isOpaque()) {
1996 if (STy->getName().equals("opencl.sampler_t")) {
1997 //
1998 // Generate OpTypeSampler
1999 //
2000 // Empty Ops.
2001 SPIRVOperandList Ops;
2002
David Neto87846742018-04-11 17:36:22 -04002003 auto *Inst = new SPIRVInstruction(spv::OpTypeSampler, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002004 SPIRVInstList.push_back(Inst);
2005 break;
alan-bakerf906d2b2019-12-10 11:26:23 -05002006 } else if (STy->getName().startswith("opencl.image1d_ro_t") ||
2007 STy->getName().startswith("opencl.image1d_wo_t") ||
alan-baker7150a1d2020-02-25 08:31:06 -05002008 STy->getName().startswith("opencl.image1d_array_ro_t") ||
2009 STy->getName().startswith("opencl.image1d_array_wo_t") ||
alan-bakerf906d2b2019-12-10 11:26:23 -05002010 STy->getName().startswith("opencl.image2d_ro_t") ||
alan-bakerf67468c2019-11-25 15:51:49 -05002011 STy->getName().startswith("opencl.image2d_wo_t") ||
alan-baker7150a1d2020-02-25 08:31:06 -05002012 STy->getName().startswith("opencl.image2d_array_ro_t") ||
2013 STy->getName().startswith("opencl.image2d_array_wo_t") ||
alan-bakerf67468c2019-11-25 15:51:49 -05002014 STy->getName().startswith("opencl.image3d_ro_t") ||
2015 STy->getName().startswith("opencl.image3d_wo_t")) {
David Neto22f144c2017-06-12 14:26:21 -04002016 //
2017 // Generate OpTypeImage
2018 //
2019 // Ops[0] = Sampled Type ID
2020 // Ops[1] = Dim ID
2021 // Ops[2] = Depth (Literal Number)
2022 // Ops[3] = Arrayed (Literal Number)
2023 // Ops[4] = MS (Literal Number)
2024 // Ops[5] = Sampled (Literal Number)
2025 // Ops[6] = Image Format ID
2026 //
2027 SPIRVOperandList Ops;
2028
alan-bakerf67468c2019-11-25 15:51:49 -05002029 uint32_t ImageTyID = nextID++;
2030 uint32_t SampledTyID = 0;
2031 if (STy->getName().contains(".float")) {
2032 SampledTyID = lookupType(Type::getFloatTy(Context));
2033 } else if (STy->getName().contains(".uint")) {
2034 SampledTyID = lookupType(Type::getInt32Ty(Context));
2035 } else if (STy->getName().contains(".int")) {
2036 // Generate a signed 32-bit integer if necessary.
2037 if (int32ID == 0) {
2038 int32ID = nextID++;
2039 SPIRVOperandList intOps;
2040 intOps << MkNum(32);
2041 intOps << MkNum(1);
2042 auto signed_int =
2043 new SPIRVInstruction(spv::OpTypeInt, int32ID, intOps);
2044 SPIRVInstList.push_back(signed_int);
2045 }
2046 SampledTyID = int32ID;
2047
2048 // Generate a vec4 of the signed int if necessary.
2049 if (v4int32ID == 0) {
2050 v4int32ID = nextID++;
2051 SPIRVOperandList vecOps;
2052 vecOps << MkId(int32ID);
2053 vecOps << MkNum(4);
2054 auto int_vec =
2055 new SPIRVInstruction(spv::OpTypeVector, v4int32ID, vecOps);
2056 SPIRVInstList.push_back(int_vec);
2057 }
2058 } else {
2059 // This was likely an UndefValue.
2060 SampledTyID = lookupType(Type::getFloatTy(Context));
2061 }
David Neto257c3892018-04-11 13:19:45 -04002062 Ops << MkId(SampledTyID);
David Neto22f144c2017-06-12 14:26:21 -04002063
2064 spv::Dim DimID = spv::Dim2D;
alan-bakerf906d2b2019-12-10 11:26:23 -05002065 if (STy->getName().startswith("opencl.image1d_ro_t") ||
alan-baker7150a1d2020-02-25 08:31:06 -05002066 STy->getName().startswith("opencl.image1d_wo_t") ||
2067 STy->getName().startswith("opencl.image1d_array_ro_t") ||
2068 STy->getName().startswith("opencl.image1d_array_wo_t")) {
alan-bakerf906d2b2019-12-10 11:26:23 -05002069 DimID = spv::Dim1D;
2070 } else if (STy->getName().startswith("opencl.image3d_ro_t") ||
2071 STy->getName().startswith("opencl.image3d_wo_t")) {
David Neto22f144c2017-06-12 14:26:21 -04002072 DimID = spv::Dim3D;
2073 }
David Neto257c3892018-04-11 13:19:45 -04002074 Ops << MkNum(DimID);
David Neto22f144c2017-06-12 14:26:21 -04002075
2076 // TODO: Set up Depth.
David Neto257c3892018-04-11 13:19:45 -04002077 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04002078
alan-baker7150a1d2020-02-25 08:31:06 -05002079 uint32_t arrayed = STy->getName().contains("_array_") ? 1 : 0;
2080 Ops << MkNum(arrayed);
David Neto22f144c2017-06-12 14:26:21 -04002081
2082 // TODO: Set up MS.
David Neto257c3892018-04-11 13:19:45 -04002083 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04002084
alan-baker7150a1d2020-02-25 08:31:06 -05002085 // Set up Sampled.
David Neto22f144c2017-06-12 14:26:21 -04002086 //
2087 // From Spec
2088 //
2089 // 0 indicates this is only known at run time, not at compile time
2090 // 1 indicates will be used with sampler
2091 // 2 indicates will be used without a sampler (a storage image)
2092 uint32_t Sampled = 1;
alan-bakerf67468c2019-11-25 15:51:49 -05002093 if (!STy->getName().contains(".sampled")) {
David Neto22f144c2017-06-12 14:26:21 -04002094 Sampled = 2;
2095 }
David Neto257c3892018-04-11 13:19:45 -04002096 Ops << MkNum(Sampled);
David Neto22f144c2017-06-12 14:26:21 -04002097
2098 // TODO: Set up Image Format.
David Neto257c3892018-04-11 13:19:45 -04002099 Ops << MkNum(spv::ImageFormatUnknown);
David Neto22f144c2017-06-12 14:26:21 -04002100
alan-bakerf67468c2019-11-25 15:51:49 -05002101 auto *Inst = new SPIRVInstruction(spv::OpTypeImage, ImageTyID, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002102 SPIRVInstList.push_back(Inst);
2103 break;
2104 }
2105 }
2106
2107 //
2108 // Generate OpTypeStruct
2109 //
2110 // Ops[0] ... Ops[n] = Member IDs
2111 SPIRVOperandList Ops;
2112
2113 for (auto *EleTy : STy->elements()) {
David Neto862b7d82018-06-14 18:48:37 -04002114 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04002115 }
2116
David Neto22f144c2017-06-12 14:26:21 -04002117 uint32_t STyID = nextID;
2118
alan-bakerb6b09dc2018-11-08 16:59:28 -05002119 auto *Inst = new SPIRVInstruction(spv::OpTypeStruct, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002120 SPIRVInstList.push_back(Inst);
2121
2122 // Generate OpMemberDecorate.
2123 auto DecoInsertPoint =
2124 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2125 [](SPIRVInstruction *Inst) -> bool {
2126 return Inst->getOpcode() != spv::OpDecorate &&
2127 Inst->getOpcode() != spv::OpMemberDecorate &&
2128 Inst->getOpcode() != spv::OpExtInstImport;
2129 });
2130
Kévin Petitbbbda972020-03-03 19:16:31 +00002131 if (TypesNeedingLayout.idFor(STy)) {
2132 for (unsigned MemberIdx = 0; MemberIdx < STy->getNumElements();
2133 MemberIdx++) {
2134 // Ops[0] = Structure Type ID
2135 // Ops[1] = Member Index(Literal Number)
2136 // Ops[2] = Decoration (Offset)
2137 // Ops[3] = Byte Offset (Literal Number)
2138 Ops.clear();
David Netoc463b372017-08-10 15:32:21 -04002139
Kévin Petitbbbda972020-03-03 19:16:31 +00002140 Ops << MkId(STyID) << MkNum(MemberIdx)
2141 << MkNum(spv::DecorationOffset);
David Neto22f144c2017-06-12 14:26:21 -04002142
Kévin Petitbbbda972020-03-03 19:16:31 +00002143 const auto ByteOffset =
2144 GetExplicitLayoutStructMemberOffset(STy, MemberIdx, DL);
David Neto22f144c2017-06-12 14:26:21 -04002145
Kévin Petitbbbda972020-03-03 19:16:31 +00002146 Ops << MkNum(ByteOffset);
2147
2148 auto *DecoInst = new SPIRVInstruction(spv::OpMemberDecorate, Ops);
2149 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
Alan Bakerfcda9482018-10-02 17:09:59 -04002150 }
David Neto22f144c2017-06-12 14:26:21 -04002151 }
2152
2153 // Generate OpDecorate.
David Neto862b7d82018-06-14 18:48:37 -04002154 if (StructTypesNeedingBlock.idFor(STy)) {
2155 Ops.clear();
2156 // Use Block decorations with StorageBuffer storage class.
2157 Ops << MkId(STyID) << MkNum(spv::DecorationBlock);
David Neto22f144c2017-06-12 14:26:21 -04002158
David Neto862b7d82018-06-14 18:48:37 -04002159 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
2160 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04002161 }
2162 break;
2163 }
2164 case Type::IntegerTyID: {
alan-baker0e64a592019-11-18 13:36:25 -05002165 uint32_t BitWidth = static_cast<uint32_t>(Ty->getPrimitiveSizeInBits());
David Neto22f144c2017-06-12 14:26:21 -04002166
2167 if (BitWidth == 1) {
David Netoef5ba2b2019-12-20 08:35:54 -05002168 auto *Inst = new SPIRVInstruction(spv::OpTypeBool, nextID++);
David Neto22f144c2017-06-12 14:26:21 -04002169 SPIRVInstList.push_back(Inst);
2170 } else {
alan-bakerb39c8262019-03-08 14:03:37 -05002171 if (!clspv::Option::Int8Support()) {
2172 // i8 is added to TypeMap as i32.
2173 // No matter what LLVM type is requested first, always alias the
2174 // second one's SPIR-V type to be the same as the one we generated
2175 // first.
2176 unsigned aliasToWidth = 0;
2177 if (BitWidth == 8) {
2178 aliasToWidth = 32;
2179 BitWidth = 32;
2180 } else if (BitWidth == 32) {
2181 aliasToWidth = 8;
2182 }
2183 if (aliasToWidth) {
2184 Type *otherType = Type::getIntNTy(Ty->getContext(), aliasToWidth);
2185 auto where = TypeMap.find(otherType);
2186 if (where == TypeMap.end()) {
2187 // Go ahead and make it, but also map the other type to it.
2188 TypeMap[otherType] = nextID;
2189 } else {
2190 // Alias this SPIR-V type the existing type.
2191 TypeMap[Ty] = where->second;
2192 break;
2193 }
David Neto391aeb12017-08-26 15:51:58 -04002194 }
David Neto22f144c2017-06-12 14:26:21 -04002195 }
2196
David Neto257c3892018-04-11 13:19:45 -04002197 SPIRVOperandList Ops;
2198 Ops << MkNum(BitWidth) << MkNum(0 /* not signed */);
David Neto22f144c2017-06-12 14:26:21 -04002199
2200 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002201 new SPIRVInstruction(spv::OpTypeInt, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002202 }
2203 break;
2204 }
2205 case Type::HalfTyID:
2206 case Type::FloatTyID:
2207 case Type::DoubleTyID: {
alan-baker0e64a592019-11-18 13:36:25 -05002208 uint32_t BitWidth = static_cast<uint32_t>(Ty->getPrimitiveSizeInBits());
James Price11010dc2019-12-19 13:53:09 -05002209 auto WidthOp = MkNum(BitWidth);
David Neto22f144c2017-06-12 14:26:21 -04002210
2211 SPIRVInstList.push_back(
David Netoef5ba2b2019-12-20 08:35:54 -05002212 new SPIRVInstruction(spv::OpTypeFloat, nextID++, std::move(WidthOp)));
David Neto22f144c2017-06-12 14:26:21 -04002213 break;
2214 }
2215 case Type::ArrayTyID: {
David Neto22f144c2017-06-12 14:26:21 -04002216 ArrayType *ArrTy = cast<ArrayType>(Ty);
David Neto862b7d82018-06-14 18:48:37 -04002217 const uint64_t Length = ArrTy->getArrayNumElements();
2218 if (Length == 0) {
2219 // By convention, map it to a RuntimeArray.
David Neto22f144c2017-06-12 14:26:21 -04002220
David Neto862b7d82018-06-14 18:48:37 -04002221 // Only generate the type once.
2222 // TODO(dneto): Can it ever be generated more than once?
2223 // Doesn't LLVM type uniqueness guarantee we'll only see this
2224 // once?
2225 Type *EleTy = ArrTy->getArrayElementType();
2226 if (OpRuntimeTyMap.count(EleTy) == 0) {
2227 uint32_t OpTypeRuntimeArrayID = nextID;
2228 OpRuntimeTyMap[Ty] = nextID;
David Neto22f144c2017-06-12 14:26:21 -04002229
David Neto862b7d82018-06-14 18:48:37 -04002230 //
2231 // Generate OpTypeRuntimeArray.
2232 //
David Neto22f144c2017-06-12 14:26:21 -04002233
David Neto862b7d82018-06-14 18:48:37 -04002234 // OpTypeRuntimeArray
2235 // Ops[0] = Element Type ID
2236 SPIRVOperandList Ops;
2237 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04002238
David Neto862b7d82018-06-14 18:48:37 -04002239 SPIRVInstList.push_back(
2240 new SPIRVInstruction(spv::OpTypeRuntimeArray, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002241
David Neto862b7d82018-06-14 18:48:37 -04002242 if (Hack_generate_runtime_array_stride_early) {
2243 // Generate OpDecorate.
2244 auto DecoInsertPoint = std::find_if(
2245 SPIRVInstList.begin(), SPIRVInstList.end(),
2246 [](SPIRVInstruction *Inst) -> bool {
2247 return Inst->getOpcode() != spv::OpDecorate &&
2248 Inst->getOpcode() != spv::OpMemberDecorate &&
2249 Inst->getOpcode() != spv::OpExtInstImport;
2250 });
David Neto22f144c2017-06-12 14:26:21 -04002251
David Neto862b7d82018-06-14 18:48:37 -04002252 // Ops[0] = Target ID
2253 // Ops[1] = Decoration (ArrayStride)
2254 // Ops[2] = Stride Number(Literal Number)
2255 Ops.clear();
David Neto85082642018-03-24 06:55:20 -07002256
David Neto862b7d82018-06-14 18:48:37 -04002257 Ops << MkId(OpTypeRuntimeArrayID)
2258 << MkNum(spv::DecorationArrayStride)
Alan Bakerfcda9482018-10-02 17:09:59 -04002259 << MkNum(static_cast<uint32_t>(GetTypeAllocSize(EleTy, DL)));
David Neto22f144c2017-06-12 14:26:21 -04002260
David Neto862b7d82018-06-14 18:48:37 -04002261 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
2262 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
2263 }
2264 }
David Neto22f144c2017-06-12 14:26:21 -04002265
David Neto862b7d82018-06-14 18:48:37 -04002266 } else {
David Neto22f144c2017-06-12 14:26:21 -04002267
David Neto862b7d82018-06-14 18:48:37 -04002268 //
2269 // Generate OpConstant and OpTypeArray.
2270 //
2271
2272 //
2273 // Generate OpConstant for array length.
2274 //
2275 // Ops[0] = Result Type ID
2276 // Ops[1] .. Ops[n] = Values LiteralNumber
2277 SPIRVOperandList Ops;
2278
2279 Type *LengthTy = Type::getInt32Ty(Context);
2280 uint32_t ResTyID = lookupType(LengthTy);
2281 Ops << MkId(ResTyID);
2282
2283 assert(Length < UINT32_MAX);
2284 Ops << MkNum(static_cast<uint32_t>(Length));
2285
2286 // Add constant for length to constant list.
2287 Constant *CstLength = ConstantInt::get(LengthTy, Length);
2288 AllocatedVMap[CstLength] = nextID;
2289 VMap[CstLength] = nextID;
2290 uint32_t LengthID = nextID;
2291
2292 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
2293 SPIRVInstList.push_back(CstInst);
2294
2295 // Remember to generate ArrayStride later
2296 getTypesNeedingArrayStride().insert(Ty);
2297
2298 //
2299 // Generate OpTypeArray.
2300 //
2301 // Ops[0] = Element Type ID
2302 // Ops[1] = Array Length Constant ID
2303 Ops.clear();
2304
2305 uint32_t EleTyID = lookupType(ArrTy->getElementType());
2306 Ops << MkId(EleTyID) << MkId(LengthID);
2307
2308 // Update TypeMap with nextID.
2309 TypeMap[Ty] = nextID;
2310
2311 auto *ArrayInst = new SPIRVInstruction(spv::OpTypeArray, nextID++, Ops);
2312 SPIRVInstList.push_back(ArrayInst);
2313 }
David Neto22f144c2017-06-12 14:26:21 -04002314 break;
2315 }
2316 case Type::VectorTyID: {
alan-bakerb39c8262019-03-08 14:03:37 -05002317 // <4 x i8> is changed to i32 if i8 is not generally supported.
2318 if (!clspv::Option::Int8Support() &&
2319 Ty->getVectorElementType() == Type::getInt8Ty(Context)) {
David Neto22f144c2017-06-12 14:26:21 -04002320 if (Ty->getVectorNumElements() == 4) {
2321 TypeMap[Ty] = lookupType(Ty->getVectorElementType());
2322 break;
2323 } else {
2324 Ty->print(errs());
2325 llvm_unreachable("Support above i8 vector type");
2326 }
2327 }
2328
2329 // Ops[0] = Component Type ID
2330 // Ops[1] = Component Count (Literal Number)
David Neto257c3892018-04-11 13:19:45 -04002331 SPIRVOperandList Ops;
2332 Ops << MkId(lookupType(Ty->getVectorElementType()))
2333 << MkNum(Ty->getVectorNumElements());
David Neto22f144c2017-06-12 14:26:21 -04002334
alan-bakerb6b09dc2018-11-08 16:59:28 -05002335 SPIRVInstruction *inst =
2336 new SPIRVInstruction(spv::OpTypeVector, nextID++, Ops);
David Netoc6f3ab22018-04-06 18:02:31 -04002337 SPIRVInstList.push_back(inst);
David Neto22f144c2017-06-12 14:26:21 -04002338 break;
2339 }
2340 case Type::VoidTyID: {
David Netoef5ba2b2019-12-20 08:35:54 -05002341 auto *Inst = new SPIRVInstruction(spv::OpTypeVoid, nextID++);
David Neto22f144c2017-06-12 14:26:21 -04002342 SPIRVInstList.push_back(Inst);
2343 break;
2344 }
2345 case Type::FunctionTyID: {
2346 // Generate SPIRV instruction for function type.
2347 FunctionType *FTy = cast<FunctionType>(Ty);
2348
2349 // Ops[0] = Return Type ID
2350 // Ops[1] ... Ops[n] = Parameter Type IDs
2351 SPIRVOperandList Ops;
2352
2353 // Find SPIRV instruction for return type
David Netoc6f3ab22018-04-06 18:02:31 -04002354 Ops << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04002355
2356 // Find SPIRV instructions for parameter types
2357 for (unsigned k = 0; k < FTy->getNumParams(); k++) {
2358 // Find SPIRV instruction for parameter type.
2359 auto ParamTy = FTy->getParamType(k);
2360 if (ParamTy->isPointerTy()) {
2361 auto PointeeTy = ParamTy->getPointerElementType();
2362 if (PointeeTy->isStructTy() &&
2363 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
2364 ParamTy = PointeeTy;
2365 }
2366 }
2367
David Netoc6f3ab22018-04-06 18:02:31 -04002368 Ops << MkId(lookupType(ParamTy));
David Neto22f144c2017-06-12 14:26:21 -04002369 }
2370
David Neto87846742018-04-11 17:36:22 -04002371 auto *Inst = new SPIRVInstruction(spv::OpTypeFunction, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002372 SPIRVInstList.push_back(Inst);
2373 break;
2374 }
2375 }
2376 }
2377
2378 // Generate OpTypeSampledImage.
alan-bakerabd82722019-12-03 17:14:51 -05002379 for (auto &ImgTy : getImageTypeList()) {
David Neto22f144c2017-06-12 14:26:21 -04002380 //
2381 // Generate OpTypeSampledImage.
2382 //
2383 // Ops[0] = Image Type ID
2384 //
2385 SPIRVOperandList Ops;
2386
David Netoc6f3ab22018-04-06 18:02:31 -04002387 Ops << MkId(TypeMap[ImgTy]);
David Neto22f144c2017-06-12 14:26:21 -04002388
alan-bakerabd82722019-12-03 17:14:51 -05002389 // Update the image type map.
2390 getImageTypeMap()[ImgTy] = nextID;
David Neto22f144c2017-06-12 14:26:21 -04002391
David Neto87846742018-04-11 17:36:22 -04002392 auto *Inst = new SPIRVInstruction(spv::OpTypeSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002393 SPIRVInstList.push_back(Inst);
2394 }
David Netoc6f3ab22018-04-06 18:02:31 -04002395
2396 // Generate types for pointer-to-local arguments.
Alan Baker202c8c72018-08-13 13:47:44 -04002397 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
2398 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002399 LocalArgInfo &arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04002400
2401 // Generate the spec constant.
2402 SPIRVOperandList Ops;
2403 Ops << MkId(lookupType(Type::getInt32Ty(Context))) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04002404 SPIRVInstList.push_back(
2405 new SPIRVInstruction(spv::OpSpecConstant, arg_info.array_size_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002406
2407 // Generate the array type.
2408 Ops.clear();
2409 // The element type must have been created.
2410 uint32_t elem_ty_id = lookupType(arg_info.elem_type);
2411 assert(elem_ty_id);
2412 Ops << MkId(elem_ty_id) << MkId(arg_info.array_size_id);
2413
2414 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002415 new SPIRVInstruction(spv::OpTypeArray, arg_info.array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002416
2417 Ops.clear();
2418 Ops << MkNum(spv::StorageClassWorkgroup) << MkId(arg_info.array_type_id);
David Neto87846742018-04-11 17:36:22 -04002419 SPIRVInstList.push_back(new SPIRVInstruction(
2420 spv::OpTypePointer, arg_info.ptr_array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002421 }
David Neto22f144c2017-06-12 14:26:21 -04002422}
2423
2424void SPIRVProducerPass::GenerateSPIRVConstants() {
2425 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2426 ValueMapType &VMap = getValueMap();
2427 ValueMapType &AllocatedVMap = getAllocatedValueMap();
2428 ValueList &CstList = getConstantList();
David Neto482550a2018-03-24 05:21:07 -07002429 const bool hack_undef = clspv::Option::HackUndef();
David Neto22f144c2017-06-12 14:26:21 -04002430
2431 for (uint32_t i = 0; i < CstList.size(); i++) {
David Netofb9a7972017-08-25 17:08:24 -04002432 // UniqueVector ids are 1-based.
alan-bakerb6b09dc2018-11-08 16:59:28 -05002433 Constant *Cst = cast<Constant>(CstList[i + 1]);
David Neto22f144c2017-06-12 14:26:21 -04002434
2435 // OpTypeArray's constant was already generated.
David Netofb9a7972017-08-25 17:08:24 -04002436 if (AllocatedVMap.find_as(Cst) != AllocatedVMap.end()) {
David Neto22f144c2017-06-12 14:26:21 -04002437 continue;
2438 }
2439
David Netofb9a7972017-08-25 17:08:24 -04002440 // Set ValueMap with nextID for reference later.
David Neto22f144c2017-06-12 14:26:21 -04002441 VMap[Cst] = nextID;
2442
2443 //
2444 // Generate OpConstant.
2445 //
2446
2447 // Ops[0] = Result Type ID
2448 // Ops[1] .. Ops[n] = Values LiteralNumber
2449 SPIRVOperandList Ops;
2450
David Neto257c3892018-04-11 13:19:45 -04002451 Ops << MkId(lookupType(Cst->getType()));
David Neto22f144c2017-06-12 14:26:21 -04002452
2453 std::vector<uint32_t> LiteralNum;
David Neto22f144c2017-06-12 14:26:21 -04002454 spv::Op Opcode = spv::OpNop;
2455
2456 if (isa<UndefValue>(Cst)) {
2457 // Ops[0] = Result Type ID
David Netoc66b3352017-10-20 14:28:46 -04002458 Opcode = spv::OpUndef;
Alan Baker9bf93fb2018-08-28 16:59:26 -04002459 if (hack_undef && IsTypeNullable(Cst->getType())) {
2460 Opcode = spv::OpConstantNull;
David Netoc66b3352017-10-20 14:28:46 -04002461 }
David Neto22f144c2017-06-12 14:26:21 -04002462 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(Cst)) {
2463 unsigned BitWidth = CI->getBitWidth();
2464 if (BitWidth == 1) {
2465 // If the bitwidth of constant is 1, generate OpConstantTrue or
2466 // OpConstantFalse.
2467 if (CI->getZExtValue()) {
2468 // Ops[0] = Result Type ID
2469 Opcode = spv::OpConstantTrue;
2470 } else {
2471 // Ops[0] = Result Type ID
2472 Opcode = spv::OpConstantFalse;
2473 }
David Neto22f144c2017-06-12 14:26:21 -04002474 } else {
2475 auto V = CI->getZExtValue();
2476 LiteralNum.push_back(V & 0xFFFFFFFF);
2477
2478 if (BitWidth > 32) {
2479 LiteralNum.push_back(V >> 32);
2480 }
2481
2482 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002483
David Neto257c3892018-04-11 13:19:45 -04002484 Ops << MkInteger(LiteralNum);
David Neto22f144c2017-06-12 14:26:21 -04002485 }
2486 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Cst)) {
2487 uint64_t FPVal = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
2488 Type *CFPTy = CFP->getType();
2489 if (CFPTy->isFloatTy()) {
2490 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
Kévin Petit02ee34e2019-04-04 19:03:22 +01002491 } else if (CFPTy->isDoubleTy()) {
2492 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
2493 LiteralNum.push_back(FPVal >> 32);
alan-baker089bf932020-01-07 16:35:45 -05002494 } else if (CFPTy->isHalfTy()) {
2495 LiteralNum.push_back(FPVal & 0xFFFF);
David Neto22f144c2017-06-12 14:26:21 -04002496 } else {
2497 CFPTy->print(errs());
2498 llvm_unreachable("Implement this ConstantFP Type");
2499 }
2500
2501 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002502
David Neto257c3892018-04-11 13:19:45 -04002503 Ops << MkFloat(LiteralNum);
David Neto22f144c2017-06-12 14:26:21 -04002504 } else if (isa<ConstantDataSequential>(Cst) &&
2505 cast<ConstantDataSequential>(Cst)->isString()) {
2506 Cst->print(errs());
2507 llvm_unreachable("Implement this Constant");
2508
2509 } else if (const ConstantDataSequential *CDS =
2510 dyn_cast<ConstantDataSequential>(Cst)) {
David Neto49351ac2017-08-26 17:32:20 -04002511 // Let's convert <4 x i8> constant to int constant specially.
2512 // This case occurs when all the values are specified as constant
2513 // ints.
2514 Type *CstTy = Cst->getType();
2515 if (is4xi8vec(CstTy)) {
2516 LLVMContext &Context = CstTy->getContext();
2517
2518 //
2519 // Generate OpConstant with OpTypeInt 32 0.
2520 //
Neil Henning39672102017-09-29 14:33:13 +01002521 uint32_t IntValue = 0;
2522 for (unsigned k = 0; k < 4; k++) {
2523 const uint64_t Val = CDS->getElementAsInteger(k);
David Neto49351ac2017-08-26 17:32:20 -04002524 IntValue = (IntValue << 8) | (Val & 0xffu);
2525 }
2526
2527 Type *i32 = Type::getInt32Ty(Context);
2528 Constant *CstInt = ConstantInt::get(i32, IntValue);
2529 // If this constant is already registered on VMap, use it.
2530 if (VMap.count(CstInt)) {
2531 uint32_t CstID = VMap[CstInt];
2532 VMap[Cst] = CstID;
2533 continue;
2534 }
2535
David Neto257c3892018-04-11 13:19:45 -04002536 Ops << MkNum(IntValue);
David Neto49351ac2017-08-26 17:32:20 -04002537
David Neto87846742018-04-11 17:36:22 -04002538 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto49351ac2017-08-26 17:32:20 -04002539 SPIRVInstList.push_back(CstInst);
2540
2541 continue;
2542 }
2543
2544 // A normal constant-data-sequential case.
David Neto22f144c2017-06-12 14:26:21 -04002545 for (unsigned k = 0; k < CDS->getNumElements(); k++) {
2546 Constant *EleCst = CDS->getElementAsConstant(k);
2547 uint32_t EleCstID = VMap[EleCst];
David Neto257c3892018-04-11 13:19:45 -04002548 Ops << MkId(EleCstID);
David Neto22f144c2017-06-12 14:26:21 -04002549 }
2550
2551 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002552 } else if (const ConstantAggregate *CA = dyn_cast<ConstantAggregate>(Cst)) {
2553 // Let's convert <4 x i8> constant to int constant specially.
David Neto49351ac2017-08-26 17:32:20 -04002554 // This case occurs when at least one of the values is an undef.
David Neto22f144c2017-06-12 14:26:21 -04002555 Type *CstTy = Cst->getType();
2556 if (is4xi8vec(CstTy)) {
2557 LLVMContext &Context = CstTy->getContext();
2558
2559 //
2560 // Generate OpConstant with OpTypeInt 32 0.
2561 //
Neil Henning39672102017-09-29 14:33:13 +01002562 uint32_t IntValue = 0;
David Neto22f144c2017-06-12 14:26:21 -04002563 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end();
2564 I != E; ++I) {
2565 uint64_t Val = 0;
alan-bakerb6b09dc2018-11-08 16:59:28 -05002566 const Value *CV = *I;
Neil Henning39672102017-09-29 14:33:13 +01002567 if (auto *CI2 = dyn_cast<ConstantInt>(CV)) {
2568 Val = CI2->getZExtValue();
David Neto22f144c2017-06-12 14:26:21 -04002569 }
David Neto49351ac2017-08-26 17:32:20 -04002570 IntValue = (IntValue << 8) | (Val & 0xffu);
David Neto22f144c2017-06-12 14:26:21 -04002571 }
2572
David Neto49351ac2017-08-26 17:32:20 -04002573 Type *i32 = Type::getInt32Ty(Context);
2574 Constant *CstInt = ConstantInt::get(i32, IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002575 // If this constant is already registered on VMap, use it.
2576 if (VMap.count(CstInt)) {
2577 uint32_t CstID = VMap[CstInt];
2578 VMap[Cst] = CstID;
David Neto19a1bad2017-08-25 15:01:41 -04002579 continue;
David Neto22f144c2017-06-12 14:26:21 -04002580 }
2581
David Neto257c3892018-04-11 13:19:45 -04002582 Ops << MkNum(IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002583
David Neto87846742018-04-11 17:36:22 -04002584 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002585 SPIRVInstList.push_back(CstInst);
2586
David Neto19a1bad2017-08-25 15:01:41 -04002587 continue;
David Neto22f144c2017-06-12 14:26:21 -04002588 }
2589
2590 // We use a constant composite in SPIR-V for our constant aggregate in
2591 // LLVM.
2592 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002593
2594 for (unsigned k = 0; k < CA->getNumOperands(); k++) {
2595 // Look up the ID of the element of this aggregate (which we will
2596 // previously have created a constant for).
2597 uint32_t ElementConstantID = VMap[CA->getAggregateElement(k)];
2598
2599 // And add an operand to the composite we are constructing
David Neto257c3892018-04-11 13:19:45 -04002600 Ops << MkId(ElementConstantID);
David Neto22f144c2017-06-12 14:26:21 -04002601 }
2602 } else if (Cst->isNullValue()) {
2603 Opcode = spv::OpConstantNull;
David Neto22f144c2017-06-12 14:26:21 -04002604 } else {
2605 Cst->print(errs());
2606 llvm_unreachable("Unsupported Constant???");
2607 }
2608
alan-baker5b86ed72019-02-15 08:26:50 -05002609 if (Opcode == spv::OpConstantNull && Cst->getType()->isPointerTy()) {
2610 // Null pointer requires variable pointers.
2611 setVariablePointersCapabilities(Cst->getType()->getPointerAddressSpace());
2612 }
2613
David Neto87846742018-04-11 17:36:22 -04002614 auto *CstInst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002615 SPIRVInstList.push_back(CstInst);
2616 }
2617}
2618
2619void SPIRVProducerPass::GenerateSamplers(Module &M) {
2620 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
David Neto22f144c2017-06-12 14:26:21 -04002621
alan-bakerb6b09dc2018-11-08 16:59:28 -05002622 auto &sampler_map = getSamplerMap();
alan-baker09cb9802019-12-10 13:16:27 -05002623 SamplerLiteralToIDMap.clear();
David Neto862b7d82018-06-14 18:48:37 -04002624 DenseMap<unsigned, unsigned> SamplerLiteralToDescriptorSetMap;
2625 DenseMap<unsigned, unsigned> SamplerLiteralToBindingMap;
David Neto22f144c2017-06-12 14:26:21 -04002626
David Neto862b7d82018-06-14 18:48:37 -04002627 // We might have samplers in the sampler map that are not used
2628 // in the translation unit. We need to allocate variables
2629 // for them and bindings too.
2630 DenseSet<unsigned> used_bindings;
David Neto22f144c2017-06-12 14:26:21 -04002631
Kévin Petitdf71de32019-04-09 14:09:50 +01002632 auto *var_fn = M.getFunction(clspv::LiteralSamplerFunction());
alan-baker09cb9802019-12-10 13:16:27 -05002633 // Return if there are no literal samplers.
alan-bakerb6b09dc2018-11-08 16:59:28 -05002634 if (!var_fn)
2635 return;
alan-baker09cb9802019-12-10 13:16:27 -05002636
David Neto862b7d82018-06-14 18:48:37 -04002637 for (auto user : var_fn->users()) {
2638 // Populate SamplerLiteralToDescriptorSetMap and
2639 // SamplerLiteralToBindingMap.
2640 //
2641 // Look for calls like
2642 // call %opencl.sampler_t addrspace(2)*
2643 // @clspv.sampler.var.literal(
2644 // i32 descriptor,
2645 // i32 binding,
alan-baker09cb9802019-12-10 13:16:27 -05002646 // i32 (index-into-sampler-map|sampler_mask))
alan-bakerb6b09dc2018-11-08 16:59:28 -05002647 if (auto *call = dyn_cast<CallInst>(user)) {
alan-baker09cb9802019-12-10 13:16:27 -05002648 const auto third_param = static_cast<unsigned>(
alan-bakerb6b09dc2018-11-08 16:59:28 -05002649 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
alan-baker09cb9802019-12-10 13:16:27 -05002650 auto sampler_value = third_param;
2651 if (clspv::Option::UseSamplerMap()) {
2652 if (third_param >= sampler_map.size()) {
2653 errs() << "Out of bounds index to sampler map: " << third_param;
2654 llvm_unreachable("bad sampler init: out of bounds");
2655 }
2656 sampler_value = sampler_map[third_param].first;
David Neto862b7d82018-06-14 18:48:37 -04002657 }
2658
David Neto862b7d82018-06-14 18:48:37 -04002659 const auto descriptor_set = static_cast<unsigned>(
2660 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
2661 const auto binding = static_cast<unsigned>(
2662 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
2663
2664 SamplerLiteralToDescriptorSetMap[sampler_value] = descriptor_set;
2665 SamplerLiteralToBindingMap[sampler_value] = binding;
2666 used_bindings.insert(binding);
2667 }
2668 }
2669
alan-baker09cb9802019-12-10 13:16:27 -05002670 DenseSet<size_t> seen;
2671 for (auto user : var_fn->users()) {
2672 if (!isa<CallInst>(user))
2673 continue;
2674
2675 auto call = cast<CallInst>(user);
2676 const unsigned third_param = static_cast<unsigned>(
2677 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
2678
2679 // Already allocated a variable for this value.
2680 if (!seen.insert(third_param).second)
2681 continue;
2682
2683 auto sampler_value = third_param;
2684 if (clspv::Option::UseSamplerMap()) {
2685 sampler_value = sampler_map[third_param].first;
2686 }
2687
David Neto22f144c2017-06-12 14:26:21 -04002688 // Generate OpVariable.
2689 //
2690 // GIDOps[0] : Result Type ID
2691 // GIDOps[1] : Storage Class
2692 SPIRVOperandList Ops;
2693
David Neto257c3892018-04-11 13:19:45 -04002694 Ops << MkId(lookupType(SamplerTy))
2695 << MkNum(spv::StorageClassUniformConstant);
David Neto22f144c2017-06-12 14:26:21 -04002696
David Neto862b7d82018-06-14 18:48:37 -04002697 auto sampler_var_id = nextID++;
2698 auto *Inst = new SPIRVInstruction(spv::OpVariable, sampler_var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002699 SPIRVInstList.push_back(Inst);
2700
alan-baker09cb9802019-12-10 13:16:27 -05002701 SamplerLiteralToIDMap[sampler_value] = sampler_var_id;
David Neto22f144c2017-06-12 14:26:21 -04002702
2703 // Find Insert Point for OpDecorate.
2704 auto DecoInsertPoint =
2705 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2706 [](SPIRVInstruction *Inst) -> bool {
2707 return Inst->getOpcode() != spv::OpDecorate &&
2708 Inst->getOpcode() != spv::OpMemberDecorate &&
2709 Inst->getOpcode() != spv::OpExtInstImport;
2710 });
2711
2712 // Ops[0] = Target ID
2713 // Ops[1] = Decoration (DescriptorSet)
2714 // Ops[2] = LiteralNumber according to Decoration
2715 Ops.clear();
2716
David Neto862b7d82018-06-14 18:48:37 -04002717 unsigned descriptor_set;
2718 unsigned binding;
alan-baker09cb9802019-12-10 13:16:27 -05002719 if (SamplerLiteralToBindingMap.find(sampler_value) ==
alan-bakerb6b09dc2018-11-08 16:59:28 -05002720 SamplerLiteralToBindingMap.end()) {
David Neto862b7d82018-06-14 18:48:37 -04002721 // This sampler is not actually used. Find the next one.
2722 for (binding = 0; used_bindings.count(binding); binding++)
2723 ;
2724 descriptor_set = 0; // Literal samplers always use descriptor set 0.
2725 used_bindings.insert(binding);
2726 } else {
alan-baker09cb9802019-12-10 13:16:27 -05002727 descriptor_set = SamplerLiteralToDescriptorSetMap[sampler_value];
2728 binding = SamplerLiteralToBindingMap[sampler_value];
alan-bakercff80152019-06-15 00:38:00 -04002729
alan-baker09cb9802019-12-10 13:16:27 -05002730 version0::DescriptorMapEntry::SamplerData sampler_data = {sampler_value};
alan-bakercff80152019-06-15 00:38:00 -04002731 descriptorMapEntries->emplace_back(std::move(sampler_data),
2732 descriptor_set, binding);
David Neto862b7d82018-06-14 18:48:37 -04002733 }
2734
2735 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationDescriptorSet)
2736 << MkNum(descriptor_set);
David Neto22f144c2017-06-12 14:26:21 -04002737
David Neto87846742018-04-11 17:36:22 -04002738 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002739 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
2740
2741 // Ops[0] = Target ID
2742 // Ops[1] = Decoration (Binding)
2743 // Ops[2] = LiteralNumber according to Decoration
2744 Ops.clear();
David Neto862b7d82018-06-14 18:48:37 -04002745 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationBinding)
2746 << MkNum(binding);
David Neto22f144c2017-06-12 14:26:21 -04002747
David Neto87846742018-04-11 17:36:22 -04002748 auto *BindDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002749 SPIRVInstList.insert(DecoInsertPoint, BindDecoInst);
2750 }
David Neto862b7d82018-06-14 18:48:37 -04002751}
David Neto22f144c2017-06-12 14:26:21 -04002752
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01002753void SPIRVProducerPass::GenerateResourceVars(Module &) {
David Neto862b7d82018-06-14 18:48:37 -04002754 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2755 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04002756
David Neto862b7d82018-06-14 18:48:37 -04002757 // Generate variables. Make one for each of resource var info object.
2758 for (auto *info : ModuleOrderedResourceVars) {
2759 Type *type = info->var_fn->getReturnType();
2760 // Remap the address space for opaque types.
2761 switch (info->arg_kind) {
2762 case clspv::ArgKind::Sampler:
2763 case clspv::ArgKind::ReadOnlyImage:
2764 case clspv::ArgKind::WriteOnlyImage:
2765 type = PointerType::get(type->getPointerElementType(),
2766 clspv::AddressSpace::UniformConstant);
2767 break;
2768 default:
2769 break;
2770 }
David Neto22f144c2017-06-12 14:26:21 -04002771
David Neto862b7d82018-06-14 18:48:37 -04002772 info->var_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04002773
David Neto862b7d82018-06-14 18:48:37 -04002774 const auto type_id = lookupType(type);
2775 const auto sc = GetStorageClassForArgKind(info->arg_kind);
2776 SPIRVOperandList Ops;
2777 Ops << MkId(type_id) << MkNum(sc);
David Neto22f144c2017-06-12 14:26:21 -04002778
David Neto862b7d82018-06-14 18:48:37 -04002779 auto *Inst = new SPIRVInstruction(spv::OpVariable, info->var_id, Ops);
2780 SPIRVInstList.push_back(Inst);
2781
2782 // Map calls to the variable-builtin-function.
2783 for (auto &U : info->var_fn->uses()) {
2784 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
2785 const auto set = unsigned(
2786 dyn_cast<ConstantInt>(call->getOperand(0))->getZExtValue());
2787 const auto binding = unsigned(
2788 dyn_cast<ConstantInt>(call->getOperand(1))->getZExtValue());
2789 if (set == info->descriptor_set && binding == info->binding) {
2790 switch (info->arg_kind) {
2791 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002792 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002793 case clspv::ArgKind::Pod:
2794 // The call maps to the variable directly.
2795 VMap[call] = info->var_id;
2796 break;
2797 case clspv::ArgKind::Sampler:
2798 case clspv::ArgKind::ReadOnlyImage:
2799 case clspv::ArgKind::WriteOnlyImage:
2800 // The call maps to a load we generate later.
2801 ResourceVarDeferredLoadCalls[call] = info->var_id;
2802 break;
2803 default:
2804 llvm_unreachable("Unhandled arg kind");
2805 }
2806 }
David Neto22f144c2017-06-12 14:26:21 -04002807 }
David Neto862b7d82018-06-14 18:48:37 -04002808 }
2809 }
David Neto22f144c2017-06-12 14:26:21 -04002810
David Neto862b7d82018-06-14 18:48:37 -04002811 // Generate associated decorations.
David Neto22f144c2017-06-12 14:26:21 -04002812
David Neto862b7d82018-06-14 18:48:37 -04002813 // Find Insert Point for OpDecorate.
2814 auto DecoInsertPoint =
2815 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2816 [](SPIRVInstruction *Inst) -> bool {
2817 return Inst->getOpcode() != spv::OpDecorate &&
2818 Inst->getOpcode() != spv::OpMemberDecorate &&
2819 Inst->getOpcode() != spv::OpExtInstImport;
2820 });
2821
2822 SPIRVOperandList Ops;
2823 for (auto *info : ModuleOrderedResourceVars) {
2824 // Decorate with DescriptorSet and Binding.
2825 Ops.clear();
2826 Ops << MkId(info->var_id) << MkNum(spv::DecorationDescriptorSet)
2827 << MkNum(info->descriptor_set);
2828 SPIRVInstList.insert(DecoInsertPoint,
2829 new SPIRVInstruction(spv::OpDecorate, Ops));
2830
2831 Ops.clear();
2832 Ops << MkId(info->var_id) << MkNum(spv::DecorationBinding)
2833 << MkNum(info->binding);
2834 SPIRVInstList.insert(DecoInsertPoint,
2835 new SPIRVInstruction(spv::OpDecorate, Ops));
2836
alan-bakere9308012019-03-15 10:25:13 -04002837 if (info->coherent) {
2838 // Decorate with Coherent if required for the variable.
2839 Ops.clear();
2840 Ops << MkId(info->var_id) << MkNum(spv::DecorationCoherent);
2841 SPIRVInstList.insert(DecoInsertPoint,
2842 new SPIRVInstruction(spv::OpDecorate, Ops));
2843 }
2844
David Neto862b7d82018-06-14 18:48:37 -04002845 // Generate NonWritable and NonReadable
2846 switch (info->arg_kind) {
2847 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002848 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002849 if (info->var_fn->getReturnType()->getPointerAddressSpace() ==
2850 clspv::AddressSpace::Constant) {
2851 Ops.clear();
2852 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonWritable);
2853 SPIRVInstList.insert(DecoInsertPoint,
2854 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002855 }
David Neto862b7d82018-06-14 18:48:37 -04002856 break;
David Neto862b7d82018-06-14 18:48:37 -04002857 case clspv::ArgKind::WriteOnlyImage:
2858 Ops.clear();
2859 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonReadable);
2860 SPIRVInstList.insert(DecoInsertPoint,
2861 new SPIRVInstruction(spv::OpDecorate, Ops));
2862 break;
2863 default:
2864 break;
David Neto22f144c2017-06-12 14:26:21 -04002865 }
2866 }
2867}
2868
Kévin Petitbbbda972020-03-03 19:16:31 +00002869namespace {
2870
2871bool isScalarType(Type *type) {
2872 return type->isIntegerTy() || type->isFloatTy();
2873}
2874
2875uint64_t structAlignment(StructType *type,
2876 std::function<uint64_t(Type *)> alignFn) {
2877 uint64_t maxAlign = 1;
2878 for (unsigned i = 0; i < type->getStructNumElements(); i++) {
2879 uint64_t align = alignFn(type->getStructElementType(i));
2880 maxAlign = std::max(align, maxAlign);
2881 }
2882 return maxAlign;
2883}
2884
2885uint64_t scalarAlignment(Type *type) {
2886 // A scalar of size N has a scalar alignment of N.
2887 if (isScalarType(type)) {
2888 return type->getScalarSizeInBits() / 8;
2889 }
2890
2891 // A vector or matrix type has a scalar alignment equal to that of its
2892 // component type.
2893 if (type->isVectorTy()) {
2894 return scalarAlignment(type->getVectorElementType());
2895 }
2896
2897 // An array type has a scalar alignment equal to that of its element type.
2898 if (type->isArrayTy()) {
2899 return scalarAlignment(type->getArrayElementType());
2900 }
2901
2902 // A structure has a scalar alignment equal to the largest scalar alignment of
2903 // any of its members.
2904 if (type->isStructTy()) {
2905 return structAlignment(cast<StructType>(type), scalarAlignment);
2906 }
2907
2908 llvm_unreachable("Unsupported type");
2909}
2910
2911uint64_t baseAlignment(Type *type) {
2912 // A scalar has a base alignment equal to its scalar alignment.
2913 if (isScalarType(type)) {
2914 return scalarAlignment(type);
2915 }
2916
2917 if (type->isVectorTy()) {
2918 unsigned numElems = type->getVectorNumElements();
2919
2920 // A two-component vector has a base alignment equal to twice its scalar
2921 // alignment.
2922 if (numElems == 2) {
2923 return 2 * scalarAlignment(type);
2924 }
2925 // A three- or four-component vector has a base alignment equal to four
2926 // times its scalar alignment.
2927 if ((numElems == 3) || (numElems == 4)) {
2928 return 4 * scalarAlignment(type);
2929 }
2930 }
2931
2932 // An array has a base alignment equal to the base alignment of its element
2933 // type.
2934 if (type->isArrayTy()) {
2935 return baseAlignment(type->getArrayElementType());
2936 }
2937
2938 // A structure has a base alignment equal to the largest base alignment of any
2939 // of its members.
2940 if (type->isStructTy()) {
2941 return structAlignment(cast<StructType>(type), baseAlignment);
2942 }
2943
2944 // TODO A row-major matrix of C columns has a base alignment equal to the base
2945 // alignment of a vector of C matrix components.
2946 // TODO A column-major matrix has a base alignment equal to the base alignment
2947 // of the matrix column type.
2948
2949 llvm_unreachable("Unsupported type");
2950}
2951
2952uint64_t extendedAlignment(Type *type) {
2953 // A scalar, vector or matrix type has an extended alignment equal to its base
2954 // alignment.
2955 // TODO matrix type
2956 if (isScalarType(type) || type->isVectorTy()) {
2957 return baseAlignment(type);
2958 }
2959
2960 // An array or structure type has an extended alignment equal to the largest
2961 // extended alignment of any of its members, rounded up to a multiple of 16
2962 if (type->isStructTy()) {
2963 auto salign = structAlignment(cast<StructType>(type), extendedAlignment);
2964 return alignTo(salign, 16);
2965 }
2966
2967 if (type->isArrayTy()) {
2968 auto salign = extendedAlignment(type->getArrayElementType());
2969 return alignTo(salign, 16);
2970 }
2971
2972 llvm_unreachable("Unsupported type");
2973}
2974
2975uint64_t standardAlignment(Type *type, spv::StorageClass sclass) {
2976 // If the scalarBlockLayout feature is enabled on the device then every member
2977 // must be aligned according to its scalar alignment
2978 if (clspv::Option::ScalarBlockLayout()) {
2979 return scalarAlignment(type);
2980 }
2981
2982 // All vectors must be aligned according to their scalar alignment
2983 if (type->isVectorTy()) {
2984 return scalarAlignment(type);
2985 }
2986
2987 // If the uniformBufferStandardLayout feature is not enabled on the device,
2988 // then any member of an OpTypeStruct with a storage class of Uniform and a
2989 // decoration of Block must be aligned according to its extended alignment.
2990 if (!clspv::Option::Std430UniformBufferLayout() &&
2991 sclass == spv::StorageClassUniform) {
2992 return extendedAlignment(type);
2993 }
2994
2995 // Every other member must be aligned according to its base alignment
2996 return baseAlignment(type);
2997}
2998
2999bool improperlyStraddles(const DataLayout &DL, Type *type, unsigned offset) {
3000 assert(type->isVectorTy());
3001
3002 auto size = DL.getTypeStoreSize(type);
3003
3004 // It is a vector with total size less than or equal to 16 bytes, and has
3005 // Offset decorations placing its first byte at F and its last byte at L,
3006 // where floor(F / 16) != floor(L / 16).
3007 if ((size <= 16) && (offset % 16 + size > 16)) {
3008 return true;
3009 }
3010
3011 // It is a vector with total size greater than 16 bytes and has its Offset
3012 // decorations placing its first byte at a non-integer multiple of 16
3013 if ((size > 16) && (offset % 16 != 0)) {
3014 return true;
3015 }
3016
3017 return false;
3018}
3019
3020// See 14.5 Shader Resource Interface in Vulkan spec
3021bool isValidExplicitLayout(Module &M, StructType *STy, unsigned Member,
3022 spv::StorageClass SClass, unsigned Offset,
3023 unsigned PreviousMemberOffset) {
3024
3025 auto MemberType = STy->getElementType(Member);
3026 auto Align = standardAlignment(MemberType, SClass);
3027 auto &DL = M.getDataLayout();
3028
3029 // The Offset decoration of any member must be a multiple of its alignment
3030 if (Offset % Align != 0) {
3031 return false;
3032 }
3033
3034 // TODO Any ArrayStride or MatrixStride decoration must be a multiple of the
3035 // alignment of the array or matrix as defined above
3036
3037 if (!clspv::Option::ScalarBlockLayout()) {
3038 // Vectors must not improperly straddle, as defined above
3039 if (MemberType->isVectorTy() &&
3040 improperlyStraddles(DL, MemberType, Offset)) {
3041 return true;
3042 }
3043
3044 // The Offset decoration of a member must not place it between the end
3045 // of a structure or an array and the next multiple of the alignment of that
3046 // structure or array
3047 if (Member > 0) {
3048 auto PType = STy->getElementType(Member - 1);
3049 if (PType->isStructTy() || PType->isArrayTy()) {
3050 auto PAlign = standardAlignment(PType, SClass);
3051 if (Offset - PreviousMemberOffset < PAlign) {
3052 return false;
3053 }
3054 }
3055 }
3056 }
3057
3058 return true;
3059}
3060
3061} // namespace
3062
3063void SPIRVProducerPass::GeneratePushConstantDescriptormapEntries(Module &M) {
3064
3065 if (auto GV = M.getGlobalVariable(clspv::PushConstantsVariableName())) {
3066 auto const &DL = M.getDataLayout();
3067 auto MD = GV->getMetadata(clspv::PushConstantsMetadataName());
3068 auto STy = cast<StructType>(GV->getValueType());
3069
3070 for (unsigned i = 0; i < STy->getNumElements(); i++) {
3071 auto pc = static_cast<clspv::PushConstant>(
3072 mdconst::extract<ConstantInt>(MD->getOperand(i))->getZExtValue());
3073 auto memberType = STy->getElementType(i);
3074 auto offset = GetExplicitLayoutStructMemberOffset(STy, i, DL);
3075 unsigned previousOffset = 0;
3076 if (i > 0) {
3077 previousOffset = GetExplicitLayoutStructMemberOffset(STy, i - 1, DL);
3078 }
3079 auto size = static_cast<uint32_t>(GetTypeSizeInBits(memberType, DL)) / 8;
3080 assert(isValidExplicitLayout(M, STy, i, spv::StorageClassPushConstant,
3081 offset, previousOffset));
3082 version0::DescriptorMapEntry::PushConstantData data = {pc, offset, size};
3083 descriptorMapEntries->emplace_back(std::move(data));
3084 }
3085 }
3086}
3087
David Neto22f144c2017-06-12 14:26:21 -04003088void SPIRVProducerPass::GenerateGlobalVar(GlobalVariable &GV) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05003089 Module &M = *GV.getParent();
David Neto22f144c2017-06-12 14:26:21 -04003090 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3091 ValueMapType &VMap = getValueMap();
3092 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
David Neto85082642018-03-24 06:55:20 -07003093 const DataLayout &DL = GV.getParent()->getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04003094
3095 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
3096 Type *Ty = GV.getType();
3097 PointerType *PTy = cast<PointerType>(Ty);
3098
3099 uint32_t InitializerID = 0;
3100
3101 // Workgroup size is handled differently (it goes into a constant)
3102 if (spv::BuiltInWorkgroupSize == BuiltinType) {
3103 std::vector<bool> HasMDVec;
3104 uint32_t PrevXDimCst = 0xFFFFFFFF;
3105 uint32_t PrevYDimCst = 0xFFFFFFFF;
3106 uint32_t PrevZDimCst = 0xFFFFFFFF;
3107 for (Function &Func : *GV.getParent()) {
3108 if (Func.isDeclaration()) {
3109 continue;
3110 }
3111
3112 // We only need to check kernels.
3113 if (Func.getCallingConv() != CallingConv::SPIR_KERNEL) {
3114 continue;
3115 }
3116
3117 if (const MDNode *MD =
3118 dyn_cast<Function>(&Func)->getMetadata("reqd_work_group_size")) {
3119 uint32_t CurXDimCst = static_cast<uint32_t>(
3120 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
3121 uint32_t CurYDimCst = static_cast<uint32_t>(
3122 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
3123 uint32_t CurZDimCst = static_cast<uint32_t>(
3124 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
3125
3126 if (PrevXDimCst == 0xFFFFFFFF && PrevYDimCst == 0xFFFFFFFF &&
3127 PrevZDimCst == 0xFFFFFFFF) {
3128 PrevXDimCst = CurXDimCst;
3129 PrevYDimCst = CurYDimCst;
3130 PrevZDimCst = CurZDimCst;
3131 } else if (CurXDimCst != PrevXDimCst || CurYDimCst != PrevYDimCst ||
3132 CurZDimCst != PrevZDimCst) {
3133 llvm_unreachable(
3134 "reqd_work_group_size must be the same across all kernels");
3135 } else {
3136 continue;
3137 }
3138
3139 //
3140 // Generate OpConstantComposite.
3141 //
3142 // Ops[0] : Result Type ID
3143 // Ops[1] : Constant size for x dimension.
3144 // Ops[2] : Constant size for y dimension.
3145 // Ops[3] : Constant size for z dimension.
3146 SPIRVOperandList Ops;
3147
3148 uint32_t XDimCstID =
3149 VMap[mdconst::extract<ConstantInt>(MD->getOperand(0))];
3150 uint32_t YDimCstID =
3151 VMap[mdconst::extract<ConstantInt>(MD->getOperand(1))];
3152 uint32_t ZDimCstID =
3153 VMap[mdconst::extract<ConstantInt>(MD->getOperand(2))];
3154
3155 InitializerID = nextID;
3156
David Neto257c3892018-04-11 13:19:45 -04003157 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
3158 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04003159
David Neto87846742018-04-11 17:36:22 -04003160 auto *Inst =
3161 new SPIRVInstruction(spv::OpConstantComposite, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003162 SPIRVInstList.push_back(Inst);
3163
3164 HasMDVec.push_back(true);
3165 } else {
3166 HasMDVec.push_back(false);
3167 }
3168 }
3169
3170 // Check all kernels have same definitions for work_group_size.
3171 bool HasMD = false;
3172 if (!HasMDVec.empty()) {
3173 HasMD = HasMDVec[0];
3174 for (uint32_t i = 1; i < HasMDVec.size(); i++) {
3175 if (HasMD != HasMDVec[i]) {
3176 llvm_unreachable(
3177 "Kernels should have consistent work group size definition");
3178 }
3179 }
3180 }
3181
3182 // If all kernels do not have metadata for reqd_work_group_size, generate
3183 // OpSpecConstants for x/y/z dimension.
3184 if (!HasMD) {
3185 //
3186 // Generate OpSpecConstants for x/y/z dimension.
3187 //
3188 // Ops[0] : Result Type ID
3189 // Ops[1] : Constant size for x/y/z dimension (Literal Number).
3190 uint32_t XDimCstID = 0;
3191 uint32_t YDimCstID = 0;
3192 uint32_t ZDimCstID = 0;
3193
David Neto22f144c2017-06-12 14:26:21 -04003194 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04003195 uint32_t result_type_id =
3196 lookupType(Ty->getPointerElementType()->getSequentialElementType());
David Neto22f144c2017-06-12 14:26:21 -04003197
David Neto257c3892018-04-11 13:19:45 -04003198 // X Dimension
3199 Ops << MkId(result_type_id) << MkNum(1);
3200 XDimCstID = nextID++;
3201 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04003202 new SPIRVInstruction(spv::OpSpecConstant, XDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003203
3204 // Y Dimension
3205 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003206 Ops << MkId(result_type_id) << MkNum(1);
3207 YDimCstID = nextID++;
3208 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04003209 new SPIRVInstruction(spv::OpSpecConstant, YDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003210
3211 // Z Dimension
3212 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003213 Ops << MkId(result_type_id) << MkNum(1);
3214 ZDimCstID = nextID++;
3215 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04003216 new SPIRVInstruction(spv::OpSpecConstant, ZDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003217
David Neto257c3892018-04-11 13:19:45 -04003218 BuiltinDimVec.push_back(XDimCstID);
3219 BuiltinDimVec.push_back(YDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04003220 BuiltinDimVec.push_back(ZDimCstID);
3221
David Neto22f144c2017-06-12 14:26:21 -04003222 //
3223 // Generate OpSpecConstantComposite.
3224 //
3225 // Ops[0] : Result Type ID
3226 // Ops[1] : Constant size for x dimension.
3227 // Ops[2] : Constant size for y dimension.
3228 // Ops[3] : Constant size for z dimension.
3229 InitializerID = nextID;
3230
3231 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003232 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
3233 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04003234
David Neto87846742018-04-11 17:36:22 -04003235 auto *Inst =
3236 new SPIRVInstruction(spv::OpSpecConstantComposite, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003237 SPIRVInstList.push_back(Inst);
3238 }
3239 }
3240
David Neto22f144c2017-06-12 14:26:21 -04003241 VMap[&GV] = nextID;
3242
3243 //
3244 // Generate OpVariable.
3245 //
3246 // GIDOps[0] : Result Type ID
3247 // GIDOps[1] : Storage Class
3248 SPIRVOperandList Ops;
3249
David Neto85082642018-03-24 06:55:20 -07003250 const auto AS = PTy->getAddressSpace();
David Netoc6f3ab22018-04-06 18:02:31 -04003251 Ops << MkId(lookupType(Ty)) << MkNum(GetStorageClass(AS));
David Neto22f144c2017-06-12 14:26:21 -04003252
David Neto85082642018-03-24 06:55:20 -07003253 const bool module_scope_constant_external_init =
David Neto862b7d82018-06-14 18:48:37 -04003254 (AS == AddressSpace::Constant) && GV.hasInitializer() &&
David Neto85082642018-03-24 06:55:20 -07003255 clspv::Option::ModuleConstantsInStorageBuffer();
3256
Kévin Petit23d5f182019-08-13 16:21:29 +01003257 if (GV.hasInitializer()) {
3258 auto GVInit = GV.getInitializer();
3259 if (!isa<UndefValue>(GVInit) && !module_scope_constant_external_init) {
3260 assert(VMap.count(GVInit) == 1);
3261 InitializerID = VMap[GVInit];
David Neto85082642018-03-24 06:55:20 -07003262 }
3263 }
Kévin Petit23d5f182019-08-13 16:21:29 +01003264
3265 if (0 != InitializerID) {
Kévin Petitbbbda972020-03-03 19:16:31 +00003266 // Emit the ID of the initializer as part of the variable definition.
Kévin Petit23d5f182019-08-13 16:21:29 +01003267 Ops << MkId(InitializerID);
3268 }
David Neto85082642018-03-24 06:55:20 -07003269 const uint32_t var_id = nextID++;
3270
David Neto87846742018-04-11 17:36:22 -04003271 auto *Inst = new SPIRVInstruction(spv::OpVariable, var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003272 SPIRVInstList.push_back(Inst);
3273
3274 // If we have a builtin.
3275 if (spv::BuiltInMax != BuiltinType) {
3276 // Find Insert Point for OpDecorate.
3277 auto DecoInsertPoint =
3278 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
3279 [](SPIRVInstruction *Inst) -> bool {
3280 return Inst->getOpcode() != spv::OpDecorate &&
3281 Inst->getOpcode() != spv::OpMemberDecorate &&
3282 Inst->getOpcode() != spv::OpExtInstImport;
3283 });
3284 //
3285 // Generate OpDecorate.
3286 //
3287 // DOps[0] = Target ID
3288 // DOps[1] = Decoration (Builtin)
3289 // DOps[2] = BuiltIn ID
3290 uint32_t ResultID;
3291
3292 // WorkgroupSize is different, we decorate the constant composite that has
3293 // its value, rather than the variable that we use to access the value.
3294 if (spv::BuiltInWorkgroupSize == BuiltinType) {
3295 ResultID = InitializerID;
David Netoa60b00b2017-09-15 16:34:09 -04003296 // Save both the value and variable IDs for later.
3297 WorkgroupSizeValueID = InitializerID;
3298 WorkgroupSizeVarID = VMap[&GV];
David Neto22f144c2017-06-12 14:26:21 -04003299 } else {
3300 ResultID = VMap[&GV];
3301 }
3302
3303 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04003304 DOps << MkId(ResultID) << MkNum(spv::DecorationBuiltIn)
3305 << MkNum(BuiltinType);
David Neto22f144c2017-06-12 14:26:21 -04003306
David Neto87846742018-04-11 17:36:22 -04003307 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, DOps);
David Neto22f144c2017-06-12 14:26:21 -04003308 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
David Neto85082642018-03-24 06:55:20 -07003309 } else if (module_scope_constant_external_init) {
3310 // This module scope constant is initialized from a storage buffer with data
3311 // provided by the host at binding 0 of the next descriptor set.
David Neto78383442018-06-15 20:31:56 -04003312 const uint32_t descriptor_set = TakeDescriptorIndex(&M);
David Neto85082642018-03-24 06:55:20 -07003313
David Neto862b7d82018-06-14 18:48:37 -04003314 // Emit the intializer to the descriptor map file.
David Neto85082642018-03-24 06:55:20 -07003315 // Use "kind,buffer" to indicate storage buffer. We might want to expand
3316 // that later to other types, like uniform buffer.
alan-bakerf5e5f692018-11-27 08:33:24 -05003317 std::string hexbytes;
3318 llvm::raw_string_ostream str(hexbytes);
3319 clspv::ConstantEmitter(DL, str).Emit(GV.getInitializer());
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003320 version0::DescriptorMapEntry::ConstantData constant_data = {ArgKind::Buffer,
3321 str.str()};
3322 descriptorMapEntries->emplace_back(std::move(constant_data), descriptor_set,
3323 0);
David Neto85082642018-03-24 06:55:20 -07003324
3325 // Find Insert Point for OpDecorate.
3326 auto DecoInsertPoint =
3327 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
3328 [](SPIRVInstruction *Inst) -> bool {
3329 return Inst->getOpcode() != spv::OpDecorate &&
3330 Inst->getOpcode() != spv::OpMemberDecorate &&
3331 Inst->getOpcode() != spv::OpExtInstImport;
3332 });
3333
David Neto257c3892018-04-11 13:19:45 -04003334 // OpDecorate %var Binding <binding>
David Neto85082642018-03-24 06:55:20 -07003335 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04003336 DOps << MkId(var_id) << MkNum(spv::DecorationBinding) << MkNum(0);
3337 DecoInsertPoint = SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04003338 DecoInsertPoint, new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto85082642018-03-24 06:55:20 -07003339
3340 // OpDecorate %var DescriptorSet <descriptor_set>
3341 DOps.clear();
David Neto257c3892018-04-11 13:19:45 -04003342 DOps << MkId(var_id) << MkNum(spv::DecorationDescriptorSet)
3343 << MkNum(descriptor_set);
David Netoc6f3ab22018-04-06 18:02:31 -04003344 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04003345 new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto22f144c2017-06-12 14:26:21 -04003346 }
3347}
3348
David Netoc6f3ab22018-04-06 18:02:31 -04003349void SPIRVProducerPass::GenerateWorkgroupVars() {
3350 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
Alan Baker202c8c72018-08-13 13:47:44 -04003351 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
3352 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05003353 LocalArgInfo &info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04003354
3355 // Generate OpVariable.
3356 //
3357 // GIDOps[0] : Result Type ID
3358 // GIDOps[1] : Storage Class
3359 SPIRVOperandList Ops;
3360 Ops << MkId(info.ptr_array_type_id) << MkNum(spv::StorageClassWorkgroup);
3361
3362 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04003363 new SPIRVInstruction(spv::OpVariable, info.variable_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04003364 }
3365}
3366
David Neto862b7d82018-06-14 18:48:37 -04003367void SPIRVProducerPass::GenerateDescriptorMapInfo(const DataLayout &DL,
3368 Function &F) {
David Netoc5fb5242018-07-30 13:28:31 -04003369 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
3370 return;
3371 }
David Neto862b7d82018-06-14 18:48:37 -04003372 // Gather the list of resources that are used by this function's arguments.
3373 auto &resource_var_at_index = FunctionToResourceVarsMap[&F];
3374
alan-bakerf5e5f692018-11-27 08:33:24 -05003375 // TODO(alan-baker): This should become unnecessary by fixing the rest of the
3376 // flow to generate pod_ubo arguments earlier.
David Neto862b7d82018-06-14 18:48:37 -04003377 auto remap_arg_kind = [](StringRef argKind) {
alan-bakerf5e5f692018-11-27 08:33:24 -05003378 std::string kind =
3379 clspv::Option::PodArgsInUniformBuffer() && argKind.equals("pod")
3380 ? "pod_ubo"
alan-baker21574d32020-01-29 16:00:31 -05003381 : argKind.str();
alan-bakerf5e5f692018-11-27 08:33:24 -05003382 return GetArgKindFromName(kind);
David Neto862b7d82018-06-14 18:48:37 -04003383 };
3384
3385 auto *fty = F.getType()->getPointerElementType();
3386 auto *func_ty = dyn_cast<FunctionType>(fty);
3387
alan-baker038e9242019-04-19 22:14:41 -04003388 // If we've clustered POD arguments, then argument details are in metadata.
David Neto862b7d82018-06-14 18:48:37 -04003389 // If an argument maps to a resource variable, then get descriptor set and
3390 // binding from the resoure variable. Other info comes from the metadata.
3391 const auto *arg_map = F.getMetadata("kernel_arg_map");
3392 if (arg_map) {
3393 for (const auto &arg : arg_map->operands()) {
3394 const MDNode *arg_node = dyn_cast<MDNode>(arg.get());
Kévin PETITa353c832018-03-20 23:21:21 +00003395 assert(arg_node->getNumOperands() == 7);
David Neto862b7d82018-06-14 18:48:37 -04003396 const auto name =
3397 dyn_cast<MDString>(arg_node->getOperand(0))->getString();
3398 const auto old_index =
3399 dyn_extract<ConstantInt>(arg_node->getOperand(1))->getZExtValue();
3400 // Remapped argument index
alan-bakerb6b09dc2018-11-08 16:59:28 -05003401 const size_t new_index = static_cast<size_t>(
3402 dyn_extract<ConstantInt>(arg_node->getOperand(2))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04003403 const auto offset =
3404 dyn_extract<ConstantInt>(arg_node->getOperand(3))->getZExtValue();
Kévin PETITa353c832018-03-20 23:21:21 +00003405 const auto arg_size =
3406 dyn_extract<ConstantInt>(arg_node->getOperand(4))->getZExtValue();
David Neto862b7d82018-06-14 18:48:37 -04003407 const auto argKind = remap_arg_kind(
Kévin PETITa353c832018-03-20 23:21:21 +00003408 dyn_cast<MDString>(arg_node->getOperand(5))->getString());
David Neto862b7d82018-06-14 18:48:37 -04003409 const auto spec_id =
Kévin PETITa353c832018-03-20 23:21:21 +00003410 dyn_extract<ConstantInt>(arg_node->getOperand(6))->getSExtValue();
alan-bakerf5e5f692018-11-27 08:33:24 -05003411
3412 uint32_t descriptor_set = 0;
3413 uint32_t binding = 0;
3414 version0::DescriptorMapEntry::KernelArgData kernel_data = {
alan-baker21574d32020-01-29 16:00:31 -05003415 F.getName().str(), name.str(), static_cast<uint32_t>(old_index),
3416 argKind, static_cast<uint32_t>(spec_id),
alan-bakerf5e5f692018-11-27 08:33:24 -05003417 // This will be set below for pointer-to-local args.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003418 0, static_cast<uint32_t>(offset), static_cast<uint32_t>(arg_size)};
David Neto862b7d82018-06-14 18:48:37 -04003419 if (spec_id > 0) {
alan-bakerf5e5f692018-11-27 08:33:24 -05003420 kernel_data.local_element_size = static_cast<uint32_t>(GetTypeAllocSize(
3421 func_ty->getParamType(unsigned(new_index))->getPointerElementType(),
3422 DL));
David Neto862b7d82018-06-14 18:48:37 -04003423 } else {
3424 auto *info = resource_var_at_index[new_index];
3425 assert(info);
alan-bakerf5e5f692018-11-27 08:33:24 -05003426 descriptor_set = info->descriptor_set;
3427 binding = info->binding;
David Neto862b7d82018-06-14 18:48:37 -04003428 }
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003429 descriptorMapEntries->emplace_back(std::move(kernel_data), descriptor_set,
3430 binding);
David Neto862b7d82018-06-14 18:48:37 -04003431 }
3432 } else {
3433 // There is no argument map.
3434 // Take descriptor info from the resource variable calls.
Kévin PETITa353c832018-03-20 23:21:21 +00003435 // Take argument name and size from the arguments list.
David Neto862b7d82018-06-14 18:48:37 -04003436
3437 SmallVector<Argument *, 4> arguments;
3438 for (auto &arg : F.args()) {
3439 arguments.push_back(&arg);
3440 }
3441
3442 unsigned arg_index = 0;
3443 for (auto *info : resource_var_at_index) {
3444 if (info) {
Kévin PETITa353c832018-03-20 23:21:21 +00003445 auto arg = arguments[arg_index];
alan-bakerb6b09dc2018-11-08 16:59:28 -05003446 unsigned arg_size = 0;
Kévin PETITa353c832018-03-20 23:21:21 +00003447 if (info->arg_kind == clspv::ArgKind::Pod) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05003448 arg_size = static_cast<uint32_t>(DL.getTypeStoreSize(arg->getType()));
Kévin PETITa353c832018-03-20 23:21:21 +00003449 }
3450
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003451 // Local pointer arguments are unused in this case. Offset is always
3452 // zero.
alan-bakerf5e5f692018-11-27 08:33:24 -05003453 version0::DescriptorMapEntry::KernelArgData kernel_data = {
alan-baker21574d32020-01-29 16:00:31 -05003454 F.getName().str(),
3455 arg->getName().str(),
3456 arg_index,
3457 remap_arg_kind(clspv::GetArgKindName(info->arg_kind)),
3458 0,
3459 0,
3460 0,
3461 arg_size};
alan-bakerf5e5f692018-11-27 08:33:24 -05003462 descriptorMapEntries->emplace_back(std::move(kernel_data),
3463 info->descriptor_set, info->binding);
David Neto862b7d82018-06-14 18:48:37 -04003464 }
3465 arg_index++;
3466 }
3467 // Generate mappings for pointer-to-local arguments.
3468 for (arg_index = 0; arg_index < arguments.size(); ++arg_index) {
3469 Argument *arg = arguments[arg_index];
Alan Baker202c8c72018-08-13 13:47:44 -04003470 auto where = LocalArgSpecIds.find(arg);
3471 if (where != LocalArgSpecIds.end()) {
3472 auto &local_arg_info = LocalSpecIdInfoMap[where->second];
alan-bakerf5e5f692018-11-27 08:33:24 -05003473 // Pod arguments members are unused in this case.
3474 version0::DescriptorMapEntry::KernelArgData kernel_data = {
alan-baker21574d32020-01-29 16:00:31 -05003475 F.getName().str(),
3476 arg->getName().str(),
alan-bakerf5e5f692018-11-27 08:33:24 -05003477 arg_index,
3478 ArgKind::Local,
3479 static_cast<uint32_t>(local_arg_info.spec_id),
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003480 static_cast<uint32_t>(
3481 GetTypeAllocSize(local_arg_info.elem_type, DL)),
alan-bakerf5e5f692018-11-27 08:33:24 -05003482 0,
3483 0};
3484 // Pointer-to-local arguments do not utilize descriptor set and binding.
3485 descriptorMapEntries->emplace_back(std::move(kernel_data), 0, 0);
David Neto862b7d82018-06-14 18:48:37 -04003486 }
3487 }
3488 }
3489}
3490
David Neto22f144c2017-06-12 14:26:21 -04003491void SPIRVProducerPass::GenerateFuncPrologue(Function &F) {
3492 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3493 ValueMapType &VMap = getValueMap();
3494 EntryPointVecType &EntryPoints = getEntryPointVec();
David Neto22f144c2017-06-12 14:26:21 -04003495 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
3496 auto &GlobalConstArgSet = getGlobalConstArgSet();
3497
3498 FunctionType *FTy = F.getFunctionType();
3499
3500 //
David Neto22f144c2017-06-12 14:26:21 -04003501 // Generate OPFunction.
3502 //
3503
3504 // FOps[0] : Result Type ID
3505 // FOps[1] : Function Control
3506 // FOps[2] : Function Type ID
3507 SPIRVOperandList FOps;
3508
3509 // Find SPIRV instruction for return type.
David Neto257c3892018-04-11 13:19:45 -04003510 FOps << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04003511
3512 // Check function attributes for SPIRV Function Control.
3513 uint32_t FuncControl = spv::FunctionControlMaskNone;
3514 if (F.hasFnAttribute(Attribute::AlwaysInline)) {
3515 FuncControl |= spv::FunctionControlInlineMask;
3516 }
3517 if (F.hasFnAttribute(Attribute::NoInline)) {
3518 FuncControl |= spv::FunctionControlDontInlineMask;
3519 }
3520 // TODO: Check llvm attribute for Function Control Pure.
3521 if (F.hasFnAttribute(Attribute::ReadOnly)) {
3522 FuncControl |= spv::FunctionControlPureMask;
3523 }
3524 // TODO: Check llvm attribute for Function Control Const.
3525 if (F.hasFnAttribute(Attribute::ReadNone)) {
3526 FuncControl |= spv::FunctionControlConstMask;
3527 }
3528
David Neto257c3892018-04-11 13:19:45 -04003529 FOps << MkNum(FuncControl);
David Neto22f144c2017-06-12 14:26:21 -04003530
3531 uint32_t FTyID;
3532 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3533 SmallVector<Type *, 4> NewFuncParamTys;
3534 FunctionType *NewFTy =
3535 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
3536 FTyID = lookupType(NewFTy);
3537 } else {
David Neto9ed8e2f2018-03-24 06:47:24 -07003538 // Handle regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04003539 if (GlobalConstFuncTyMap.count(FTy)) {
3540 FTyID = lookupType(GlobalConstFuncTyMap[FTy].first);
3541 } else {
3542 FTyID = lookupType(FTy);
3543 }
3544 }
3545
David Neto257c3892018-04-11 13:19:45 -04003546 FOps << MkId(FTyID);
David Neto22f144c2017-06-12 14:26:21 -04003547
3548 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3549 EntryPoints.push_back(std::make_pair(&F, nextID));
3550 }
3551
3552 VMap[&F] = nextID;
3553
David Neto482550a2018-03-24 05:21:07 -07003554 if (clspv::Option::ShowIDs()) {
David Netob05675d2018-02-16 12:37:49 -05003555 errs() << "Function " << F.getName() << " is " << nextID << "\n";
3556 }
David Neto22f144c2017-06-12 14:26:21 -04003557 // Generate SPIRV instruction for function.
David Neto87846742018-04-11 17:36:22 -04003558 auto *FuncInst = new SPIRVInstruction(spv::OpFunction, nextID++, FOps);
David Neto22f144c2017-06-12 14:26:21 -04003559 SPIRVInstList.push_back(FuncInst);
3560
3561 //
3562 // Generate OpFunctionParameter for Normal function.
3563 //
3564
3565 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
alan-bakere9308012019-03-15 10:25:13 -04003566
3567 // Find Insert Point for OpDecorate.
3568 auto DecoInsertPoint =
3569 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
3570 [](SPIRVInstruction *Inst) -> bool {
3571 return Inst->getOpcode() != spv::OpDecorate &&
3572 Inst->getOpcode() != spv::OpMemberDecorate &&
3573 Inst->getOpcode() != spv::OpExtInstImport;
3574 });
3575
David Neto22f144c2017-06-12 14:26:21 -04003576 // Iterate Argument for name instead of param type from function type.
3577 unsigned ArgIdx = 0;
3578 for (Argument &Arg : F.args()) {
alan-bakere9308012019-03-15 10:25:13 -04003579 uint32_t param_id = nextID++;
3580 VMap[&Arg] = param_id;
3581
3582 if (CalledWithCoherentResource(Arg)) {
3583 // If the arg is passed a coherent resource ever, then decorate this
3584 // parameter with Coherent too.
3585 SPIRVOperandList decoration_ops;
3586 decoration_ops << MkId(param_id) << MkNum(spv::DecorationCoherent);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003587 SPIRVInstList.insert(
3588 DecoInsertPoint,
3589 new SPIRVInstruction(spv::OpDecorate, decoration_ops));
alan-bakere9308012019-03-15 10:25:13 -04003590 }
David Neto22f144c2017-06-12 14:26:21 -04003591
3592 // ParamOps[0] : Result Type ID
3593 SPIRVOperandList ParamOps;
3594
3595 // Find SPIRV instruction for parameter type.
3596 uint32_t ParamTyID = lookupType(Arg.getType());
3597 if (PointerType *PTy = dyn_cast<PointerType>(Arg.getType())) {
3598 if (GlobalConstFuncTyMap.count(FTy)) {
3599 if (ArgIdx == GlobalConstFuncTyMap[FTy].second) {
3600 Type *EleTy = PTy->getPointerElementType();
3601 Type *ArgTy =
3602 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
3603 ParamTyID = lookupType(ArgTy);
3604 GlobalConstArgSet.insert(&Arg);
3605 }
3606 }
3607 }
David Neto257c3892018-04-11 13:19:45 -04003608 ParamOps << MkId(ParamTyID);
David Neto22f144c2017-06-12 14:26:21 -04003609
3610 // Generate SPIRV instruction for parameter.
David Neto87846742018-04-11 17:36:22 -04003611 auto *ParamInst =
alan-bakere9308012019-03-15 10:25:13 -04003612 new SPIRVInstruction(spv::OpFunctionParameter, param_id, ParamOps);
David Neto22f144c2017-06-12 14:26:21 -04003613 SPIRVInstList.push_back(ParamInst);
3614
3615 ArgIdx++;
3616 }
3617 }
3618}
3619
alan-bakerb6b09dc2018-11-08 16:59:28 -05003620void SPIRVProducerPass::GenerateModuleInfo(Module &module) {
David Neto22f144c2017-06-12 14:26:21 -04003621 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3622 EntryPointVecType &EntryPoints = getEntryPointVec();
3623 ValueMapType &VMap = getValueMap();
3624 ValueList &EntryPointInterfaces = getEntryPointInterfacesVec();
3625 uint32_t &ExtInstImportID = getOpExtInstImportID();
3626 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
3627
3628 // Set up insert point.
3629 auto InsertPoint = SPIRVInstList.begin();
3630
3631 //
3632 // Generate OpCapability
3633 //
3634 // TODO: Which llvm information is mapped to SPIRV Capapbility?
3635
3636 // Ops[0] = Capability
3637 SPIRVOperandList Ops;
3638
David Neto87846742018-04-11 17:36:22 -04003639 auto *CapInst =
David Netoef5ba2b2019-12-20 08:35:54 -05003640 new SPIRVInstruction(spv::OpCapability, MkNum(spv::CapabilityShader));
David Neto22f144c2017-06-12 14:26:21 -04003641 SPIRVInstList.insert(InsertPoint, CapInst);
3642
alan-bakerf906d2b2019-12-10 11:26:23 -05003643 bool write_without_format = false;
3644 bool sampled_1d = false;
3645 bool image_1d = false;
David Neto22f144c2017-06-12 14:26:21 -04003646 for (Type *Ty : getTypeList()) {
alan-bakerb39c8262019-03-08 14:03:37 -05003647 if (clspv::Option::Int8Support() && Ty->isIntegerTy(8)) {
3648 // Generate OpCapability for i8 type.
David Netoef5ba2b2019-12-20 08:35:54 -05003649 SPIRVInstList.insert(
3650 InsertPoint,
3651 new SPIRVInstruction(spv::OpCapability, MkNum(spv::CapabilityInt8)));
alan-bakerb39c8262019-03-08 14:03:37 -05003652 } else if (Ty->isIntegerTy(16)) {
David Neto22f144c2017-06-12 14:26:21 -04003653 // Generate OpCapability for i16 type.
David Netoef5ba2b2019-12-20 08:35:54 -05003654 SPIRVInstList.insert(
3655 InsertPoint,
3656 new SPIRVInstruction(spv::OpCapability, MkNum(spv::CapabilityInt16)));
David Neto22f144c2017-06-12 14:26:21 -04003657 } else if (Ty->isIntegerTy(64)) {
3658 // Generate OpCapability for i64 type.
David Netoef5ba2b2019-12-20 08:35:54 -05003659 SPIRVInstList.insert(
3660 InsertPoint,
3661 new SPIRVInstruction(spv::OpCapability, MkNum(spv::CapabilityInt64)));
David Neto22f144c2017-06-12 14:26:21 -04003662 } else if (Ty->isHalfTy()) {
3663 // Generate OpCapability for half type.
David Netoef5ba2b2019-12-20 08:35:54 -05003664 SPIRVInstList.insert(InsertPoint,
3665 new SPIRVInstruction(spv::OpCapability,
3666 MkNum(spv::CapabilityFloat16)));
David Neto22f144c2017-06-12 14:26:21 -04003667 } else if (Ty->isDoubleTy()) {
3668 // Generate OpCapability for double type.
David Netoef5ba2b2019-12-20 08:35:54 -05003669 SPIRVInstList.insert(InsertPoint,
3670 new SPIRVInstruction(spv::OpCapability,
3671 MkNum(spv::CapabilityFloat64)));
David Neto22f144c2017-06-12 14:26:21 -04003672 } else if (auto *STy = dyn_cast<StructType>(Ty)) {
3673 if (STy->isOpaque()) {
alan-bakerf906d2b2019-12-10 11:26:23 -05003674 if (STy->getName().startswith("opencl.image1d_wo_t") ||
alan-baker7150a1d2020-02-25 08:31:06 -05003675 STy->getName().startswith("opencl.image1d_array_wo_t") ||
alan-bakerf906d2b2019-12-10 11:26:23 -05003676 STy->getName().startswith("opencl.image2d_wo_t") ||
alan-baker7150a1d2020-02-25 08:31:06 -05003677 STy->getName().startswith("opencl.image2d_array_wo_t") ||
alan-bakerf67468c2019-11-25 15:51:49 -05003678 STy->getName().startswith("opencl.image3d_wo_t")) {
alan-bakerf906d2b2019-12-10 11:26:23 -05003679 write_without_format = true;
3680 }
3681 if (STy->getName().startswith("opencl.image1d_ro_t") ||
alan-baker7150a1d2020-02-25 08:31:06 -05003682 STy->getName().startswith("opencl.image1d_wo_t") ||
3683 STy->getName().startswith("opencl.image1d_array_ro_t") ||
3684 STy->getName().startswith("opencl.image1d_array_wo_t")) {
alan-bakerf906d2b2019-12-10 11:26:23 -05003685 if (STy->getName().contains(".sampled"))
3686 sampled_1d = true;
3687 else
3688 image_1d = true;
David Neto22f144c2017-06-12 14:26:21 -04003689 }
3690 }
3691 }
3692 }
3693
alan-bakerf906d2b2019-12-10 11:26:23 -05003694 if (write_without_format) {
3695 // Generate OpCapability for write only image type.
3696 SPIRVInstList.insert(
3697 InsertPoint,
3698 new SPIRVInstruction(
3699 spv::OpCapability,
3700 {MkNum(spv::CapabilityStorageImageWriteWithoutFormat)}));
3701 }
3702 if (image_1d) {
3703 // Generate OpCapability for unsampled 1D image type.
3704 SPIRVInstList.insert(InsertPoint,
3705 new SPIRVInstruction(spv::OpCapability,
3706 {MkNum(spv::CapabilityImage1D)}));
3707 } else if (sampled_1d) {
3708 // Generate OpCapability for sampled 1D image type.
3709 SPIRVInstList.insert(
3710 InsertPoint, new SPIRVInstruction(spv::OpCapability,
3711 {MkNum(spv::CapabilitySampled1D)}));
3712 }
3713
David Neto5c22a252018-03-15 16:07:41 -04003714 { // OpCapability ImageQuery
3715 bool hasImageQuery = false;
alan-bakerf67468c2019-11-25 15:51:49 -05003716 for (const auto &SymVal : module.getValueSymbolTable()) {
3717 if (auto F = dyn_cast<Function>(SymVal.getValue())) {
SJW173c7e92020-03-16 08:44:47 -05003718 if (IsImageQuery(F)) {
alan-bakerf67468c2019-11-25 15:51:49 -05003719 hasImageQuery = true;
3720 break;
3721 }
David Neto5c22a252018-03-15 16:07:41 -04003722 }
3723 }
alan-bakerf67468c2019-11-25 15:51:49 -05003724
David Neto5c22a252018-03-15 16:07:41 -04003725 if (hasImageQuery) {
David Neto87846742018-04-11 17:36:22 -04003726 auto *ImageQueryCapInst = new SPIRVInstruction(
3727 spv::OpCapability, {MkNum(spv::CapabilityImageQuery)});
David Neto5c22a252018-03-15 16:07:41 -04003728 SPIRVInstList.insert(InsertPoint, ImageQueryCapInst);
3729 }
3730 }
3731
David Neto22f144c2017-06-12 14:26:21 -04003732 if (hasVariablePointers()) {
3733 //
David Neto22f144c2017-06-12 14:26:21 -04003734 // Generate OpCapability.
3735 //
3736 // Ops[0] = Capability
3737 //
3738 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003739 Ops << MkNum(spv::CapabilityVariablePointers);
David Neto22f144c2017-06-12 14:26:21 -04003740
David Neto87846742018-04-11 17:36:22 -04003741 SPIRVInstList.insert(InsertPoint,
3742 new SPIRVInstruction(spv::OpCapability, Ops));
alan-baker5b86ed72019-02-15 08:26:50 -05003743 } else if (hasVariablePointersStorageBuffer()) {
3744 //
3745 // Generate OpCapability.
3746 //
3747 // Ops[0] = Capability
3748 //
3749 Ops.clear();
3750 Ops << MkNum(spv::CapabilityVariablePointersStorageBuffer);
David Neto22f144c2017-06-12 14:26:21 -04003751
alan-baker5b86ed72019-02-15 08:26:50 -05003752 SPIRVInstList.insert(InsertPoint,
3753 new SPIRVInstruction(spv::OpCapability, Ops));
3754 }
3755
3756 // Always add the storage buffer extension
3757 {
David Neto22f144c2017-06-12 14:26:21 -04003758 //
3759 // Generate OpExtension.
3760 //
3761 // Ops[0] = Name (Literal String)
3762 //
alan-baker5b86ed72019-02-15 08:26:50 -05003763 auto *ExtensionInst = new SPIRVInstruction(
3764 spv::OpExtension, {MkString("SPV_KHR_storage_buffer_storage_class")});
3765 SPIRVInstList.insert(InsertPoint, ExtensionInst);
3766 }
David Neto22f144c2017-06-12 14:26:21 -04003767
alan-baker5b86ed72019-02-15 08:26:50 -05003768 if (hasVariablePointers() || hasVariablePointersStorageBuffer()) {
3769 //
3770 // Generate OpExtension.
3771 //
3772 // Ops[0] = Name (Literal String)
3773 //
3774 auto *ExtensionInst = new SPIRVInstruction(
3775 spv::OpExtension, {MkString("SPV_KHR_variable_pointers")});
3776 SPIRVInstList.insert(InsertPoint, ExtensionInst);
David Neto22f144c2017-06-12 14:26:21 -04003777 }
3778
3779 if (ExtInstImportID) {
3780 ++InsertPoint;
3781 }
3782
3783 //
3784 // Generate OpMemoryModel
3785 //
3786 // Memory model for Vulkan will always be GLSL450.
3787
3788 // Ops[0] = Addressing Model
3789 // Ops[1] = Memory Model
3790 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003791 Ops << MkNum(spv::AddressingModelLogical) << MkNum(spv::MemoryModelGLSL450);
David Neto22f144c2017-06-12 14:26:21 -04003792
David Neto87846742018-04-11 17:36:22 -04003793 auto *MemModelInst = new SPIRVInstruction(spv::OpMemoryModel, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003794 SPIRVInstList.insert(InsertPoint, MemModelInst);
3795
3796 //
3797 // Generate OpEntryPoint
3798 //
3799 for (auto EntryPoint : EntryPoints) {
3800 // Ops[0] = Execution Model
3801 // Ops[1] = EntryPoint ID
3802 // Ops[2] = Name (Literal String)
3803 // ...
3804 //
3805 // TODO: Do we need to consider Interface ID for forward references???
3806 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05003807 const StringRef &name = EntryPoint.first->getName();
David Neto257c3892018-04-11 13:19:45 -04003808 Ops << MkNum(spv::ExecutionModelGLCompute) << MkId(EntryPoint.second)
3809 << MkString(name);
David Neto22f144c2017-06-12 14:26:21 -04003810
David Neto22f144c2017-06-12 14:26:21 -04003811 for (Value *Interface : EntryPointInterfaces) {
David Neto257c3892018-04-11 13:19:45 -04003812 Ops << MkId(VMap[Interface]);
David Neto22f144c2017-06-12 14:26:21 -04003813 }
3814
David Neto87846742018-04-11 17:36:22 -04003815 auto *EntryPointInst = new SPIRVInstruction(spv::OpEntryPoint, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003816 SPIRVInstList.insert(InsertPoint, EntryPointInst);
3817 }
3818
3819 for (auto EntryPoint : EntryPoints) {
3820 if (const MDNode *MD = dyn_cast<Function>(EntryPoint.first)
3821 ->getMetadata("reqd_work_group_size")) {
3822
3823 if (!BuiltinDimVec.empty()) {
3824 llvm_unreachable(
3825 "Kernels should have consistent work group size definition");
3826 }
3827
3828 //
3829 // Generate OpExecutionMode
3830 //
3831
3832 // Ops[0] = Entry Point ID
3833 // Ops[1] = Execution Mode
3834 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
3835 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05003836 Ops << MkId(EntryPoint.second) << MkNum(spv::ExecutionModeLocalSize);
David Neto22f144c2017-06-12 14:26:21 -04003837
3838 uint32_t XDim = static_cast<uint32_t>(
3839 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
3840 uint32_t YDim = static_cast<uint32_t>(
3841 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
3842 uint32_t ZDim = static_cast<uint32_t>(
3843 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
3844
David Neto257c3892018-04-11 13:19:45 -04003845 Ops << MkNum(XDim) << MkNum(YDim) << MkNum(ZDim);
David Neto22f144c2017-06-12 14:26:21 -04003846
David Neto87846742018-04-11 17:36:22 -04003847 auto *ExecModeInst = new SPIRVInstruction(spv::OpExecutionMode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003848 SPIRVInstList.insert(InsertPoint, ExecModeInst);
3849 }
3850 }
3851
3852 //
3853 // Generate OpSource.
3854 //
3855 // Ops[0] = SourceLanguage ID
3856 // Ops[1] = Version (LiteralNum)
3857 //
3858 Ops.clear();
Kévin Petitf0515712020-01-07 18:29:20 +00003859 switch (clspv::Option::Language()) {
3860 case clspv::Option::SourceLanguage::OpenCL_C_10:
3861 Ops << MkNum(spv::SourceLanguageOpenCL_C) << MkNum(100);
3862 break;
3863 case clspv::Option::SourceLanguage::OpenCL_C_11:
3864 Ops << MkNum(spv::SourceLanguageOpenCL_C) << MkNum(110);
3865 break;
3866 case clspv::Option::SourceLanguage::OpenCL_C_12:
Kévin Petit0fc88042019-04-09 23:25:02 +01003867 Ops << MkNum(spv::SourceLanguageOpenCL_C) << MkNum(120);
Kévin Petitf0515712020-01-07 18:29:20 +00003868 break;
3869 case clspv::Option::SourceLanguage::OpenCL_C_20:
3870 Ops << MkNum(spv::SourceLanguageOpenCL_C) << MkNum(200);
3871 break;
3872 case clspv::Option::SourceLanguage::OpenCL_CPP:
3873 Ops << MkNum(spv::SourceLanguageOpenCL_CPP) << MkNum(100);
3874 break;
3875 default:
3876 Ops << MkNum(spv::SourceLanguageUnknown) << MkNum(0);
3877 break;
Kévin Petit0fc88042019-04-09 23:25:02 +01003878 }
David Neto22f144c2017-06-12 14:26:21 -04003879
David Neto87846742018-04-11 17:36:22 -04003880 auto *OpenSourceInst = new SPIRVInstruction(spv::OpSource, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003881 SPIRVInstList.insert(InsertPoint, OpenSourceInst);
3882
3883 if (!BuiltinDimVec.empty()) {
3884 //
3885 // Generate OpDecorates for x/y/z dimension.
3886 //
3887 // Ops[0] = Target ID
3888 // Ops[1] = Decoration (SpecId)
David Neto257c3892018-04-11 13:19:45 -04003889 // Ops[2] = Specialization Constant ID (Literal Number)
David Neto22f144c2017-06-12 14:26:21 -04003890
3891 // X Dimension
3892 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003893 Ops << MkId(BuiltinDimVec[0]) << MkNum(spv::DecorationSpecId) << MkNum(0);
David Neto87846742018-04-11 17:36:22 -04003894 SPIRVInstList.insert(InsertPoint,
3895 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003896
3897 // Y Dimension
3898 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003899 Ops << MkId(BuiltinDimVec[1]) << MkNum(spv::DecorationSpecId) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04003900 SPIRVInstList.insert(InsertPoint,
3901 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003902
3903 // Z Dimension
3904 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003905 Ops << MkId(BuiltinDimVec[2]) << MkNum(spv::DecorationSpecId) << MkNum(2);
David Neto87846742018-04-11 17:36:22 -04003906 SPIRVInstList.insert(InsertPoint,
3907 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003908 }
3909}
3910
David Netob6e2e062018-04-25 10:32:06 -04003911void SPIRVProducerPass::GenerateEntryPointInitialStores() {
3912 // Work around a driver bug. Initializers on Private variables might not
3913 // work. So the start of the kernel should store the initializer value to the
3914 // variables. Yes, *every* entry point pays this cost if *any* entry point
3915 // uses this builtin. At this point I judge this to be an acceptable tradeoff
3916 // of complexity vs. runtime, for a broken driver.
alan-bakerb6b09dc2018-11-08 16:59:28 -05003917 // TODO(dneto): Remove this at some point once fixed drivers are widely
3918 // available.
David Netob6e2e062018-04-25 10:32:06 -04003919 if (WorkgroupSizeVarID) {
3920 assert(WorkgroupSizeValueID);
3921
3922 SPIRVOperandList Ops;
3923 Ops << MkId(WorkgroupSizeVarID) << MkId(WorkgroupSizeValueID);
3924
3925 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
3926 getSPIRVInstList().push_back(Inst);
3927 }
3928}
3929
David Neto22f144c2017-06-12 14:26:21 -04003930void SPIRVProducerPass::GenerateFuncBody(Function &F) {
3931 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3932 ValueMapType &VMap = getValueMap();
3933
David Netob6e2e062018-04-25 10:32:06 -04003934 const bool IsKernel = F.getCallingConv() == CallingConv::SPIR_KERNEL;
David Neto22f144c2017-06-12 14:26:21 -04003935
3936 for (BasicBlock &BB : F) {
3937 // Register BasicBlock to ValueMap.
3938 VMap[&BB] = nextID;
3939
3940 //
3941 // Generate OpLabel for Basic Block.
3942 //
3943 SPIRVOperandList Ops;
David Neto87846742018-04-11 17:36:22 -04003944 auto *Inst = new SPIRVInstruction(spv::OpLabel, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003945 SPIRVInstList.push_back(Inst);
3946
David Neto6dcd4712017-06-23 11:06:47 -04003947 // OpVariable instructions must come first.
3948 for (Instruction &I : BB) {
alan-baker5b86ed72019-02-15 08:26:50 -05003949 if (auto *alloca = dyn_cast<AllocaInst>(&I)) {
3950 // Allocating a pointer requires variable pointers.
3951 if (alloca->getAllocatedType()->isPointerTy()) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003952 setVariablePointersCapabilities(
3953 alloca->getAllocatedType()->getPointerAddressSpace());
alan-baker5b86ed72019-02-15 08:26:50 -05003954 }
David Neto6dcd4712017-06-23 11:06:47 -04003955 GenerateInstruction(I);
3956 }
3957 }
3958
David Neto22f144c2017-06-12 14:26:21 -04003959 if (&BB == &F.getEntryBlock() && IsKernel) {
David Netob6e2e062018-04-25 10:32:06 -04003960 if (clspv::Option::HackInitializers()) {
3961 GenerateEntryPointInitialStores();
3962 }
David Neto22f144c2017-06-12 14:26:21 -04003963 }
3964
3965 for (Instruction &I : BB) {
David Neto6dcd4712017-06-23 11:06:47 -04003966 if (!isa<AllocaInst>(I)) {
3967 GenerateInstruction(I);
3968 }
David Neto22f144c2017-06-12 14:26:21 -04003969 }
3970 }
3971}
3972
3973spv::Op SPIRVProducerPass::GetSPIRVCmpOpcode(CmpInst *I) {
3974 const std::map<CmpInst::Predicate, spv::Op> Map = {
3975 {CmpInst::ICMP_EQ, spv::OpIEqual},
3976 {CmpInst::ICMP_NE, spv::OpINotEqual},
3977 {CmpInst::ICMP_UGT, spv::OpUGreaterThan},
3978 {CmpInst::ICMP_UGE, spv::OpUGreaterThanEqual},
3979 {CmpInst::ICMP_ULT, spv::OpULessThan},
3980 {CmpInst::ICMP_ULE, spv::OpULessThanEqual},
3981 {CmpInst::ICMP_SGT, spv::OpSGreaterThan},
3982 {CmpInst::ICMP_SGE, spv::OpSGreaterThanEqual},
3983 {CmpInst::ICMP_SLT, spv::OpSLessThan},
3984 {CmpInst::ICMP_SLE, spv::OpSLessThanEqual},
3985 {CmpInst::FCMP_OEQ, spv::OpFOrdEqual},
3986 {CmpInst::FCMP_OGT, spv::OpFOrdGreaterThan},
3987 {CmpInst::FCMP_OGE, spv::OpFOrdGreaterThanEqual},
3988 {CmpInst::FCMP_OLT, spv::OpFOrdLessThan},
3989 {CmpInst::FCMP_OLE, spv::OpFOrdLessThanEqual},
3990 {CmpInst::FCMP_ONE, spv::OpFOrdNotEqual},
3991 {CmpInst::FCMP_UEQ, spv::OpFUnordEqual},
3992 {CmpInst::FCMP_UGT, spv::OpFUnordGreaterThan},
3993 {CmpInst::FCMP_UGE, spv::OpFUnordGreaterThanEqual},
3994 {CmpInst::FCMP_ULT, spv::OpFUnordLessThan},
3995 {CmpInst::FCMP_ULE, spv::OpFUnordLessThanEqual},
3996 {CmpInst::FCMP_UNE, spv::OpFUnordNotEqual}};
3997
3998 assert(0 != Map.count(I->getPredicate()));
3999
4000 return Map.at(I->getPredicate());
4001}
4002
4003spv::Op SPIRVProducerPass::GetSPIRVCastOpcode(Instruction &I) {
4004 const std::map<unsigned, spv::Op> Map{
4005 {Instruction::Trunc, spv::OpUConvert},
4006 {Instruction::ZExt, spv::OpUConvert},
4007 {Instruction::SExt, spv::OpSConvert},
4008 {Instruction::FPToUI, spv::OpConvertFToU},
4009 {Instruction::FPToSI, spv::OpConvertFToS},
4010 {Instruction::UIToFP, spv::OpConvertUToF},
4011 {Instruction::SIToFP, spv::OpConvertSToF},
4012 {Instruction::FPTrunc, spv::OpFConvert},
4013 {Instruction::FPExt, spv::OpFConvert},
4014 {Instruction::BitCast, spv::OpBitcast}};
4015
4016 assert(0 != Map.count(I.getOpcode()));
4017
4018 return Map.at(I.getOpcode());
4019}
4020
4021spv::Op SPIRVProducerPass::GetSPIRVBinaryOpcode(Instruction &I) {
Kévin Petit24272b62018-10-18 19:16:12 +00004022 if (I.getType()->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04004023 switch (I.getOpcode()) {
4024 default:
4025 break;
4026 case Instruction::Or:
4027 return spv::OpLogicalOr;
4028 case Instruction::And:
4029 return spv::OpLogicalAnd;
4030 case Instruction::Xor:
4031 return spv::OpLogicalNotEqual;
4032 }
4033 }
4034
alan-bakerb6b09dc2018-11-08 16:59:28 -05004035 const std::map<unsigned, spv::Op> Map{
David Neto22f144c2017-06-12 14:26:21 -04004036 {Instruction::Add, spv::OpIAdd},
4037 {Instruction::FAdd, spv::OpFAdd},
4038 {Instruction::Sub, spv::OpISub},
4039 {Instruction::FSub, spv::OpFSub},
4040 {Instruction::Mul, spv::OpIMul},
4041 {Instruction::FMul, spv::OpFMul},
4042 {Instruction::UDiv, spv::OpUDiv},
4043 {Instruction::SDiv, spv::OpSDiv},
4044 {Instruction::FDiv, spv::OpFDiv},
4045 {Instruction::URem, spv::OpUMod},
4046 {Instruction::SRem, spv::OpSRem},
4047 {Instruction::FRem, spv::OpFRem},
4048 {Instruction::Or, spv::OpBitwiseOr},
4049 {Instruction::Xor, spv::OpBitwiseXor},
4050 {Instruction::And, spv::OpBitwiseAnd},
4051 {Instruction::Shl, spv::OpShiftLeftLogical},
4052 {Instruction::LShr, spv::OpShiftRightLogical},
4053 {Instruction::AShr, spv::OpShiftRightArithmetic}};
4054
4055 assert(0 != Map.count(I.getOpcode()));
4056
4057 return Map.at(I.getOpcode());
4058}
4059
4060void SPIRVProducerPass::GenerateInstruction(Instruction &I) {
4061 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4062 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04004063 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
4064 LLVMContext &Context = I.getParent()->getParent()->getParent()->getContext();
4065
4066 // Register Instruction to ValueMap.
4067 if (0 == VMap[&I]) {
4068 VMap[&I] = nextID;
4069 }
4070
4071 switch (I.getOpcode()) {
4072 default: {
4073 if (Instruction::isCast(I.getOpcode())) {
4074 //
4075 // Generate SPIRV instructions for cast operators.
4076 //
4077
David Netod2de94a2017-08-28 17:27:47 -04004078 auto Ty = I.getType();
David Neto22f144c2017-06-12 14:26:21 -04004079 auto OpTy = I.getOperand(0)->getType();
David Netod2de94a2017-08-28 17:27:47 -04004080 auto toI8 = Ty == Type::getInt8Ty(Context);
4081 auto fromI32 = OpTy == Type::getInt32Ty(Context);
David Neto22f144c2017-06-12 14:26:21 -04004082 // Handle zext, sext and uitofp with i1 type specially.
4083 if ((I.getOpcode() == Instruction::ZExt ||
4084 I.getOpcode() == Instruction::SExt ||
4085 I.getOpcode() == Instruction::UIToFP) &&
alan-bakerb6b09dc2018-11-08 16:59:28 -05004086 OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04004087 //
4088 // Generate OpSelect.
4089 //
4090
4091 // Ops[0] = Result Type ID
4092 // Ops[1] = Condition ID
4093 // Ops[2] = True Constant ID
4094 // Ops[3] = False Constant ID
4095 SPIRVOperandList Ops;
4096
David Neto257c3892018-04-11 13:19:45 -04004097 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004098
David Neto22f144c2017-06-12 14:26:21 -04004099 uint32_t CondID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04004100 Ops << MkId(CondID);
David Neto22f144c2017-06-12 14:26:21 -04004101
4102 uint32_t TrueID = 0;
4103 if (I.getOpcode() == Instruction::ZExt) {
Kévin Petit7bfb8992019-02-26 13:45:08 +00004104 TrueID = VMap[ConstantInt::get(I.getType(), 1)];
David Neto22f144c2017-06-12 14:26:21 -04004105 } else if (I.getOpcode() == Instruction::SExt) {
Kévin Petit7bfb8992019-02-26 13:45:08 +00004106 TrueID = VMap[ConstantInt::getSigned(I.getType(), -1)];
David Neto22f144c2017-06-12 14:26:21 -04004107 } else {
4108 TrueID = VMap[ConstantFP::get(Context, APFloat(1.0f))];
4109 }
David Neto257c3892018-04-11 13:19:45 -04004110 Ops << MkId(TrueID);
David Neto22f144c2017-06-12 14:26:21 -04004111
4112 uint32_t FalseID = 0;
4113 if (I.getOpcode() == Instruction::ZExt) {
4114 FalseID = VMap[Constant::getNullValue(I.getType())];
4115 } else if (I.getOpcode() == Instruction::SExt) {
4116 FalseID = VMap[Constant::getNullValue(I.getType())];
4117 } else {
4118 FalseID = VMap[ConstantFP::get(Context, APFloat(0.0f))];
4119 }
David Neto257c3892018-04-11 13:19:45 -04004120 Ops << MkId(FalseID);
David Neto22f144c2017-06-12 14:26:21 -04004121
David Neto87846742018-04-11 17:36:22 -04004122 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004123 SPIRVInstList.push_back(Inst);
alan-bakerb39c8262019-03-08 14:03:37 -05004124 } else if (!clspv::Option::Int8Support() &&
4125 I.getOpcode() == Instruction::Trunc && fromI32 && toI8) {
David Netod2de94a2017-08-28 17:27:47 -04004126 // The SPIR-V target type is a 32-bit int. Keep only the bottom
4127 // 8 bits.
4128 // Before:
4129 // %result = trunc i32 %a to i8
4130 // After
4131 // %result = OpBitwiseAnd %uint %a %uint_255
4132
4133 SPIRVOperandList Ops;
4134
David Neto257c3892018-04-11 13:19:45 -04004135 Ops << MkId(lookupType(OpTy)) << MkId(VMap[I.getOperand(0)]);
David Netod2de94a2017-08-28 17:27:47 -04004136
4137 Type *UintTy = Type::getInt32Ty(Context);
4138 uint32_t MaskID = VMap[ConstantInt::get(UintTy, 255)];
David Neto257c3892018-04-11 13:19:45 -04004139 Ops << MkId(MaskID);
David Netod2de94a2017-08-28 17:27:47 -04004140
David Neto87846742018-04-11 17:36:22 -04004141 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Netod2de94a2017-08-28 17:27:47 -04004142 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04004143 } else {
4144 // Ops[0] = Result Type ID
4145 // Ops[1] = Source Value ID
4146 SPIRVOperandList Ops;
4147
David Neto257c3892018-04-11 13:19:45 -04004148 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004149
David Neto87846742018-04-11 17:36:22 -04004150 auto *Inst = new SPIRVInstruction(GetSPIRVCastOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004151 SPIRVInstList.push_back(Inst);
4152 }
4153 } else if (isa<BinaryOperator>(I)) {
4154 //
4155 // Generate SPIRV instructions for binary operators.
4156 //
4157
4158 // Handle xor with i1 type specially.
4159 if (I.getOpcode() == Instruction::Xor &&
4160 I.getType() == Type::getInt1Ty(Context) &&
Kévin Petit24272b62018-10-18 19:16:12 +00004161 ((isa<ConstantInt>(I.getOperand(0)) &&
4162 !cast<ConstantInt>(I.getOperand(0))->isZero()) ||
4163 (isa<ConstantInt>(I.getOperand(1)) &&
4164 !cast<ConstantInt>(I.getOperand(1))->isZero()))) {
David Neto22f144c2017-06-12 14:26:21 -04004165 //
4166 // Generate OpLogicalNot.
4167 //
4168 // Ops[0] = Result Type ID
4169 // Ops[1] = Operand
4170 SPIRVOperandList Ops;
4171
David Neto257c3892018-04-11 13:19:45 -04004172 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004173
4174 Value *CondV = I.getOperand(0);
4175 if (isa<Constant>(I.getOperand(0))) {
4176 CondV = I.getOperand(1);
4177 }
David Neto257c3892018-04-11 13:19:45 -04004178 Ops << MkId(VMap[CondV]);
David Neto22f144c2017-06-12 14:26:21 -04004179
David Neto87846742018-04-11 17:36:22 -04004180 auto *Inst = new SPIRVInstruction(spv::OpLogicalNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004181 SPIRVInstList.push_back(Inst);
4182 } else {
4183 // Ops[0] = Result Type ID
4184 // Ops[1] = Operand 0
4185 // Ops[2] = Operand 1
4186 SPIRVOperandList Ops;
4187
David Neto257c3892018-04-11 13:19:45 -04004188 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
4189 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004190
David Neto87846742018-04-11 17:36:22 -04004191 auto *Inst =
4192 new SPIRVInstruction(GetSPIRVBinaryOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004193 SPIRVInstList.push_back(Inst);
4194 }
alan-bakerc9c55ae2019-12-02 16:01:27 -05004195 } else if (I.getOpcode() == Instruction::FNeg) {
4196 // The only unary operator.
4197 //
4198 // Ops[0] = Result Type ID
4199 // Ops[1] = Operand 0
4200 SPIRVOperandList ops;
4201
4202 ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
4203 auto *Inst = new SPIRVInstruction(spv::OpFNegate, nextID++, ops);
4204 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04004205 } else {
4206 I.print(errs());
4207 llvm_unreachable("Unsupported instruction???");
4208 }
4209 break;
4210 }
4211 case Instruction::GetElementPtr: {
4212 auto &GlobalConstArgSet = getGlobalConstArgSet();
4213
4214 //
4215 // Generate OpAccessChain.
4216 //
4217 GetElementPtrInst *GEP = cast<GetElementPtrInst>(&I);
4218
4219 //
4220 // Generate OpAccessChain.
4221 //
4222
4223 // Ops[0] = Result Type ID
4224 // Ops[1] = Base ID
4225 // Ops[2] ... Ops[n] = Indexes ID
4226 SPIRVOperandList Ops;
4227
alan-bakerb6b09dc2018-11-08 16:59:28 -05004228 PointerType *ResultType = cast<PointerType>(GEP->getType());
David Neto22f144c2017-06-12 14:26:21 -04004229 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate ||
4230 GlobalConstArgSet.count(GEP->getPointerOperand())) {
4231 // Use pointer type with private address space for global constant.
4232 Type *EleTy = I.getType()->getPointerElementType();
David Neto1a1a0582017-07-07 12:01:44 -04004233 ResultType = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
David Neto22f144c2017-06-12 14:26:21 -04004234 }
David Neto257c3892018-04-11 13:19:45 -04004235
4236 Ops << MkId(lookupType(ResultType));
David Neto22f144c2017-06-12 14:26:21 -04004237
David Neto862b7d82018-06-14 18:48:37 -04004238 // Generate the base pointer.
4239 Ops << MkId(VMap[GEP->getPointerOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04004240
David Neto862b7d82018-06-14 18:48:37 -04004241 // TODO(dneto): Simplify the following?
David Neto22f144c2017-06-12 14:26:21 -04004242
4243 //
4244 // Follows below rules for gep.
4245 //
David Neto862b7d82018-06-14 18:48:37 -04004246 // 1. If gep's first index is 0 generate OpAccessChain and ignore gep's
4247 // first index.
David Neto22f144c2017-06-12 14:26:21 -04004248 // 2. If gep's first index is not 0, generate OpPtrAccessChain and use gep's
4249 // first index.
4250 // 3. If gep's first index is not constant, generate OpPtrAccessChain and
4251 // use gep's first index.
4252 // 4. If it is not above case 1, 2 and 3, generate OpAccessChain and use
4253 // gep's first index.
4254 //
4255 spv::Op Opcode = spv::OpAccessChain;
4256 unsigned offset = 0;
4257 if (ConstantInt *CstInt = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
David Neto862b7d82018-06-14 18:48:37 -04004258 if (CstInt->getZExtValue() == 0) {
David Neto22f144c2017-06-12 14:26:21 -04004259 offset = 1;
David Neto862b7d82018-06-14 18:48:37 -04004260 } else if (CstInt->getZExtValue() != 0) {
David Neto22f144c2017-06-12 14:26:21 -04004261 Opcode = spv::OpPtrAccessChain;
David Neto22f144c2017-06-12 14:26:21 -04004262 }
David Neto862b7d82018-06-14 18:48:37 -04004263 } else {
David Neto22f144c2017-06-12 14:26:21 -04004264 Opcode = spv::OpPtrAccessChain;
David Neto1a1a0582017-07-07 12:01:44 -04004265 }
4266
4267 if (Opcode == spv::OpPtrAccessChain) {
David Neto1a1a0582017-07-07 12:01:44 -04004268 // Do we need to generate ArrayStride? Check against the GEP result type
4269 // rather than the pointer type of the base because when indexing into
4270 // an OpenCL program-scope constant, we'll swap out the LLVM base pointer
4271 // for something else in the SPIR-V.
4272 // E.g. see test/PointerAccessChain/pointer_index_is_constant_1.cl
alan-baker5b86ed72019-02-15 08:26:50 -05004273 auto address_space = ResultType->getAddressSpace();
4274 setVariablePointersCapabilities(address_space);
4275 switch (GetStorageClass(address_space)) {
Alan Bakerfcda9482018-10-02 17:09:59 -04004276 case spv::StorageClassStorageBuffer:
4277 case spv::StorageClassUniform:
David Neto1a1a0582017-07-07 12:01:44 -04004278 // Save the need to generate an ArrayStride decoration. But defer
4279 // generation until later, so we only make one decoration.
David Neto85082642018-03-24 06:55:20 -07004280 getTypesNeedingArrayStride().insert(ResultType);
Alan Bakerfcda9482018-10-02 17:09:59 -04004281 break;
4282 default:
4283 break;
David Neto1a1a0582017-07-07 12:01:44 -04004284 }
David Neto22f144c2017-06-12 14:26:21 -04004285 }
4286
4287 for (auto II = GEP->idx_begin() + offset; II != GEP->idx_end(); II++) {
David Neto257c3892018-04-11 13:19:45 -04004288 Ops << MkId(VMap[*II]);
David Neto22f144c2017-06-12 14:26:21 -04004289 }
4290
David Neto87846742018-04-11 17:36:22 -04004291 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004292 SPIRVInstList.push_back(Inst);
4293 break;
4294 }
4295 case Instruction::ExtractValue: {
4296 ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
4297 // Ops[0] = Result Type ID
4298 // Ops[1] = Composite ID
4299 // Ops[2] ... Ops[n] = Indexes (Literal Number)
4300 SPIRVOperandList Ops;
4301
David Neto257c3892018-04-11 13:19:45 -04004302 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004303
4304 uint32_t CompositeID = VMap[EVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04004305 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04004306
4307 for (auto &Index : EVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04004308 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04004309 }
4310
David Neto87846742018-04-11 17:36:22 -04004311 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004312 SPIRVInstList.push_back(Inst);
4313 break;
4314 }
4315 case Instruction::InsertValue: {
4316 InsertValueInst *IVI = cast<InsertValueInst>(&I);
4317 // Ops[0] = Result Type ID
4318 // Ops[1] = Object ID
4319 // Ops[2] = Composite ID
4320 // Ops[3] ... Ops[n] = Indexes (Literal Number)
4321 SPIRVOperandList Ops;
4322
4323 uint32_t ResTyID = lookupType(I.getType());
David Neto257c3892018-04-11 13:19:45 -04004324 Ops << MkId(ResTyID);
David Neto22f144c2017-06-12 14:26:21 -04004325
4326 uint32_t ObjectID = VMap[IVI->getInsertedValueOperand()];
David Neto257c3892018-04-11 13:19:45 -04004327 Ops << MkId(ObjectID);
David Neto22f144c2017-06-12 14:26:21 -04004328
4329 uint32_t CompositeID = VMap[IVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04004330 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04004331
4332 for (auto &Index : IVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04004333 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04004334 }
4335
David Neto87846742018-04-11 17:36:22 -04004336 auto *Inst = new SPIRVInstruction(spv::OpCompositeInsert, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004337 SPIRVInstList.push_back(Inst);
4338 break;
4339 }
4340 case Instruction::Select: {
4341 //
4342 // Generate OpSelect.
4343 //
4344
4345 // Ops[0] = Result Type ID
4346 // Ops[1] = Condition ID
4347 // Ops[2] = True Constant ID
4348 // Ops[3] = False Constant ID
4349 SPIRVOperandList Ops;
4350
4351 // Find SPIRV instruction for parameter type.
4352 auto Ty = I.getType();
4353 if (Ty->isPointerTy()) {
4354 auto PointeeTy = Ty->getPointerElementType();
4355 if (PointeeTy->isStructTy() &&
4356 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
4357 Ty = PointeeTy;
alan-baker5b86ed72019-02-15 08:26:50 -05004358 } else {
4359 // Selecting between pointers requires variable pointers.
4360 setVariablePointersCapabilities(Ty->getPointerAddressSpace());
4361 if (!hasVariablePointers() && !selectFromSameObject(&I)) {
4362 setVariablePointers(true);
4363 }
David Neto22f144c2017-06-12 14:26:21 -04004364 }
4365 }
4366
David Neto257c3892018-04-11 13:19:45 -04004367 Ops << MkId(lookupType(Ty)) << MkId(VMap[I.getOperand(0)])
4368 << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004369
David Neto87846742018-04-11 17:36:22 -04004370 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004371 SPIRVInstList.push_back(Inst);
4372 break;
4373 }
4374 case Instruction::ExtractElement: {
4375 // Handle <4 x i8> type manually.
4376 Type *CompositeTy = I.getOperand(0)->getType();
4377 if (is4xi8vec(CompositeTy)) {
4378 //
4379 // Generate OpShiftRightLogical and OpBitwiseAnd for extractelement with
4380 // <4 x i8>.
4381 //
4382
4383 //
4384 // Generate OpShiftRightLogical
4385 //
4386 // Ops[0] = Result Type ID
4387 // Ops[1] = Operand 0
4388 // Ops[2] = Operand 1
4389 //
4390 SPIRVOperandList Ops;
4391
David Neto257c3892018-04-11 13:19:45 -04004392 Ops << MkId(lookupType(CompositeTy));
David Neto22f144c2017-06-12 14:26:21 -04004393
4394 uint32_t Op0ID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04004395 Ops << MkId(Op0ID);
David Neto22f144c2017-06-12 14:26:21 -04004396
4397 uint32_t Op1ID = 0;
4398 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
4399 // Handle constant index.
4400 uint64_t Idx = CI->getZExtValue();
4401 Value *ShiftAmount =
4402 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
4403 Op1ID = VMap[ShiftAmount];
4404 } else {
4405 // Handle variable index.
4406 SPIRVOperandList TmpOps;
4407
David Neto257c3892018-04-11 13:19:45 -04004408 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
4409 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004410
4411 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04004412 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04004413
4414 Op1ID = nextID;
4415
David Neto87846742018-04-11 17:36:22 -04004416 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04004417 SPIRVInstList.push_back(TmpInst);
4418 }
David Neto257c3892018-04-11 13:19:45 -04004419 Ops << MkId(Op1ID);
David Neto22f144c2017-06-12 14:26:21 -04004420
4421 uint32_t ShiftID = nextID;
4422
David Neto87846742018-04-11 17:36:22 -04004423 auto *Inst =
4424 new SPIRVInstruction(spv::OpShiftRightLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004425 SPIRVInstList.push_back(Inst);
4426
4427 //
4428 // Generate OpBitwiseAnd
4429 //
4430 // Ops[0] = Result Type ID
4431 // Ops[1] = Operand 0
4432 // Ops[2] = Operand 1
4433 //
4434 Ops.clear();
4435
David Neto257c3892018-04-11 13:19:45 -04004436 Ops << MkId(lookupType(CompositeTy)) << MkId(ShiftID);
David Neto22f144c2017-06-12 14:26:21 -04004437
4438 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
David Neto257c3892018-04-11 13:19:45 -04004439 Ops << MkId(VMap[CstFF]);
David Neto22f144c2017-06-12 14:26:21 -04004440
David Neto9b2d6252017-09-06 15:47:37 -04004441 // Reset mapping for this value to the result of the bitwise and.
4442 VMap[&I] = nextID;
4443
David Neto87846742018-04-11 17:36:22 -04004444 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004445 SPIRVInstList.push_back(Inst);
4446 break;
4447 }
4448
4449 // Ops[0] = Result Type ID
4450 // Ops[1] = Composite ID
4451 // Ops[2] ... Ops[n] = Indexes (Literal Number)
4452 SPIRVOperandList Ops;
4453
David Neto257c3892018-04-11 13:19:45 -04004454 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004455
4456 spv::Op Opcode = spv::OpCompositeExtract;
4457 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
David Neto257c3892018-04-11 13:19:45 -04004458 Ops << MkNum(static_cast<uint32_t>(CI->getZExtValue()));
David Neto22f144c2017-06-12 14:26:21 -04004459 } else {
David Neto257c3892018-04-11 13:19:45 -04004460 Ops << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004461 Opcode = spv::OpVectorExtractDynamic;
4462 }
4463
David Neto87846742018-04-11 17:36:22 -04004464 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004465 SPIRVInstList.push_back(Inst);
4466 break;
4467 }
4468 case Instruction::InsertElement: {
4469 // Handle <4 x i8> type manually.
4470 Type *CompositeTy = I.getOperand(0)->getType();
4471 if (is4xi8vec(CompositeTy)) {
4472 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
4473 uint32_t CstFFID = VMap[CstFF];
4474
4475 uint32_t ShiftAmountID = 0;
4476 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
4477 // Handle constant index.
4478 uint64_t Idx = CI->getZExtValue();
4479 Value *ShiftAmount =
4480 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
4481 ShiftAmountID = VMap[ShiftAmount];
4482 } else {
4483 // Handle variable index.
4484 SPIRVOperandList TmpOps;
4485
David Neto257c3892018-04-11 13:19:45 -04004486 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
4487 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004488
4489 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04004490 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04004491
4492 ShiftAmountID = nextID;
4493
David Neto87846742018-04-11 17:36:22 -04004494 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04004495 SPIRVInstList.push_back(TmpInst);
4496 }
4497
4498 //
4499 // Generate mask operations.
4500 //
4501
4502 // ShiftLeft mask according to index of insertelement.
4503 SPIRVOperandList Ops;
4504
David Neto257c3892018-04-11 13:19:45 -04004505 const uint32_t ResTyID = lookupType(CompositeTy);
4506 Ops << MkId(ResTyID) << MkId(CstFFID) << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04004507
4508 uint32_t MaskID = nextID;
4509
David Neto87846742018-04-11 17:36:22 -04004510 auto *Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004511 SPIRVInstList.push_back(Inst);
4512
4513 // Inverse mask.
4514 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004515 Ops << MkId(ResTyID) << MkId(MaskID);
David Neto22f144c2017-06-12 14:26:21 -04004516
4517 uint32_t InvMaskID = nextID;
4518
David Neto87846742018-04-11 17:36:22 -04004519 Inst = new SPIRVInstruction(spv::OpNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004520 SPIRVInstList.push_back(Inst);
4521
4522 // Apply mask.
4523 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004524 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(0)]) << MkId(InvMaskID);
David Neto22f144c2017-06-12 14:26:21 -04004525
4526 uint32_t OrgValID = nextID;
4527
David Neto87846742018-04-11 17:36:22 -04004528 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004529 SPIRVInstList.push_back(Inst);
4530
4531 // Create correct value according to index of insertelement.
4532 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05004533 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(1)])
4534 << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04004535
4536 uint32_t InsertValID = nextID;
4537
David Neto87846742018-04-11 17:36:22 -04004538 Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004539 SPIRVInstList.push_back(Inst);
4540
4541 // Insert value to original value.
4542 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004543 Ops << MkId(ResTyID) << MkId(OrgValID) << MkId(InsertValID);
David Neto22f144c2017-06-12 14:26:21 -04004544
David Netoa394f392017-08-26 20:45:29 -04004545 VMap[&I] = nextID;
4546
David Neto87846742018-04-11 17:36:22 -04004547 Inst = new SPIRVInstruction(spv::OpBitwiseOr, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004548 SPIRVInstList.push_back(Inst);
4549
4550 break;
4551 }
4552
David Neto22f144c2017-06-12 14:26:21 -04004553 SPIRVOperandList Ops;
4554
James Priced26efea2018-06-09 23:28:32 +01004555 // Ops[0] = Result Type ID
4556 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004557
4558 spv::Op Opcode = spv::OpCompositeInsert;
4559 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
David Neto257c3892018-04-11 13:19:45 -04004560 const auto value = CI->getZExtValue();
4561 assert(value <= UINT32_MAX);
James Priced26efea2018-06-09 23:28:32 +01004562 // Ops[1] = Object ID
4563 // Ops[2] = Composite ID
4564 // Ops[3] ... Ops[n] = Indexes (Literal Number)
alan-bakerb6b09dc2018-11-08 16:59:28 -05004565 Ops << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(0)])
James Priced26efea2018-06-09 23:28:32 +01004566 << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004567 } else {
James Priced26efea2018-06-09 23:28:32 +01004568 // Ops[1] = Composite ID
4569 // Ops[2] = Object ID
4570 // Ops[3] ... Ops[n] = Indexes (Literal Number)
alan-bakerb6b09dc2018-11-08 16:59:28 -05004571 Ops << MkId(VMap[I.getOperand(0)]) << MkId(VMap[I.getOperand(1)])
James Priced26efea2018-06-09 23:28:32 +01004572 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004573 Opcode = spv::OpVectorInsertDynamic;
4574 }
4575
David Neto87846742018-04-11 17:36:22 -04004576 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004577 SPIRVInstList.push_back(Inst);
4578 break;
4579 }
4580 case Instruction::ShuffleVector: {
4581 // Ops[0] = Result Type ID
4582 // Ops[1] = Vector 1 ID
4583 // Ops[2] = Vector 2 ID
4584 // Ops[3] ... Ops[n] = Components (Literal Number)
4585 SPIRVOperandList Ops;
4586
David Neto257c3892018-04-11 13:19:45 -04004587 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
4588 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004589
4590 uint64_t NumElements = 0;
4591 if (Constant *Cst = dyn_cast<Constant>(I.getOperand(2))) {
4592 NumElements = cast<VectorType>(Cst->getType())->getNumElements();
4593
4594 if (Cst->isNullValue()) {
4595 for (unsigned i = 0; i < NumElements; i++) {
David Neto257c3892018-04-11 13:19:45 -04004596 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04004597 }
4598 } else if (const ConstantDataSequential *CDS =
4599 dyn_cast<ConstantDataSequential>(Cst)) {
4600 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
4601 std::vector<uint32_t> LiteralNum;
David Neto257c3892018-04-11 13:19:45 -04004602 const auto value = CDS->getElementAsInteger(i);
4603 assert(value <= UINT32_MAX);
4604 Ops << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004605 }
4606 } else if (const ConstantVector *CV = dyn_cast<ConstantVector>(Cst)) {
4607 for (unsigned i = 0; i < CV->getNumOperands(); i++) {
4608 auto Op = CV->getOperand(i);
4609
4610 uint32_t literal = 0;
4611
4612 if (auto CI = dyn_cast<ConstantInt>(Op)) {
4613 literal = static_cast<uint32_t>(CI->getZExtValue());
4614 } else if (auto UI = dyn_cast<UndefValue>(Op)) {
4615 literal = 0xFFFFFFFFu;
4616 } else {
4617 Op->print(errs());
4618 llvm_unreachable("Unsupported element in ConstantVector!");
4619 }
4620
David Neto257c3892018-04-11 13:19:45 -04004621 Ops << MkNum(literal);
David Neto22f144c2017-06-12 14:26:21 -04004622 }
4623 } else {
4624 Cst->print(errs());
4625 llvm_unreachable("Unsupported constant mask in ShuffleVector!");
4626 }
4627 }
4628
David Neto87846742018-04-11 17:36:22 -04004629 auto *Inst = new SPIRVInstruction(spv::OpVectorShuffle, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004630 SPIRVInstList.push_back(Inst);
4631 break;
4632 }
4633 case Instruction::ICmp:
4634 case Instruction::FCmp: {
4635 CmpInst *CmpI = cast<CmpInst>(&I);
4636
David Netod4ca2e62017-07-06 18:47:35 -04004637 // Pointer equality is invalid.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004638 Type *ArgTy = CmpI->getOperand(0)->getType();
David Netod4ca2e62017-07-06 18:47:35 -04004639 if (isa<PointerType>(ArgTy)) {
4640 CmpI->print(errs());
alan-baker21574d32020-01-29 16:00:31 -05004641 std::string name = I.getParent()->getParent()->getName().str();
David Netod4ca2e62017-07-06 18:47:35 -04004642 errs()
4643 << "\nPointer equality test is not supported by SPIR-V for Vulkan, "
4644 << "in function " << name << "\n";
4645 llvm_unreachable("Pointer equality check is invalid");
4646 break;
4647 }
4648
David Neto257c3892018-04-11 13:19:45 -04004649 // Ops[0] = Result Type ID
4650 // Ops[1] = Operand 1 ID
4651 // Ops[2] = Operand 2 ID
4652 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04004653
David Neto257c3892018-04-11 13:19:45 -04004654 Ops << MkId(lookupType(CmpI->getType())) << MkId(VMap[CmpI->getOperand(0)])
4655 << MkId(VMap[CmpI->getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004656
4657 spv::Op Opcode = GetSPIRVCmpOpcode(CmpI);
David Neto87846742018-04-11 17:36:22 -04004658 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004659 SPIRVInstList.push_back(Inst);
4660 break;
4661 }
4662 case Instruction::Br: {
4663 // Branch instrucion is deferred because it needs label's ID. Record slot's
4664 // location on SPIRVInstructionList.
4665 DeferredInsts.push_back(
4666 std::make_tuple(&I, --SPIRVInstList.end(), 0 /* No id */));
4667 break;
4668 }
4669 case Instruction::Switch: {
4670 I.print(errs());
4671 llvm_unreachable("Unsupported instruction???");
4672 break;
4673 }
4674 case Instruction::IndirectBr: {
4675 I.print(errs());
4676 llvm_unreachable("Unsupported instruction???");
4677 break;
4678 }
4679 case Instruction::PHI: {
4680 // Branch instrucion is deferred because it needs label's ID. Record slot's
4681 // location on SPIRVInstructionList.
4682 DeferredInsts.push_back(
4683 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4684 break;
4685 }
4686 case Instruction::Alloca: {
4687 //
4688 // Generate OpVariable.
4689 //
4690 // Ops[0] : Result Type ID
4691 // Ops[1] : Storage Class
4692 SPIRVOperandList Ops;
4693
David Neto257c3892018-04-11 13:19:45 -04004694 Ops << MkId(lookupType(I.getType())) << MkNum(spv::StorageClassFunction);
David Neto22f144c2017-06-12 14:26:21 -04004695
David Neto87846742018-04-11 17:36:22 -04004696 auto *Inst = new SPIRVInstruction(spv::OpVariable, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004697 SPIRVInstList.push_back(Inst);
4698 break;
4699 }
4700 case Instruction::Load: {
4701 LoadInst *LD = cast<LoadInst>(&I);
4702 //
4703 // Generate OpLoad.
4704 //
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04004705
alan-baker5b86ed72019-02-15 08:26:50 -05004706 if (LD->getType()->isPointerTy()) {
4707 // Loading a pointer requires variable pointers.
4708 setVariablePointersCapabilities(LD->getType()->getPointerAddressSpace());
4709 }
David Neto22f144c2017-06-12 14:26:21 -04004710
David Neto0a2f98d2017-09-15 19:38:40 -04004711 uint32_t ResTyID = lookupType(LD->getType());
David Netoa60b00b2017-09-15 16:34:09 -04004712 uint32_t PointerID = VMap[LD->getPointerOperand()];
4713
4714 // This is a hack to work around what looks like a driver bug.
4715 // When we're loading from the special variable holding the WorkgroupSize
David Neto0a2f98d2017-09-15 19:38:40 -04004716 // builtin value, use an OpBitWiseAnd of the value's ID rather than
4717 // generating a load.
David Neto66cfe642018-03-24 06:13:56 -07004718 // TODO(dneto): Remove this awful hack once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -04004719 if (PointerID == WorkgroupSizeVarID) {
David Neto0a2f98d2017-09-15 19:38:40 -04004720 // Generate a bitwise-and of the original value with itself.
4721 // We should have been able to get away with just an OpCopyObject,
4722 // but we need something more complex to get past certain driver bugs.
4723 // This is ridiculous, but necessary.
4724 // TODO(dneto): Revisit this once drivers fix their bugs.
4725
4726 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004727 Ops << MkId(ResTyID) << MkId(WorkgroupSizeValueID)
4728 << MkId(WorkgroupSizeValueID);
David Neto0a2f98d2017-09-15 19:38:40 -04004729
David Neto87846742018-04-11 17:36:22 -04004730 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto0a2f98d2017-09-15 19:38:40 -04004731 SPIRVInstList.push_back(Inst);
David Netoa60b00b2017-09-15 16:34:09 -04004732 break;
4733 }
4734
4735 // This is the normal path. Generate a load.
4736
David Neto22f144c2017-06-12 14:26:21 -04004737 // Ops[0] = Result Type ID
4738 // Ops[1] = Pointer ID
4739 // Ops[2] ... Ops[n] = Optional Memory Access
4740 //
4741 // TODO: Do we need to implement Optional Memory Access???
David Neto0a2f98d2017-09-15 19:38:40 -04004742
David Neto22f144c2017-06-12 14:26:21 -04004743 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004744 Ops << MkId(ResTyID) << MkId(PointerID);
David Neto22f144c2017-06-12 14:26:21 -04004745
David Neto87846742018-04-11 17:36:22 -04004746 auto *Inst = new SPIRVInstruction(spv::OpLoad, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004747 SPIRVInstList.push_back(Inst);
4748 break;
4749 }
4750 case Instruction::Store: {
4751 StoreInst *ST = cast<StoreInst>(&I);
4752 //
4753 // Generate OpStore.
4754 //
4755
alan-baker5b86ed72019-02-15 08:26:50 -05004756 if (ST->getValueOperand()->getType()->isPointerTy()) {
4757 // Storing a pointer requires variable pointers.
4758 setVariablePointersCapabilities(
4759 ST->getValueOperand()->getType()->getPointerAddressSpace());
4760 }
4761
David Neto22f144c2017-06-12 14:26:21 -04004762 // Ops[0] = Pointer ID
4763 // Ops[1] = Object ID
4764 // Ops[2] ... Ops[n] = Optional Memory Access (later???)
4765 //
4766 // TODO: Do we need to implement Optional Memory Access???
David Neto257c3892018-04-11 13:19:45 -04004767 SPIRVOperandList Ops;
4768 Ops << MkId(VMap[ST->getPointerOperand()])
4769 << MkId(VMap[ST->getValueOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04004770
David Neto87846742018-04-11 17:36:22 -04004771 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004772 SPIRVInstList.push_back(Inst);
4773 break;
4774 }
4775 case Instruction::AtomicCmpXchg: {
4776 I.print(errs());
4777 llvm_unreachable("Unsupported instruction???");
4778 break;
4779 }
4780 case Instruction::AtomicRMW: {
Neil Henning39672102017-09-29 14:33:13 +01004781 AtomicRMWInst *AtomicRMW = dyn_cast<AtomicRMWInst>(&I);
4782
4783 spv::Op opcode;
4784
4785 switch (AtomicRMW->getOperation()) {
4786 default:
4787 I.print(errs());
4788 llvm_unreachable("Unsupported instruction???");
4789 case llvm::AtomicRMWInst::Add:
4790 opcode = spv::OpAtomicIAdd;
4791 break;
4792 case llvm::AtomicRMWInst::Sub:
4793 opcode = spv::OpAtomicISub;
4794 break;
4795 case llvm::AtomicRMWInst::Xchg:
4796 opcode = spv::OpAtomicExchange;
4797 break;
4798 case llvm::AtomicRMWInst::Min:
4799 opcode = spv::OpAtomicSMin;
4800 break;
4801 case llvm::AtomicRMWInst::Max:
4802 opcode = spv::OpAtomicSMax;
4803 break;
4804 case llvm::AtomicRMWInst::UMin:
4805 opcode = spv::OpAtomicUMin;
4806 break;
4807 case llvm::AtomicRMWInst::UMax:
4808 opcode = spv::OpAtomicUMax;
4809 break;
4810 case llvm::AtomicRMWInst::And:
4811 opcode = spv::OpAtomicAnd;
4812 break;
4813 case llvm::AtomicRMWInst::Or:
4814 opcode = spv::OpAtomicOr;
4815 break;
4816 case llvm::AtomicRMWInst::Xor:
4817 opcode = spv::OpAtomicXor;
4818 break;
4819 }
4820
4821 //
4822 // Generate OpAtomic*.
4823 //
4824 SPIRVOperandList Ops;
4825
David Neto257c3892018-04-11 13:19:45 -04004826 Ops << MkId(lookupType(I.getType()))
4827 << MkId(VMap[AtomicRMW->getPointerOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004828
4829 auto IntTy = Type::getInt32Ty(I.getContext());
Neil Henning39672102017-09-29 14:33:13 +01004830 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
David Neto257c3892018-04-11 13:19:45 -04004831 Ops << MkId(VMap[ConstantScopeDevice]);
Neil Henning39672102017-09-29 14:33:13 +01004832
4833 const auto ConstantMemorySemantics = ConstantInt::get(
4834 IntTy, spv::MemorySemanticsUniformMemoryMask |
4835 spv::MemorySemanticsSequentiallyConsistentMask);
David Neto257c3892018-04-11 13:19:45 -04004836 Ops << MkId(VMap[ConstantMemorySemantics]);
Neil Henning39672102017-09-29 14:33:13 +01004837
David Neto257c3892018-04-11 13:19:45 -04004838 Ops << MkId(VMap[AtomicRMW->getValOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004839
4840 VMap[&I] = nextID;
4841
David Neto87846742018-04-11 17:36:22 -04004842 auto *Inst = new SPIRVInstruction(opcode, nextID++, Ops);
Neil Henning39672102017-09-29 14:33:13 +01004843 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04004844 break;
4845 }
4846 case Instruction::Fence: {
4847 I.print(errs());
4848 llvm_unreachable("Unsupported instruction???");
4849 break;
4850 }
4851 case Instruction::Call: {
4852 CallInst *Call = dyn_cast<CallInst>(&I);
4853 Function *Callee = Call->getCalledFunction();
4854
Alan Baker202c8c72018-08-13 13:47:44 -04004855 if (Callee->getName().startswith(clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04004856 if (ResourceVarDeferredLoadCalls.count(Call) && Call->hasNUsesOrMore(1)) {
4857 // Generate an OpLoad
4858 SPIRVOperandList Ops;
4859 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004860
David Neto862b7d82018-06-14 18:48:37 -04004861 Ops << MkId(lookupType(Call->getType()->getPointerElementType()))
4862 << MkId(ResourceVarDeferredLoadCalls[Call]);
4863
4864 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
4865 SPIRVInstList.push_back(Inst);
4866 VMap[Call] = load_id;
4867 break;
4868
4869 } else {
4870 // This maps to an OpVariable we've already generated.
4871 // No code is generated for the call.
4872 }
4873 break;
alan-bakerb6b09dc2018-11-08 16:59:28 -05004874 } else if (Callee->getName().startswith(
4875 clspv::WorkgroupAccessorFunction())) {
Alan Baker202c8c72018-08-13 13:47:44 -04004876 // Don't codegen an instruction here, but instead map this call directly
4877 // to the workgroup variable id.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004878 int spec_id = static_cast<int>(
4879 cast<ConstantInt>(Call->getOperand(0))->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04004880 const auto &info = LocalSpecIdInfoMap[spec_id];
4881 VMap[Call] = info.variable_id;
4882 break;
David Neto862b7d82018-06-14 18:48:37 -04004883 }
4884
4885 // Sampler initializers become a load of the corresponding sampler.
4886
Kévin Petitdf71de32019-04-09 14:09:50 +01004887 if (Callee->getName().equals(clspv::LiteralSamplerFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04004888 // Map this to a load from the variable.
alan-baker09cb9802019-12-10 13:16:27 -05004889 const auto third_param = static_cast<unsigned>(
4890 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue());
4891 auto sampler_value = third_param;
4892 if (clspv::Option::UseSamplerMap()) {
4893 sampler_value = getSamplerMap()[third_param].first;
4894 }
David Neto862b7d82018-06-14 18:48:37 -04004895
4896 // Generate an OpLoad
David Neto22f144c2017-06-12 14:26:21 -04004897 SPIRVOperandList Ops;
David Neto862b7d82018-06-14 18:48:37 -04004898 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004899
David Neto257c3892018-04-11 13:19:45 -04004900 Ops << MkId(lookupType(SamplerTy->getPointerElementType()))
alan-baker09cb9802019-12-10 13:16:27 -05004901 << MkId(SamplerLiteralToIDMap[sampler_value]);
David Neto22f144c2017-06-12 14:26:21 -04004902
David Neto862b7d82018-06-14 18:48:37 -04004903 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004904 SPIRVInstList.push_back(Inst);
David Neto862b7d82018-06-14 18:48:37 -04004905 VMap[Call] = load_id;
David Neto22f144c2017-06-12 14:26:21 -04004906 break;
4907 }
4908
Kévin Petit349c9502019-03-28 17:24:14 +00004909 // Handle SPIR-V intrinsics
Kévin Petit9b340262019-06-19 18:31:11 +01004910 spv::Op opcode = StringSwitch<spv::Op>(Callee->getName())
4911 .Case("spirv.atomic_xor", spv::OpAtomicXor)
4912 .Default(spv::OpNop);
David Neto22f144c2017-06-12 14:26:21 -04004913
Kévin Petit617a76d2019-04-04 13:54:16 +01004914 // If the switch above didn't have an entry maybe the intrinsic
4915 // is using the name mangling logic.
4916 bool usesMangler = false;
4917 if (opcode == spv::OpNop) {
4918 if (Callee->getName().startswith(clspv::SPIRVOpIntrinsicFunction())) {
4919 auto OpCst = cast<ConstantInt>(Call->getOperand(0));
4920 opcode = static_cast<spv::Op>(OpCst->getZExtValue());
4921 usesMangler = true;
4922 }
4923 }
4924
Kévin Petit349c9502019-03-28 17:24:14 +00004925 if (opcode != spv::OpNop) {
4926
David Neto22f144c2017-06-12 14:26:21 -04004927 SPIRVOperandList Ops;
4928
Kévin Petit349c9502019-03-28 17:24:14 +00004929 if (!I.getType()->isVoidTy()) {
4930 Ops << MkId(lookupType(I.getType()));
4931 }
David Neto22f144c2017-06-12 14:26:21 -04004932
Kévin Petit617a76d2019-04-04 13:54:16 +01004933 unsigned firstOperand = usesMangler ? 1 : 0;
4934 for (unsigned i = firstOperand; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004935 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004936 }
4937
Kévin Petit349c9502019-03-28 17:24:14 +00004938 if (!I.getType()->isVoidTy()) {
4939 VMap[&I] = nextID;
Kévin Petit8a560882019-03-21 15:24:34 +00004940 }
4941
Kévin Petit349c9502019-03-28 17:24:14 +00004942 SPIRVInstruction *Inst;
4943 if (!I.getType()->isVoidTy()) {
4944 Inst = new SPIRVInstruction(opcode, nextID++, Ops);
4945 } else {
4946 Inst = new SPIRVInstruction(opcode, Ops);
4947 }
Kévin Petit8a560882019-03-21 15:24:34 +00004948 SPIRVInstList.push_back(Inst);
4949 break;
4950 }
4951
David Neto22f144c2017-06-12 14:26:21 -04004952 // spirv.copy_memory.* intrinsics become OpMemoryMemory's.
4953 if (Callee->getName().startswith("spirv.copy_memory")) {
4954 //
4955 // Generate OpCopyMemory.
4956 //
4957
4958 // Ops[0] = Dst ID
4959 // Ops[1] = Src ID
4960 // Ops[2] = Memory Access
4961 // Ops[3] = Alignment
4962
4963 auto IsVolatile =
4964 dyn_cast<ConstantInt>(Call->getArgOperand(3))->getZExtValue() != 0;
4965
4966 auto VolatileMemoryAccess = (IsVolatile) ? spv::MemoryAccessVolatileMask
4967 : spv::MemoryAccessMaskNone;
4968
4969 auto MemoryAccess = VolatileMemoryAccess | spv::MemoryAccessAlignedMask;
4970
4971 auto Alignment =
4972 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4973
David Neto257c3892018-04-11 13:19:45 -04004974 SPIRVOperandList Ops;
4975 Ops << MkId(VMap[Call->getArgOperand(0)])
4976 << MkId(VMap[Call->getArgOperand(1)]) << MkNum(MemoryAccess)
4977 << MkNum(static_cast<uint32_t>(Alignment));
David Neto22f144c2017-06-12 14:26:21 -04004978
David Neto87846742018-04-11 17:36:22 -04004979 auto *Inst = new SPIRVInstruction(spv::OpCopyMemory, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004980
4981 SPIRVInstList.push_back(Inst);
4982
4983 break;
4984 }
4985
SJW2c317da2020-03-23 07:39:13 -05004986 // read_image is converted to OpSampledImage and OpImageSampleExplicitLod.
4987 // Additionally, OpTypeSampledImage is generated.
SJW173c7e92020-03-16 08:44:47 -05004988 if (IsSampledImageRead(Callee)) {
David Neto22f144c2017-06-12 14:26:21 -04004989 //
4990 // Generate OpSampledImage.
4991 //
4992 // Ops[0] = Result Type ID
4993 // Ops[1] = Image ID
4994 // Ops[2] = Sampler ID
4995 //
4996 SPIRVOperandList Ops;
4997
4998 Value *Image = Call->getArgOperand(0);
4999 Value *Sampler = Call->getArgOperand(1);
5000 Value *Coordinate = Call->getArgOperand(2);
5001
5002 TypeMapType &OpImageTypeMap = getImageTypeMap();
5003 Type *ImageTy = Image->getType()->getPointerElementType();
5004 uint32_t ImageTyID = OpImageTypeMap[ImageTy];
David Neto22f144c2017-06-12 14:26:21 -04005005 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04005006 uint32_t SamplerID = VMap[Sampler];
David Neto257c3892018-04-11 13:19:45 -04005007
5008 Ops << MkId(ImageTyID) << MkId(ImageID) << MkId(SamplerID);
David Neto22f144c2017-06-12 14:26:21 -04005009
5010 uint32_t SampledImageID = nextID;
5011
David Neto87846742018-04-11 17:36:22 -04005012 auto *Inst = new SPIRVInstruction(spv::OpSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04005013 SPIRVInstList.push_back(Inst);
5014
5015 //
5016 // Generate OpImageSampleExplicitLod.
5017 //
5018 // Ops[0] = Result Type ID
5019 // Ops[1] = Sampled Image ID
5020 // Ops[2] = Coordinate ID
5021 // Ops[3] = Image Operands Type ID
5022 // Ops[4] ... Ops[n] = Operands ID
5023 //
5024 Ops.clear();
5025
alan-bakerf67468c2019-11-25 15:51:49 -05005026 const bool is_int_image = IsIntImageType(Image->getType());
5027 uint32_t result_type = 0;
5028 if (is_int_image) {
5029 result_type = v4int32ID;
5030 } else {
5031 result_type = lookupType(Call->getType());
5032 }
5033
5034 Ops << MkId(result_type) << MkId(SampledImageID) << MkId(VMap[Coordinate])
5035 << MkNum(spv::ImageOperandsLodMask);
David Neto22f144c2017-06-12 14:26:21 -04005036
5037 Constant *CstFP0 = ConstantFP::get(Context, APFloat(0.0f));
David Neto257c3892018-04-11 13:19:45 -04005038 Ops << MkId(VMap[CstFP0]);
David Neto22f144c2017-06-12 14:26:21 -04005039
alan-bakerf67468c2019-11-25 15:51:49 -05005040 uint32_t final_id = nextID++;
5041 VMap[&I] = final_id;
David Neto22f144c2017-06-12 14:26:21 -04005042
alan-bakerf67468c2019-11-25 15:51:49 -05005043 uint32_t image_id = final_id;
5044 if (is_int_image) {
5045 // Int image requires a bitcast from v4int to v4uint.
5046 image_id = nextID++;
5047 }
5048
5049 Inst = new SPIRVInstruction(spv::OpImageSampleExplicitLod, image_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04005050 SPIRVInstList.push_back(Inst);
alan-bakerf67468c2019-11-25 15:51:49 -05005051
5052 if (is_int_image) {
5053 // Generate the bitcast.
5054 Ops.clear();
5055 Ops << MkId(lookupType(Call->getType())) << MkId(image_id);
5056 Inst = new SPIRVInstruction(spv::OpBitcast, final_id, Ops);
5057 SPIRVInstList.push_back(Inst);
5058 }
David Neto22f144c2017-06-12 14:26:21 -04005059 break;
5060 }
5061
alan-baker75090e42020-02-20 11:21:04 -05005062 // read_image (without a sampler) is mapped to OpImageFetch.
SJW173c7e92020-03-16 08:44:47 -05005063 if (IsUnsampledImageRead(Callee)) {
alan-baker75090e42020-02-20 11:21:04 -05005064 Value *Image = Call->getArgOperand(0);
5065 Value *Coordinate = Call->getArgOperand(1);
5066
5067 //
5068 // Generate OpImageFetch
5069 //
5070 // Ops[0] = Result Type ID
5071 // Ops[1] = Image ID
5072 // Ops[2] = Coordinate ID
5073 // Ops[3] = Lod
5074 // Ops[4] = 0
5075 //
5076 SPIRVOperandList Ops;
5077
5078 const bool is_int_image = IsIntImageType(Image->getType());
5079 uint32_t result_type = 0;
5080 if (is_int_image) {
5081 result_type = v4int32ID;
5082 } else {
5083 result_type = lookupType(Call->getType());
5084 }
5085
5086 Ops << MkId(result_type) << MkId(VMap[Image]) << MkId(VMap[Coordinate])
5087 << MkNum(spv::ImageOperandsLodMask);
5088
5089 Constant *CstInt0 = ConstantInt::get(Context, APInt(32, 0));
5090 Ops << MkId(VMap[CstInt0]);
5091
5092 uint32_t final_id = nextID++;
5093 VMap[&I] = final_id;
5094
5095 uint32_t image_id = final_id;
5096 if (is_int_image) {
5097 // Int image requires a bitcast from v4int to v4uint.
5098 image_id = nextID++;
5099 }
5100
5101 auto *Inst = new SPIRVInstruction(spv::OpImageFetch, image_id, Ops);
5102 SPIRVInstList.push_back(Inst);
5103
5104 if (is_int_image) {
5105 // Generate the bitcast.
5106 Ops.clear();
5107 Ops << MkId(lookupType(Call->getType())) << MkId(image_id);
5108 Inst = new SPIRVInstruction(spv::OpBitcast, final_id, Ops);
5109 SPIRVInstList.push_back(Inst);
5110 }
5111 break;
5112 }
5113
alan-bakerf67468c2019-11-25 15:51:49 -05005114 // write_image is mapped to OpImageWrite.
SJW173c7e92020-03-16 08:44:47 -05005115 if (IsImageWrite(Callee)) {
David Neto22f144c2017-06-12 14:26:21 -04005116 //
5117 // Generate OpImageWrite.
5118 //
5119 // Ops[0] = Image ID
5120 // Ops[1] = Coordinate ID
5121 // Ops[2] = Texel ID
5122 // Ops[3] = (Optional) Image Operands Type (Literal Number)
5123 // Ops[4] ... Ops[n] = (Optional) Operands ID
5124 //
5125 SPIRVOperandList Ops;
5126
5127 Value *Image = Call->getArgOperand(0);
5128 Value *Coordinate = Call->getArgOperand(1);
5129 Value *Texel = Call->getArgOperand(2);
5130
5131 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04005132 uint32_t CoordinateID = VMap[Coordinate];
David Neto22f144c2017-06-12 14:26:21 -04005133 uint32_t TexelID = VMap[Texel];
alan-bakerf67468c2019-11-25 15:51:49 -05005134
5135 const bool is_int_image = IsIntImageType(Image->getType());
5136 if (is_int_image) {
5137 // Generate a bitcast to v4int and use it as the texel value.
5138 uint32_t castID = nextID++;
5139 Ops << MkId(v4int32ID) << MkId(TexelID);
5140 auto cast = new SPIRVInstruction(spv::OpBitcast, castID, Ops);
5141 SPIRVInstList.push_back(cast);
5142 Ops.clear();
5143 TexelID = castID;
5144 }
David Neto257c3892018-04-11 13:19:45 -04005145 Ops << MkId(ImageID) << MkId(CoordinateID) << MkId(TexelID);
David Neto22f144c2017-06-12 14:26:21 -04005146
David Neto87846742018-04-11 17:36:22 -04005147 auto *Inst = new SPIRVInstruction(spv::OpImageWrite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04005148 SPIRVInstList.push_back(Inst);
5149 break;
5150 }
5151
alan-bakerce179f12019-12-06 19:02:22 -05005152 // get_image_* is mapped to OpImageQuerySize or OpImageQuerySizeLod
SJW173c7e92020-03-16 08:44:47 -05005153 if (IsImageQuery(Callee)) {
David Neto5c22a252018-03-15 16:07:41 -04005154 //
alan-bakerce179f12019-12-06 19:02:22 -05005155 // Generate OpImageQuerySize[Lod]
David Neto5c22a252018-03-15 16:07:41 -04005156 //
5157 // Ops[0] = Image ID
5158 //
alan-bakerce179f12019-12-06 19:02:22 -05005159 // Result type has components equal to the dimensionality of the image,
5160 // plus 1 if the image is arrayed.
5161 //
alan-bakerf906d2b2019-12-10 11:26:23 -05005162 // %sizes = OpImageQuerySize[Lod] %uint[2|3|4] %im [%uint_0]
David Neto5c22a252018-03-15 16:07:41 -04005163 SPIRVOperandList Ops;
5164
5165 // Implement:
alan-bakerce179f12019-12-06 19:02:22 -05005166 // %sizes = OpImageQuerySize[Lod] %uint[2|3|4] %im [%uint_0]
5167 uint32_t SizesTypeID = 0;
5168
David Neto5c22a252018-03-15 16:07:41 -04005169 Value *Image = Call->getArgOperand(0);
alan-bakerce179f12019-12-06 19:02:22 -05005170 const uint32_t dim = ImageDimensionality(Image->getType());
alan-baker7150a1d2020-02-25 08:31:06 -05005171 const uint32_t components =
5172 dim + (IsArrayImageType(Image->getType()) ? 1 : 0);
alan-bakerce179f12019-12-06 19:02:22 -05005173 if (components == 1) {
alan-bakerce179f12019-12-06 19:02:22 -05005174 SizesTypeID = TypeMap[Type::getInt32Ty(Context)];
5175 } else {
alan-baker7150a1d2020-02-25 08:31:06 -05005176 SizesTypeID =
5177 TypeMap[VectorType::get(Type::getInt32Ty(Context), components)];
alan-bakerce179f12019-12-06 19:02:22 -05005178 }
David Neto5c22a252018-03-15 16:07:41 -04005179 uint32_t ImageID = VMap[Image];
David Neto257c3892018-04-11 13:19:45 -04005180 Ops << MkId(SizesTypeID) << MkId(ImageID);
alan-bakerce179f12019-12-06 19:02:22 -05005181 spv::Op query_opcode = spv::OpImageQuerySize;
SJW173c7e92020-03-16 08:44:47 -05005182 if (IsSampledImageType(Image->getType())) {
alan-bakerce179f12019-12-06 19:02:22 -05005183 query_opcode = spv::OpImageQuerySizeLod;
5184 // Need explicit 0 for Lod operand.
5185 Constant *CstInt0 = ConstantInt::get(Context, APInt(32, 0));
5186 Ops << MkId(VMap[CstInt0]);
5187 }
David Neto5c22a252018-03-15 16:07:41 -04005188
5189 uint32_t SizesID = nextID++;
alan-bakerce179f12019-12-06 19:02:22 -05005190 auto *QueryInst = new SPIRVInstruction(query_opcode, SizesID, Ops);
David Neto5c22a252018-03-15 16:07:41 -04005191 SPIRVInstList.push_back(QueryInst);
5192
alan-bakerce179f12019-12-06 19:02:22 -05005193 // May require an extra instruction to create the appropriate result of
5194 // the builtin function.
SJW173c7e92020-03-16 08:44:47 -05005195 if (IsGetImageDim(Callee)) {
alan-bakerce179f12019-12-06 19:02:22 -05005196 if (dim == 3) {
5197 // get_image_dim returns an int4 for 3D images.
5198 //
5199 // Reset value map entry since we generated an intermediate
5200 // instruction.
5201 VMap[&I] = nextID;
David Neto5c22a252018-03-15 16:07:41 -04005202
alan-bakerce179f12019-12-06 19:02:22 -05005203 // Implement:
5204 // %result = OpCompositeConstruct %uint4 %sizes %uint_0
5205 Ops.clear();
5206 Ops << MkId(lookupType(VectorType::get(Type::getInt32Ty(Context), 4)))
5207 << MkId(SizesID);
David Neto5c22a252018-03-15 16:07:41 -04005208
alan-bakerce179f12019-12-06 19:02:22 -05005209 Constant *CstInt0 = ConstantInt::get(Context, APInt(32, 0));
5210 Ops << MkId(VMap[CstInt0]);
David Neto5c22a252018-03-15 16:07:41 -04005211
alan-bakerce179f12019-12-06 19:02:22 -05005212 auto *Inst =
5213 new SPIRVInstruction(spv::OpCompositeConstruct, nextID++, Ops);
5214 SPIRVInstList.push_back(Inst);
5215 } else if (dim != components) {
5216 // get_image_dim return an int2 regardless of the arrayedness of the
5217 // image. If the image is arrayed an element must be dropped from the
5218 // query result.
5219 //
5220 // Reset value map entry since we generated an intermediate
5221 // instruction.
5222 VMap[&I] = nextID;
5223
5224 // Implement:
5225 // %result = OpVectorShuffle %uint2 %sizes %sizes 0 1
5226 Ops.clear();
5227 Ops << MkId(lookupType(VectorType::get(Type::getInt32Ty(Context), 2)))
5228 << MkId(SizesID) << MkId(SizesID) << MkNum(0) << MkNum(1);
5229
5230 auto *Inst =
5231 new SPIRVInstruction(spv::OpVectorShuffle, nextID++, Ops);
5232 SPIRVInstList.push_back(Inst);
5233 }
5234 } else if (components > 1) {
5235 // Reset value map entry since we generated an intermediate instruction.
5236 VMap[&I] = nextID;
5237
5238 // Implement:
5239 // %result = OpCompositeExtract %uint %sizes <component number>
5240 Ops.clear();
5241 Ops << MkId(TypeMap[I.getType()]) << MkId(SizesID);
5242
5243 uint32_t component = 0;
5244 if (IsGetImageHeight(Callee))
5245 component = 1;
5246 else if (IsGetImageDepth(Callee))
5247 component = 2;
5248 Ops << MkNum(component);
5249
5250 auto *Inst =
5251 new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
5252 SPIRVInstList.push_back(Inst);
5253 }
David Neto5c22a252018-03-15 16:07:41 -04005254 break;
5255 }
5256
David Neto22f144c2017-06-12 14:26:21 -04005257 // Call instrucion is deferred because it needs function's ID. Record
5258 // slot's location on SPIRVInstructionList.
5259 DeferredInsts.push_back(
5260 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
5261
David Neto3fbb4072017-10-16 11:28:14 -04005262 // Check whether the implementation of this call uses an extended
5263 // instruction plus one more value-producing instruction. If so, then
5264 // reserve the id for the extra value-producing slot.
5265 glsl::ExtInst EInst = getIndirectExtInstEnum(Callee->getName());
5266 if (EInst != kGlslExtInstBad) {
5267 // Reserve a spot for the extra value.
David Neto4d02a532017-09-17 12:57:44 -04005268 // Increase nextID.
David Neto22f144c2017-06-12 14:26:21 -04005269 VMap[&I] = nextID;
5270 nextID++;
5271 }
5272 break;
5273 }
5274 case Instruction::Ret: {
5275 unsigned NumOps = I.getNumOperands();
5276 if (NumOps == 0) {
5277 //
5278 // Generate OpReturn.
5279 //
David Netoef5ba2b2019-12-20 08:35:54 -05005280 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpReturn));
David Neto22f144c2017-06-12 14:26:21 -04005281 } else {
5282 //
5283 // Generate OpReturnValue.
5284 //
5285
5286 // Ops[0] = Return Value ID
5287 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04005288
5289 Ops << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04005290
David Neto87846742018-04-11 17:36:22 -04005291 auto *Inst = new SPIRVInstruction(spv::OpReturnValue, Ops);
David Neto22f144c2017-06-12 14:26:21 -04005292 SPIRVInstList.push_back(Inst);
5293 break;
5294 }
5295 break;
5296 }
5297 }
5298}
5299
5300void SPIRVProducerPass::GenerateFuncEpilogue() {
5301 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
5302
5303 //
5304 // Generate OpFunctionEnd
5305 //
5306
David Netoef5ba2b2019-12-20 08:35:54 -05005307 auto *Inst = new SPIRVInstruction(spv::OpFunctionEnd);
David Neto22f144c2017-06-12 14:26:21 -04005308 SPIRVInstList.push_back(Inst);
5309}
5310
5311bool SPIRVProducerPass::is4xi8vec(Type *Ty) const {
alan-bakerb39c8262019-03-08 14:03:37 -05005312 // Don't specialize <4 x i8> if i8 is generally supported.
5313 if (clspv::Option::Int8Support())
5314 return false;
5315
David Neto22f144c2017-06-12 14:26:21 -04005316 LLVMContext &Context = Ty->getContext();
5317 if (Ty->isVectorTy()) {
5318 if (Ty->getVectorElementType() == Type::getInt8Ty(Context) &&
5319 Ty->getVectorNumElements() == 4) {
5320 return true;
5321 }
5322 }
5323
5324 return false;
5325}
5326
5327void SPIRVProducerPass::HandleDeferredInstruction() {
5328 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
5329 ValueMapType &VMap = getValueMap();
5330 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
5331
5332 for (auto DeferredInst = DeferredInsts.rbegin();
5333 DeferredInst != DeferredInsts.rend(); ++DeferredInst) {
5334 Value *Inst = std::get<0>(*DeferredInst);
5335 SPIRVInstructionList::iterator InsertPoint = ++std::get<1>(*DeferredInst);
5336 if (InsertPoint != SPIRVInstList.end()) {
5337 while ((*InsertPoint)->getOpcode() == spv::OpPhi) {
5338 ++InsertPoint;
5339 }
5340 }
5341
5342 if (BranchInst *Br = dyn_cast<BranchInst>(Inst)) {
alan-baker06cad652019-12-03 17:56:47 -05005343 // Check whether this branch needs to be preceeded by merge instruction.
David Neto22f144c2017-06-12 14:26:21 -04005344 BasicBlock *BrBB = Br->getParent();
alan-baker06cad652019-12-03 17:56:47 -05005345 if (ContinueBlocks.count(BrBB)) {
David Neto22f144c2017-06-12 14:26:21 -04005346 //
5347 // Generate OpLoopMerge.
5348 //
5349 // Ops[0] = Merge Block ID
5350 // Ops[1] = Continue Target ID
5351 // Ops[2] = Selection Control
5352 SPIRVOperandList Ops;
5353
alan-baker06cad652019-12-03 17:56:47 -05005354 auto MergeBB = MergeBlocks[BrBB];
5355 auto ContinueBB = ContinueBlocks[BrBB];
David Neto22f144c2017-06-12 14:26:21 -04005356 uint32_t MergeBBID = VMap[MergeBB];
David Neto22f144c2017-06-12 14:26:21 -04005357 uint32_t ContinueBBID = VMap[ContinueBB];
David Neto257c3892018-04-11 13:19:45 -04005358 Ops << MkId(MergeBBID) << MkId(ContinueBBID)
alan-baker06cad652019-12-03 17:56:47 -05005359 << MkNum(spv::LoopControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04005360
David Neto87846742018-04-11 17:36:22 -04005361 auto *MergeInst = new SPIRVInstruction(spv::OpLoopMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04005362 SPIRVInstList.insert(InsertPoint, MergeInst);
alan-baker06cad652019-12-03 17:56:47 -05005363 } else if (MergeBlocks.count(BrBB)) {
5364 //
5365 // Generate OpSelectionMerge.
5366 //
5367 // Ops[0] = Merge Block ID
5368 // Ops[1] = Selection Control
5369 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04005370
alan-baker06cad652019-12-03 17:56:47 -05005371 auto MergeBB = MergeBlocks[BrBB];
5372 uint32_t MergeBBID = VMap[MergeBB];
5373 Ops << MkId(MergeBBID) << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04005374
alan-baker06cad652019-12-03 17:56:47 -05005375 auto *MergeInst = new SPIRVInstruction(spv::OpSelectionMerge, Ops);
5376 SPIRVInstList.insert(InsertPoint, MergeInst);
David Neto22f144c2017-06-12 14:26:21 -04005377 }
5378
5379 if (Br->isConditional()) {
5380 //
5381 // Generate OpBranchConditional.
5382 //
5383 // Ops[0] = Condition ID
5384 // Ops[1] = True Label ID
5385 // Ops[2] = False Label ID
5386 // Ops[3] ... Ops[n] = Branch weights (Literal Number)
5387 SPIRVOperandList Ops;
5388
5389 uint32_t CondID = VMap[Br->getCondition()];
David Neto22f144c2017-06-12 14:26:21 -04005390 uint32_t TrueBBID = VMap[Br->getSuccessor(0)];
David Neto22f144c2017-06-12 14:26:21 -04005391 uint32_t FalseBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04005392
5393 Ops << MkId(CondID) << MkId(TrueBBID) << MkId(FalseBBID);
David Neto22f144c2017-06-12 14:26:21 -04005394
David Neto87846742018-04-11 17:36:22 -04005395 auto *BrInst = new SPIRVInstruction(spv::OpBranchConditional, Ops);
David Neto22f144c2017-06-12 14:26:21 -04005396 SPIRVInstList.insert(InsertPoint, BrInst);
5397 } else {
5398 //
5399 // Generate OpBranch.
5400 //
5401 // Ops[0] = Target Label ID
5402 SPIRVOperandList Ops;
5403
5404 uint32_t TargetID = VMap[Br->getSuccessor(0)];
David Neto257c3892018-04-11 13:19:45 -04005405 Ops << MkId(TargetID);
David Neto22f144c2017-06-12 14:26:21 -04005406
David Neto87846742018-04-11 17:36:22 -04005407 SPIRVInstList.insert(InsertPoint,
5408 new SPIRVInstruction(spv::OpBranch, Ops));
David Neto22f144c2017-06-12 14:26:21 -04005409 }
5410 } else if (PHINode *PHI = dyn_cast<PHINode>(Inst)) {
alan-baker5ed87542020-03-23 11:05:22 -04005411 if (PHI->getType()->isPointerTy() && !IsSamplerType(PHI->getType()) &&
5412 !IsImageType(PHI->getType())) {
alan-baker5b86ed72019-02-15 08:26:50 -05005413 // OpPhi on pointers requires variable pointers.
5414 setVariablePointersCapabilities(
5415 PHI->getType()->getPointerAddressSpace());
5416 if (!hasVariablePointers() && !selectFromSameObject(PHI)) {
5417 setVariablePointers(true);
5418 }
5419 }
5420
David Neto22f144c2017-06-12 14:26:21 -04005421 //
5422 // Generate OpPhi.
5423 //
5424 // Ops[0] = Result Type ID
5425 // Ops[1] ... Ops[n] = (Variable ID, Parent ID) pairs
5426 SPIRVOperandList Ops;
5427
David Neto257c3892018-04-11 13:19:45 -04005428 Ops << MkId(lookupType(PHI->getType()));
David Neto22f144c2017-06-12 14:26:21 -04005429
David Neto22f144c2017-06-12 14:26:21 -04005430 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
5431 uint32_t VarID = VMap[PHI->getIncomingValue(i)];
David Neto22f144c2017-06-12 14:26:21 -04005432 uint32_t ParentID = VMap[PHI->getIncomingBlock(i)];
David Neto257c3892018-04-11 13:19:45 -04005433 Ops << MkId(VarID) << MkId(ParentID);
David Neto22f144c2017-06-12 14:26:21 -04005434 }
5435
5436 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005437 InsertPoint,
5438 new SPIRVInstruction(spv::OpPhi, std::get<2>(*DeferredInst), Ops));
David Neto22f144c2017-06-12 14:26:21 -04005439 } else if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
5440 Function *Callee = Call->getCalledFunction();
SJW2c317da2020-03-23 07:39:13 -05005441 LLVMContext &Context = Callee->getContext();
5442 auto IntTy = Type::getInt32Ty(Context);
5443 auto callee_code = Builtins::Lookup(Callee);
David Neto3fbb4072017-10-16 11:28:14 -04005444 auto callee_name = Callee->getName();
5445 glsl::ExtInst EInst = getDirectOrIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04005446
5447 if (EInst) {
5448 uint32_t &ExtInstImportID = getOpExtInstImportID();
5449
5450 //
5451 // Generate OpExtInst.
5452 //
5453
5454 // Ops[0] = Result Type ID
5455 // Ops[1] = Set ID (OpExtInstImport ID)
5456 // Ops[2] = Instruction Number (Literal Number)
5457 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
5458 SPIRVOperandList Ops;
5459
David Neto862b7d82018-06-14 18:48:37 -04005460 Ops << MkId(lookupType(Call->getType())) << MkId(ExtInstImportID)
5461 << MkNum(EInst);
David Neto22f144c2017-06-12 14:26:21 -04005462
David Neto22f144c2017-06-12 14:26:21 -04005463 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5464 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
David Neto257c3892018-04-11 13:19:45 -04005465 Ops << MkId(VMap[Call->getOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04005466 }
5467
David Neto87846742018-04-11 17:36:22 -04005468 auto *ExtInst = new SPIRVInstruction(spv::OpExtInst,
5469 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04005470 SPIRVInstList.insert(InsertPoint, ExtInst);
5471
David Neto3fbb4072017-10-16 11:28:14 -04005472 const auto IndirectExtInst = getIndirectExtInstEnum(callee_name);
5473 if (IndirectExtInst != kGlslExtInstBad) {
5474 // Generate one more instruction that uses the result of the extended
5475 // instruction. Its result id is one more than the id of the
5476 // extended instruction.
David Neto3fbb4072017-10-16 11:28:14 -04005477 auto generate_extra_inst = [this, &Context, &Call, &DeferredInst,
5478 &VMap, &SPIRVInstList, &InsertPoint](
5479 spv::Op opcode, Constant *constant) {
5480 //
5481 // Generate instruction like:
5482 // result = opcode constant <extinst-result>
5483 //
5484 // Ops[0] = Result Type ID
5485 // Ops[1] = Operand 0 ;; the constant, suitably splatted
5486 // Ops[2] = Operand 1 ;; the result of the extended instruction
5487 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04005488
David Neto3fbb4072017-10-16 11:28:14 -04005489 Type *resultTy = Call->getType();
David Neto257c3892018-04-11 13:19:45 -04005490 Ops << MkId(lookupType(resultTy));
David Neto3fbb4072017-10-16 11:28:14 -04005491
5492 if (auto *vectorTy = dyn_cast<VectorType>(resultTy)) {
5493 constant = ConstantVector::getSplat(
alan-baker7261e062020-03-15 14:35:48 -04005494 {static_cast<unsigned>(vectorTy->getNumElements()), false},
5495 constant);
David Neto3fbb4072017-10-16 11:28:14 -04005496 }
David Neto257c3892018-04-11 13:19:45 -04005497 Ops << MkId(VMap[constant]) << MkId(std::get<2>(*DeferredInst));
David Neto3fbb4072017-10-16 11:28:14 -04005498
5499 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005500 InsertPoint, new SPIRVInstruction(
5501 opcode, std::get<2>(*DeferredInst) + 1, Ops));
David Neto3fbb4072017-10-16 11:28:14 -04005502 };
5503
5504 switch (IndirectExtInst) {
5505 case glsl::ExtInstFindUMsb: // Implementing clz
SJW2c317da2020-03-23 07:39:13 -05005506 generate_extra_inst(spv::OpISub, ConstantInt::get(IntTy, 31));
David Neto3fbb4072017-10-16 11:28:14 -04005507 break;
5508 case glsl::ExtInstAcos: // Implementing acospi
5509 case glsl::ExtInstAsin: // Implementing asinpi
Kévin Petiteb9f90a2018-09-29 12:29:34 +01005510 case glsl::ExtInstAtan: // Implementing atanpi
David Neto3fbb4072017-10-16 11:28:14 -04005511 case glsl::ExtInstAtan2: // Implementing atan2pi
5512 generate_extra_inst(
5513 spv::OpFMul,
5514 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
5515 break;
5516
5517 default:
5518 assert(false && "internally inconsistent");
David Neto4d02a532017-09-17 12:57:44 -04005519 }
David Neto22f144c2017-06-12 14:26:21 -04005520 }
David Neto3fbb4072017-10-16 11:28:14 -04005521
SJW2c317da2020-03-23 07:39:13 -05005522 } else if (callee_code == Builtins::kPopcount) {
David Neto22f144c2017-06-12 14:26:21 -04005523 //
5524 // Generate OpBitCount
5525 //
5526 // Ops[0] = Result Type ID
5527 // Ops[1] = Base ID
David Neto257c3892018-04-11 13:19:45 -04005528 SPIRVOperandList Ops;
5529 Ops << MkId(lookupType(Call->getType()))
5530 << MkId(VMap[Call->getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04005531
5532 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005533 InsertPoint, new SPIRVInstruction(spv::OpBitCount,
David Neto22f144c2017-06-12 14:26:21 -04005534 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005535
David Neto862b7d82018-06-14 18:48:37 -04005536 } else if (callee_name.startswith(kCompositeConstructFunctionPrefix)) {
David Netoab03f432017-11-03 17:00:44 -04005537
5538 // Generate an OpCompositeConstruct
5539 SPIRVOperandList Ops;
5540
5541 // The result type.
David Neto257c3892018-04-11 13:19:45 -04005542 Ops << MkId(lookupType(Call->getType()));
David Netoab03f432017-11-03 17:00:44 -04005543
5544 for (Use &use : Call->arg_operands()) {
David Neto257c3892018-04-11 13:19:45 -04005545 Ops << MkId(VMap[use.get()]);
David Netoab03f432017-11-03 17:00:44 -04005546 }
5547
5548 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005549 InsertPoint, new SPIRVInstruction(spv::OpCompositeConstruct,
5550 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005551
Alan Baker202c8c72018-08-13 13:47:44 -04005552 } else if (callee_name.startswith(clspv::ResourceAccessorFunction())) {
5553
5554 // We have already mapped the call's result value to an ID.
5555 // Don't generate any code now.
5556
5557 } else if (callee_name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04005558
5559 // We have already mapped the call's result value to an ID.
5560 // Don't generate any code now.
5561
David Neto22f144c2017-06-12 14:26:21 -04005562 } else {
alan-baker5b86ed72019-02-15 08:26:50 -05005563 if (Call->getType()->isPointerTy()) {
5564 // Functions returning pointers require variable pointers.
5565 setVariablePointersCapabilities(
5566 Call->getType()->getPointerAddressSpace());
5567 }
5568
David Neto22f144c2017-06-12 14:26:21 -04005569 //
5570 // Generate OpFunctionCall.
5571 //
5572
5573 // Ops[0] = Result Type ID
5574 // Ops[1] = Callee Function ID
5575 // Ops[2] ... Ops[n] = Argument 0, ... , Argument n
5576 SPIRVOperandList Ops;
5577
David Neto862b7d82018-06-14 18:48:37 -04005578 Ops << MkId(lookupType(Call->getType()));
David Neto22f144c2017-06-12 14:26:21 -04005579
5580 uint32_t CalleeID = VMap[Callee];
David Neto43568eb2017-10-13 18:25:25 -04005581 if (CalleeID == 0) {
5582 errs() << "Can't translate function call. Missing builtin? "
David Neto862b7d82018-06-14 18:48:37 -04005583 << callee_name << " in: " << *Call << "\n";
David Neto43568eb2017-10-13 18:25:25 -04005584 // TODO(dneto): Can we error out? Enabling this llvm_unreachable
5585 // causes an infinite loop. Instead, go ahead and generate
5586 // the bad function call. A validator will catch the 0-Id.
5587 // llvm_unreachable("Can't translate function call");
5588 }
David Neto22f144c2017-06-12 14:26:21 -04005589
David Neto257c3892018-04-11 13:19:45 -04005590 Ops << MkId(CalleeID);
David Neto22f144c2017-06-12 14:26:21 -04005591
David Neto22f144c2017-06-12 14:26:21 -04005592 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5593 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
alan-baker5b86ed72019-02-15 08:26:50 -05005594 auto *operand = Call->getOperand(i);
alan-bakerd4d50652019-12-03 17:17:15 -05005595 auto *operand_type = operand->getType();
5596 // Images and samplers can be passed as function parameters without
5597 // variable pointers.
5598 if (operand_type->isPointerTy() && !IsImageType(operand_type) &&
5599 !IsSamplerType(operand_type)) {
alan-baker5b86ed72019-02-15 08:26:50 -05005600 auto sc =
5601 GetStorageClass(operand->getType()->getPointerAddressSpace());
5602 if (sc == spv::StorageClassStorageBuffer) {
5603 // Passing SSBO by reference requires variable pointers storage
5604 // buffer.
5605 setVariablePointersStorageBuffer(true);
5606 } else if (sc == spv::StorageClassWorkgroup) {
5607 // Workgroup references require variable pointers if they are not
5608 // memory object declarations.
5609 if (auto *operand_call = dyn_cast<CallInst>(operand)) {
5610 // Workgroup accessor represents a variable reference.
5611 if (!operand_call->getCalledFunction()->getName().startswith(
5612 clspv::WorkgroupAccessorFunction()))
5613 setVariablePointers(true);
5614 } else {
5615 // Arguments are function parameters.
5616 if (!isa<Argument>(operand))
5617 setVariablePointers(true);
5618 }
5619 }
5620 }
5621 Ops << MkId(VMap[operand]);
David Neto22f144c2017-06-12 14:26:21 -04005622 }
5623
David Neto87846742018-04-11 17:36:22 -04005624 auto *CallInst = new SPIRVInstruction(spv::OpFunctionCall,
5625 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04005626 SPIRVInstList.insert(InsertPoint, CallInst);
5627 }
5628 }
5629 }
5630}
5631
David Neto1a1a0582017-07-07 12:01:44 -04005632void SPIRVProducerPass::HandleDeferredDecorations(const DataLayout &DL) {
Alan Baker202c8c72018-08-13 13:47:44 -04005633 if (getTypesNeedingArrayStride().empty() && LocalArgSpecIds.empty()) {
David Neto1a1a0582017-07-07 12:01:44 -04005634 return;
David Netoc6f3ab22018-04-06 18:02:31 -04005635 }
David Neto1a1a0582017-07-07 12:01:44 -04005636
5637 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
David Neto1a1a0582017-07-07 12:01:44 -04005638
5639 // Find an iterator pointing just past the last decoration.
5640 bool seen_decorations = false;
5641 auto DecoInsertPoint =
5642 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
5643 [&seen_decorations](SPIRVInstruction *Inst) -> bool {
5644 const bool is_decoration =
5645 Inst->getOpcode() == spv::OpDecorate ||
5646 Inst->getOpcode() == spv::OpMemberDecorate;
5647 if (is_decoration) {
5648 seen_decorations = true;
5649 return false;
5650 } else {
5651 return seen_decorations;
5652 }
5653 });
5654
David Netoc6f3ab22018-04-06 18:02:31 -04005655 // Insert ArrayStride decorations on pointer types, due to OpPtrAccessChain
5656 // instructions we generated earlier.
David Neto85082642018-03-24 06:55:20 -07005657 for (auto *type : getTypesNeedingArrayStride()) {
5658 Type *elemTy = nullptr;
5659 if (auto *ptrTy = dyn_cast<PointerType>(type)) {
5660 elemTy = ptrTy->getElementType();
alan-bakerb6b09dc2018-11-08 16:59:28 -05005661 } else if (auto *arrayTy = dyn_cast<ArrayType>(type)) {
David Neto85082642018-03-24 06:55:20 -07005662 elemTy = arrayTy->getArrayElementType();
alan-bakerb6b09dc2018-11-08 16:59:28 -05005663 } else if (auto *seqTy = dyn_cast<SequentialType>(type)) {
David Neto85082642018-03-24 06:55:20 -07005664 elemTy = seqTy->getSequentialElementType();
5665 } else {
5666 errs() << "Unhandled strided type " << *type << "\n";
5667 llvm_unreachable("Unhandled strided type");
5668 }
David Neto1a1a0582017-07-07 12:01:44 -04005669
5670 // Ops[0] = Target ID
5671 // Ops[1] = Decoration (ArrayStride)
5672 // Ops[2] = Stride number (Literal Number)
5673 SPIRVOperandList Ops;
5674
David Neto85082642018-03-24 06:55:20 -07005675 // Same as DL.getIndexedOffsetInType( elemTy, { 1 } );
Alan Bakerfcda9482018-10-02 17:09:59 -04005676 const uint32_t stride = static_cast<uint32_t>(GetTypeAllocSize(elemTy, DL));
David Neto257c3892018-04-11 13:19:45 -04005677
5678 Ops << MkId(lookupType(type)) << MkNum(spv::DecorationArrayStride)
5679 << MkNum(stride);
David Neto1a1a0582017-07-07 12:01:44 -04005680
David Neto87846742018-04-11 17:36:22 -04005681 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto1a1a0582017-07-07 12:01:44 -04005682 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
5683 }
David Netoc6f3ab22018-04-06 18:02:31 -04005684
5685 // Emit SpecId decorations targeting the array size value.
Alan Baker202c8c72018-08-13 13:47:44 -04005686 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
5687 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05005688 LocalArgInfo &arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04005689 SPIRVOperandList Ops;
5690 Ops << MkId(arg_info.array_size_id) << MkNum(spv::DecorationSpecId)
5691 << MkNum(arg_info.spec_id);
5692 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04005693 new SPIRVInstruction(spv::OpDecorate, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04005694 }
David Neto1a1a0582017-07-07 12:01:44 -04005695}
5696
David Neto22f144c2017-06-12 14:26:21 -04005697glsl::ExtInst SPIRVProducerPass::getExtInstEnum(StringRef Name) {
SJW2c317da2020-03-23 07:39:13 -05005698
5699 const auto &fi = Builtins::Lookup(Name);
5700 switch (fi) {
5701 case Builtins::kClamp: {
5702 auto param_type = fi.getParameter(0);
5703 if (param_type.type_id == Type::FloatTyID) {
5704 return glsl::ExtInst::ExtInstFClamp;
5705 }
5706 return param_type.is_signed ? glsl::ExtInst::ExtInstSClamp
5707 : glsl::ExtInst::ExtInstUClamp;
5708 }
5709 case Builtins::kMax: {
5710 auto param_type = fi.getParameter(0);
5711 if (param_type.type_id == Type::FloatTyID) {
5712 return glsl::ExtInst::ExtInstFMax;
5713 }
5714 return param_type.is_signed ? glsl::ExtInst::ExtInstSMax
5715 : glsl::ExtInst::ExtInstUMax;
5716 }
5717 case Builtins::kMin: {
5718 auto param_type = fi.getParameter(0);
5719 if (param_type.type_id == Type::FloatTyID) {
5720 return glsl::ExtInst::ExtInstFMin;
5721 }
5722 return param_type.is_signed ? glsl::ExtInst::ExtInstSMin
5723 : glsl::ExtInst::ExtInstUMin;
5724 }
5725 case Builtins::kAbs:
5726 return glsl::ExtInst::ExtInstSAbs;
5727 case Builtins::kFmax:
5728 return glsl::ExtInst::ExtInstFMax;
5729 case Builtins::kFmin:
5730 return glsl::ExtInst::ExtInstFMin;
5731 case Builtins::kDegrees:
5732 return glsl::ExtInst::ExtInstDegrees;
5733 case Builtins::kRadians:
5734 return glsl::ExtInst::ExtInstRadians;
5735 case Builtins::kMix:
5736 return glsl::ExtInst::ExtInstFMix;
5737 case Builtins::kAcos:
5738 case Builtins::kAcospi:
5739 return glsl::ExtInst::ExtInstAcos;
5740 case Builtins::kAcosh:
5741 return glsl::ExtInst::ExtInstAcosh;
5742 case Builtins::kAsin:
5743 case Builtins::kAsinpi:
5744 return glsl::ExtInst::ExtInstAsin;
5745 case Builtins::kAsinh:
5746 return glsl::ExtInst::ExtInstAsinh;
5747 case Builtins::kAtan:
5748 case Builtins::kAtanpi:
5749 return glsl::ExtInst::ExtInstAtan;
5750 case Builtins::kAtanh:
5751 return glsl::ExtInst::ExtInstAtanh;
5752 case Builtins::kAtan2:
5753 case Builtins::kAtan2pi:
5754 return glsl::ExtInst::ExtInstAtan2;
5755 case Builtins::kCeil:
5756 return glsl::ExtInst::ExtInstCeil;
5757 case Builtins::kSin:
5758 case Builtins::kHalfSin:
5759 case Builtins::kNativeSin:
5760 return glsl::ExtInst::ExtInstSin;
5761 case Builtins::kSinh:
5762 return glsl::ExtInst::ExtInstSinh;
5763 case Builtins::kCos:
5764 case Builtins::kHalfCos:
5765 case Builtins::kNativeCos:
5766 return glsl::ExtInst::ExtInstCos;
5767 case Builtins::kCosh:
5768 return glsl::ExtInst::ExtInstCosh;
5769 case Builtins::kTan:
5770 case Builtins::kHalfTan:
5771 case Builtins::kNativeTan:
5772 return glsl::ExtInst::ExtInstTan;
5773 case Builtins::kTanh:
5774 return glsl::ExtInst::ExtInstTanh;
5775 case Builtins::kExp:
5776 case Builtins::kHalfExp:
5777 case Builtins::kNativeExp:
5778 return glsl::ExtInst::ExtInstExp;
5779 case Builtins::kExp2:
5780 case Builtins::kHalfExp2:
5781 case Builtins::kNativeExp2:
5782 return glsl::ExtInst::ExtInstExp2;
5783 case Builtins::kLog:
5784 case Builtins::kHalfLog:
5785 case Builtins::kNativeLog:
5786 return glsl::ExtInst::ExtInstLog;
5787 case Builtins::kLog2:
5788 case Builtins::kHalfLog2:
5789 case Builtins::kNativeLog2:
5790 return glsl::ExtInst::ExtInstLog2;
5791 case Builtins::kFabs:
5792 return glsl::ExtInst::ExtInstFAbs;
5793 case Builtins::kFma:
5794 return glsl::ExtInst::ExtInstFma;
5795 case Builtins::kFloor:
5796 return glsl::ExtInst::ExtInstFloor;
5797 case Builtins::kLdexp:
5798 return glsl::ExtInst::ExtInstLdexp;
5799 case Builtins::kPow:
5800 case Builtins::kPowr:
5801 case Builtins::kHalfPowr:
5802 case Builtins::kNativePowr:
5803 return glsl::ExtInst::ExtInstPow;
5804 case Builtins::kRound:
5805 return glsl::ExtInst::ExtInstRound;
5806 case Builtins::kSqrt:
5807 case Builtins::kHalfSqrt:
5808 case Builtins::kNativeSqrt:
5809 return glsl::ExtInst::ExtInstSqrt;
5810 case Builtins::kRsqrt:
5811 case Builtins::kHalfRsqrt:
5812 case Builtins::kNativeRsqrt:
5813 return glsl::ExtInst::ExtInstInverseSqrt;
5814 case Builtins::kTrunc:
5815 return glsl::ExtInst::ExtInstTrunc;
5816 case Builtins::kFrexp:
5817 return glsl::ExtInst::ExtInstFrexp;
5818 case Builtins::kFract:
5819 return glsl::ExtInst::ExtInstFract;
5820 case Builtins::kSign:
5821 return glsl::ExtInst::ExtInstFSign;
5822 case Builtins::kLength:
5823 case Builtins::kFastLength:
5824 return glsl::ExtInst::ExtInstLength;
5825 case Builtins::kDistance:
5826 case Builtins::kFastDistance:
5827 return glsl::ExtInst::ExtInstDistance;
5828 case Builtins::kStep:
5829 return glsl::ExtInst::ExtInstStep;
5830 case Builtins::kSmoothstep:
5831 return glsl::ExtInst::ExtInstSmoothStep;
5832 case Builtins::kCross:
5833 return glsl::ExtInst::ExtInstCross;
5834 case Builtins::kNormalize:
5835 case Builtins::kFastNormalize:
5836 return glsl::ExtInst::ExtInstNormalize;
5837 default:
5838 break;
5839 }
5840
David Neto22f144c2017-06-12 14:26:21 -04005841 return StringSwitch<glsl::ExtInst>(Name)
David Neto22f144c2017-06-12 14:26:21 -04005842 .StartsWith("llvm.fmuladd.", glsl::ExtInst::ExtInstFma)
5843 .Case("spirv.unpack.v2f16", glsl::ExtInst::ExtInstUnpackHalf2x16)
5844 .Case("spirv.pack.v2f16", glsl::ExtInst::ExtInstPackHalf2x16)
David Neto3fbb4072017-10-16 11:28:14 -04005845 .Default(kGlslExtInstBad);
5846}
5847
5848glsl::ExtInst SPIRVProducerPass::getIndirectExtInstEnum(StringRef Name) {
SJW2c317da2020-03-23 07:39:13 -05005849 switch (Builtins::Lookup(Name)) {
5850 case Builtins::kClz:
5851 return glsl::ExtInst::ExtInstFindUMsb;
5852 case Builtins::kAcospi:
5853 return glsl::ExtInst::ExtInstAcos;
5854 case Builtins::kAsinpi:
5855 return glsl::ExtInst::ExtInstAsin;
5856 case Builtins::kAtanpi:
5857 return glsl::ExtInst::ExtInstAtan;
5858 case Builtins::kAtan2pi:
5859 return glsl::ExtInst::ExtInstAtan2;
5860 default:
5861 break;
5862 }
5863 return kGlslExtInstBad;
David Neto3fbb4072017-10-16 11:28:14 -04005864}
5865
alan-bakerb6b09dc2018-11-08 16:59:28 -05005866glsl::ExtInst
5867SPIRVProducerPass::getDirectOrIndirectExtInstEnum(StringRef Name) {
David Neto3fbb4072017-10-16 11:28:14 -04005868 auto direct = getExtInstEnum(Name);
5869 if (direct != kGlslExtInstBad)
5870 return direct;
5871 return getIndirectExtInstEnum(Name);
David Neto22f144c2017-06-12 14:26:21 -04005872}
5873
David Neto22f144c2017-06-12 14:26:21 -04005874void SPIRVProducerPass::WriteOneWord(uint32_t Word) {
David Neto0676e6f2017-07-11 18:47:44 -04005875 binaryOut->write(reinterpret_cast<const char *>(&Word), sizeof(uint32_t));
David Neto22f144c2017-06-12 14:26:21 -04005876}
5877
5878void SPIRVProducerPass::WriteResultID(SPIRVInstruction *Inst) {
5879 WriteOneWord(Inst->getResultID());
5880}
5881
5882void SPIRVProducerPass::WriteWordCountAndOpcode(SPIRVInstruction *Inst) {
5883 // High 16 bit : Word Count
5884 // Low 16 bit : Opcode
5885 uint32_t Word = Inst->getOpcode();
David Netoee2660d2018-06-28 16:31:29 -04005886 const uint32_t count = Inst->getWordCount();
5887 if (count > 65535) {
5888 errs() << "Word count limit of 65535 exceeded: " << count << "\n";
5889 llvm_unreachable("Word count too high");
5890 }
David Neto22f144c2017-06-12 14:26:21 -04005891 Word |= Inst->getWordCount() << 16;
5892 WriteOneWord(Word);
5893}
5894
David Netoef5ba2b2019-12-20 08:35:54 -05005895void SPIRVProducerPass::WriteOperand(const std::unique_ptr<SPIRVOperand> &Op) {
David Neto22f144c2017-06-12 14:26:21 -04005896 SPIRVOperandType OpTy = Op->getType();
5897 switch (OpTy) {
5898 default: {
5899 llvm_unreachable("Unsupported SPIRV Operand Type???");
5900 break;
5901 }
5902 case SPIRVOperandType::NUMBERID: {
5903 WriteOneWord(Op->getNumID());
5904 break;
5905 }
5906 case SPIRVOperandType::LITERAL_STRING: {
5907 std::string Str = Op->getLiteralStr();
5908 const char *Data = Str.c_str();
5909 size_t WordSize = Str.size() / 4;
5910 for (unsigned Idx = 0; Idx < WordSize; Idx++) {
5911 WriteOneWord(*reinterpret_cast<const uint32_t *>(&Data[4 * Idx]));
5912 }
5913
5914 uint32_t Remainder = Str.size() % 4;
5915 uint32_t LastWord = 0;
5916 if (Remainder) {
5917 for (unsigned Idx = 0; Idx < Remainder; Idx++) {
5918 LastWord |= Data[4 * WordSize + Idx] << 8 * Idx;
5919 }
5920 }
5921
5922 WriteOneWord(LastWord);
5923 break;
5924 }
5925 case SPIRVOperandType::LITERAL_INTEGER:
5926 case SPIRVOperandType::LITERAL_FLOAT: {
5927 auto LiteralNum = Op->getLiteralNum();
5928 // TODO: Handle LiteranNum carefully.
5929 for (auto Word : LiteralNum) {
5930 WriteOneWord(Word);
5931 }
5932 break;
5933 }
5934 }
5935}
5936
5937void SPIRVProducerPass::WriteSPIRVBinary() {
5938 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
5939
5940 for (auto Inst : SPIRVInstList) {
David Netoef5ba2b2019-12-20 08:35:54 -05005941 const auto &Ops = Inst->getOperands();
David Neto22f144c2017-06-12 14:26:21 -04005942 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5943
5944 switch (Opcode) {
5945 default: {
David Neto5c22a252018-03-15 16:07:41 -04005946 errs() << "Unsupported SPIR-V instruction opcode " << int(Opcode) << "\n";
David Neto22f144c2017-06-12 14:26:21 -04005947 llvm_unreachable("Unsupported SPIRV instruction");
5948 break;
5949 }
5950 case spv::OpCapability:
5951 case spv::OpExtension:
5952 case spv::OpMemoryModel:
5953 case spv::OpEntryPoint:
5954 case spv::OpExecutionMode:
5955 case spv::OpSource:
5956 case spv::OpDecorate:
5957 case spv::OpMemberDecorate:
5958 case spv::OpBranch:
5959 case spv::OpBranchConditional:
5960 case spv::OpSelectionMerge:
5961 case spv::OpLoopMerge:
5962 case spv::OpStore:
5963 case spv::OpImageWrite:
5964 case spv::OpReturnValue:
5965 case spv::OpControlBarrier:
5966 case spv::OpMemoryBarrier:
5967 case spv::OpReturn:
5968 case spv::OpFunctionEnd:
5969 case spv::OpCopyMemory: {
5970 WriteWordCountAndOpcode(Inst);
5971 for (uint32_t i = 0; i < Ops.size(); i++) {
5972 WriteOperand(Ops[i]);
5973 }
5974 break;
5975 }
5976 case spv::OpTypeBool:
5977 case spv::OpTypeVoid:
5978 case spv::OpTypeSampler:
5979 case spv::OpLabel:
5980 case spv::OpExtInstImport:
5981 case spv::OpTypePointer:
5982 case spv::OpTypeRuntimeArray:
5983 case spv::OpTypeStruct:
5984 case spv::OpTypeImage:
5985 case spv::OpTypeSampledImage:
5986 case spv::OpTypeInt:
5987 case spv::OpTypeFloat:
5988 case spv::OpTypeArray:
5989 case spv::OpTypeVector:
5990 case spv::OpTypeFunction: {
5991 WriteWordCountAndOpcode(Inst);
5992 WriteResultID(Inst);
5993 for (uint32_t i = 0; i < Ops.size(); i++) {
5994 WriteOperand(Ops[i]);
5995 }
5996 break;
5997 }
5998 case spv::OpFunction:
5999 case spv::OpFunctionParameter:
6000 case spv::OpAccessChain:
6001 case spv::OpPtrAccessChain:
6002 case spv::OpInBoundsAccessChain:
6003 case spv::OpUConvert:
6004 case spv::OpSConvert:
6005 case spv::OpConvertFToU:
6006 case spv::OpConvertFToS:
6007 case spv::OpConvertUToF:
6008 case spv::OpConvertSToF:
6009 case spv::OpFConvert:
6010 case spv::OpConvertPtrToU:
6011 case spv::OpConvertUToPtr:
6012 case spv::OpBitcast:
alan-bakerc9c55ae2019-12-02 16:01:27 -05006013 case spv::OpFNegate:
David Neto22f144c2017-06-12 14:26:21 -04006014 case spv::OpIAdd:
6015 case spv::OpFAdd:
6016 case spv::OpISub:
6017 case spv::OpFSub:
6018 case spv::OpIMul:
6019 case spv::OpFMul:
6020 case spv::OpUDiv:
6021 case spv::OpSDiv:
6022 case spv::OpFDiv:
6023 case spv::OpUMod:
6024 case spv::OpSRem:
6025 case spv::OpFRem:
Kévin Petit8a560882019-03-21 15:24:34 +00006026 case spv::OpUMulExtended:
6027 case spv::OpSMulExtended:
David Neto22f144c2017-06-12 14:26:21 -04006028 case spv::OpBitwiseOr:
6029 case spv::OpBitwiseXor:
6030 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04006031 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04006032 case spv::OpShiftLeftLogical:
6033 case spv::OpShiftRightLogical:
6034 case spv::OpShiftRightArithmetic:
6035 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04006036 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04006037 case spv::OpCompositeExtract:
6038 case spv::OpVectorExtractDynamic:
6039 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04006040 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04006041 case spv::OpVectorInsertDynamic:
6042 case spv::OpVectorShuffle:
6043 case spv::OpIEqual:
6044 case spv::OpINotEqual:
6045 case spv::OpUGreaterThan:
6046 case spv::OpUGreaterThanEqual:
6047 case spv::OpULessThan:
6048 case spv::OpULessThanEqual:
6049 case spv::OpSGreaterThan:
6050 case spv::OpSGreaterThanEqual:
6051 case spv::OpSLessThan:
6052 case spv::OpSLessThanEqual:
6053 case spv::OpFOrdEqual:
6054 case spv::OpFOrdGreaterThan:
6055 case spv::OpFOrdGreaterThanEqual:
6056 case spv::OpFOrdLessThan:
6057 case spv::OpFOrdLessThanEqual:
6058 case spv::OpFOrdNotEqual:
6059 case spv::OpFUnordEqual:
6060 case spv::OpFUnordGreaterThan:
6061 case spv::OpFUnordGreaterThanEqual:
6062 case spv::OpFUnordLessThan:
6063 case spv::OpFUnordLessThanEqual:
6064 case spv::OpFUnordNotEqual:
6065 case spv::OpExtInst:
6066 case spv::OpIsInf:
6067 case spv::OpIsNan:
6068 case spv::OpAny:
6069 case spv::OpAll:
6070 case spv::OpUndef:
6071 case spv::OpConstantNull:
6072 case spv::OpLogicalOr:
6073 case spv::OpLogicalAnd:
6074 case spv::OpLogicalNot:
6075 case spv::OpLogicalNotEqual:
6076 case spv::OpConstantComposite:
6077 case spv::OpSpecConstantComposite:
6078 case spv::OpConstantTrue:
6079 case spv::OpConstantFalse:
6080 case spv::OpConstant:
6081 case spv::OpSpecConstant:
6082 case spv::OpVariable:
6083 case spv::OpFunctionCall:
6084 case spv::OpSampledImage:
alan-baker75090e42020-02-20 11:21:04 -05006085 case spv::OpImageFetch:
David Neto22f144c2017-06-12 14:26:21 -04006086 case spv::OpImageSampleExplicitLod:
David Neto5c22a252018-03-15 16:07:41 -04006087 case spv::OpImageQuerySize:
alan-bakerce179f12019-12-06 19:02:22 -05006088 case spv::OpImageQuerySizeLod:
David Neto22f144c2017-06-12 14:26:21 -04006089 case spv::OpSelect:
6090 case spv::OpPhi:
6091 case spv::OpLoad:
6092 case spv::OpAtomicIAdd:
6093 case spv::OpAtomicISub:
6094 case spv::OpAtomicExchange:
6095 case spv::OpAtomicIIncrement:
6096 case spv::OpAtomicIDecrement:
6097 case spv::OpAtomicCompareExchange:
6098 case spv::OpAtomicUMin:
6099 case spv::OpAtomicSMin:
6100 case spv::OpAtomicUMax:
6101 case spv::OpAtomicSMax:
6102 case spv::OpAtomicAnd:
6103 case spv::OpAtomicOr:
6104 case spv::OpAtomicXor:
6105 case spv::OpDot: {
6106 WriteWordCountAndOpcode(Inst);
6107 WriteOperand(Ops[0]);
6108 WriteResultID(Inst);
6109 for (uint32_t i = 1; i < Ops.size(); i++) {
6110 WriteOperand(Ops[i]);
6111 }
6112 break;
6113 }
6114 }
6115 }
6116}
Alan Baker9bf93fb2018-08-28 16:59:26 -04006117
alan-bakerb6b09dc2018-11-08 16:59:28 -05006118bool SPIRVProducerPass::IsTypeNullable(const Type *type) const {
Alan Baker9bf93fb2018-08-28 16:59:26 -04006119 switch (type->getTypeID()) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05006120 case Type::HalfTyID:
6121 case Type::FloatTyID:
6122 case Type::DoubleTyID:
6123 case Type::IntegerTyID:
6124 case Type::VectorTyID:
6125 return true;
6126 case Type::PointerTyID: {
6127 const PointerType *pointer_type = cast<PointerType>(type);
6128 if (pointer_type->getPointerAddressSpace() !=
6129 AddressSpace::UniformConstant) {
6130 auto pointee_type = pointer_type->getPointerElementType();
6131 if (pointee_type->isStructTy() &&
6132 cast<StructType>(pointee_type)->isOpaque()) {
6133 // Images and samplers are not nullable.
6134 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04006135 }
Alan Baker9bf93fb2018-08-28 16:59:26 -04006136 }
alan-bakerb6b09dc2018-11-08 16:59:28 -05006137 return true;
6138 }
6139 case Type::ArrayTyID:
alan-baker077517b2020-03-19 13:52:12 -04006140 return IsTypeNullable(cast<SequentialType>(type)->getElementType());
alan-bakerb6b09dc2018-11-08 16:59:28 -05006141 case Type::StructTyID: {
6142 const StructType *struct_type = cast<StructType>(type);
6143 // Images and samplers are not nullable.
6144 if (struct_type->isOpaque())
Alan Baker9bf93fb2018-08-28 16:59:26 -04006145 return false;
alan-bakerb6b09dc2018-11-08 16:59:28 -05006146 for (const auto element : struct_type->elements()) {
6147 if (!IsTypeNullable(element))
6148 return false;
6149 }
6150 return true;
6151 }
6152 default:
6153 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04006154 }
6155}
Alan Bakerfcda9482018-10-02 17:09:59 -04006156
6157void SPIRVProducerPass::PopulateUBOTypeMaps(Module &module) {
6158 if (auto *offsets_md =
6159 module.getNamedMetadata(clspv::RemappedTypeOffsetMetadataName())) {
6160 // Metdata is stored as key-value pair operands. The first element of each
6161 // operand is the type and the second is a vector of offsets.
6162 for (const auto *operand : offsets_md->operands()) {
6163 const auto *pair = cast<MDTuple>(operand);
6164 auto *type =
6165 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
6166 const auto *offset_vector = cast<MDTuple>(pair->getOperand(1));
6167 std::vector<uint32_t> offsets;
6168 for (const Metadata *offset_md : offset_vector->operands()) {
6169 const auto *constant_md = cast<ConstantAsMetadata>(offset_md);
alan-bakerb6b09dc2018-11-08 16:59:28 -05006170 offsets.push_back(static_cast<uint32_t>(
6171 cast<ConstantInt>(constant_md->getValue())->getZExtValue()));
Alan Bakerfcda9482018-10-02 17:09:59 -04006172 }
6173 RemappedUBOTypeOffsets.insert(std::make_pair(type, offsets));
6174 }
6175 }
6176
6177 if (auto *sizes_md =
6178 module.getNamedMetadata(clspv::RemappedTypeSizesMetadataName())) {
6179 // Metadata is stored as key-value pair operands. The first element of each
6180 // operand is the type and the second is a triple of sizes: type size in
6181 // bits, store size and alloc size.
6182 for (const auto *operand : sizes_md->operands()) {
6183 const auto *pair = cast<MDTuple>(operand);
6184 auto *type =
6185 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
6186 const auto *size_triple = cast<MDTuple>(pair->getOperand(1));
6187 uint64_t type_size_in_bits =
6188 cast<ConstantInt>(
6189 cast<ConstantAsMetadata>(size_triple->getOperand(0))->getValue())
6190 ->getZExtValue();
6191 uint64_t type_store_size =
6192 cast<ConstantInt>(
6193 cast<ConstantAsMetadata>(size_triple->getOperand(1))->getValue())
6194 ->getZExtValue();
6195 uint64_t type_alloc_size =
6196 cast<ConstantInt>(
6197 cast<ConstantAsMetadata>(size_triple->getOperand(2))->getValue())
6198 ->getZExtValue();
6199 RemappedUBOTypeSizes.insert(std::make_pair(
6200 type, std::make_tuple(type_size_in_bits, type_store_size,
6201 type_alloc_size)));
6202 }
6203 }
6204}
6205
6206uint64_t SPIRVProducerPass::GetTypeSizeInBits(Type *type,
6207 const DataLayout &DL) {
6208 auto iter = RemappedUBOTypeSizes.find(type);
6209 if (iter != RemappedUBOTypeSizes.end()) {
6210 return std::get<0>(iter->second);
6211 }
6212
6213 return DL.getTypeSizeInBits(type);
6214}
6215
6216uint64_t SPIRVProducerPass::GetTypeStoreSize(Type *type, const DataLayout &DL) {
6217 auto iter = RemappedUBOTypeSizes.find(type);
6218 if (iter != RemappedUBOTypeSizes.end()) {
6219 return std::get<1>(iter->second);
6220 }
6221
6222 return DL.getTypeStoreSize(type);
6223}
6224
6225uint64_t SPIRVProducerPass::GetTypeAllocSize(Type *type, const DataLayout &DL) {
6226 auto iter = RemappedUBOTypeSizes.find(type);
6227 if (iter != RemappedUBOTypeSizes.end()) {
6228 return std::get<2>(iter->second);
6229 }
6230
6231 return DL.getTypeAllocSize(type);
6232}
alan-baker5b86ed72019-02-15 08:26:50 -05006233
Kévin Petitbbbda972020-03-03 19:16:31 +00006234uint32_t SPIRVProducerPass::GetExplicitLayoutStructMemberOffset(
6235 StructType *type, unsigned member, const DataLayout &DL) {
6236 const auto StructLayout = DL.getStructLayout(type);
6237 // Search for the correct offsets if this type was remapped.
6238 std::vector<uint32_t> *offsets = nullptr;
6239 auto iter = RemappedUBOTypeOffsets.find(type);
6240 if (iter != RemappedUBOTypeOffsets.end()) {
6241 offsets = &iter->second;
6242 }
6243 auto ByteOffset =
6244 static_cast<uint32_t>(StructLayout->getElementOffset(member));
6245 if (offsets) {
6246 ByteOffset = (*offsets)[member];
6247 }
6248
6249 return ByteOffset;
6250}
6251
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04006252void SPIRVProducerPass::setVariablePointersCapabilities(
6253 unsigned address_space) {
alan-baker5b86ed72019-02-15 08:26:50 -05006254 if (GetStorageClass(address_space) == spv::StorageClassStorageBuffer) {
6255 setVariablePointersStorageBuffer(true);
6256 } else {
6257 setVariablePointers(true);
6258 }
6259}
6260
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04006261Value *SPIRVProducerPass::GetBasePointer(Value *v) {
alan-baker5b86ed72019-02-15 08:26:50 -05006262 if (auto *gep = dyn_cast<GetElementPtrInst>(v)) {
6263 return GetBasePointer(gep->getPointerOperand());
6264 }
6265
6266 // Conservatively return |v|.
6267 return v;
6268}
6269
6270bool SPIRVProducerPass::sameResource(Value *lhs, Value *rhs) const {
6271 if (auto *lhs_call = dyn_cast<CallInst>(lhs)) {
6272 if (auto *rhs_call = dyn_cast<CallInst>(rhs)) {
6273 if (lhs_call->getCalledFunction()->getName().startswith(
6274 clspv::ResourceAccessorFunction()) &&
6275 rhs_call->getCalledFunction()->getName().startswith(
6276 clspv::ResourceAccessorFunction())) {
6277 // For resource accessors, match descriptor set and binding.
6278 if (lhs_call->getOperand(0) == rhs_call->getOperand(0) &&
6279 lhs_call->getOperand(1) == rhs_call->getOperand(1))
6280 return true;
6281 } else if (lhs_call->getCalledFunction()->getName().startswith(
6282 clspv::WorkgroupAccessorFunction()) &&
6283 rhs_call->getCalledFunction()->getName().startswith(
6284 clspv::WorkgroupAccessorFunction())) {
6285 // For workgroup resources, match spec id.
6286 if (lhs_call->getOperand(0) == rhs_call->getOperand(0))
6287 return true;
6288 }
6289 }
6290 }
6291
6292 return false;
6293}
6294
6295bool SPIRVProducerPass::selectFromSameObject(Instruction *inst) {
6296 assert(inst->getType()->isPointerTy());
6297 assert(GetStorageClass(inst->getType()->getPointerAddressSpace()) ==
6298 spv::StorageClassStorageBuffer);
6299 const bool hack_undef = clspv::Option::HackUndef();
6300 if (auto *select = dyn_cast<SelectInst>(inst)) {
6301 auto *true_base = GetBasePointer(select->getTrueValue());
6302 auto *false_base = GetBasePointer(select->getFalseValue());
6303
6304 if (true_base == false_base)
6305 return true;
6306
6307 // If either the true or false operand is a null, then we satisfy the same
6308 // object constraint.
6309 if (auto *true_cst = dyn_cast<Constant>(true_base)) {
6310 if (true_cst->isNullValue() || (hack_undef && isa<UndefValue>(true_base)))
6311 return true;
6312 }
6313
6314 if (auto *false_cst = dyn_cast<Constant>(false_base)) {
6315 if (false_cst->isNullValue() ||
6316 (hack_undef && isa<UndefValue>(false_base)))
6317 return true;
6318 }
6319
6320 if (sameResource(true_base, false_base))
6321 return true;
6322 } else if (auto *phi = dyn_cast<PHINode>(inst)) {
6323 Value *value = nullptr;
6324 bool ok = true;
6325 for (unsigned i = 0; ok && i != phi->getNumIncomingValues(); ++i) {
6326 auto *base = GetBasePointer(phi->getIncomingValue(i));
6327 // Null values satisfy the constraint of selecting of selecting from the
6328 // same object.
6329 if (!value) {
6330 if (auto *cst = dyn_cast<Constant>(base)) {
6331 if (!cst->isNullValue() && !(hack_undef && isa<UndefValue>(base)))
6332 value = base;
6333 } else {
6334 value = base;
6335 }
6336 } else if (base != value) {
6337 if (auto *base_cst = dyn_cast<Constant>(base)) {
6338 if (base_cst->isNullValue() || (hack_undef && isa<UndefValue>(base)))
6339 continue;
6340 }
6341
6342 if (sameResource(value, base))
6343 continue;
6344
6345 // Values don't represent the same base.
6346 ok = false;
6347 }
6348 }
6349
6350 return ok;
6351 }
6352
6353 // Conservatively return false.
6354 return false;
6355}
alan-bakere9308012019-03-15 10:25:13 -04006356
6357bool SPIRVProducerPass::CalledWithCoherentResource(Argument &Arg) {
6358 if (!Arg.getType()->isPointerTy() ||
6359 Arg.getType()->getPointerAddressSpace() != clspv::AddressSpace::Global) {
6360 // Only SSBOs need to be annotated as coherent.
6361 return false;
6362 }
6363
6364 DenseSet<Value *> visited;
6365 std::vector<Value *> stack;
6366 for (auto *U : Arg.getParent()->users()) {
6367 if (auto *call = dyn_cast<CallInst>(U)) {
6368 stack.push_back(call->getOperand(Arg.getArgNo()));
6369 }
6370 }
6371
6372 while (!stack.empty()) {
6373 Value *v = stack.back();
6374 stack.pop_back();
6375
6376 if (!visited.insert(v).second)
6377 continue;
6378
6379 auto *resource_call = dyn_cast<CallInst>(v);
6380 if (resource_call &&
6381 resource_call->getCalledFunction()->getName().startswith(
6382 clspv::ResourceAccessorFunction())) {
6383 // If this is a resource accessor function, check if the coherent operand
6384 // is set.
6385 const auto coherent =
6386 unsigned(dyn_cast<ConstantInt>(resource_call->getArgOperand(5))
6387 ->getZExtValue());
6388 if (coherent == 1)
6389 return true;
6390 } else if (auto *arg = dyn_cast<Argument>(v)) {
6391 // If this is a function argument, trace through its callers.
alan-bakere98f3f92019-04-08 15:06:36 -04006392 for (auto U : arg->getParent()->users()) {
alan-bakere9308012019-03-15 10:25:13 -04006393 if (auto *call = dyn_cast<CallInst>(U)) {
6394 stack.push_back(call->getOperand(arg->getArgNo()));
6395 }
6396 }
6397 } else if (auto *user = dyn_cast<User>(v)) {
6398 // If this is a user, traverse all operands that could lead to resource
6399 // variables.
6400 for (unsigned i = 0; i != user->getNumOperands(); ++i) {
6401 Value *operand = user->getOperand(i);
6402 if (operand->getType()->isPointerTy() &&
6403 operand->getType()->getPointerAddressSpace() ==
6404 clspv::AddressSpace::Global) {
6405 stack.push_back(operand);
6406 }
6407 }
6408 }
6409 }
6410
6411 // No coherent resource variables encountered.
6412 return false;
6413}
alan-baker06cad652019-12-03 17:56:47 -05006414
6415void SPIRVProducerPass::PopulateStructuredCFGMaps(Module &module) {
6416 // First, track loop merges and continues.
6417 DenseSet<BasicBlock *> LoopMergesAndContinues;
6418 for (auto &F : module) {
6419 if (F.isDeclaration())
6420 continue;
6421
6422 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
6423 const LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>(F).getLoopInfo();
6424 std::deque<BasicBlock *> order;
6425 DenseSet<BasicBlock *> visited;
6426 clspv::ComputeStructuredOrder(&*F.begin(), &DT, LI, &order, &visited);
6427
6428 for (auto BB : order) {
6429 auto terminator = BB->getTerminator();
6430 auto branch = dyn_cast<BranchInst>(terminator);
6431 if (LI.isLoopHeader(BB)) {
6432 auto L = LI.getLoopFor(BB);
6433 BasicBlock *ContinueBB = nullptr;
6434 BasicBlock *MergeBB = nullptr;
6435
6436 MergeBB = L->getExitBlock();
6437 if (!MergeBB) {
6438 // StructurizeCFG pass converts CFG into triangle shape and the cfg
6439 // has regions with single entry/exit. As a result, loop should not
6440 // have multiple exits.
6441 llvm_unreachable("Loop has multiple exits???");
6442 }
6443
6444 if (L->isLoopLatch(BB)) {
6445 ContinueBB = BB;
6446 } else {
6447 // From SPIR-V spec 2.11, Continue Target must dominate that back-edge
6448 // block.
6449 BasicBlock *Header = L->getHeader();
6450 BasicBlock *Latch = L->getLoopLatch();
6451 for (auto *loop_block : L->blocks()) {
6452 if (loop_block == Header) {
6453 continue;
6454 }
6455
6456 // Check whether block dominates block with back-edge.
6457 // The loop latch is the single block with a back-edge. If it was
6458 // possible, StructurizeCFG made the loop conform to this
6459 // requirement, otherwise |Latch| is a nullptr.
6460 if (DT.dominates(loop_block, Latch)) {
6461 ContinueBB = loop_block;
6462 }
6463 }
6464
6465 if (!ContinueBB) {
6466 llvm_unreachable("Wrong continue block from loop");
6467 }
6468 }
6469
6470 // Record the continue and merge blocks.
6471 MergeBlocks[BB] = MergeBB;
6472 ContinueBlocks[BB] = ContinueBB;
6473 LoopMergesAndContinues.insert(MergeBB);
6474 LoopMergesAndContinues.insert(ContinueBB);
6475 } else if (branch && branch->isConditional()) {
6476 auto L = LI.getLoopFor(BB);
6477 bool HasBackedge = false;
6478 while (L && !HasBackedge) {
6479 if (L->isLoopLatch(BB)) {
6480 HasBackedge = true;
6481 }
6482 L = L->getParentLoop();
6483 }
6484
6485 if (!HasBackedge) {
6486 // Only need a merge if the branch doesn't include a loop break or
6487 // continue.
6488 auto true_bb = branch->getSuccessor(0);
6489 auto false_bb = branch->getSuccessor(1);
6490 if (!LoopMergesAndContinues.count(true_bb) &&
6491 !LoopMergesAndContinues.count(false_bb)) {
6492 // StructurizeCFG pass already manipulated CFG. Just use false block
6493 // of branch instruction as merge block.
6494 MergeBlocks[BB] = false_bb;
6495 }
6496 }
6497 }
6498 }
6499 }
6500}