blob: 5429366a116b272d24196d9407b101ec4486bc06 [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"
42#include "llvm/Support/raw_ostream.h"
43#include "llvm/Transforms/Utils/Cloning.h"
David Neto22f144c2017-06-12 14:26:21 -040044
David Neto85082642018-03-24 06:55:20 -070045#include "spirv/1.0/spirv.hpp"
David Neto118188e2018-08-24 11:27:54 -040046
David Neto85082642018-03-24 06:55:20 -070047#include "clspv/AddressSpace.h"
alan-bakerf5e5f692018-11-27 08:33:24 -050048#include "clspv/DescriptorMap.h"
David Neto118188e2018-08-24 11:27:54 -040049#include "clspv/Option.h"
David Neto85082642018-03-24 06:55:20 -070050#include "clspv/spirv_c_strings.hpp"
51#include "clspv/spirv_glsl.hpp"
David Neto22f144c2017-06-12 14:26:21 -040052
David Neto4feb7a42017-10-06 17:29:42 -040053#include "ArgKind.h"
alan-bakerf67468c2019-11-25 15:51:49 -050054#include "Builtins.h"
alan-baker06cad652019-12-03 17:56:47 -050055#include "ComputeStructuredOrder.h"
David Neto85082642018-03-24 06:55:20 -070056#include "ConstantEmitter.h"
Alan Baker202c8c72018-08-13 13:47:44 -040057#include "Constants.h"
David Neto78383442018-06-15 20:31:56 -040058#include "DescriptorCounter.h"
alan-baker56f7aff2019-05-22 08:06:42 -040059#include "NormalizeGlobalVariable.h"
Diego Novilloa4c44fa2019-04-11 10:56:15 -040060#include "Passes.h"
alan-bakerce179f12019-12-06 19:02:22 -050061#include "Types.h"
David Neto48f56a42017-10-06 16:44:25 -040062
David Neto22f144c2017-06-12 14:26:21 -040063#if defined(_MSC_VER)
64#pragma warning(pop)
65#endif
66
67using namespace llvm;
68using namespace clspv;
David Neto156783e2017-07-05 15:39:41 -040069using namespace mdconst;
David Neto22f144c2017-06-12 14:26:21 -040070
71namespace {
David Netocd8ca5f2017-10-02 23:34:11 -040072
David Neto862b7d82018-06-14 18:48:37 -040073cl::opt<bool> ShowResourceVars("show-rv", cl::init(false), cl::Hidden,
74 cl::desc("Show resource variable creation"));
75
76// These hacks exist to help transition code generation algorithms
77// without making huge noise in detailed test output.
78const bool Hack_generate_runtime_array_stride_early = true;
79
David Neto3fbb4072017-10-16 11:28:14 -040080// The value of 1/pi. This value is from MSDN
81// https://msdn.microsoft.com/en-us/library/4hwaceh6.aspx
82const double kOneOverPi = 0.318309886183790671538;
83const glsl::ExtInst kGlslExtInstBad = static_cast<glsl::ExtInst>(0);
84
alan-bakerb6b09dc2018-11-08 16:59:28 -050085const char *kCompositeConstructFunctionPrefix = "clspv.composite_construct.";
David Netoab03f432017-11-03 17:00:44 -040086
David Neto22f144c2017-06-12 14:26:21 -040087enum SPIRVOperandType {
88 NUMBERID,
89 LITERAL_INTEGER,
90 LITERAL_STRING,
91 LITERAL_FLOAT
92};
93
94struct SPIRVOperand {
95 explicit SPIRVOperand(SPIRVOperandType Ty, uint32_t Num)
96 : Type(Ty), LiteralNum(1, Num) {}
97 explicit SPIRVOperand(SPIRVOperandType Ty, const char *Str)
98 : Type(Ty), LiteralStr(Str) {}
99 explicit SPIRVOperand(SPIRVOperandType Ty, StringRef Str)
100 : Type(Ty), LiteralStr(Str) {}
101 explicit SPIRVOperand(SPIRVOperandType Ty, ArrayRef<uint32_t> NumVec)
102 : Type(Ty), LiteralNum(NumVec.begin(), NumVec.end()) {}
103
James Price11010dc2019-12-19 13:53:09 -0500104 SPIRVOperandType getType() const { return Type; };
105 uint32_t getNumID() const { return LiteralNum[0]; };
106 std::string getLiteralStr() const { return LiteralStr; };
107 ArrayRef<uint32_t> getLiteralNum() const { return LiteralNum; };
David Neto22f144c2017-06-12 14:26:21 -0400108
David Neto87846742018-04-11 17:36:22 -0400109 uint32_t GetNumWords() const {
110 switch (Type) {
111 case NUMBERID:
112 return 1;
113 case LITERAL_INTEGER:
114 case LITERAL_FLOAT:
David Netoee2660d2018-06-28 16:31:29 -0400115 return uint32_t(LiteralNum.size());
David Neto87846742018-04-11 17:36:22 -0400116 case LITERAL_STRING:
117 // Account for the terminating null character.
David Netoee2660d2018-06-28 16:31:29 -0400118 return uint32_t((LiteralStr.size() + 4) / 4);
David Neto87846742018-04-11 17:36:22 -0400119 }
120 llvm_unreachable("Unhandled case in SPIRVOperand::GetNumWords()");
121 }
122
David Neto22f144c2017-06-12 14:26:21 -0400123private:
124 SPIRVOperandType Type;
125 std::string LiteralStr;
126 SmallVector<uint32_t, 4> LiteralNum;
127};
128
David Netoc6f3ab22018-04-06 18:02:31 -0400129class SPIRVOperandList {
130public:
David Netoef5ba2b2019-12-20 08:35:54 -0500131 typedef std::unique_ptr<SPIRVOperand> element_type;
132 typedef SmallVector<element_type, 8> container_type;
133 typedef container_type::iterator iterator;
David Netoc6f3ab22018-04-06 18:02:31 -0400134 SPIRVOperandList() {}
alan-bakerb6b09dc2018-11-08 16:59:28 -0500135 SPIRVOperandList(const SPIRVOperandList &other) = delete;
136 SPIRVOperandList(SPIRVOperandList &&other) {
David Netoc6f3ab22018-04-06 18:02:31 -0400137 contents_ = std::move(other.contents_);
138 other.contents_.clear();
139 }
David Netoef5ba2b2019-12-20 08:35:54 -0500140 iterator begin() { return contents_.begin(); }
141 iterator end() { return contents_.end(); }
142 operator ArrayRef<element_type>() { return contents_; }
143 void push_back(element_type op) { contents_.push_back(std::move(op)); }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500144 void clear() { contents_.clear(); }
David Netoc6f3ab22018-04-06 18:02:31 -0400145 size_t size() const { return contents_.size(); }
James Price11010dc2019-12-19 13:53:09 -0500146 const SPIRVOperand *operator[](size_t i) { return contents_[i].get(); }
David Netoc6f3ab22018-04-06 18:02:31 -0400147
David Netoef5ba2b2019-12-20 08:35:54 -0500148 const container_type &getOperands() const { return contents_; }
David Neto87846742018-04-11 17:36:22 -0400149
David Netoc6f3ab22018-04-06 18:02:31 -0400150private:
David Netoef5ba2b2019-12-20 08:35:54 -0500151 container_type contents_;
David Netoc6f3ab22018-04-06 18:02:31 -0400152};
153
James Price11010dc2019-12-19 13:53:09 -0500154SPIRVOperandList &operator<<(SPIRVOperandList &list,
David Netoef5ba2b2019-12-20 08:35:54 -0500155 std::unique_ptr<SPIRVOperand> elem) {
156 list.push_back(std::move(elem));
David Netoc6f3ab22018-04-06 18:02:31 -0400157 return list;
158}
159
David Netoef5ba2b2019-12-20 08:35:54 -0500160std::unique_ptr<SPIRVOperand> MkNum(uint32_t num) {
161 return std::make_unique<SPIRVOperand>(LITERAL_INTEGER, num);
David Netoc6f3ab22018-04-06 18:02:31 -0400162}
David Netoef5ba2b2019-12-20 08:35:54 -0500163std::unique_ptr<SPIRVOperand> MkInteger(ArrayRef<uint32_t> num_vec) {
164 return std::make_unique<SPIRVOperand>(LITERAL_INTEGER, num_vec);
David Neto257c3892018-04-11 13:19:45 -0400165}
David Netoef5ba2b2019-12-20 08:35:54 -0500166std::unique_ptr<SPIRVOperand> MkFloat(ArrayRef<uint32_t> num_vec) {
167 return std::make_unique<SPIRVOperand>(LITERAL_FLOAT, num_vec);
David Neto257c3892018-04-11 13:19:45 -0400168}
David Netoef5ba2b2019-12-20 08:35:54 -0500169std::unique_ptr<SPIRVOperand> MkId(uint32_t id) {
170 return std::make_unique<SPIRVOperand>(NUMBERID, id);
James Price11010dc2019-12-19 13:53:09 -0500171}
David Netoef5ba2b2019-12-20 08:35:54 -0500172std::unique_ptr<SPIRVOperand> MkString(StringRef str) {
173 return std::make_unique<SPIRVOperand>(LITERAL_STRING, str);
David Neto257c3892018-04-11 13:19:45 -0400174}
David Netoc6f3ab22018-04-06 18:02:31 -0400175
David Neto22f144c2017-06-12 14:26:21 -0400176struct SPIRVInstruction {
David Netoef5ba2b2019-12-20 08:35:54 -0500177 // Creates an instruction with an opcode and no result ID, and with the given
178 // operands. This computes its own word count. Takes ownership of the
179 // operands and clears |Ops|.
180 SPIRVInstruction(spv::Op Opc, SPIRVOperandList &Ops)
181 : WordCount(1), Opcode(static_cast<uint16_t>(Opc)), ResultID(0) {
James Price11010dc2019-12-19 13:53:09 -0500182 for (auto &operand : Ops) {
David Netoee2660d2018-06-28 16:31:29 -0400183 WordCount += uint16_t(operand->GetNumWords());
David Neto87846742018-04-11 17:36:22 -0400184 }
David Netoef5ba2b2019-12-20 08:35:54 -0500185 Operands.reserve(Ops.size());
186 for (auto &ptr : Ops) {
187 Operands.emplace_back(std::move(ptr));
188 ptr.reset(nullptr);
David Neto87846742018-04-11 17:36:22 -0400189 }
David Netoef5ba2b2019-12-20 08:35:54 -0500190 Ops.clear();
191 }
192 // Creates an instruction with an opcode and a no-zero result ID, and
193 // with the given operands. This computes its own word count. Takes ownership
194 // of the operands and clears |Ops|.
195 SPIRVInstruction(spv::Op Opc, uint32_t ResID, SPIRVOperandList &Ops)
196 : WordCount(2), Opcode(static_cast<uint16_t>(Opc)), ResultID(ResID) {
James Price11010dc2019-12-19 13:53:09 -0500197 for (auto &operand : Ops) {
David Neto87846742018-04-11 17:36:22 -0400198 WordCount += operand->GetNumWords();
199 }
David Netoef5ba2b2019-12-20 08:35:54 -0500200 Operands.reserve(Ops.size());
201 for (auto &ptr : Ops) {
202 Operands.emplace_back(std::move(ptr));
203 ptr.reset(nullptr);
204 }
205 if (ResID == 0) {
206 llvm_unreachable("Result ID of 0 was provided");
207 }
208 Ops.clear();
David Neto87846742018-04-11 17:36:22 -0400209 }
David Neto22f144c2017-06-12 14:26:21 -0400210
David Netoef5ba2b2019-12-20 08:35:54 -0500211 // Creates an instruction with an opcode and no result ID, and with the single
212 // operand. This computes its own word count.
213 SPIRVInstruction(spv::Op Opc, SPIRVOperandList::element_type operand)
214 : WordCount(1), Opcode(static_cast<uint16_t>(Opc)), ResultID(0) {
215 WordCount += operand->GetNumWords();
216 Operands.emplace_back(std::move(operand));
217 operand.reset(nullptr);
218 }
219 // Creates an instruction with an opcode and a non-zero result ID, and
220 // with the single operand. This computes its own word count.
221 SPIRVInstruction(spv::Op Opc, uint32_t ResID,
222 SPIRVOperandList::element_type operand)
223 : WordCount(2), Opcode(static_cast<uint16_t>(Opc)), ResultID(ResID) {
224 WordCount += operand->GetNumWords();
225 if (ResID == 0) {
226 llvm_unreachable("Result ID of 0 was provided");
227 }
228 Operands.emplace_back(std::move(operand));
229 operand.reset(nullptr);
230 }
231 // Creates an instruction with an opcode and a no-zero result ID, and no
232 // operands.
233 SPIRVInstruction(spv::Op Opc, uint32_t ResID)
234 : WordCount(2), Opcode(static_cast<uint16_t>(Opc)), ResultID(ResID) {
235 if (ResID == 0) {
236 llvm_unreachable("Result ID of 0 was provided");
237 }
238 }
239 // Creates an instruction with an opcode, no result ID, no type ID, and no
240 // operands.
241 SPIRVInstruction(spv::Op Opc)
242 : WordCount(1), Opcode(static_cast<uint16_t>(Opc)), ResultID(0) {}
243
David Netoee2660d2018-06-28 16:31:29 -0400244 uint32_t getWordCount() const { return WordCount; }
David Neto22f144c2017-06-12 14:26:21 -0400245 uint16_t getOpcode() const { return Opcode; }
246 uint32_t getResultID() const { return ResultID; }
David Netoef5ba2b2019-12-20 08:35:54 -0500247 ArrayRef<std::unique_ptr<SPIRVOperand>> getOperands() const {
James Price11010dc2019-12-19 13:53:09 -0500248 return Operands;
249 }
David Neto22f144c2017-06-12 14:26:21 -0400250
251private:
David Netoee2660d2018-06-28 16:31:29 -0400252 uint32_t WordCount; // Check the 16-bit bound at code generation time.
David Neto22f144c2017-06-12 14:26:21 -0400253 uint16_t Opcode;
254 uint32_t ResultID;
David Netoef5ba2b2019-12-20 08:35:54 -0500255 SmallVector<std::unique_ptr<SPIRVOperand>, 4> Operands;
David Neto22f144c2017-06-12 14:26:21 -0400256};
257
258struct SPIRVProducerPass final : public ModulePass {
David Neto22f144c2017-06-12 14:26:21 -0400259 typedef DenseMap<Type *, uint32_t> TypeMapType;
260 typedef UniqueVector<Type *> TypeList;
261 typedef DenseMap<Value *, uint32_t> ValueMapType;
David Netofb9a7972017-08-25 17:08:24 -0400262 typedef UniqueVector<Value *> ValueList;
David Neto22f144c2017-06-12 14:26:21 -0400263 typedef std::vector<std::pair<Value *, uint32_t>> EntryPointVecType;
264 typedef std::list<SPIRVInstruction *> SPIRVInstructionList;
David Neto87846742018-04-11 17:36:22 -0400265 // A vector of tuples, each of which is:
266 // - the LLVM instruction that we will later generate SPIR-V code for
267 // - where the SPIR-V instruction should be inserted
268 // - the result ID of the SPIR-V instruction
David Neto22f144c2017-06-12 14:26:21 -0400269 typedef std::vector<
270 std::tuple<Value *, SPIRVInstructionList::iterator, uint32_t>>
271 DeferredInstVecType;
272 typedef DenseMap<FunctionType *, std::pair<FunctionType *, uint32_t>>
273 GlobalConstFuncMapType;
274
David Neto44795152017-07-13 15:45:28 -0400275 explicit SPIRVProducerPass(
alan-bakerf5e5f692018-11-27 08:33:24 -0500276 raw_pwrite_stream &out,
277 std::vector<clspv::version0::DescriptorMapEntry> *descriptor_map_entries,
alan-baker00e7a582019-06-07 12:54:21 -0400278 ArrayRef<std::pair<unsigned, std::string>> samplerMap,
David Neto44795152017-07-13 15:45:28 -0400279 bool outputCInitList)
David Netoc2c368d2017-06-30 16:50:17 -0400280 : ModulePass(ID), samplerMap(samplerMap), out(out),
David Neto0676e6f2017-07-11 18:47:44 -0400281 binaryTempOut(binaryTempUnderlyingVector), binaryOut(&out),
alan-baker00e7a582019-06-07 12:54:21 -0400282 descriptorMapEntries(descriptor_map_entries),
David Neto0676e6f2017-07-11 18:47:44 -0400283 outputCInitList(outputCInitList), patchBoundOffset(0), nextID(1),
alan-baker5b86ed72019-02-15 08:26:50 -0500284 OpExtInstImportID(0), HasVariablePointersStorageBuffer(false),
285 HasVariablePointers(false), SamplerTy(nullptr), WorkgroupSizeValueID(0),
Kévin Petit89a525c2019-06-15 08:13:07 +0100286 WorkgroupSizeVarID(0), max_local_spec_id_(0) {}
David Neto22f144c2017-06-12 14:26:21 -0400287
James Price11010dc2019-12-19 13:53:09 -0500288 virtual ~SPIRVProducerPass() {
289 for (auto *Inst : SPIRVInsts) {
290 delete Inst;
291 }
292 }
293
David Neto22f144c2017-06-12 14:26:21 -0400294 void getAnalysisUsage(AnalysisUsage &AU) const override {
295 AU.addRequired<DominatorTreeWrapperPass>();
296 AU.addRequired<LoopInfoWrapperPass>();
297 }
298
299 virtual bool runOnModule(Module &module) override;
300
301 // output the SPIR-V header block
302 void outputHeader();
303
304 // patch the SPIR-V header block
305 void patchHeader();
306
307 uint32_t lookupType(Type *Ty) {
308 if (Ty->isPointerTy() &&
309 (Ty->getPointerAddressSpace() != AddressSpace::UniformConstant)) {
310 auto PointeeTy = Ty->getPointerElementType();
311 if (PointeeTy->isStructTy() &&
312 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
313 Ty = PointeeTy;
314 }
315 }
316
David Neto862b7d82018-06-14 18:48:37 -0400317 auto where = TypeMap.find(Ty);
318 if (where == TypeMap.end()) {
319 if (Ty) {
320 errs() << "Unhandled type " << *Ty << "\n";
321 } else {
322 errs() << "Unhandled type (null)\n";
323 }
David Netoe439d702018-03-23 13:14:08 -0700324 llvm_unreachable("\nUnhandled type!");
David Neto22f144c2017-06-12 14:26:21 -0400325 }
326
David Neto862b7d82018-06-14 18:48:37 -0400327 return where->second;
David Neto22f144c2017-06-12 14:26:21 -0400328 }
329 TypeMapType &getImageTypeMap() { return ImageTypeMap; }
alan-bakerabd82722019-12-03 17:14:51 -0500330 TypeList &getImageTypeList() { return ImageTypeList; }
David Neto22f144c2017-06-12 14:26:21 -0400331 TypeList &getTypeList() { return Types; };
332 ValueList &getConstantList() { return Constants; };
333 ValueMapType &getValueMap() { return ValueMap; }
334 ValueMapType &getAllocatedValueMap() { return AllocatedValueMap; }
335 SPIRVInstructionList &getSPIRVInstList() { return SPIRVInsts; };
David Neto22f144c2017-06-12 14:26:21 -0400336 EntryPointVecType &getEntryPointVec() { return EntryPointVec; };
337 DeferredInstVecType &getDeferredInstVec() { return DeferredInstVec; };
338 ValueList &getEntryPointInterfacesVec() { return EntryPointInterfacesVec; };
339 uint32_t &getOpExtInstImportID() { return OpExtInstImportID; };
340 std::vector<uint32_t> &getBuiltinDimVec() { return BuiltinDimensionVec; };
alan-baker5b86ed72019-02-15 08:26:50 -0500341 bool hasVariablePointersStorageBuffer() {
342 return HasVariablePointersStorageBuffer;
343 }
344 void setVariablePointersStorageBuffer(bool Val) {
345 HasVariablePointersStorageBuffer = Val;
346 }
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400347 bool hasVariablePointers() { return HasVariablePointers; };
David Neto22f144c2017-06-12 14:26:21 -0400348 void setVariablePointers(bool Val) { HasVariablePointers = Val; };
alan-bakerb6b09dc2018-11-08 16:59:28 -0500349 ArrayRef<std::pair<unsigned, std::string>> &getSamplerMap() {
350 return samplerMap;
351 }
David Neto22f144c2017-06-12 14:26:21 -0400352 GlobalConstFuncMapType &getGlobalConstFuncTypeMap() {
353 return GlobalConstFuncTypeMap;
354 }
355 SmallPtrSet<Value *, 16> &getGlobalConstArgSet() {
356 return GlobalConstArgumentSet;
357 }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500358 TypeList &getTypesNeedingArrayStride() { return TypesNeedingArrayStride; }
David Neto22f144c2017-06-12 14:26:21 -0400359
David Netoc6f3ab22018-04-06 18:02:31 -0400360 void GenerateLLVMIRInfo(Module &M, const DataLayout &DL);
alan-bakerb6b09dc2018-11-08 16:59:28 -0500361 // Populate GlobalConstFuncTypeMap. Also, if module-scope __constant will
362 // *not* be converted to a storage buffer, replace each such global variable
363 // with one in the storage class expecgted by SPIR-V.
David Neto862b7d82018-06-14 18:48:37 -0400364 void FindGlobalConstVars(Module &M, const DataLayout &DL);
365 // Populate ResourceVarInfoList, FunctionToResourceVarsMap, and
366 // ModuleOrderedResourceVars.
367 void FindResourceVars(Module &M, const DataLayout &DL);
Alan Baker202c8c72018-08-13 13:47:44 -0400368 void FindWorkgroupVars(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400369 bool FindExtInst(Module &M);
370 void FindTypePerGlobalVar(GlobalVariable &GV);
371 void FindTypePerFunc(Function &F);
David Neto862b7d82018-06-14 18:48:37 -0400372 void FindTypesForSamplerMap(Module &M);
373 void FindTypesForResourceVars(Module &M);
alan-bakerb6b09dc2018-11-08 16:59:28 -0500374 // Inserts |Ty| and relevant sub-types into the |Types| member, indicating
375 // that |Ty| and its subtypes will need a corresponding SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400376 void FindType(Type *Ty);
377 void FindConstantPerGlobalVar(GlobalVariable &GV);
378 void FindConstantPerFunc(Function &F);
379 void FindConstant(Value *V);
380 void GenerateExtInstImport();
David Neto19a1bad2017-08-25 15:01:41 -0400381 // Generates instructions for SPIR-V types corresponding to the LLVM types
382 // saved in the |Types| member. A type follows its subtypes. IDs are
383 // allocated sequentially starting with the current value of nextID, and
384 // with a type following its subtypes. Also updates nextID to just beyond
385 // the last generated ID.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500386 void GenerateSPIRVTypes(LLVMContext &context, Module &module);
David Neto22f144c2017-06-12 14:26:21 -0400387 void GenerateSPIRVConstants();
David Neto5c22a252018-03-15 16:07:41 -0400388 void GenerateModuleInfo(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400389 void GenerateGlobalVar(GlobalVariable &GV);
David Netoc6f3ab22018-04-06 18:02:31 -0400390 void GenerateWorkgroupVars();
David Neto862b7d82018-06-14 18:48:37 -0400391 // Generate descriptor map entries for resource variables associated with
392 // arguments to F.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500393 void GenerateDescriptorMapInfo(const DataLayout &DL, Function &F);
David Neto22f144c2017-06-12 14:26:21 -0400394 void GenerateSamplers(Module &M);
David Neto862b7d82018-06-14 18:48:37 -0400395 // Generate OpVariables for %clspv.resource.var.* calls.
396 void GenerateResourceVars(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400397 void GenerateFuncPrologue(Function &F);
398 void GenerateFuncBody(Function &F);
David Netob6e2e062018-04-25 10:32:06 -0400399 void GenerateEntryPointInitialStores();
David Neto22f144c2017-06-12 14:26:21 -0400400 spv::Op GetSPIRVCmpOpcode(CmpInst *CmpI);
401 spv::Op GetSPIRVCastOpcode(Instruction &I);
402 spv::Op GetSPIRVBinaryOpcode(Instruction &I);
403 void GenerateInstruction(Instruction &I);
404 void GenerateFuncEpilogue();
405 void HandleDeferredInstruction();
alan-bakerb6b09dc2018-11-08 16:59:28 -0500406 void HandleDeferredDecorations(const DataLayout &DL);
David Neto22f144c2017-06-12 14:26:21 -0400407 bool is4xi8vec(Type *Ty) const;
408 spv::StorageClass GetStorageClass(unsigned AddrSpace) const;
David Neto862b7d82018-06-14 18:48:37 -0400409 spv::StorageClass GetStorageClassForArgKind(clspv::ArgKind arg_kind) const;
David Neto22f144c2017-06-12 14:26:21 -0400410 spv::BuiltIn GetBuiltin(StringRef globalVarName) const;
David Neto3fbb4072017-10-16 11:28:14 -0400411 // Returns the GLSL extended instruction enum that the given function
412 // call maps to. If none, then returns the 0 value, i.e. GLSLstd4580Bad.
David Neto22f144c2017-06-12 14:26:21 -0400413 glsl::ExtInst getExtInstEnum(StringRef Name);
David Neto3fbb4072017-10-16 11:28:14 -0400414 // Returns the GLSL extended instruction enum indirectly used by the given
415 // function. That is, to implement the given function, we use an extended
416 // instruction plus one more instruction. If none, then returns the 0 value,
417 // i.e. GLSLstd4580Bad.
418 glsl::ExtInst getIndirectExtInstEnum(StringRef Name);
419 // Returns the single GLSL extended instruction used directly or
420 // indirectly by the given function call.
421 glsl::ExtInst getDirectOrIndirectExtInstEnum(StringRef Name);
David Neto22f144c2017-06-12 14:26:21 -0400422 void WriteOneWord(uint32_t Word);
423 void WriteResultID(SPIRVInstruction *Inst);
424 void WriteWordCountAndOpcode(SPIRVInstruction *Inst);
David Netoef5ba2b2019-12-20 08:35:54 -0500425 void WriteOperand(const std::unique_ptr<SPIRVOperand> &Op);
David Neto22f144c2017-06-12 14:26:21 -0400426 void WriteSPIRVBinary();
427
Alan Baker9bf93fb2018-08-28 16:59:26 -0400428 // Returns true if |type| is compatible with OpConstantNull.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500429 bool IsTypeNullable(const Type *type) const;
Alan Baker9bf93fb2018-08-28 16:59:26 -0400430
Alan Bakerfcda9482018-10-02 17:09:59 -0400431 // Populate UBO remapped type maps.
432 void PopulateUBOTypeMaps(Module &module);
433
alan-baker06cad652019-12-03 17:56:47 -0500434 // Populate the merge and continue block maps.
435 void PopulateStructuredCFGMaps(Module &module);
436
Alan Bakerfcda9482018-10-02 17:09:59 -0400437 // Wrapped methods of DataLayout accessors. If |type| was remapped for UBOs,
438 // uses the internal map, otherwise it falls back on the data layout.
439 uint64_t GetTypeSizeInBits(Type *type, const DataLayout &DL);
440 uint64_t GetTypeStoreSize(Type *type, const DataLayout &DL);
441 uint64_t GetTypeAllocSize(Type *type, const DataLayout &DL);
442
alan-baker5b86ed72019-02-15 08:26:50 -0500443 // Returns the base pointer of |v|.
444 Value *GetBasePointer(Value *v);
445
446 // Sets |HasVariablePointersStorageBuffer| or |HasVariablePointers| base on
447 // |address_space|.
448 void setVariablePointersCapabilities(unsigned address_space);
449
450 // Returns true if |lhs| and |rhs| represent the same resource or workgroup
451 // variable.
452 bool sameResource(Value *lhs, Value *rhs) const;
453
454 // Returns true if |inst| is phi or select that selects from the same
455 // structure (or null).
456 bool selectFromSameObject(Instruction *inst);
457
alan-bakere9308012019-03-15 10:25:13 -0400458 // Returns true if |Arg| is called with a coherent resource.
459 bool CalledWithCoherentResource(Argument &Arg);
460
David Neto22f144c2017-06-12 14:26:21 -0400461private:
462 static char ID;
David Neto44795152017-07-13 15:45:28 -0400463 ArrayRef<std::pair<unsigned, std::string>> samplerMap;
David Neto22f144c2017-06-12 14:26:21 -0400464 raw_pwrite_stream &out;
David Neto0676e6f2017-07-11 18:47:44 -0400465
466 // TODO(dneto): Wouldn't it be better to always just emit a binary, and then
467 // convert to other formats on demand?
468
469 // When emitting a C initialization list, the WriteSPIRVBinary method
470 // will actually write its words to this vector via binaryTempOut.
471 SmallVector<char, 100> binaryTempUnderlyingVector;
472 raw_svector_ostream binaryTempOut;
473
474 // Binary output writes to this stream, which might be |out| or
475 // |binaryTempOut|. It's the latter when we really want to write a C
476 // initializer list.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400477 raw_pwrite_stream *binaryOut;
alan-bakerf5e5f692018-11-27 08:33:24 -0500478 std::vector<version0::DescriptorMapEntry> *descriptorMapEntries;
David Neto0676e6f2017-07-11 18:47:44 -0400479 const bool outputCInitList; // If true, output look like {0x7023, ... , 5}
David Neto22f144c2017-06-12 14:26:21 -0400480 uint64_t patchBoundOffset;
481 uint32_t nextID;
482
alan-bakerf67468c2019-11-25 15:51:49 -0500483 // ID for OpTypeInt 32 1.
484 uint32_t int32ID = 0;
485 // ID for OpTypeVector %int 4.
486 uint32_t v4int32ID = 0;
487
David Neto19a1bad2017-08-25 15:01:41 -0400488 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400489 TypeMapType TypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400490 // Maps an LLVM image type to its SPIR-V ID.
David Neto22f144c2017-06-12 14:26:21 -0400491 TypeMapType ImageTypeMap;
alan-bakerabd82722019-12-03 17:14:51 -0500492 // A unique-vector of LLVM image types. This list is used to provide
493 // deterministic traversal of image types.
494 TypeList ImageTypeList;
David Neto19a1bad2017-08-25 15:01:41 -0400495 // A unique-vector of LLVM types that map to a SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400496 TypeList Types;
497 ValueList Constants;
David Neto19a1bad2017-08-25 15:01:41 -0400498 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400499 ValueMapType ValueMap;
500 ValueMapType AllocatedValueMap;
501 SPIRVInstructionList SPIRVInsts;
David Neto862b7d82018-06-14 18:48:37 -0400502
David Neto22f144c2017-06-12 14:26:21 -0400503 EntryPointVecType EntryPointVec;
504 DeferredInstVecType DeferredInstVec;
505 ValueList EntryPointInterfacesVec;
506 uint32_t OpExtInstImportID;
507 std::vector<uint32_t> BuiltinDimensionVec;
alan-baker5b86ed72019-02-15 08:26:50 -0500508 bool HasVariablePointersStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -0400509 bool HasVariablePointers;
510 Type *SamplerTy;
alan-baker09cb9802019-12-10 13:16:27 -0500511 DenseMap<unsigned, unsigned> SamplerLiteralToIDMap;
David Netoc77d9e22018-03-24 06:30:28 -0700512
513 // If a function F has a pointer-to-__constant parameter, then this variable
David Neto9ed8e2f2018-03-24 06:47:24 -0700514 // will map F's type to (G, index of the parameter), where in a first phase
515 // G is F's type. During FindTypePerFunc, G will be changed to F's type
516 // but replacing the pointer-to-constant parameter with
517 // pointer-to-ModuleScopePrivate.
David Netoc77d9e22018-03-24 06:30:28 -0700518 // TODO(dneto): This doesn't seem general enough? A function might have
519 // more than one such parameter.
David Neto22f144c2017-06-12 14:26:21 -0400520 GlobalConstFuncMapType GlobalConstFuncTypeMap;
521 SmallPtrSet<Value *, 16> GlobalConstArgumentSet;
David Neto1a1a0582017-07-07 12:01:44 -0400522 // An ordered set of pointer types of Base arguments to OpPtrAccessChain,
David Neto85082642018-03-24 06:55:20 -0700523 // or array types, and which point into transparent memory (StorageBuffer
524 // storage class). These will require an ArrayStride decoration.
David Neto1a1a0582017-07-07 12:01:44 -0400525 // See SPV_KHR_variable_pointers rev 13.
David Neto85082642018-03-24 06:55:20 -0700526 TypeList TypesNeedingArrayStride;
David Netoa60b00b2017-09-15 16:34:09 -0400527
528 // This is truly ugly, but works around what look like driver bugs.
529 // For get_local_size, an earlier part of the flow has created a module-scope
530 // variable in Private address space to hold the value for the workgroup
531 // size. Its intializer is a uint3 value marked as builtin WorkgroupSize.
532 // When this is present, save the IDs of the initializer value and variable
533 // in these two variables. We only ever do a vector load from it, and
534 // when we see one of those, substitute just the value of the intializer.
535 // This mimics what Glslang does, and that's what drivers are used to.
David Neto66cfe642018-03-24 06:13:56 -0700536 // TODO(dneto): Remove this once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -0400537 uint32_t WorkgroupSizeValueID;
538 uint32_t WorkgroupSizeVarID;
David Neto26aaf622017-10-23 18:11:53 -0400539
David Neto862b7d82018-06-14 18:48:37 -0400540 // Bookkeeping for mapping kernel arguments to resource variables.
541 struct ResourceVarInfo {
542 ResourceVarInfo(int index_arg, unsigned set_arg, unsigned binding_arg,
alan-bakere9308012019-03-15 10:25:13 -0400543 Function *fn, clspv::ArgKind arg_kind_arg, int coherent_arg)
David Neto862b7d82018-06-14 18:48:37 -0400544 : index(index_arg), descriptor_set(set_arg), binding(binding_arg),
alan-bakere9308012019-03-15 10:25:13 -0400545 var_fn(fn), arg_kind(arg_kind_arg), coherent(coherent_arg),
David Neto862b7d82018-06-14 18:48:37 -0400546 addr_space(fn->getReturnType()->getPointerAddressSpace()) {}
547 const int index; // Index into ResourceVarInfoList
548 const unsigned descriptor_set;
549 const unsigned binding;
550 Function *const var_fn; // The @clspv.resource.var.* function.
551 const clspv::ArgKind arg_kind;
alan-bakere9308012019-03-15 10:25:13 -0400552 const int coherent;
David Neto862b7d82018-06-14 18:48:37 -0400553 const unsigned addr_space; // The LLVM address space
554 // The SPIR-V ID of the OpVariable. Not populated at construction time.
555 uint32_t var_id = 0;
556 };
557 // A list of resource var info. Each one correponds to a module-scope
558 // resource variable we will have to create. Resource var indices are
559 // indices into this vector.
560 SmallVector<std::unique_ptr<ResourceVarInfo>, 8> ResourceVarInfoList;
561 // This is a vector of pointers of all the resource vars, but ordered by
562 // kernel function, and then by argument.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500563 UniqueVector<ResourceVarInfo *> ModuleOrderedResourceVars;
David Neto862b7d82018-06-14 18:48:37 -0400564 // Map a function to the ordered list of resource variables it uses, one for
565 // each argument. If an argument does not use a resource variable, it
566 // will have a null pointer entry.
567 using FunctionToResourceVarsMapType =
568 DenseMap<Function *, SmallVector<ResourceVarInfo *, 8>>;
569 FunctionToResourceVarsMapType FunctionToResourceVarsMap;
570
571 // What LLVM types map to SPIR-V types needing layout? These are the
572 // arrays and structures supporting storage buffers and uniform buffers.
573 TypeList TypesNeedingLayout;
574 // What LLVM struct types map to a SPIR-V struct type with Block decoration?
575 UniqueVector<StructType *> StructTypesNeedingBlock;
576 // For a call that represents a load from an opaque type (samplers, images),
577 // map it to the variable id it should load from.
578 DenseMap<CallInst *, uint32_t> ResourceVarDeferredLoadCalls;
David Neto85082642018-03-24 06:55:20 -0700579
Alan Baker202c8c72018-08-13 13:47:44 -0400580 // One larger than the maximum used SpecId for pointer-to-local arguments.
581 int max_local_spec_id_;
David Netoc6f3ab22018-04-06 18:02:31 -0400582 // An ordered list of the kernel arguments of type pointer-to-local.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500583 using LocalArgList = SmallVector<Argument *, 8>;
David Netoc6f3ab22018-04-06 18:02:31 -0400584 LocalArgList LocalArgs;
585 // Information about a pointer-to-local argument.
586 struct LocalArgInfo {
587 // The SPIR-V ID of the array variable.
588 uint32_t variable_id;
589 // The element type of the
alan-bakerb6b09dc2018-11-08 16:59:28 -0500590 Type *elem_type;
David Netoc6f3ab22018-04-06 18:02:31 -0400591 // The ID of the array type.
592 uint32_t array_size_id;
593 // The ID of the array type.
594 uint32_t array_type_id;
595 // The ID of the pointer to the array type.
596 uint32_t ptr_array_type_id;
David Netoc6f3ab22018-04-06 18:02:31 -0400597 // The specialization constant ID of the array size.
598 int spec_id;
599 };
Alan Baker202c8c72018-08-13 13:47:44 -0400600 // A mapping from Argument to its assigned SpecId.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500601 DenseMap<const Argument *, int> LocalArgSpecIds;
Alan Baker202c8c72018-08-13 13:47:44 -0400602 // A mapping from SpecId to its LocalArgInfo.
603 DenseMap<int, LocalArgInfo> LocalSpecIdInfoMap;
Alan Bakerfcda9482018-10-02 17:09:59 -0400604 // A mapping from a remapped type to its real offsets.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500605 DenseMap<Type *, std::vector<uint32_t>> RemappedUBOTypeOffsets;
Alan Bakerfcda9482018-10-02 17:09:59 -0400606 // A mapping from a remapped type to its real sizes.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500607 DenseMap<Type *, std::tuple<uint64_t, uint64_t, uint64_t>>
608 RemappedUBOTypeSizes;
alan-baker06cad652019-12-03 17:56:47 -0500609
610 // Maps basic block to its merge block.
611 DenseMap<BasicBlock *, BasicBlock *> MergeBlocks;
612 // Maps basic block to its continue block.
613 DenseMap<BasicBlock *, BasicBlock *> ContinueBlocks;
David Neto22f144c2017-06-12 14:26:21 -0400614};
615
616char SPIRVProducerPass::ID;
David Netoc6f3ab22018-04-06 18:02:31 -0400617
alan-bakerb6b09dc2018-11-08 16:59:28 -0500618} // namespace
David Neto22f144c2017-06-12 14:26:21 -0400619
620namespace clspv {
alan-bakerf5e5f692018-11-27 08:33:24 -0500621ModulePass *createSPIRVProducerPass(
622 raw_pwrite_stream &out,
623 std::vector<version0::DescriptorMapEntry> *descriptor_map_entries,
alan-baker00e7a582019-06-07 12:54:21 -0400624 ArrayRef<std::pair<unsigned, std::string>> samplerMap,
alan-bakerf5e5f692018-11-27 08:33:24 -0500625 bool outputCInitList) {
626 return new SPIRVProducerPass(out, descriptor_map_entries, samplerMap,
alan-baker00e7a582019-06-07 12:54:21 -0400627 outputCInitList);
David Neto22f144c2017-06-12 14:26:21 -0400628}
David Netoc2c368d2017-06-30 16:50:17 -0400629} // namespace clspv
David Neto22f144c2017-06-12 14:26:21 -0400630
631bool SPIRVProducerPass::runOnModule(Module &module) {
David Neto0676e6f2017-07-11 18:47:44 -0400632 binaryOut = outputCInitList ? &binaryTempOut : &out;
633
Alan Bakerfcda9482018-10-02 17:09:59 -0400634 PopulateUBOTypeMaps(module);
alan-baker06cad652019-12-03 17:56:47 -0500635 PopulateStructuredCFGMaps(module);
Alan Bakerfcda9482018-10-02 17:09:59 -0400636
David Neto22f144c2017-06-12 14:26:21 -0400637 // SPIR-V always begins with its header information
638 outputHeader();
639
David Netoc6f3ab22018-04-06 18:02:31 -0400640 const DataLayout &DL = module.getDataLayout();
641
David Neto22f144c2017-06-12 14:26:21 -0400642 // Gather information from the LLVM IR that we require.
David Netoc6f3ab22018-04-06 18:02:31 -0400643 GenerateLLVMIRInfo(module, DL);
David Neto22f144c2017-06-12 14:26:21 -0400644
David Neto22f144c2017-06-12 14:26:21 -0400645 // Collect information on global variables too.
646 for (GlobalVariable &GV : module.globals()) {
647 // If the GV is one of our special __spirv_* variables, remove the
648 // initializer as it was only placed there to force LLVM to not throw the
649 // value away.
650 if (GV.getName().startswith("__spirv_")) {
651 GV.setInitializer(nullptr);
652 }
653
654 // Collect types' information from global variable.
655 FindTypePerGlobalVar(GV);
656
657 // Collect constant information from global variable.
658 FindConstantPerGlobalVar(GV);
659
660 // If the variable is an input, entry points need to know about it.
661 if (AddressSpace::Input == GV.getType()->getPointerAddressSpace()) {
David Netofb9a7972017-08-25 17:08:24 -0400662 getEntryPointInterfacesVec().insert(&GV);
David Neto22f144c2017-06-12 14:26:21 -0400663 }
664 }
665
666 // If there are extended instructions, generate OpExtInstImport.
667 if (FindExtInst(module)) {
668 GenerateExtInstImport();
669 }
670
671 // Generate SPIRV instructions for types.
Alan Bakerfcda9482018-10-02 17:09:59 -0400672 GenerateSPIRVTypes(module.getContext(), module);
David Neto22f144c2017-06-12 14:26:21 -0400673
674 // Generate SPIRV constants.
675 GenerateSPIRVConstants();
676
alan-baker09cb9802019-12-10 13:16:27 -0500677 // Generate literal samplers if necessary.
678 GenerateSamplers(module);
David Neto22f144c2017-06-12 14:26:21 -0400679
680 // Generate SPIRV variables.
681 for (GlobalVariable &GV : module.globals()) {
682 GenerateGlobalVar(GV);
683 }
David Neto862b7d82018-06-14 18:48:37 -0400684 GenerateResourceVars(module);
David Netoc6f3ab22018-04-06 18:02:31 -0400685 GenerateWorkgroupVars();
David Neto22f144c2017-06-12 14:26:21 -0400686
687 // Generate SPIRV instructions for each function.
688 for (Function &F : module) {
689 if (F.isDeclaration()) {
690 continue;
691 }
692
David Neto862b7d82018-06-14 18:48:37 -0400693 GenerateDescriptorMapInfo(DL, F);
694
David Neto22f144c2017-06-12 14:26:21 -0400695 // Generate Function Prologue.
696 GenerateFuncPrologue(F);
697
698 // Generate SPIRV instructions for function body.
699 GenerateFuncBody(F);
700
701 // Generate Function Epilogue.
702 GenerateFuncEpilogue();
703 }
704
705 HandleDeferredInstruction();
David Neto1a1a0582017-07-07 12:01:44 -0400706 HandleDeferredDecorations(DL);
David Neto22f144c2017-06-12 14:26:21 -0400707
708 // Generate SPIRV module information.
David Neto5c22a252018-03-15 16:07:41 -0400709 GenerateModuleInfo(module);
David Neto22f144c2017-06-12 14:26:21 -0400710
alan-baker00e7a582019-06-07 12:54:21 -0400711 WriteSPIRVBinary();
David Neto22f144c2017-06-12 14:26:21 -0400712
713 // We need to patch the SPIR-V header to set bound correctly.
714 patchHeader();
David Neto0676e6f2017-07-11 18:47:44 -0400715
716 if (outputCInitList) {
717 bool first = true;
David Neto0676e6f2017-07-11 18:47:44 -0400718 std::ostringstream os;
719
David Neto57fb0b92017-08-04 15:35:09 -0400720 auto emit_word = [&os, &first](uint32_t word) {
David Neto0676e6f2017-07-11 18:47:44 -0400721 if (!first)
David Neto57fb0b92017-08-04 15:35:09 -0400722 os << ",\n";
723 os << word;
David Neto0676e6f2017-07-11 18:47:44 -0400724 first = false;
725 };
726
727 os << "{";
David Neto57fb0b92017-08-04 15:35:09 -0400728 const std::string str(binaryTempOut.str());
729 for (unsigned i = 0; i < str.size(); i += 4) {
730 const uint32_t a = static_cast<unsigned char>(str[i]);
731 const uint32_t b = static_cast<unsigned char>(str[i + 1]);
732 const uint32_t c = static_cast<unsigned char>(str[i + 2]);
733 const uint32_t d = static_cast<unsigned char>(str[i + 3]);
734 emit_word(a | (b << 8) | (c << 16) | (d << 24));
David Neto0676e6f2017-07-11 18:47:44 -0400735 }
736 os << "}\n";
737 out << os.str();
738 }
739
David Neto22f144c2017-06-12 14:26:21 -0400740 return false;
741}
742
743void SPIRVProducerPass::outputHeader() {
alan-baker00e7a582019-06-07 12:54:21 -0400744 binaryOut->write(reinterpret_cast<const char *>(&spv::MagicNumber),
745 sizeof(spv::MagicNumber));
746 binaryOut->write(reinterpret_cast<const char *>(&spv::Version),
747 sizeof(spv::Version));
David Neto22f144c2017-06-12 14:26:21 -0400748
alan-baker0c18ab02019-06-12 10:23:21 -0400749 // use Google's vendor ID
750 const uint32_t vendor = 21 << 16;
alan-baker00e7a582019-06-07 12:54:21 -0400751 binaryOut->write(reinterpret_cast<const char *>(&vendor), sizeof(vendor));
David Neto22f144c2017-06-12 14:26:21 -0400752
alan-baker00e7a582019-06-07 12:54:21 -0400753 // we record where we need to come back to and patch in the bound value
754 patchBoundOffset = binaryOut->tell();
David Neto22f144c2017-06-12 14:26:21 -0400755
alan-baker00e7a582019-06-07 12:54:21 -0400756 // output a bad bound for now
757 binaryOut->write(reinterpret_cast<const char *>(&nextID), sizeof(nextID));
David Neto22f144c2017-06-12 14:26:21 -0400758
alan-baker00e7a582019-06-07 12:54:21 -0400759 // output the schema (reserved for use and must be 0)
760 const uint32_t schema = 0;
761 binaryOut->write(reinterpret_cast<const char *>(&schema), sizeof(schema));
David Neto22f144c2017-06-12 14:26:21 -0400762}
763
764void SPIRVProducerPass::patchHeader() {
alan-baker00e7a582019-06-07 12:54:21 -0400765 // for a binary we just write the value of nextID over bound
766 binaryOut->pwrite(reinterpret_cast<char *>(&nextID), sizeof(nextID),
767 patchBoundOffset);
David Neto22f144c2017-06-12 14:26:21 -0400768}
769
David Netoc6f3ab22018-04-06 18:02:31 -0400770void SPIRVProducerPass::GenerateLLVMIRInfo(Module &M, const DataLayout &DL) {
David Neto22f144c2017-06-12 14:26:21 -0400771 // This function generates LLVM IR for function such as global variable for
772 // argument, constant and pointer type for argument access. These information
773 // is artificial one because we need Vulkan SPIR-V output. This function is
774 // executed ahead of FindType and FindConstant.
David Neto22f144c2017-06-12 14:26:21 -0400775 LLVMContext &Context = M.getContext();
776
David Neto862b7d82018-06-14 18:48:37 -0400777 FindGlobalConstVars(M, DL);
David Neto5c22a252018-03-15 16:07:41 -0400778
David Neto862b7d82018-06-14 18:48:37 -0400779 FindResourceVars(M, DL);
David Neto22f144c2017-06-12 14:26:21 -0400780
781 bool HasWorkGroupBuiltin = false;
782 for (GlobalVariable &GV : M.globals()) {
783 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
784 if (spv::BuiltInWorkgroupSize == BuiltinType) {
785 HasWorkGroupBuiltin = true;
786 }
787 }
788
David Neto862b7d82018-06-14 18:48:37 -0400789 FindTypesForSamplerMap(M);
790 FindTypesForResourceVars(M);
Alan Baker202c8c72018-08-13 13:47:44 -0400791 FindWorkgroupVars(M);
David Neto22f144c2017-06-12 14:26:21 -0400792
793 for (Function &F : M) {
Kévin Petitabef4522019-03-27 13:08:01 +0000794 if (F.isDeclaration()) {
David Neto22f144c2017-06-12 14:26:21 -0400795 continue;
796 }
797
798 for (BasicBlock &BB : F) {
799 for (Instruction &I : BB) {
800 if (I.getOpcode() == Instruction::ZExt ||
801 I.getOpcode() == Instruction::SExt ||
802 I.getOpcode() == Instruction::UIToFP) {
803 // If there is zext with i1 type, it will be changed to OpSelect. The
804 // OpSelect needs constant 0 and 1 so the constants are added here.
805
806 auto OpTy = I.getOperand(0)->getType();
807
Kévin Petit24272b62018-10-18 19:16:12 +0000808 if (OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -0400809 if (I.getOpcode() == Instruction::ZExt) {
David Neto22f144c2017-06-12 14:26:21 -0400810 FindConstant(Constant::getNullValue(I.getType()));
Kévin Petit7bfb8992019-02-26 13:45:08 +0000811 FindConstant(ConstantInt::get(I.getType(), 1));
David Neto22f144c2017-06-12 14:26:21 -0400812 } else if (I.getOpcode() == Instruction::SExt) {
David Neto22f144c2017-06-12 14:26:21 -0400813 FindConstant(Constant::getNullValue(I.getType()));
Kévin Petit7bfb8992019-02-26 13:45:08 +0000814 FindConstant(ConstantInt::getSigned(I.getType(), -1));
David Neto22f144c2017-06-12 14:26:21 -0400815 } else {
816 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
817 FindConstant(ConstantFP::get(Context, APFloat(1.0f)));
818 }
819 }
820 } else if (CallInst *Call = dyn_cast<CallInst>(&I)) {
David Neto862b7d82018-06-14 18:48:37 -0400821 StringRef callee_name = Call->getCalledFunction()->getName();
David Neto22f144c2017-06-12 14:26:21 -0400822
823 // Handle image type specially.
alan-bakerf67468c2019-11-25 15:51:49 -0500824 if (clspv::IsSampledImageRead(callee_name)) {
David Neto22f144c2017-06-12 14:26:21 -0400825 TypeMapType &OpImageTypeMap = getImageTypeMap();
826 Type *ImageTy =
827 Call->getArgOperand(0)->getType()->getPointerElementType();
828 OpImageTypeMap[ImageTy] = 0;
alan-bakerabd82722019-12-03 17:14:51 -0500829 getImageTypeList().insert(ImageTy);
David Neto22f144c2017-06-12 14:26:21 -0400830
alan-bakerf67468c2019-11-25 15:51:49 -0500831 // All sampled reads need a floating point 0 for the Lod operand.
David Neto22f144c2017-06-12 14:26:21 -0400832 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
833 }
David Neto5c22a252018-03-15 16:07:41 -0400834
alan-bakerce179f12019-12-06 19:02:22 -0500835 if (clspv::IsImageQuery(callee_name)) {
836 Type *ImageTy = Call->getOperand(0)->getType();
837 const uint32_t dim = ImageDimensionality(ImageTy);
838 uint32_t components = dim;
839 if (components > 1) {
840 // OpImageQuerySize* return |components| components.
841 FindType(VectorType::get(Type::getInt32Ty(Context), components));
842 if (dim == 3 && IsGetImageDim(callee_name)) {
843 // get_image_dim for 3D images returns an int4.
844 FindType(
845 VectorType::get(Type::getInt32Ty(Context), components + 1));
846 }
847 }
848
849 if (clspv::IsSampledImageType(ImageTy)) {
850 // All sampled image queries need a integer 0 for the Lod
851 // operand.
852 FindConstant(ConstantInt::get(Context, APInt(32, 0)));
853 }
David Neto5c22a252018-03-15 16:07:41 -0400854 }
David Neto22f144c2017-06-12 14:26:21 -0400855 }
856 }
857 }
858
Kévin Petitabef4522019-03-27 13:08:01 +0000859 // More things to do on kernel functions
860 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
861 if (const MDNode *MD =
862 dyn_cast<Function>(&F)->getMetadata("reqd_work_group_size")) {
863 // We generate constants if the WorkgroupSize builtin is being used.
864 if (HasWorkGroupBuiltin) {
865 // Collect constant information for work group size.
866 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(0)));
867 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(1)));
868 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(2)));
David Neto22f144c2017-06-12 14:26:21 -0400869 }
870 }
871 }
872
alan-bakerf67468c2019-11-25 15:51:49 -0500873 // TODO(alan-baker): make this better.
alan-bakerf906d2b2019-12-10 11:26:23 -0500874 if (M.getTypeByName("opencl.image1d_ro_t.float") ||
875 M.getTypeByName("opencl.image1d_ro_t.float.sampled") ||
876 M.getTypeByName("opencl.image1d_wo_t.float") ||
877 M.getTypeByName("opencl.image2d_ro_t.float") ||
alan-bakerf67468c2019-11-25 15:51:49 -0500878 M.getTypeByName("opencl.image2d_ro_t.float.sampled") ||
879 M.getTypeByName("opencl.image2d_wo_t.float") ||
880 M.getTypeByName("opencl.image3d_ro_t.float") ||
881 M.getTypeByName("opencl.image3d_ro_t.float.sampled") ||
882 M.getTypeByName("opencl.image3d_wo_t.float")) {
883 FindType(Type::getFloatTy(Context));
alan-bakerf906d2b2019-12-10 11:26:23 -0500884 } else if (M.getTypeByName("opencl.image1d_ro_t.uint") ||
885 M.getTypeByName("opencl.image1d_ro_t.uint.sampled") ||
886 M.getTypeByName("opencl.image1d_wo_t.uint") ||
887 M.getTypeByName("opencl.image2d_ro_t.uint") ||
alan-bakerf67468c2019-11-25 15:51:49 -0500888 M.getTypeByName("opencl.image2d_ro_t.uint.sampled") ||
889 M.getTypeByName("opencl.image2d_wo_t.uint") ||
890 M.getTypeByName("opencl.image3d_ro_t.uint") ||
891 M.getTypeByName("opencl.image3d_ro_t.uint.sampled") ||
892 M.getTypeByName("opencl.image3d_wo_t.uint")) {
893 FindType(Type::getInt32Ty(Context));
alan-bakerf906d2b2019-12-10 11:26:23 -0500894 } else if (M.getTypeByName("opencl.image1d_ro_t.int") ||
895 M.getTypeByName("opencl.image1d_ro_t.int.sampled") ||
896 M.getTypeByName("opencl.image1d_wo_t.int") ||
897 M.getTypeByName("opencl.image2d_ro_t.int") ||
alan-bakerf67468c2019-11-25 15:51:49 -0500898 M.getTypeByName("opencl.image2d_ro_t.int.sampled") ||
899 M.getTypeByName("opencl.image2d_wo_t.int") ||
900 M.getTypeByName("opencl.image3d_ro_t.int") ||
901 M.getTypeByName("opencl.image3d_ro_t.int.sampled") ||
902 M.getTypeByName("opencl.image3d_wo_t.int")) {
903 // Nothing for now...
904 } else {
905 // This was likely an UndefValue.
David Neto22f144c2017-06-12 14:26:21 -0400906 FindType(Type::getFloatTy(Context));
907 }
908
909 // Collect types' information from function.
910 FindTypePerFunc(F);
911
912 // Collect constant information from function.
913 FindConstantPerFunc(F);
914 }
915}
916
David Neto862b7d82018-06-14 18:48:37 -0400917void SPIRVProducerPass::FindGlobalConstVars(Module &M, const DataLayout &DL) {
alan-baker56f7aff2019-05-22 08:06:42 -0400918 clspv::NormalizeGlobalVariables(M);
919
David Neto862b7d82018-06-14 18:48:37 -0400920 SmallVector<GlobalVariable *, 8> GVList;
921 SmallVector<GlobalVariable *, 8> DeadGVList;
922 for (GlobalVariable &GV : M.globals()) {
923 if (GV.getType()->getAddressSpace() == AddressSpace::Constant) {
924 if (GV.use_empty()) {
925 DeadGVList.push_back(&GV);
926 } else {
927 GVList.push_back(&GV);
928 }
929 }
930 }
931
932 // Remove dead global __constant variables.
933 for (auto GV : DeadGVList) {
934 GV->eraseFromParent();
935 }
936 DeadGVList.clear();
937
938 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
939 // For now, we only support a single storage buffer.
940 if (GVList.size() > 0) {
941 assert(GVList.size() == 1);
942 const auto *GV = GVList[0];
943 const auto constants_byte_size =
Alan Bakerfcda9482018-10-02 17:09:59 -0400944 (GetTypeSizeInBits(GV->getInitializer()->getType(), DL)) / 8;
David Neto862b7d82018-06-14 18:48:37 -0400945 const size_t kConstantMaxSize = 65536;
946 if (constants_byte_size > kConstantMaxSize) {
947 outs() << "Max __constant capacity of " << kConstantMaxSize
948 << " bytes exceeded: " << constants_byte_size << " bytes used\n";
949 llvm_unreachable("Max __constant capacity exceeded");
950 }
951 }
952 } else {
953 // Change global constant variable's address space to ModuleScopePrivate.
954 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
955 for (auto GV : GVList) {
956 // Create new gv with ModuleScopePrivate address space.
957 Type *NewGVTy = GV->getType()->getPointerElementType();
958 GlobalVariable *NewGV = new GlobalVariable(
959 M, NewGVTy, false, GV->getLinkage(), GV->getInitializer(), "",
960 nullptr, GV->getThreadLocalMode(), AddressSpace::ModuleScopePrivate);
961 NewGV->takeName(GV);
962
963 const SmallVector<User *, 8> GVUsers(GV->user_begin(), GV->user_end());
964 SmallVector<User *, 8> CandidateUsers;
965
966 auto record_called_function_type_as_user =
967 [&GlobalConstFuncTyMap](Value *gv, CallInst *call) {
968 // Find argument index.
969 unsigned index = 0;
970 for (unsigned i = 0; i < call->getNumArgOperands(); i++) {
971 if (gv == call->getOperand(i)) {
972 // TODO(dneto): Should we break here?
973 index = i;
974 }
975 }
976
977 // Record function type with global constant.
978 GlobalConstFuncTyMap[call->getFunctionType()] =
979 std::make_pair(call->getFunctionType(), index);
980 };
981
982 for (User *GVU : GVUsers) {
983 if (CallInst *Call = dyn_cast<CallInst>(GVU)) {
984 record_called_function_type_as_user(GV, Call);
985 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(GVU)) {
986 // Check GEP users.
987 for (User *GEPU : GEP->users()) {
988 if (CallInst *GEPCall = dyn_cast<CallInst>(GEPU)) {
989 record_called_function_type_as_user(GEP, GEPCall);
990 }
991 }
992 }
993
994 CandidateUsers.push_back(GVU);
995 }
996
997 for (User *U : CandidateUsers) {
998 // Update users of gv with new gv.
alan-bakered80f572019-02-11 17:28:26 -0500999 if (!isa<Constant>(U)) {
1000 // #254: Can't change operands of a constant, but this shouldn't be
1001 // something that sticks around in the module.
1002 U->replaceUsesOfWith(GV, NewGV);
1003 }
David Neto862b7d82018-06-14 18:48:37 -04001004 }
1005
1006 // Delete original gv.
1007 GV->eraseFromParent();
1008 }
1009 }
1010}
1011
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001012void SPIRVProducerPass::FindResourceVars(Module &M, const DataLayout &) {
David Neto862b7d82018-06-14 18:48:37 -04001013 ResourceVarInfoList.clear();
1014 FunctionToResourceVarsMap.clear();
1015 ModuleOrderedResourceVars.reset();
1016 // Normally, there is one resource variable per clspv.resource.var.*
1017 // function, since that is unique'd by arg type and index. By design,
1018 // we can share these resource variables across kernels because all
1019 // kernels use the same descriptor set.
1020 //
1021 // But if the user requested distinct descriptor sets per kernel, then
1022 // the descriptor allocator has made different (set,binding) pairs for
1023 // the same (type,arg_index) pair. Since we can decorate a resource
1024 // variable with only exactly one DescriptorSet and Binding, we are
1025 // forced in this case to make distinct resource variables whenever
1026 // the same clspv.reource.var.X function is seen with disintct
1027 // (set,binding) values.
1028 const bool always_distinct_sets =
1029 clspv::Option::DistinctKernelDescriptorSets();
1030 for (Function &F : M) {
1031 // Rely on the fact the resource var functions have a stable ordering
1032 // in the module.
Alan Baker202c8c72018-08-13 13:47:44 -04001033 if (F.getName().startswith(clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001034 // Find all calls to this function with distinct set and binding pairs.
1035 // Save them in ResourceVarInfoList.
1036
1037 // Determine uniqueness of the (set,binding) pairs only withing this
1038 // one resource-var builtin function.
1039 using SetAndBinding = std::pair<unsigned, unsigned>;
1040 // Maps set and binding to the resource var info.
1041 DenseMap<SetAndBinding, ResourceVarInfo *> set_and_binding_map;
1042 bool first_use = true;
1043 for (auto &U : F.uses()) {
1044 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
1045 const auto set = unsigned(
1046 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
1047 const auto binding = unsigned(
1048 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
1049 const auto arg_kind = clspv::ArgKind(
1050 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
1051 const auto arg_index = unsigned(
1052 dyn_cast<ConstantInt>(call->getArgOperand(3))->getZExtValue());
alan-bakere9308012019-03-15 10:25:13 -04001053 const auto coherent = unsigned(
1054 dyn_cast<ConstantInt>(call->getArgOperand(5))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04001055
1056 // Find or make the resource var info for this combination.
1057 ResourceVarInfo *rv = nullptr;
1058 if (always_distinct_sets) {
1059 // Make a new resource var any time we see a different
1060 // (set,binding) pair.
1061 SetAndBinding key{set, binding};
1062 auto where = set_and_binding_map.find(key);
1063 if (where == set_and_binding_map.end()) {
1064 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
alan-bakere9308012019-03-15 10:25:13 -04001065 binding, &F, arg_kind, coherent);
David Neto862b7d82018-06-14 18:48:37 -04001066 ResourceVarInfoList.emplace_back(rv);
1067 set_and_binding_map[key] = rv;
1068 } else {
1069 rv = where->second;
1070 }
1071 } else {
1072 // The default is to make exactly one resource for each
1073 // clspv.resource.var.* function.
1074 if (first_use) {
1075 first_use = false;
1076 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
alan-bakere9308012019-03-15 10:25:13 -04001077 binding, &F, arg_kind, coherent);
David Neto862b7d82018-06-14 18:48:37 -04001078 ResourceVarInfoList.emplace_back(rv);
1079 } else {
1080 rv = ResourceVarInfoList.back().get();
1081 }
1082 }
1083
1084 // Now populate FunctionToResourceVarsMap.
1085 auto &mapping =
1086 FunctionToResourceVarsMap[call->getParent()->getParent()];
1087 while (mapping.size() <= arg_index) {
1088 mapping.push_back(nullptr);
1089 }
1090 mapping[arg_index] = rv;
1091 }
1092 }
1093 }
1094 }
1095
1096 // Populate ModuleOrderedResourceVars.
1097 for (Function &F : M) {
1098 auto where = FunctionToResourceVarsMap.find(&F);
1099 if (where != FunctionToResourceVarsMap.end()) {
1100 for (auto &rv : where->second) {
1101 if (rv != nullptr) {
1102 ModuleOrderedResourceVars.insert(rv);
1103 }
1104 }
1105 }
1106 }
1107 if (ShowResourceVars) {
1108 for (auto *info : ModuleOrderedResourceVars) {
1109 outs() << "MORV index " << info->index << " (" << info->descriptor_set
1110 << "," << info->binding << ") " << *(info->var_fn->getReturnType())
1111 << "\n";
1112 }
1113 }
1114}
1115
David Neto22f144c2017-06-12 14:26:21 -04001116bool SPIRVProducerPass::FindExtInst(Module &M) {
1117 LLVMContext &Context = M.getContext();
1118 bool HasExtInst = false;
1119
1120 for (Function &F : M) {
1121 for (BasicBlock &BB : F) {
1122 for (Instruction &I : BB) {
1123 if (CallInst *Call = dyn_cast<CallInst>(&I)) {
1124 Function *Callee = Call->getCalledFunction();
1125 // Check whether this call is for extend instructions.
David Neto3fbb4072017-10-16 11:28:14 -04001126 auto callee_name = Callee->getName();
1127 const glsl::ExtInst EInst = getExtInstEnum(callee_name);
1128 const glsl::ExtInst IndirectEInst =
1129 getIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04001130
David Neto3fbb4072017-10-16 11:28:14 -04001131 HasExtInst |=
1132 (EInst != kGlslExtInstBad) || (IndirectEInst != kGlslExtInstBad);
1133
1134 if (IndirectEInst) {
1135 // Register extra constants if needed.
1136
1137 // Registers a type and constant for computing the result of the
1138 // given instruction. If the result of the instruction is a vector,
1139 // then make a splat vector constant with the same number of
1140 // elements.
1141 auto register_constant = [this, &I](Constant *constant) {
1142 FindType(constant->getType());
1143 FindConstant(constant);
1144 if (auto *vectorTy = dyn_cast<VectorType>(I.getType())) {
1145 // Register the splat vector of the value with the same
1146 // width as the result of the instruction.
1147 auto *vec_constant = ConstantVector::getSplat(
1148 static_cast<unsigned>(vectorTy->getNumElements()),
1149 constant);
1150 FindConstant(vec_constant);
1151 FindType(vec_constant->getType());
1152 }
1153 };
1154 switch (IndirectEInst) {
1155 case glsl::ExtInstFindUMsb:
1156 // clz needs OpExtInst and OpISub with constant 31, or splat
1157 // vector of 31. Add it to the constant list here.
1158 register_constant(
1159 ConstantInt::get(Type::getInt32Ty(Context), 31));
1160 break;
1161 case glsl::ExtInstAcos:
1162 case glsl::ExtInstAsin:
Kévin Petiteb9f90a2018-09-29 12:29:34 +01001163 case glsl::ExtInstAtan:
David Neto3fbb4072017-10-16 11:28:14 -04001164 case glsl::ExtInstAtan2:
1165 // We need 1/pi for acospi, asinpi, atan2pi.
1166 register_constant(
1167 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
1168 break;
1169 default:
1170 assert(false && "internally inconsistent");
1171 }
David Neto22f144c2017-06-12 14:26:21 -04001172 }
1173 }
1174 }
1175 }
1176 }
1177
1178 return HasExtInst;
1179}
1180
1181void SPIRVProducerPass::FindTypePerGlobalVar(GlobalVariable &GV) {
1182 // Investigate global variable's type.
1183 FindType(GV.getType());
1184}
1185
1186void SPIRVProducerPass::FindTypePerFunc(Function &F) {
1187 // Investigate function's type.
1188 FunctionType *FTy = F.getFunctionType();
1189
1190 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
1191 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
David Neto9ed8e2f2018-03-24 06:47:24 -07001192 // Handle a regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04001193 if (GlobalConstFuncTyMap.count(FTy)) {
1194 uint32_t GVCstArgIdx = GlobalConstFuncTypeMap[FTy].second;
1195 SmallVector<Type *, 4> NewFuncParamTys;
1196 for (unsigned i = 0; i < FTy->getNumParams(); i++) {
1197 Type *ParamTy = FTy->getParamType(i);
1198 if (i == GVCstArgIdx) {
1199 Type *EleTy = ParamTy->getPointerElementType();
1200 ParamTy = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1201 }
1202
1203 NewFuncParamTys.push_back(ParamTy);
1204 }
1205
1206 FunctionType *NewFTy =
1207 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1208 GlobalConstFuncTyMap[FTy] = std::make_pair(NewFTy, GVCstArgIdx);
1209 FTy = NewFTy;
1210 }
1211
1212 FindType(FTy);
1213 } else {
1214 // As kernel functions do not have parameters, create new function type and
1215 // add it to type map.
1216 SmallVector<Type *, 4> NewFuncParamTys;
1217 FunctionType *NewFTy =
1218 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1219 FindType(NewFTy);
1220 }
1221
1222 // Investigate instructions' type in function body.
1223 for (BasicBlock &BB : F) {
1224 for (Instruction &I : BB) {
1225 if (isa<ShuffleVectorInst>(I)) {
1226 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1227 // Ignore type for mask of shuffle vector instruction.
1228 if (i == 2) {
1229 continue;
1230 }
1231
1232 Value *Op = I.getOperand(i);
1233 if (!isa<MetadataAsValue>(Op)) {
1234 FindType(Op->getType());
1235 }
1236 }
1237
1238 FindType(I.getType());
1239 continue;
1240 }
1241
David Neto862b7d82018-06-14 18:48:37 -04001242 CallInst *Call = dyn_cast<CallInst>(&I);
1243
1244 if (Call && Call->getCalledFunction()->getName().startswith(
Alan Baker202c8c72018-08-13 13:47:44 -04001245 clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001246 // This is a fake call representing access to a resource variable.
1247 // We handle that elsewhere.
1248 continue;
1249 }
1250
Alan Baker202c8c72018-08-13 13:47:44 -04001251 if (Call && Call->getCalledFunction()->getName().startswith(
1252 clspv::WorkgroupAccessorFunction())) {
1253 // This is a fake call representing access to a workgroup variable.
1254 // We handle that elsewhere.
1255 continue;
1256 }
1257
David Neto22f144c2017-06-12 14:26:21 -04001258 // Work through the operands of the instruction.
1259 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1260 Value *const Op = I.getOperand(i);
1261 // If any of the operands is a constant, find the type!
1262 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1263 FindType(Op->getType());
1264 }
1265 }
1266
1267 for (Use &Op : I.operands()) {
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001268 if (isa<CallInst>(&I)) {
David Neto22f144c2017-06-12 14:26:21 -04001269 // Avoid to check call instruction's type.
1270 break;
1271 }
Alan Baker202c8c72018-08-13 13:47:44 -04001272 if (CallInst *OpCall = dyn_cast<CallInst>(Op)) {
1273 if (OpCall && OpCall->getCalledFunction()->getName().startswith(
1274 clspv::WorkgroupAccessorFunction())) {
1275 // This is a fake call representing access to a workgroup variable.
1276 // We handle that elsewhere.
1277 continue;
1278 }
1279 }
David Neto22f144c2017-06-12 14:26:21 -04001280 if (!isa<MetadataAsValue>(&Op)) {
1281 FindType(Op->getType());
1282 continue;
1283 }
1284 }
1285
David Neto22f144c2017-06-12 14:26:21 -04001286 // We don't want to track the type of this call as we are going to replace
1287 // it.
Kévin Petitdf71de32019-04-09 14:09:50 +01001288 if (Call && (clspv::LiteralSamplerFunction() ==
David Neto22f144c2017-06-12 14:26:21 -04001289 Call->getCalledFunction()->getName())) {
1290 continue;
1291 }
1292
1293 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
1294 // If gep's base operand has ModuleScopePrivate address space, make gep
1295 // return ModuleScopePrivate address space.
1296 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate) {
1297 // Add pointer type with private address space for global constant to
1298 // type list.
1299 Type *EleTy = I.getType()->getPointerElementType();
1300 Type *NewPTy =
1301 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1302
1303 FindType(NewPTy);
1304 continue;
1305 }
1306 }
1307
1308 FindType(I.getType());
1309 }
1310 }
1311}
1312
David Neto862b7d82018-06-14 18:48:37 -04001313void SPIRVProducerPass::FindTypesForSamplerMap(Module &M) {
1314 // If we are using a sampler map, find the type of the sampler.
Kévin Petitdf71de32019-04-09 14:09:50 +01001315 if (M.getFunction(clspv::LiteralSamplerFunction()) ||
David Neto862b7d82018-06-14 18:48:37 -04001316 0 < getSamplerMap().size()) {
1317 auto SamplerStructTy = M.getTypeByName("opencl.sampler_t");
1318 if (!SamplerStructTy) {
1319 SamplerStructTy = StructType::create(M.getContext(), "opencl.sampler_t");
1320 }
1321
1322 SamplerTy = SamplerStructTy->getPointerTo(AddressSpace::UniformConstant);
1323
1324 FindType(SamplerTy);
1325 }
1326}
1327
1328void SPIRVProducerPass::FindTypesForResourceVars(Module &M) {
1329 // Record types so they are generated.
1330 TypesNeedingLayout.reset();
1331 StructTypesNeedingBlock.reset();
1332
1333 // To match older clspv codegen, generate the float type first if required
1334 // for images.
1335 for (const auto *info : ModuleOrderedResourceVars) {
1336 if (info->arg_kind == clspv::ArgKind::ReadOnlyImage ||
1337 info->arg_kind == clspv::ArgKind::WriteOnlyImage) {
alan-bakerf67468c2019-11-25 15:51:49 -05001338 if (IsIntImageType(info->var_fn->getReturnType())) {
1339 // Nothing for now...
1340 } else if (IsUintImageType(info->var_fn->getReturnType())) {
1341 FindType(Type::getInt32Ty(M.getContext()));
1342 }
1343
1344 // We need "float" either for the sampled type or for the Lod operand.
David Neto862b7d82018-06-14 18:48:37 -04001345 FindType(Type::getFloatTy(M.getContext()));
David Neto862b7d82018-06-14 18:48:37 -04001346 }
1347 }
1348
1349 for (const auto *info : ModuleOrderedResourceVars) {
1350 Type *type = info->var_fn->getReturnType();
1351
1352 switch (info->arg_kind) {
1353 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04001354 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04001355 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1356 StructTypesNeedingBlock.insert(sty);
1357 } else {
1358 errs() << *type << "\n";
1359 llvm_unreachable("Buffer arguments must map to structures!");
1360 }
1361 break;
1362 case clspv::ArgKind::Pod:
1363 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1364 StructTypesNeedingBlock.insert(sty);
1365 } else {
1366 errs() << *type << "\n";
1367 llvm_unreachable("POD arguments must map to structures!");
1368 }
1369 break;
1370 case clspv::ArgKind::ReadOnlyImage:
1371 case clspv::ArgKind::WriteOnlyImage:
1372 case clspv::ArgKind::Sampler:
1373 // Sampler and image types map to the pointee type but
1374 // in the uniform constant address space.
1375 type = PointerType::get(type->getPointerElementType(),
1376 clspv::AddressSpace::UniformConstant);
1377 break;
1378 default:
1379 break;
1380 }
1381
1382 // The converted type is the type of the OpVariable we will generate.
1383 // If the pointee type is an array of size zero, FindType will convert it
1384 // to a runtime array.
1385 FindType(type);
1386 }
1387
alan-bakerdcd97412019-09-16 15:32:30 -04001388 // If module constants are clustered in a storage buffer then that struct
1389 // needs layout decorations.
1390 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
1391 for (GlobalVariable &GV : M.globals()) {
1392 PointerType *PTy = cast<PointerType>(GV.getType());
1393 const auto AS = PTy->getAddressSpace();
1394 const bool module_scope_constant_external_init =
1395 (AS == AddressSpace::Constant) && GV.hasInitializer();
1396 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
1397 if (module_scope_constant_external_init &&
1398 spv::BuiltInMax == BuiltinType) {
1399 StructTypesNeedingBlock.insert(
1400 cast<StructType>(PTy->getPointerElementType()));
1401 }
1402 }
1403 }
1404
David Neto862b7d82018-06-14 18:48:37 -04001405 // Traverse the arrays and structures underneath each Block, and
1406 // mark them as needing layout.
1407 std::vector<Type *> work_list(StructTypesNeedingBlock.begin(),
1408 StructTypesNeedingBlock.end());
1409 while (!work_list.empty()) {
1410 Type *type = work_list.back();
1411 work_list.pop_back();
1412 TypesNeedingLayout.insert(type);
1413 switch (type->getTypeID()) {
1414 case Type::ArrayTyID:
1415 work_list.push_back(type->getArrayElementType());
1416 if (!Hack_generate_runtime_array_stride_early) {
1417 // Remember this array type for deferred decoration.
1418 TypesNeedingArrayStride.insert(type);
1419 }
1420 break;
1421 case Type::StructTyID:
1422 for (auto *elem_ty : cast<StructType>(type)->elements()) {
1423 work_list.push_back(elem_ty);
1424 }
1425 default:
1426 // This type and its contained types don't get layout.
1427 break;
1428 }
1429 }
1430}
1431
Alan Baker202c8c72018-08-13 13:47:44 -04001432void SPIRVProducerPass::FindWorkgroupVars(Module &M) {
1433 // The SpecId assignment for pointer-to-local arguments is recorded in
1434 // module-level metadata. Translate that information into local argument
1435 // information.
1436 NamedMDNode *nmd = M.getNamedMetadata(clspv::LocalSpecIdMetadataName());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001437 if (!nmd)
1438 return;
Alan Baker202c8c72018-08-13 13:47:44 -04001439 for (auto operand : nmd->operands()) {
1440 MDTuple *tuple = cast<MDTuple>(operand);
1441 ValueAsMetadata *fn_md = cast<ValueAsMetadata>(tuple->getOperand(0));
1442 Function *func = cast<Function>(fn_md->getValue());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001443 ConstantAsMetadata *arg_index_md =
1444 cast<ConstantAsMetadata>(tuple->getOperand(1));
1445 int arg_index = static_cast<int>(
1446 cast<ConstantInt>(arg_index_md->getValue())->getSExtValue());
1447 Argument *arg = &*(func->arg_begin() + arg_index);
Alan Baker202c8c72018-08-13 13:47:44 -04001448
1449 ConstantAsMetadata *spec_id_md =
1450 cast<ConstantAsMetadata>(tuple->getOperand(2));
alan-bakerb6b09dc2018-11-08 16:59:28 -05001451 int spec_id = static_cast<int>(
1452 cast<ConstantInt>(spec_id_md->getValue())->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04001453
1454 max_local_spec_id_ = std::max(max_local_spec_id_, spec_id + 1);
1455 LocalArgSpecIds[arg] = spec_id;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001456 if (LocalSpecIdInfoMap.count(spec_id))
1457 continue;
Alan Baker202c8c72018-08-13 13:47:44 -04001458
1459 // We haven't seen this SpecId yet, so generate the LocalArgInfo for it.
1460 LocalArgInfo info{nextID, arg->getType()->getPointerElementType(),
1461 nextID + 1, nextID + 2,
1462 nextID + 3, spec_id};
1463 LocalSpecIdInfoMap[spec_id] = info;
1464 nextID += 4;
1465
1466 // Ensure the types necessary for this argument get generated.
1467 Type *IdxTy = Type::getInt32Ty(M.getContext());
1468 FindConstant(ConstantInt::get(IdxTy, 0));
1469 FindType(IdxTy);
1470 FindType(arg->getType());
1471 }
1472}
1473
David Neto22f144c2017-06-12 14:26:21 -04001474void SPIRVProducerPass::FindType(Type *Ty) {
1475 TypeList &TyList = getTypeList();
1476
1477 if (0 != TyList.idFor(Ty)) {
1478 return;
1479 }
1480
1481 if (Ty->isPointerTy()) {
1482 auto AddrSpace = Ty->getPointerAddressSpace();
1483 if ((AddressSpace::Constant == AddrSpace) ||
1484 (AddressSpace::Global == AddrSpace)) {
1485 auto PointeeTy = Ty->getPointerElementType();
1486
1487 if (PointeeTy->isStructTy() &&
1488 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1489 FindType(PointeeTy);
1490 auto ActualPointerTy =
1491 PointeeTy->getPointerTo(AddressSpace::UniformConstant);
1492 FindType(ActualPointerTy);
1493 return;
1494 }
1495 }
1496 }
1497
David Neto862b7d82018-06-14 18:48:37 -04001498 // By convention, LLVM array type with 0 elements will map to
1499 // OpTypeRuntimeArray. Otherwise, it will map to OpTypeArray, which
1500 // has a constant number of elements. We need to support type of the
1501 // constant.
1502 if (auto *arrayTy = dyn_cast<ArrayType>(Ty)) {
1503 if (arrayTy->getNumElements() > 0) {
1504 LLVMContext &Context = Ty->getContext();
1505 FindType(Type::getInt32Ty(Context));
1506 }
David Neto22f144c2017-06-12 14:26:21 -04001507 }
1508
1509 for (Type *SubTy : Ty->subtypes()) {
1510 FindType(SubTy);
1511 }
1512
1513 TyList.insert(Ty);
1514}
1515
1516void SPIRVProducerPass::FindConstantPerGlobalVar(GlobalVariable &GV) {
1517 // If the global variable has a (non undef) initializer.
1518 if (GV.hasInitializer() && !isa<UndefValue>(GV.getInitializer())) {
David Neto862b7d82018-06-14 18:48:37 -04001519 // Generate the constant if it's not the initializer to a module scope
1520 // constant that we will expect in a storage buffer.
1521 const bool module_scope_constant_external_init =
1522 (GV.getType()->getPointerAddressSpace() == AddressSpace::Constant) &&
1523 clspv::Option::ModuleConstantsInStorageBuffer();
1524 if (!module_scope_constant_external_init) {
1525 FindConstant(GV.getInitializer());
1526 }
David Neto22f144c2017-06-12 14:26:21 -04001527 }
1528}
1529
1530void SPIRVProducerPass::FindConstantPerFunc(Function &F) {
1531 // Investigate constants in function body.
1532 for (BasicBlock &BB : F) {
1533 for (Instruction &I : BB) {
David Neto862b7d82018-06-14 18:48:37 -04001534 if (auto *call = dyn_cast<CallInst>(&I)) {
1535 auto name = call->getCalledFunction()->getName();
Kévin Petitdf71de32019-04-09 14:09:50 +01001536 if (name == clspv::LiteralSamplerFunction()) {
David Neto862b7d82018-06-14 18:48:37 -04001537 // We've handled these constants elsewhere, so skip it.
1538 continue;
1539 }
Alan Baker202c8c72018-08-13 13:47:44 -04001540 if (name.startswith(clspv::ResourceAccessorFunction())) {
1541 continue;
1542 }
1543 if (name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001544 continue;
1545 }
Kévin Petit617a76d2019-04-04 13:54:16 +01001546 if (name.startswith(clspv::SPIRVOpIntrinsicFunction())) {
1547 // Skip the first operand that has the SPIR-V Opcode
1548 for (unsigned i = 1; i < I.getNumOperands(); i++) {
1549 if (isa<Constant>(I.getOperand(i)) &&
1550 !isa<GlobalValue>(I.getOperand(i))) {
1551 FindConstant(I.getOperand(i));
1552 }
1553 }
1554 continue;
1555 }
David Neto22f144c2017-06-12 14:26:21 -04001556 }
1557
1558 if (isa<AllocaInst>(I)) {
1559 // Alloca instruction has constant for the number of element. Ignore it.
1560 continue;
1561 } else if (isa<ShuffleVectorInst>(I)) {
1562 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1563 // Ignore constant for mask of shuffle vector instruction.
1564 if (i == 2) {
1565 continue;
1566 }
1567
1568 if (isa<Constant>(I.getOperand(i)) &&
1569 !isa<GlobalValue>(I.getOperand(i))) {
1570 FindConstant(I.getOperand(i));
1571 }
1572 }
1573
1574 continue;
1575 } else if (isa<InsertElementInst>(I)) {
1576 // Handle InsertElement with <4 x i8> specially.
1577 Type *CompositeTy = I.getOperand(0)->getType();
1578 if (is4xi8vec(CompositeTy)) {
1579 LLVMContext &Context = CompositeTy->getContext();
1580 if (isa<Constant>(I.getOperand(0))) {
1581 FindConstant(I.getOperand(0));
1582 }
1583
1584 if (isa<Constant>(I.getOperand(1))) {
1585 FindConstant(I.getOperand(1));
1586 }
1587
1588 // Add mask constant 0xFF.
1589 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1590 FindConstant(CstFF);
1591
1592 // Add shift amount constant.
1593 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
1594 uint64_t Idx = CI->getZExtValue();
1595 Constant *CstShiftAmount =
1596 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1597 FindConstant(CstShiftAmount);
1598 }
1599
1600 continue;
1601 }
1602
1603 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1604 // Ignore constant for index of InsertElement instruction.
1605 if (i == 2) {
1606 continue;
1607 }
1608
1609 if (isa<Constant>(I.getOperand(i)) &&
1610 !isa<GlobalValue>(I.getOperand(i))) {
1611 FindConstant(I.getOperand(i));
1612 }
1613 }
1614
1615 continue;
1616 } else if (isa<ExtractElementInst>(I)) {
1617 // Handle ExtractElement with <4 x i8> specially.
1618 Type *CompositeTy = I.getOperand(0)->getType();
1619 if (is4xi8vec(CompositeTy)) {
1620 LLVMContext &Context = CompositeTy->getContext();
1621 if (isa<Constant>(I.getOperand(0))) {
1622 FindConstant(I.getOperand(0));
1623 }
1624
1625 // Add mask constant 0xFF.
1626 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1627 FindConstant(CstFF);
1628
1629 // Add shift amount constant.
1630 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
1631 uint64_t Idx = CI->getZExtValue();
1632 Constant *CstShiftAmount =
1633 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1634 FindConstant(CstShiftAmount);
1635 } else {
1636 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
1637 FindConstant(Cst8);
1638 }
1639
1640 continue;
1641 }
1642
1643 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1644 // Ignore constant for index of ExtractElement instruction.
1645 if (i == 1) {
1646 continue;
1647 }
1648
1649 if (isa<Constant>(I.getOperand(i)) &&
1650 !isa<GlobalValue>(I.getOperand(i))) {
1651 FindConstant(I.getOperand(i));
1652 }
1653 }
1654
1655 continue;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001656 } else if ((Instruction::Xor == I.getOpcode()) &&
1657 I.getType()->isIntegerTy(1)) {
1658 // We special case for Xor where the type is i1 and one of the arguments
1659 // is a constant 1 (true), this is an OpLogicalNot in SPIR-V, and we
1660 // don't need the constant
David Neto22f144c2017-06-12 14:26:21 -04001661 bool foundConstantTrue = false;
1662 for (Use &Op : I.operands()) {
1663 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1664 auto CI = cast<ConstantInt>(Op);
1665
1666 if (CI->isZero() || foundConstantTrue) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05001667 // If we already found the true constant, we might (probably only
1668 // on -O0) have an OpLogicalNot which is taking a constant
1669 // argument, so discover it anyway.
David Neto22f144c2017-06-12 14:26:21 -04001670 FindConstant(Op);
1671 } else {
1672 foundConstantTrue = true;
1673 }
1674 }
1675 }
1676
1677 continue;
David Netod2de94a2017-08-28 17:27:47 -04001678 } else if (isa<TruncInst>(I)) {
alan-bakerb39c8262019-03-08 14:03:37 -05001679 // Special case if i8 is not generally handled.
1680 if (!clspv::Option::Int8Support()) {
1681 // For truncation to i8 we mask against 255.
1682 Type *ToTy = I.getType();
1683 if (8u == ToTy->getPrimitiveSizeInBits()) {
1684 LLVMContext &Context = ToTy->getContext();
1685 Constant *Cst255 =
1686 ConstantInt::get(Type::getInt32Ty(Context), 0xff);
1687 FindConstant(Cst255);
1688 }
David Netod2de94a2017-08-28 17:27:47 -04001689 }
Neil Henning39672102017-09-29 14:33:13 +01001690 } else if (isa<AtomicRMWInst>(I)) {
1691 LLVMContext &Context = I.getContext();
1692
1693 FindConstant(
1694 ConstantInt::get(Type::getInt32Ty(Context), spv::ScopeDevice));
1695 FindConstant(ConstantInt::get(
1696 Type::getInt32Ty(Context),
1697 spv::MemorySemanticsUniformMemoryMask |
1698 spv::MemorySemanticsSequentiallyConsistentMask));
David Neto22f144c2017-06-12 14:26:21 -04001699 }
1700
1701 for (Use &Op : I.operands()) {
1702 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1703 FindConstant(Op);
1704 }
1705 }
1706 }
1707 }
1708}
1709
1710void SPIRVProducerPass::FindConstant(Value *V) {
David Neto22f144c2017-06-12 14:26:21 -04001711 ValueList &CstList = getConstantList();
1712
David Netofb9a7972017-08-25 17:08:24 -04001713 // If V is already tracked, ignore it.
1714 if (0 != CstList.idFor(V)) {
David Neto22f144c2017-06-12 14:26:21 -04001715 return;
1716 }
1717
David Neto862b7d82018-06-14 18:48:37 -04001718 if (isa<GlobalValue>(V) && clspv::Option::ModuleConstantsInStorageBuffer()) {
1719 return;
1720 }
1721
David Neto22f144c2017-06-12 14:26:21 -04001722 Constant *Cst = cast<Constant>(V);
David Neto862b7d82018-06-14 18:48:37 -04001723 Type *CstTy = Cst->getType();
David Neto22f144c2017-06-12 14:26:21 -04001724
1725 // Handle constant with <4 x i8> type specially.
David Neto22f144c2017-06-12 14:26:21 -04001726 if (is4xi8vec(CstTy)) {
1727 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001728 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001729 }
1730 }
1731
1732 if (Cst->getNumOperands()) {
1733 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end(); I != E;
1734 ++I) {
1735 FindConstant(*I);
1736 }
1737
David Netofb9a7972017-08-25 17:08:24 -04001738 CstList.insert(Cst);
David Neto22f144c2017-06-12 14:26:21 -04001739 return;
1740 } else if (const ConstantDataSequential *CDS =
1741 dyn_cast<ConstantDataSequential>(Cst)) {
1742 // Add constants for each element to constant list.
1743 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
1744 Constant *EleCst = CDS->getElementAsConstant(i);
1745 FindConstant(EleCst);
1746 }
1747 }
1748
1749 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001750 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001751 }
1752}
1753
1754spv::StorageClass SPIRVProducerPass::GetStorageClass(unsigned AddrSpace) const {
1755 switch (AddrSpace) {
1756 default:
1757 llvm_unreachable("Unsupported OpenCL address space");
1758 case AddressSpace::Private:
1759 return spv::StorageClassFunction;
1760 case AddressSpace::Global:
David Neto22f144c2017-06-12 14:26:21 -04001761 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001762 case AddressSpace::Constant:
1763 return clspv::Option::ConstantArgsInUniformBuffer()
1764 ? spv::StorageClassUniform
1765 : spv::StorageClassStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -04001766 case AddressSpace::Input:
1767 return spv::StorageClassInput;
1768 case AddressSpace::Local:
1769 return spv::StorageClassWorkgroup;
1770 case AddressSpace::UniformConstant:
1771 return spv::StorageClassUniformConstant;
David Neto9ed8e2f2018-03-24 06:47:24 -07001772 case AddressSpace::Uniform:
David Netoe439d702018-03-23 13:14:08 -07001773 return spv::StorageClassUniform;
David Neto22f144c2017-06-12 14:26:21 -04001774 case AddressSpace::ModuleScopePrivate:
1775 return spv::StorageClassPrivate;
1776 }
1777}
1778
David Neto862b7d82018-06-14 18:48:37 -04001779spv::StorageClass
1780SPIRVProducerPass::GetStorageClassForArgKind(clspv::ArgKind arg_kind) const {
1781 switch (arg_kind) {
1782 case clspv::ArgKind::Buffer:
1783 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001784 case clspv::ArgKind::BufferUBO:
1785 return spv::StorageClassUniform;
David Neto862b7d82018-06-14 18:48:37 -04001786 case clspv::ArgKind::Pod:
1787 return clspv::Option::PodArgsInUniformBuffer()
1788 ? spv::StorageClassUniform
1789 : spv::StorageClassStorageBuffer;
1790 case clspv::ArgKind::Local:
1791 return spv::StorageClassWorkgroup;
1792 case clspv::ArgKind::ReadOnlyImage:
1793 case clspv::ArgKind::WriteOnlyImage:
1794 case clspv::ArgKind::Sampler:
1795 return spv::StorageClassUniformConstant;
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001796 default:
1797 llvm_unreachable("Unsupported storage class for argument kind");
David Neto862b7d82018-06-14 18:48:37 -04001798 }
1799}
1800
David Neto22f144c2017-06-12 14:26:21 -04001801spv::BuiltIn SPIRVProducerPass::GetBuiltin(StringRef Name) const {
1802 return StringSwitch<spv::BuiltIn>(Name)
1803 .Case("__spirv_GlobalInvocationId", spv::BuiltInGlobalInvocationId)
1804 .Case("__spirv_LocalInvocationId", spv::BuiltInLocalInvocationId)
1805 .Case("__spirv_WorkgroupSize", spv::BuiltInWorkgroupSize)
1806 .Case("__spirv_NumWorkgroups", spv::BuiltInNumWorkgroups)
1807 .Case("__spirv_WorkgroupId", spv::BuiltInWorkgroupId)
1808 .Default(spv::BuiltInMax);
1809}
1810
1811void SPIRVProducerPass::GenerateExtInstImport() {
1812 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1813 uint32_t &ExtInstImportID = getOpExtInstImportID();
1814
1815 //
1816 // Generate OpExtInstImport.
1817 //
1818 // Ops[0] ... Ops[n] = Name (Literal String)
David Neto22f144c2017-06-12 14:26:21 -04001819 ExtInstImportID = nextID;
David Neto87846742018-04-11 17:36:22 -04001820 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpExtInstImport, nextID++,
1821 MkString("GLSL.std.450")));
David Neto22f144c2017-06-12 14:26:21 -04001822}
1823
alan-bakerb6b09dc2018-11-08 16:59:28 -05001824void SPIRVProducerPass::GenerateSPIRVTypes(LLVMContext &Context,
1825 Module &module) {
David Neto22f144c2017-06-12 14:26:21 -04001826 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1827 ValueMapType &VMap = getValueMap();
1828 ValueMapType &AllocatedVMap = getAllocatedValueMap();
Alan Bakerfcda9482018-10-02 17:09:59 -04001829 const auto &DL = module.getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04001830
1831 // Map for OpTypeRuntimeArray. If argument has pointer type, 2 spirv type
1832 // instructions are generated. They are OpTypePointer and OpTypeRuntimeArray.
1833 DenseMap<Type *, uint32_t> OpRuntimeTyMap;
1834
1835 for (Type *Ty : getTypeList()) {
1836 // Update TypeMap with nextID for reference later.
1837 TypeMap[Ty] = nextID;
1838
1839 switch (Ty->getTypeID()) {
1840 default: {
1841 Ty->print(errs());
1842 llvm_unreachable("Unsupported type???");
1843 break;
1844 }
1845 case Type::MetadataTyID:
1846 case Type::LabelTyID: {
1847 // Ignore these types.
1848 break;
1849 }
1850 case Type::PointerTyID: {
1851 PointerType *PTy = cast<PointerType>(Ty);
1852 unsigned AddrSpace = PTy->getAddressSpace();
1853
1854 // For the purposes of our Vulkan SPIR-V type system, constant and global
1855 // are conflated.
1856 bool UseExistingOpTypePointer = false;
1857 if (AddressSpace::Constant == AddrSpace) {
Alan Bakerfcda9482018-10-02 17:09:59 -04001858 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1859 AddrSpace = AddressSpace::Global;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001860 // Check to see if we already created this type (for instance, if we
1861 // had a constant <type>* and a global <type>*, the type would be
1862 // created by one of these types, and shared by both).
Alan Bakerfcda9482018-10-02 17:09:59 -04001863 auto GlobalTy = PTy->getPointerElementType()->getPointerTo(AddrSpace);
1864 if (0 < TypeMap.count(GlobalTy)) {
1865 TypeMap[PTy] = TypeMap[GlobalTy];
1866 UseExistingOpTypePointer = true;
1867 break;
1868 }
David Neto22f144c2017-06-12 14:26:21 -04001869 }
1870 } else if (AddressSpace::Global == AddrSpace) {
Alan Bakerfcda9482018-10-02 17:09:59 -04001871 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1872 AddrSpace = AddressSpace::Constant;
David Neto22f144c2017-06-12 14:26:21 -04001873
alan-bakerb6b09dc2018-11-08 16:59:28 -05001874 // Check to see if we already created this type (for instance, if we
1875 // had a constant <type>* and a global <type>*, the type would be
1876 // created by one of these types, and shared by both).
1877 auto ConstantTy =
1878 PTy->getPointerElementType()->getPointerTo(AddrSpace);
Alan Bakerfcda9482018-10-02 17:09:59 -04001879 if (0 < TypeMap.count(ConstantTy)) {
1880 TypeMap[PTy] = TypeMap[ConstantTy];
1881 UseExistingOpTypePointer = true;
1882 }
David Neto22f144c2017-06-12 14:26:21 -04001883 }
1884 }
1885
David Neto862b7d82018-06-14 18:48:37 -04001886 const bool HasArgUser = true;
David Neto22f144c2017-06-12 14:26:21 -04001887
David Neto862b7d82018-06-14 18:48:37 -04001888 if (HasArgUser && !UseExistingOpTypePointer) {
David Neto22f144c2017-06-12 14:26:21 -04001889 //
1890 // Generate OpTypePointer.
1891 //
1892
1893 // OpTypePointer
1894 // Ops[0] = Storage Class
1895 // Ops[1] = Element Type ID
1896 SPIRVOperandList Ops;
1897
David Neto257c3892018-04-11 13:19:45 -04001898 Ops << MkNum(GetStorageClass(AddrSpace))
1899 << MkId(lookupType(PTy->getElementType()));
David Neto22f144c2017-06-12 14:26:21 -04001900
David Neto87846742018-04-11 17:36:22 -04001901 auto *Inst = new SPIRVInstruction(spv::OpTypePointer, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001902 SPIRVInstList.push_back(Inst);
1903 }
David Neto22f144c2017-06-12 14:26:21 -04001904 break;
1905 }
1906 case Type::StructTyID: {
David Neto22f144c2017-06-12 14:26:21 -04001907 StructType *STy = cast<StructType>(Ty);
1908
1909 // Handle sampler type.
1910 if (STy->isOpaque()) {
1911 if (STy->getName().equals("opencl.sampler_t")) {
1912 //
1913 // Generate OpTypeSampler
1914 //
1915 // Empty Ops.
1916 SPIRVOperandList Ops;
1917
David Neto87846742018-04-11 17:36:22 -04001918 auto *Inst = new SPIRVInstruction(spv::OpTypeSampler, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001919 SPIRVInstList.push_back(Inst);
1920 break;
alan-bakerf906d2b2019-12-10 11:26:23 -05001921 } else if (STy->getName().startswith("opencl.image1d_ro_t") ||
1922 STy->getName().startswith("opencl.image1d_wo_t") ||
1923 STy->getName().startswith("opencl.image2d_ro_t") ||
alan-bakerf67468c2019-11-25 15:51:49 -05001924 STy->getName().startswith("opencl.image2d_wo_t") ||
1925 STy->getName().startswith("opencl.image3d_ro_t") ||
1926 STy->getName().startswith("opencl.image3d_wo_t")) {
David Neto22f144c2017-06-12 14:26:21 -04001927 //
1928 // Generate OpTypeImage
1929 //
1930 // Ops[0] = Sampled Type ID
1931 // Ops[1] = Dim ID
1932 // Ops[2] = Depth (Literal Number)
1933 // Ops[3] = Arrayed (Literal Number)
1934 // Ops[4] = MS (Literal Number)
1935 // Ops[5] = Sampled (Literal Number)
1936 // Ops[6] = Image Format ID
1937 //
1938 SPIRVOperandList Ops;
1939
alan-bakerf67468c2019-11-25 15:51:49 -05001940 uint32_t ImageTyID = nextID++;
1941 uint32_t SampledTyID = 0;
1942 if (STy->getName().contains(".float")) {
1943 SampledTyID = lookupType(Type::getFloatTy(Context));
1944 } else if (STy->getName().contains(".uint")) {
1945 SampledTyID = lookupType(Type::getInt32Ty(Context));
1946 } else if (STy->getName().contains(".int")) {
1947 // Generate a signed 32-bit integer if necessary.
1948 if (int32ID == 0) {
1949 int32ID = nextID++;
1950 SPIRVOperandList intOps;
1951 intOps << MkNum(32);
1952 intOps << MkNum(1);
1953 auto signed_int =
1954 new SPIRVInstruction(spv::OpTypeInt, int32ID, intOps);
1955 SPIRVInstList.push_back(signed_int);
1956 }
1957 SampledTyID = int32ID;
1958
1959 // Generate a vec4 of the signed int if necessary.
1960 if (v4int32ID == 0) {
1961 v4int32ID = nextID++;
1962 SPIRVOperandList vecOps;
1963 vecOps << MkId(int32ID);
1964 vecOps << MkNum(4);
1965 auto int_vec =
1966 new SPIRVInstruction(spv::OpTypeVector, v4int32ID, vecOps);
1967 SPIRVInstList.push_back(int_vec);
1968 }
1969 } else {
1970 // This was likely an UndefValue.
1971 SampledTyID = lookupType(Type::getFloatTy(Context));
1972 }
David Neto257c3892018-04-11 13:19:45 -04001973 Ops << MkId(SampledTyID);
David Neto22f144c2017-06-12 14:26:21 -04001974
1975 spv::Dim DimID = spv::Dim2D;
alan-bakerf906d2b2019-12-10 11:26:23 -05001976 if (STy->getName().startswith("opencl.image1d_ro_t") ||
1977 STy->getName().startswith("opencl.image1d_wo_t")) {
1978 DimID = spv::Dim1D;
1979 } else if (STy->getName().startswith("opencl.image3d_ro_t") ||
1980 STy->getName().startswith("opencl.image3d_wo_t")) {
David Neto22f144c2017-06-12 14:26:21 -04001981 DimID = spv::Dim3D;
1982 }
David Neto257c3892018-04-11 13:19:45 -04001983 Ops << MkNum(DimID);
David Neto22f144c2017-06-12 14:26:21 -04001984
1985 // TODO: Set up Depth.
David Neto257c3892018-04-11 13:19:45 -04001986 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001987
1988 // TODO: Set up Arrayed.
David Neto257c3892018-04-11 13:19:45 -04001989 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001990
1991 // TODO: Set up MS.
David Neto257c3892018-04-11 13:19:45 -04001992 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001993
1994 // TODO: Set up Sampled.
1995 //
1996 // From Spec
1997 //
1998 // 0 indicates this is only known at run time, not at compile time
1999 // 1 indicates will be used with sampler
2000 // 2 indicates will be used without a sampler (a storage image)
2001 uint32_t Sampled = 1;
alan-bakerf67468c2019-11-25 15:51:49 -05002002 if (!STy->getName().contains(".sampled")) {
David Neto22f144c2017-06-12 14:26:21 -04002003 Sampled = 2;
2004 }
David Neto257c3892018-04-11 13:19:45 -04002005 Ops << MkNum(Sampled);
David Neto22f144c2017-06-12 14:26:21 -04002006
2007 // TODO: Set up Image Format.
David Neto257c3892018-04-11 13:19:45 -04002008 Ops << MkNum(spv::ImageFormatUnknown);
David Neto22f144c2017-06-12 14:26:21 -04002009
alan-bakerf67468c2019-11-25 15:51:49 -05002010 auto *Inst = new SPIRVInstruction(spv::OpTypeImage, ImageTyID, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002011 SPIRVInstList.push_back(Inst);
2012 break;
2013 }
2014 }
2015
2016 //
2017 // Generate OpTypeStruct
2018 //
2019 // Ops[0] ... Ops[n] = Member IDs
2020 SPIRVOperandList Ops;
2021
2022 for (auto *EleTy : STy->elements()) {
David Neto862b7d82018-06-14 18:48:37 -04002023 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04002024 }
2025
David Neto22f144c2017-06-12 14:26:21 -04002026 uint32_t STyID = nextID;
2027
alan-bakerb6b09dc2018-11-08 16:59:28 -05002028 auto *Inst = new SPIRVInstruction(spv::OpTypeStruct, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002029 SPIRVInstList.push_back(Inst);
2030
2031 // Generate OpMemberDecorate.
2032 auto DecoInsertPoint =
2033 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2034 [](SPIRVInstruction *Inst) -> bool {
2035 return Inst->getOpcode() != spv::OpDecorate &&
2036 Inst->getOpcode() != spv::OpMemberDecorate &&
2037 Inst->getOpcode() != spv::OpExtInstImport;
2038 });
2039
David Netoc463b372017-08-10 15:32:21 -04002040 const auto StructLayout = DL.getStructLayout(STy);
Alan Bakerfcda9482018-10-02 17:09:59 -04002041 // Search for the correct offsets if this type was remapped.
2042 std::vector<uint32_t> *offsets = nullptr;
2043 auto iter = RemappedUBOTypeOffsets.find(STy);
2044 if (iter != RemappedUBOTypeOffsets.end()) {
2045 offsets = &iter->second;
2046 }
David Netoc463b372017-08-10 15:32:21 -04002047
David Neto862b7d82018-06-14 18:48:37 -04002048 // #error TODO(dneto): Only do this if in TypesNeedingLayout.
David Neto22f144c2017-06-12 14:26:21 -04002049 for (unsigned MemberIdx = 0; MemberIdx < STy->getNumElements();
2050 MemberIdx++) {
2051 // Ops[0] = Structure Type ID
2052 // Ops[1] = Member Index(Literal Number)
2053 // Ops[2] = Decoration (Offset)
2054 // Ops[3] = Byte Offset (Literal Number)
2055 Ops.clear();
2056
David Neto257c3892018-04-11 13:19:45 -04002057 Ops << MkId(STyID) << MkNum(MemberIdx) << MkNum(spv::DecorationOffset);
David Neto22f144c2017-06-12 14:26:21 -04002058
alan-bakerb6b09dc2018-11-08 16:59:28 -05002059 auto ByteOffset =
2060 static_cast<uint32_t>(StructLayout->getElementOffset(MemberIdx));
Alan Bakerfcda9482018-10-02 17:09:59 -04002061 if (offsets) {
2062 ByteOffset = (*offsets)[MemberIdx];
2063 }
alan-bakerb6b09dc2018-11-08 16:59:28 -05002064 // const auto ByteOffset =
Alan Bakerfcda9482018-10-02 17:09:59 -04002065 // uint32_t(StructLayout->getElementOffset(MemberIdx));
David Neto257c3892018-04-11 13:19:45 -04002066 Ops << MkNum(ByteOffset);
David Neto22f144c2017-06-12 14:26:21 -04002067
David Neto87846742018-04-11 17:36:22 -04002068 auto *DecoInst = new SPIRVInstruction(spv::OpMemberDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002069 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04002070 }
2071
2072 // Generate OpDecorate.
David Neto862b7d82018-06-14 18:48:37 -04002073 if (StructTypesNeedingBlock.idFor(STy)) {
2074 Ops.clear();
2075 // Use Block decorations with StorageBuffer storage class.
2076 Ops << MkId(STyID) << MkNum(spv::DecorationBlock);
David Neto22f144c2017-06-12 14:26:21 -04002077
David Neto862b7d82018-06-14 18:48:37 -04002078 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
2079 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04002080 }
2081 break;
2082 }
2083 case Type::IntegerTyID: {
alan-baker0e64a592019-11-18 13:36:25 -05002084 uint32_t BitWidth = static_cast<uint32_t>(Ty->getPrimitiveSizeInBits());
David Neto22f144c2017-06-12 14:26:21 -04002085
2086 if (BitWidth == 1) {
David Netoef5ba2b2019-12-20 08:35:54 -05002087 auto *Inst = new SPIRVInstruction(spv::OpTypeBool, nextID++);
David Neto22f144c2017-06-12 14:26:21 -04002088 SPIRVInstList.push_back(Inst);
2089 } else {
alan-bakerb39c8262019-03-08 14:03:37 -05002090 if (!clspv::Option::Int8Support()) {
2091 // i8 is added to TypeMap as i32.
2092 // No matter what LLVM type is requested first, always alias the
2093 // second one's SPIR-V type to be the same as the one we generated
2094 // first.
2095 unsigned aliasToWidth = 0;
2096 if (BitWidth == 8) {
2097 aliasToWidth = 32;
2098 BitWidth = 32;
2099 } else if (BitWidth == 32) {
2100 aliasToWidth = 8;
2101 }
2102 if (aliasToWidth) {
2103 Type *otherType = Type::getIntNTy(Ty->getContext(), aliasToWidth);
2104 auto where = TypeMap.find(otherType);
2105 if (where == TypeMap.end()) {
2106 // Go ahead and make it, but also map the other type to it.
2107 TypeMap[otherType] = nextID;
2108 } else {
2109 // Alias this SPIR-V type the existing type.
2110 TypeMap[Ty] = where->second;
2111 break;
2112 }
David Neto391aeb12017-08-26 15:51:58 -04002113 }
David Neto22f144c2017-06-12 14:26:21 -04002114 }
2115
David Neto257c3892018-04-11 13:19:45 -04002116 SPIRVOperandList Ops;
2117 Ops << MkNum(BitWidth) << MkNum(0 /* not signed */);
David Neto22f144c2017-06-12 14:26:21 -04002118
2119 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002120 new SPIRVInstruction(spv::OpTypeInt, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002121 }
2122 break;
2123 }
2124 case Type::HalfTyID:
2125 case Type::FloatTyID:
2126 case Type::DoubleTyID: {
alan-baker0e64a592019-11-18 13:36:25 -05002127 uint32_t BitWidth = static_cast<uint32_t>(Ty->getPrimitiveSizeInBits());
James Price11010dc2019-12-19 13:53:09 -05002128 auto WidthOp = MkNum(BitWidth);
David Neto22f144c2017-06-12 14:26:21 -04002129
2130 SPIRVInstList.push_back(
David Netoef5ba2b2019-12-20 08:35:54 -05002131 new SPIRVInstruction(spv::OpTypeFloat, nextID++, std::move(WidthOp)));
David Neto22f144c2017-06-12 14:26:21 -04002132 break;
2133 }
2134 case Type::ArrayTyID: {
David Neto22f144c2017-06-12 14:26:21 -04002135 ArrayType *ArrTy = cast<ArrayType>(Ty);
David Neto862b7d82018-06-14 18:48:37 -04002136 const uint64_t Length = ArrTy->getArrayNumElements();
2137 if (Length == 0) {
2138 // By convention, map it to a RuntimeArray.
David Neto22f144c2017-06-12 14:26:21 -04002139
David Neto862b7d82018-06-14 18:48:37 -04002140 // Only generate the type once.
2141 // TODO(dneto): Can it ever be generated more than once?
2142 // Doesn't LLVM type uniqueness guarantee we'll only see this
2143 // once?
2144 Type *EleTy = ArrTy->getArrayElementType();
2145 if (OpRuntimeTyMap.count(EleTy) == 0) {
2146 uint32_t OpTypeRuntimeArrayID = nextID;
2147 OpRuntimeTyMap[Ty] = nextID;
David Neto22f144c2017-06-12 14:26:21 -04002148
David Neto862b7d82018-06-14 18:48:37 -04002149 //
2150 // Generate OpTypeRuntimeArray.
2151 //
David Neto22f144c2017-06-12 14:26:21 -04002152
David Neto862b7d82018-06-14 18:48:37 -04002153 // OpTypeRuntimeArray
2154 // Ops[0] = Element Type ID
2155 SPIRVOperandList Ops;
2156 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04002157
David Neto862b7d82018-06-14 18:48:37 -04002158 SPIRVInstList.push_back(
2159 new SPIRVInstruction(spv::OpTypeRuntimeArray, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002160
David Neto862b7d82018-06-14 18:48:37 -04002161 if (Hack_generate_runtime_array_stride_early) {
2162 // Generate OpDecorate.
2163 auto DecoInsertPoint = std::find_if(
2164 SPIRVInstList.begin(), SPIRVInstList.end(),
2165 [](SPIRVInstruction *Inst) -> bool {
2166 return Inst->getOpcode() != spv::OpDecorate &&
2167 Inst->getOpcode() != spv::OpMemberDecorate &&
2168 Inst->getOpcode() != spv::OpExtInstImport;
2169 });
David Neto22f144c2017-06-12 14:26:21 -04002170
David Neto862b7d82018-06-14 18:48:37 -04002171 // Ops[0] = Target ID
2172 // Ops[1] = Decoration (ArrayStride)
2173 // Ops[2] = Stride Number(Literal Number)
2174 Ops.clear();
David Neto85082642018-03-24 06:55:20 -07002175
David Neto862b7d82018-06-14 18:48:37 -04002176 Ops << MkId(OpTypeRuntimeArrayID)
2177 << MkNum(spv::DecorationArrayStride)
Alan Bakerfcda9482018-10-02 17:09:59 -04002178 << MkNum(static_cast<uint32_t>(GetTypeAllocSize(EleTy, DL)));
David Neto22f144c2017-06-12 14:26:21 -04002179
David Neto862b7d82018-06-14 18:48:37 -04002180 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
2181 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
2182 }
2183 }
David Neto22f144c2017-06-12 14:26:21 -04002184
David Neto862b7d82018-06-14 18:48:37 -04002185 } else {
David Neto22f144c2017-06-12 14:26:21 -04002186
David Neto862b7d82018-06-14 18:48:37 -04002187 //
2188 // Generate OpConstant and OpTypeArray.
2189 //
2190
2191 //
2192 // Generate OpConstant for array length.
2193 //
2194 // Ops[0] = Result Type ID
2195 // Ops[1] .. Ops[n] = Values LiteralNumber
2196 SPIRVOperandList Ops;
2197
2198 Type *LengthTy = Type::getInt32Ty(Context);
2199 uint32_t ResTyID = lookupType(LengthTy);
2200 Ops << MkId(ResTyID);
2201
2202 assert(Length < UINT32_MAX);
2203 Ops << MkNum(static_cast<uint32_t>(Length));
2204
2205 // Add constant for length to constant list.
2206 Constant *CstLength = ConstantInt::get(LengthTy, Length);
2207 AllocatedVMap[CstLength] = nextID;
2208 VMap[CstLength] = nextID;
2209 uint32_t LengthID = nextID;
2210
2211 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
2212 SPIRVInstList.push_back(CstInst);
2213
2214 // Remember to generate ArrayStride later
2215 getTypesNeedingArrayStride().insert(Ty);
2216
2217 //
2218 // Generate OpTypeArray.
2219 //
2220 // Ops[0] = Element Type ID
2221 // Ops[1] = Array Length Constant ID
2222 Ops.clear();
2223
2224 uint32_t EleTyID = lookupType(ArrTy->getElementType());
2225 Ops << MkId(EleTyID) << MkId(LengthID);
2226
2227 // Update TypeMap with nextID.
2228 TypeMap[Ty] = nextID;
2229
2230 auto *ArrayInst = new SPIRVInstruction(spv::OpTypeArray, nextID++, Ops);
2231 SPIRVInstList.push_back(ArrayInst);
2232 }
David Neto22f144c2017-06-12 14:26:21 -04002233 break;
2234 }
2235 case Type::VectorTyID: {
alan-bakerb39c8262019-03-08 14:03:37 -05002236 // <4 x i8> is changed to i32 if i8 is not generally supported.
2237 if (!clspv::Option::Int8Support() &&
2238 Ty->getVectorElementType() == Type::getInt8Ty(Context)) {
David Neto22f144c2017-06-12 14:26:21 -04002239 if (Ty->getVectorNumElements() == 4) {
2240 TypeMap[Ty] = lookupType(Ty->getVectorElementType());
2241 break;
2242 } else {
2243 Ty->print(errs());
2244 llvm_unreachable("Support above i8 vector type");
2245 }
2246 }
2247
2248 // Ops[0] = Component Type ID
2249 // Ops[1] = Component Count (Literal Number)
David Neto257c3892018-04-11 13:19:45 -04002250 SPIRVOperandList Ops;
2251 Ops << MkId(lookupType(Ty->getVectorElementType()))
2252 << MkNum(Ty->getVectorNumElements());
David Neto22f144c2017-06-12 14:26:21 -04002253
alan-bakerb6b09dc2018-11-08 16:59:28 -05002254 SPIRVInstruction *inst =
2255 new SPIRVInstruction(spv::OpTypeVector, nextID++, Ops);
David Netoc6f3ab22018-04-06 18:02:31 -04002256 SPIRVInstList.push_back(inst);
David Neto22f144c2017-06-12 14:26:21 -04002257 break;
2258 }
2259 case Type::VoidTyID: {
David Netoef5ba2b2019-12-20 08:35:54 -05002260 auto *Inst = new SPIRVInstruction(spv::OpTypeVoid, nextID++);
David Neto22f144c2017-06-12 14:26:21 -04002261 SPIRVInstList.push_back(Inst);
2262 break;
2263 }
2264 case Type::FunctionTyID: {
2265 // Generate SPIRV instruction for function type.
2266 FunctionType *FTy = cast<FunctionType>(Ty);
2267
2268 // Ops[0] = Return Type ID
2269 // Ops[1] ... Ops[n] = Parameter Type IDs
2270 SPIRVOperandList Ops;
2271
2272 // Find SPIRV instruction for return type
David Netoc6f3ab22018-04-06 18:02:31 -04002273 Ops << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04002274
2275 // Find SPIRV instructions for parameter types
2276 for (unsigned k = 0; k < FTy->getNumParams(); k++) {
2277 // Find SPIRV instruction for parameter type.
2278 auto ParamTy = FTy->getParamType(k);
2279 if (ParamTy->isPointerTy()) {
2280 auto PointeeTy = ParamTy->getPointerElementType();
2281 if (PointeeTy->isStructTy() &&
2282 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
2283 ParamTy = PointeeTy;
2284 }
2285 }
2286
David Netoc6f3ab22018-04-06 18:02:31 -04002287 Ops << MkId(lookupType(ParamTy));
David Neto22f144c2017-06-12 14:26:21 -04002288 }
2289
David Neto87846742018-04-11 17:36:22 -04002290 auto *Inst = new SPIRVInstruction(spv::OpTypeFunction, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002291 SPIRVInstList.push_back(Inst);
2292 break;
2293 }
2294 }
2295 }
2296
2297 // Generate OpTypeSampledImage.
alan-bakerabd82722019-12-03 17:14:51 -05002298 for (auto &ImgTy : getImageTypeList()) {
David Neto22f144c2017-06-12 14:26:21 -04002299 //
2300 // Generate OpTypeSampledImage.
2301 //
2302 // Ops[0] = Image Type ID
2303 //
2304 SPIRVOperandList Ops;
2305
David Netoc6f3ab22018-04-06 18:02:31 -04002306 Ops << MkId(TypeMap[ImgTy]);
David Neto22f144c2017-06-12 14:26:21 -04002307
alan-bakerabd82722019-12-03 17:14:51 -05002308 // Update the image type map.
2309 getImageTypeMap()[ImgTy] = nextID;
David Neto22f144c2017-06-12 14:26:21 -04002310
David Neto87846742018-04-11 17:36:22 -04002311 auto *Inst = new SPIRVInstruction(spv::OpTypeSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002312 SPIRVInstList.push_back(Inst);
2313 }
David Netoc6f3ab22018-04-06 18:02:31 -04002314
2315 // Generate types for pointer-to-local arguments.
Alan Baker202c8c72018-08-13 13:47:44 -04002316 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
2317 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002318 LocalArgInfo &arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04002319
2320 // Generate the spec constant.
2321 SPIRVOperandList Ops;
2322 Ops << MkId(lookupType(Type::getInt32Ty(Context))) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04002323 SPIRVInstList.push_back(
2324 new SPIRVInstruction(spv::OpSpecConstant, arg_info.array_size_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002325
2326 // Generate the array type.
2327 Ops.clear();
2328 // The element type must have been created.
2329 uint32_t elem_ty_id = lookupType(arg_info.elem_type);
2330 assert(elem_ty_id);
2331 Ops << MkId(elem_ty_id) << MkId(arg_info.array_size_id);
2332
2333 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002334 new SPIRVInstruction(spv::OpTypeArray, arg_info.array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002335
2336 Ops.clear();
2337 Ops << MkNum(spv::StorageClassWorkgroup) << MkId(arg_info.array_type_id);
David Neto87846742018-04-11 17:36:22 -04002338 SPIRVInstList.push_back(new SPIRVInstruction(
2339 spv::OpTypePointer, arg_info.ptr_array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002340 }
David Neto22f144c2017-06-12 14:26:21 -04002341}
2342
2343void SPIRVProducerPass::GenerateSPIRVConstants() {
2344 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2345 ValueMapType &VMap = getValueMap();
2346 ValueMapType &AllocatedVMap = getAllocatedValueMap();
2347 ValueList &CstList = getConstantList();
David Neto482550a2018-03-24 05:21:07 -07002348 const bool hack_undef = clspv::Option::HackUndef();
David Neto22f144c2017-06-12 14:26:21 -04002349
2350 for (uint32_t i = 0; i < CstList.size(); i++) {
David Netofb9a7972017-08-25 17:08:24 -04002351 // UniqueVector ids are 1-based.
alan-bakerb6b09dc2018-11-08 16:59:28 -05002352 Constant *Cst = cast<Constant>(CstList[i + 1]);
David Neto22f144c2017-06-12 14:26:21 -04002353
2354 // OpTypeArray's constant was already generated.
David Netofb9a7972017-08-25 17:08:24 -04002355 if (AllocatedVMap.find_as(Cst) != AllocatedVMap.end()) {
David Neto22f144c2017-06-12 14:26:21 -04002356 continue;
2357 }
2358
David Netofb9a7972017-08-25 17:08:24 -04002359 // Set ValueMap with nextID for reference later.
David Neto22f144c2017-06-12 14:26:21 -04002360 VMap[Cst] = nextID;
2361
2362 //
2363 // Generate OpConstant.
2364 //
2365
2366 // Ops[0] = Result Type ID
2367 // Ops[1] .. Ops[n] = Values LiteralNumber
2368 SPIRVOperandList Ops;
2369
David Neto257c3892018-04-11 13:19:45 -04002370 Ops << MkId(lookupType(Cst->getType()));
David Neto22f144c2017-06-12 14:26:21 -04002371
2372 std::vector<uint32_t> LiteralNum;
David Neto22f144c2017-06-12 14:26:21 -04002373 spv::Op Opcode = spv::OpNop;
2374
2375 if (isa<UndefValue>(Cst)) {
2376 // Ops[0] = Result Type ID
David Netoc66b3352017-10-20 14:28:46 -04002377 Opcode = spv::OpUndef;
Alan Baker9bf93fb2018-08-28 16:59:26 -04002378 if (hack_undef && IsTypeNullable(Cst->getType())) {
2379 Opcode = spv::OpConstantNull;
David Netoc66b3352017-10-20 14:28:46 -04002380 }
David Neto22f144c2017-06-12 14:26:21 -04002381 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(Cst)) {
2382 unsigned BitWidth = CI->getBitWidth();
2383 if (BitWidth == 1) {
2384 // If the bitwidth of constant is 1, generate OpConstantTrue or
2385 // OpConstantFalse.
2386 if (CI->getZExtValue()) {
2387 // Ops[0] = Result Type ID
2388 Opcode = spv::OpConstantTrue;
2389 } else {
2390 // Ops[0] = Result Type ID
2391 Opcode = spv::OpConstantFalse;
2392 }
David Neto22f144c2017-06-12 14:26:21 -04002393 } else {
2394 auto V = CI->getZExtValue();
2395 LiteralNum.push_back(V & 0xFFFFFFFF);
2396
2397 if (BitWidth > 32) {
2398 LiteralNum.push_back(V >> 32);
2399 }
2400
2401 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002402
David Neto257c3892018-04-11 13:19:45 -04002403 Ops << MkInteger(LiteralNum);
David Neto22f144c2017-06-12 14:26:21 -04002404 }
2405 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Cst)) {
2406 uint64_t FPVal = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
2407 Type *CFPTy = CFP->getType();
2408 if (CFPTy->isFloatTy()) {
2409 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
Kévin Petit02ee34e2019-04-04 19:03:22 +01002410 } else if (CFPTy->isDoubleTy()) {
2411 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
2412 LiteralNum.push_back(FPVal >> 32);
David Neto22f144c2017-06-12 14:26:21 -04002413 } else {
2414 CFPTy->print(errs());
2415 llvm_unreachable("Implement this ConstantFP Type");
2416 }
2417
2418 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002419
David Neto257c3892018-04-11 13:19:45 -04002420 Ops << MkFloat(LiteralNum);
David Neto22f144c2017-06-12 14:26:21 -04002421 } else if (isa<ConstantDataSequential>(Cst) &&
2422 cast<ConstantDataSequential>(Cst)->isString()) {
2423 Cst->print(errs());
2424 llvm_unreachable("Implement this Constant");
2425
2426 } else if (const ConstantDataSequential *CDS =
2427 dyn_cast<ConstantDataSequential>(Cst)) {
David Neto49351ac2017-08-26 17:32:20 -04002428 // Let's convert <4 x i8> constant to int constant specially.
2429 // This case occurs when all the values are specified as constant
2430 // ints.
2431 Type *CstTy = Cst->getType();
2432 if (is4xi8vec(CstTy)) {
2433 LLVMContext &Context = CstTy->getContext();
2434
2435 //
2436 // Generate OpConstant with OpTypeInt 32 0.
2437 //
Neil Henning39672102017-09-29 14:33:13 +01002438 uint32_t IntValue = 0;
2439 for (unsigned k = 0; k < 4; k++) {
2440 const uint64_t Val = CDS->getElementAsInteger(k);
David Neto49351ac2017-08-26 17:32:20 -04002441 IntValue = (IntValue << 8) | (Val & 0xffu);
2442 }
2443
2444 Type *i32 = Type::getInt32Ty(Context);
2445 Constant *CstInt = ConstantInt::get(i32, IntValue);
2446 // If this constant is already registered on VMap, use it.
2447 if (VMap.count(CstInt)) {
2448 uint32_t CstID = VMap[CstInt];
2449 VMap[Cst] = CstID;
2450 continue;
2451 }
2452
David Neto257c3892018-04-11 13:19:45 -04002453 Ops << MkNum(IntValue);
David Neto49351ac2017-08-26 17:32:20 -04002454
David Neto87846742018-04-11 17:36:22 -04002455 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto49351ac2017-08-26 17:32:20 -04002456 SPIRVInstList.push_back(CstInst);
2457
2458 continue;
2459 }
2460
2461 // A normal constant-data-sequential case.
David Neto22f144c2017-06-12 14:26:21 -04002462 for (unsigned k = 0; k < CDS->getNumElements(); k++) {
2463 Constant *EleCst = CDS->getElementAsConstant(k);
2464 uint32_t EleCstID = VMap[EleCst];
David Neto257c3892018-04-11 13:19:45 -04002465 Ops << MkId(EleCstID);
David Neto22f144c2017-06-12 14:26:21 -04002466 }
2467
2468 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002469 } else if (const ConstantAggregate *CA = dyn_cast<ConstantAggregate>(Cst)) {
2470 // Let's convert <4 x i8> constant to int constant specially.
David Neto49351ac2017-08-26 17:32:20 -04002471 // This case occurs when at least one of the values is an undef.
David Neto22f144c2017-06-12 14:26:21 -04002472 Type *CstTy = Cst->getType();
2473 if (is4xi8vec(CstTy)) {
2474 LLVMContext &Context = CstTy->getContext();
2475
2476 //
2477 // Generate OpConstant with OpTypeInt 32 0.
2478 //
Neil Henning39672102017-09-29 14:33:13 +01002479 uint32_t IntValue = 0;
David Neto22f144c2017-06-12 14:26:21 -04002480 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end();
2481 I != E; ++I) {
2482 uint64_t Val = 0;
alan-bakerb6b09dc2018-11-08 16:59:28 -05002483 const Value *CV = *I;
Neil Henning39672102017-09-29 14:33:13 +01002484 if (auto *CI2 = dyn_cast<ConstantInt>(CV)) {
2485 Val = CI2->getZExtValue();
David Neto22f144c2017-06-12 14:26:21 -04002486 }
David Neto49351ac2017-08-26 17:32:20 -04002487 IntValue = (IntValue << 8) | (Val & 0xffu);
David Neto22f144c2017-06-12 14:26:21 -04002488 }
2489
David Neto49351ac2017-08-26 17:32:20 -04002490 Type *i32 = Type::getInt32Ty(Context);
2491 Constant *CstInt = ConstantInt::get(i32, IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002492 // If this constant is already registered on VMap, use it.
2493 if (VMap.count(CstInt)) {
2494 uint32_t CstID = VMap[CstInt];
2495 VMap[Cst] = CstID;
David Neto19a1bad2017-08-25 15:01:41 -04002496 continue;
David Neto22f144c2017-06-12 14:26:21 -04002497 }
2498
David Neto257c3892018-04-11 13:19:45 -04002499 Ops << MkNum(IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002500
David Neto87846742018-04-11 17:36:22 -04002501 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002502 SPIRVInstList.push_back(CstInst);
2503
David Neto19a1bad2017-08-25 15:01:41 -04002504 continue;
David Neto22f144c2017-06-12 14:26:21 -04002505 }
2506
2507 // We use a constant composite in SPIR-V for our constant aggregate in
2508 // LLVM.
2509 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002510
2511 for (unsigned k = 0; k < CA->getNumOperands(); k++) {
2512 // Look up the ID of the element of this aggregate (which we will
2513 // previously have created a constant for).
2514 uint32_t ElementConstantID = VMap[CA->getAggregateElement(k)];
2515
2516 // And add an operand to the composite we are constructing
David Neto257c3892018-04-11 13:19:45 -04002517 Ops << MkId(ElementConstantID);
David Neto22f144c2017-06-12 14:26:21 -04002518 }
2519 } else if (Cst->isNullValue()) {
2520 Opcode = spv::OpConstantNull;
David Neto22f144c2017-06-12 14:26:21 -04002521 } else {
2522 Cst->print(errs());
2523 llvm_unreachable("Unsupported Constant???");
2524 }
2525
alan-baker5b86ed72019-02-15 08:26:50 -05002526 if (Opcode == spv::OpConstantNull && Cst->getType()->isPointerTy()) {
2527 // Null pointer requires variable pointers.
2528 setVariablePointersCapabilities(Cst->getType()->getPointerAddressSpace());
2529 }
2530
David Neto87846742018-04-11 17:36:22 -04002531 auto *CstInst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002532 SPIRVInstList.push_back(CstInst);
2533 }
2534}
2535
2536void SPIRVProducerPass::GenerateSamplers(Module &M) {
2537 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
David Neto22f144c2017-06-12 14:26:21 -04002538
alan-bakerb6b09dc2018-11-08 16:59:28 -05002539 auto &sampler_map = getSamplerMap();
alan-baker09cb9802019-12-10 13:16:27 -05002540 SamplerLiteralToIDMap.clear();
David Neto862b7d82018-06-14 18:48:37 -04002541 DenseMap<unsigned, unsigned> SamplerLiteralToDescriptorSetMap;
2542 DenseMap<unsigned, unsigned> SamplerLiteralToBindingMap;
David Neto22f144c2017-06-12 14:26:21 -04002543
David Neto862b7d82018-06-14 18:48:37 -04002544 // We might have samplers in the sampler map that are not used
2545 // in the translation unit. We need to allocate variables
2546 // for them and bindings too.
2547 DenseSet<unsigned> used_bindings;
David Neto22f144c2017-06-12 14:26:21 -04002548
Kévin Petitdf71de32019-04-09 14:09:50 +01002549 auto *var_fn = M.getFunction(clspv::LiteralSamplerFunction());
alan-baker09cb9802019-12-10 13:16:27 -05002550 // Return if there are no literal samplers.
alan-bakerb6b09dc2018-11-08 16:59:28 -05002551 if (!var_fn)
2552 return;
alan-baker09cb9802019-12-10 13:16:27 -05002553
David Neto862b7d82018-06-14 18:48:37 -04002554 for (auto user : var_fn->users()) {
2555 // Populate SamplerLiteralToDescriptorSetMap and
2556 // SamplerLiteralToBindingMap.
2557 //
2558 // Look for calls like
2559 // call %opencl.sampler_t addrspace(2)*
2560 // @clspv.sampler.var.literal(
2561 // i32 descriptor,
2562 // i32 binding,
alan-baker09cb9802019-12-10 13:16:27 -05002563 // i32 (index-into-sampler-map|sampler_mask))
alan-bakerb6b09dc2018-11-08 16:59:28 -05002564 if (auto *call = dyn_cast<CallInst>(user)) {
alan-baker09cb9802019-12-10 13:16:27 -05002565 const auto third_param = static_cast<unsigned>(
alan-bakerb6b09dc2018-11-08 16:59:28 -05002566 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
alan-baker09cb9802019-12-10 13:16:27 -05002567 auto sampler_value = third_param;
2568 if (clspv::Option::UseSamplerMap()) {
2569 if (third_param >= sampler_map.size()) {
2570 errs() << "Out of bounds index to sampler map: " << third_param;
2571 llvm_unreachable("bad sampler init: out of bounds");
2572 }
2573 sampler_value = sampler_map[third_param].first;
David Neto862b7d82018-06-14 18:48:37 -04002574 }
2575
David Neto862b7d82018-06-14 18:48:37 -04002576 const auto descriptor_set = static_cast<unsigned>(
2577 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
2578 const auto binding = static_cast<unsigned>(
2579 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
2580
2581 SamplerLiteralToDescriptorSetMap[sampler_value] = descriptor_set;
2582 SamplerLiteralToBindingMap[sampler_value] = binding;
2583 used_bindings.insert(binding);
2584 }
2585 }
2586
alan-baker09cb9802019-12-10 13:16:27 -05002587 DenseSet<size_t> seen;
2588 for (auto user : var_fn->users()) {
2589 if (!isa<CallInst>(user))
2590 continue;
2591
2592 auto call = cast<CallInst>(user);
2593 const unsigned third_param = static_cast<unsigned>(
2594 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
2595
2596 // Already allocated a variable for this value.
2597 if (!seen.insert(third_param).second)
2598 continue;
2599
2600 auto sampler_value = third_param;
2601 if (clspv::Option::UseSamplerMap()) {
2602 sampler_value = sampler_map[third_param].first;
2603 }
2604
David Neto22f144c2017-06-12 14:26:21 -04002605 // Generate OpVariable.
2606 //
2607 // GIDOps[0] : Result Type ID
2608 // GIDOps[1] : Storage Class
2609 SPIRVOperandList Ops;
2610
David Neto257c3892018-04-11 13:19:45 -04002611 Ops << MkId(lookupType(SamplerTy))
2612 << MkNum(spv::StorageClassUniformConstant);
David Neto22f144c2017-06-12 14:26:21 -04002613
David Neto862b7d82018-06-14 18:48:37 -04002614 auto sampler_var_id = nextID++;
2615 auto *Inst = new SPIRVInstruction(spv::OpVariable, sampler_var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002616 SPIRVInstList.push_back(Inst);
2617
alan-baker09cb9802019-12-10 13:16:27 -05002618 SamplerLiteralToIDMap[sampler_value] = sampler_var_id;
David Neto22f144c2017-06-12 14:26:21 -04002619
2620 // Find Insert Point for OpDecorate.
2621 auto DecoInsertPoint =
2622 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2623 [](SPIRVInstruction *Inst) -> bool {
2624 return Inst->getOpcode() != spv::OpDecorate &&
2625 Inst->getOpcode() != spv::OpMemberDecorate &&
2626 Inst->getOpcode() != spv::OpExtInstImport;
2627 });
2628
2629 // Ops[0] = Target ID
2630 // Ops[1] = Decoration (DescriptorSet)
2631 // Ops[2] = LiteralNumber according to Decoration
2632 Ops.clear();
2633
David Neto862b7d82018-06-14 18:48:37 -04002634 unsigned descriptor_set;
2635 unsigned binding;
alan-baker09cb9802019-12-10 13:16:27 -05002636 if (SamplerLiteralToBindingMap.find(sampler_value) ==
alan-bakerb6b09dc2018-11-08 16:59:28 -05002637 SamplerLiteralToBindingMap.end()) {
David Neto862b7d82018-06-14 18:48:37 -04002638 // This sampler is not actually used. Find the next one.
2639 for (binding = 0; used_bindings.count(binding); binding++)
2640 ;
2641 descriptor_set = 0; // Literal samplers always use descriptor set 0.
2642 used_bindings.insert(binding);
2643 } else {
alan-baker09cb9802019-12-10 13:16:27 -05002644 descriptor_set = SamplerLiteralToDescriptorSetMap[sampler_value];
2645 binding = SamplerLiteralToBindingMap[sampler_value];
alan-bakercff80152019-06-15 00:38:00 -04002646
alan-baker09cb9802019-12-10 13:16:27 -05002647 version0::DescriptorMapEntry::SamplerData sampler_data = {sampler_value};
alan-bakercff80152019-06-15 00:38:00 -04002648 descriptorMapEntries->emplace_back(std::move(sampler_data),
2649 descriptor_set, binding);
David Neto862b7d82018-06-14 18:48:37 -04002650 }
2651
2652 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationDescriptorSet)
2653 << MkNum(descriptor_set);
David Neto22f144c2017-06-12 14:26:21 -04002654
David Neto87846742018-04-11 17:36:22 -04002655 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002656 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
2657
2658 // Ops[0] = Target ID
2659 // Ops[1] = Decoration (Binding)
2660 // Ops[2] = LiteralNumber according to Decoration
2661 Ops.clear();
David Neto862b7d82018-06-14 18:48:37 -04002662 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationBinding)
2663 << MkNum(binding);
David Neto22f144c2017-06-12 14:26:21 -04002664
David Neto87846742018-04-11 17:36:22 -04002665 auto *BindDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002666 SPIRVInstList.insert(DecoInsertPoint, BindDecoInst);
2667 }
David Neto862b7d82018-06-14 18:48:37 -04002668}
David Neto22f144c2017-06-12 14:26:21 -04002669
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01002670void SPIRVProducerPass::GenerateResourceVars(Module &) {
David Neto862b7d82018-06-14 18:48:37 -04002671 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2672 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04002673
David Neto862b7d82018-06-14 18:48:37 -04002674 // Generate variables. Make one for each of resource var info object.
2675 for (auto *info : ModuleOrderedResourceVars) {
2676 Type *type = info->var_fn->getReturnType();
2677 // Remap the address space for opaque types.
2678 switch (info->arg_kind) {
2679 case clspv::ArgKind::Sampler:
2680 case clspv::ArgKind::ReadOnlyImage:
2681 case clspv::ArgKind::WriteOnlyImage:
2682 type = PointerType::get(type->getPointerElementType(),
2683 clspv::AddressSpace::UniformConstant);
2684 break;
2685 default:
2686 break;
2687 }
David Neto22f144c2017-06-12 14:26:21 -04002688
David Neto862b7d82018-06-14 18:48:37 -04002689 info->var_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04002690
David Neto862b7d82018-06-14 18:48:37 -04002691 const auto type_id = lookupType(type);
2692 const auto sc = GetStorageClassForArgKind(info->arg_kind);
2693 SPIRVOperandList Ops;
2694 Ops << MkId(type_id) << MkNum(sc);
David Neto22f144c2017-06-12 14:26:21 -04002695
David Neto862b7d82018-06-14 18:48:37 -04002696 auto *Inst = new SPIRVInstruction(spv::OpVariable, info->var_id, Ops);
2697 SPIRVInstList.push_back(Inst);
2698
2699 // Map calls to the variable-builtin-function.
2700 for (auto &U : info->var_fn->uses()) {
2701 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
2702 const auto set = unsigned(
2703 dyn_cast<ConstantInt>(call->getOperand(0))->getZExtValue());
2704 const auto binding = unsigned(
2705 dyn_cast<ConstantInt>(call->getOperand(1))->getZExtValue());
2706 if (set == info->descriptor_set && binding == info->binding) {
2707 switch (info->arg_kind) {
2708 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002709 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002710 case clspv::ArgKind::Pod:
2711 // The call maps to the variable directly.
2712 VMap[call] = info->var_id;
2713 break;
2714 case clspv::ArgKind::Sampler:
2715 case clspv::ArgKind::ReadOnlyImage:
2716 case clspv::ArgKind::WriteOnlyImage:
2717 // The call maps to a load we generate later.
2718 ResourceVarDeferredLoadCalls[call] = info->var_id;
2719 break;
2720 default:
2721 llvm_unreachable("Unhandled arg kind");
2722 }
2723 }
David Neto22f144c2017-06-12 14:26:21 -04002724 }
David Neto862b7d82018-06-14 18:48:37 -04002725 }
2726 }
David Neto22f144c2017-06-12 14:26:21 -04002727
David Neto862b7d82018-06-14 18:48:37 -04002728 // Generate associated decorations.
David Neto22f144c2017-06-12 14:26:21 -04002729
David Neto862b7d82018-06-14 18:48:37 -04002730 // Find Insert Point for OpDecorate.
2731 auto DecoInsertPoint =
2732 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2733 [](SPIRVInstruction *Inst) -> bool {
2734 return Inst->getOpcode() != spv::OpDecorate &&
2735 Inst->getOpcode() != spv::OpMemberDecorate &&
2736 Inst->getOpcode() != spv::OpExtInstImport;
2737 });
2738
2739 SPIRVOperandList Ops;
2740 for (auto *info : ModuleOrderedResourceVars) {
2741 // Decorate with DescriptorSet and Binding.
2742 Ops.clear();
2743 Ops << MkId(info->var_id) << MkNum(spv::DecorationDescriptorSet)
2744 << MkNum(info->descriptor_set);
2745 SPIRVInstList.insert(DecoInsertPoint,
2746 new SPIRVInstruction(spv::OpDecorate, Ops));
2747
2748 Ops.clear();
2749 Ops << MkId(info->var_id) << MkNum(spv::DecorationBinding)
2750 << MkNum(info->binding);
2751 SPIRVInstList.insert(DecoInsertPoint,
2752 new SPIRVInstruction(spv::OpDecorate, Ops));
2753
alan-bakere9308012019-03-15 10:25:13 -04002754 if (info->coherent) {
2755 // Decorate with Coherent if required for the variable.
2756 Ops.clear();
2757 Ops << MkId(info->var_id) << MkNum(spv::DecorationCoherent);
2758 SPIRVInstList.insert(DecoInsertPoint,
2759 new SPIRVInstruction(spv::OpDecorate, Ops));
2760 }
2761
David Neto862b7d82018-06-14 18:48:37 -04002762 // Generate NonWritable and NonReadable
2763 switch (info->arg_kind) {
2764 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002765 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002766 if (info->var_fn->getReturnType()->getPointerAddressSpace() ==
2767 clspv::AddressSpace::Constant) {
2768 Ops.clear();
2769 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonWritable);
2770 SPIRVInstList.insert(DecoInsertPoint,
2771 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002772 }
David Neto862b7d82018-06-14 18:48:37 -04002773 break;
David Neto862b7d82018-06-14 18:48:37 -04002774 case clspv::ArgKind::WriteOnlyImage:
2775 Ops.clear();
2776 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonReadable);
2777 SPIRVInstList.insert(DecoInsertPoint,
2778 new SPIRVInstruction(spv::OpDecorate, Ops));
2779 break;
2780 default:
2781 break;
David Neto22f144c2017-06-12 14:26:21 -04002782 }
2783 }
2784}
2785
2786void SPIRVProducerPass::GenerateGlobalVar(GlobalVariable &GV) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002787 Module &M = *GV.getParent();
David Neto22f144c2017-06-12 14:26:21 -04002788 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2789 ValueMapType &VMap = getValueMap();
2790 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
David Neto85082642018-03-24 06:55:20 -07002791 const DataLayout &DL = GV.getParent()->getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04002792
2793 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
2794 Type *Ty = GV.getType();
2795 PointerType *PTy = cast<PointerType>(Ty);
2796
2797 uint32_t InitializerID = 0;
2798
2799 // Workgroup size is handled differently (it goes into a constant)
2800 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2801 std::vector<bool> HasMDVec;
2802 uint32_t PrevXDimCst = 0xFFFFFFFF;
2803 uint32_t PrevYDimCst = 0xFFFFFFFF;
2804 uint32_t PrevZDimCst = 0xFFFFFFFF;
2805 for (Function &Func : *GV.getParent()) {
2806 if (Func.isDeclaration()) {
2807 continue;
2808 }
2809
2810 // We only need to check kernels.
2811 if (Func.getCallingConv() != CallingConv::SPIR_KERNEL) {
2812 continue;
2813 }
2814
2815 if (const MDNode *MD =
2816 dyn_cast<Function>(&Func)->getMetadata("reqd_work_group_size")) {
2817 uint32_t CurXDimCst = static_cast<uint32_t>(
2818 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
2819 uint32_t CurYDimCst = static_cast<uint32_t>(
2820 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
2821 uint32_t CurZDimCst = static_cast<uint32_t>(
2822 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
2823
2824 if (PrevXDimCst == 0xFFFFFFFF && PrevYDimCst == 0xFFFFFFFF &&
2825 PrevZDimCst == 0xFFFFFFFF) {
2826 PrevXDimCst = CurXDimCst;
2827 PrevYDimCst = CurYDimCst;
2828 PrevZDimCst = CurZDimCst;
2829 } else if (CurXDimCst != PrevXDimCst || CurYDimCst != PrevYDimCst ||
2830 CurZDimCst != PrevZDimCst) {
2831 llvm_unreachable(
2832 "reqd_work_group_size must be the same across all kernels");
2833 } else {
2834 continue;
2835 }
2836
2837 //
2838 // Generate OpConstantComposite.
2839 //
2840 // Ops[0] : Result Type ID
2841 // Ops[1] : Constant size for x dimension.
2842 // Ops[2] : Constant size for y dimension.
2843 // Ops[3] : Constant size for z dimension.
2844 SPIRVOperandList Ops;
2845
2846 uint32_t XDimCstID =
2847 VMap[mdconst::extract<ConstantInt>(MD->getOperand(0))];
2848 uint32_t YDimCstID =
2849 VMap[mdconst::extract<ConstantInt>(MD->getOperand(1))];
2850 uint32_t ZDimCstID =
2851 VMap[mdconst::extract<ConstantInt>(MD->getOperand(2))];
2852
2853 InitializerID = nextID;
2854
David Neto257c3892018-04-11 13:19:45 -04002855 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2856 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002857
David Neto87846742018-04-11 17:36:22 -04002858 auto *Inst =
2859 new SPIRVInstruction(spv::OpConstantComposite, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002860 SPIRVInstList.push_back(Inst);
2861
2862 HasMDVec.push_back(true);
2863 } else {
2864 HasMDVec.push_back(false);
2865 }
2866 }
2867
2868 // Check all kernels have same definitions for work_group_size.
2869 bool HasMD = false;
2870 if (!HasMDVec.empty()) {
2871 HasMD = HasMDVec[0];
2872 for (uint32_t i = 1; i < HasMDVec.size(); i++) {
2873 if (HasMD != HasMDVec[i]) {
2874 llvm_unreachable(
2875 "Kernels should have consistent work group size definition");
2876 }
2877 }
2878 }
2879
2880 // If all kernels do not have metadata for reqd_work_group_size, generate
2881 // OpSpecConstants for x/y/z dimension.
2882 if (!HasMD) {
2883 //
2884 // Generate OpSpecConstants for x/y/z dimension.
2885 //
2886 // Ops[0] : Result Type ID
2887 // Ops[1] : Constant size for x/y/z dimension (Literal Number).
2888 uint32_t XDimCstID = 0;
2889 uint32_t YDimCstID = 0;
2890 uint32_t ZDimCstID = 0;
2891
David Neto22f144c2017-06-12 14:26:21 -04002892 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04002893 uint32_t result_type_id =
2894 lookupType(Ty->getPointerElementType()->getSequentialElementType());
David Neto22f144c2017-06-12 14:26:21 -04002895
David Neto257c3892018-04-11 13:19:45 -04002896 // X Dimension
2897 Ops << MkId(result_type_id) << MkNum(1);
2898 XDimCstID = nextID++;
2899 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002900 new SPIRVInstruction(spv::OpSpecConstant, XDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002901
2902 // Y Dimension
2903 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002904 Ops << MkId(result_type_id) << MkNum(1);
2905 YDimCstID = nextID++;
2906 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002907 new SPIRVInstruction(spv::OpSpecConstant, YDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002908
2909 // Z Dimension
2910 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002911 Ops << MkId(result_type_id) << MkNum(1);
2912 ZDimCstID = nextID++;
2913 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002914 new SPIRVInstruction(spv::OpSpecConstant, ZDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002915
David Neto257c3892018-04-11 13:19:45 -04002916 BuiltinDimVec.push_back(XDimCstID);
2917 BuiltinDimVec.push_back(YDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002918 BuiltinDimVec.push_back(ZDimCstID);
2919
David Neto22f144c2017-06-12 14:26:21 -04002920 //
2921 // Generate OpSpecConstantComposite.
2922 //
2923 // Ops[0] : Result Type ID
2924 // Ops[1] : Constant size for x dimension.
2925 // Ops[2] : Constant size for y dimension.
2926 // Ops[3] : Constant size for z dimension.
2927 InitializerID = nextID;
2928
2929 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002930 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2931 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002932
David Neto87846742018-04-11 17:36:22 -04002933 auto *Inst =
2934 new SPIRVInstruction(spv::OpSpecConstantComposite, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002935 SPIRVInstList.push_back(Inst);
2936 }
2937 }
2938
David Neto22f144c2017-06-12 14:26:21 -04002939 VMap[&GV] = nextID;
2940
2941 //
2942 // Generate OpVariable.
2943 //
2944 // GIDOps[0] : Result Type ID
2945 // GIDOps[1] : Storage Class
2946 SPIRVOperandList Ops;
2947
David Neto85082642018-03-24 06:55:20 -07002948 const auto AS = PTy->getAddressSpace();
David Netoc6f3ab22018-04-06 18:02:31 -04002949 Ops << MkId(lookupType(Ty)) << MkNum(GetStorageClass(AS));
David Neto22f144c2017-06-12 14:26:21 -04002950
David Neto85082642018-03-24 06:55:20 -07002951 const bool module_scope_constant_external_init =
David Neto862b7d82018-06-14 18:48:37 -04002952 (AS == AddressSpace::Constant) && GV.hasInitializer() &&
David Neto85082642018-03-24 06:55:20 -07002953 clspv::Option::ModuleConstantsInStorageBuffer();
2954
Kévin Petit23d5f182019-08-13 16:21:29 +01002955 if (GV.hasInitializer()) {
2956 auto GVInit = GV.getInitializer();
2957 if (!isa<UndefValue>(GVInit) && !module_scope_constant_external_init) {
2958 assert(VMap.count(GVInit) == 1);
2959 InitializerID = VMap[GVInit];
David Neto85082642018-03-24 06:55:20 -07002960 }
2961 }
Kévin Petit23d5f182019-08-13 16:21:29 +01002962
2963 if (0 != InitializerID) {
2964 // Emit the ID of the intiializer as part of the variable definition.
2965 Ops << MkId(InitializerID);
2966 }
David Neto85082642018-03-24 06:55:20 -07002967 const uint32_t var_id = nextID++;
2968
David Neto87846742018-04-11 17:36:22 -04002969 auto *Inst = new SPIRVInstruction(spv::OpVariable, var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002970 SPIRVInstList.push_back(Inst);
2971
2972 // If we have a builtin.
2973 if (spv::BuiltInMax != BuiltinType) {
2974 // Find Insert Point for OpDecorate.
2975 auto DecoInsertPoint =
2976 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2977 [](SPIRVInstruction *Inst) -> bool {
2978 return Inst->getOpcode() != spv::OpDecorate &&
2979 Inst->getOpcode() != spv::OpMemberDecorate &&
2980 Inst->getOpcode() != spv::OpExtInstImport;
2981 });
2982 //
2983 // Generate OpDecorate.
2984 //
2985 // DOps[0] = Target ID
2986 // DOps[1] = Decoration (Builtin)
2987 // DOps[2] = BuiltIn ID
2988 uint32_t ResultID;
2989
2990 // WorkgroupSize is different, we decorate the constant composite that has
2991 // its value, rather than the variable that we use to access the value.
2992 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2993 ResultID = InitializerID;
David Netoa60b00b2017-09-15 16:34:09 -04002994 // Save both the value and variable IDs for later.
2995 WorkgroupSizeValueID = InitializerID;
2996 WorkgroupSizeVarID = VMap[&GV];
David Neto22f144c2017-06-12 14:26:21 -04002997 } else {
2998 ResultID = VMap[&GV];
2999 }
3000
3001 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04003002 DOps << MkId(ResultID) << MkNum(spv::DecorationBuiltIn)
3003 << MkNum(BuiltinType);
David Neto22f144c2017-06-12 14:26:21 -04003004
David Neto87846742018-04-11 17:36:22 -04003005 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, DOps);
David Neto22f144c2017-06-12 14:26:21 -04003006 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
David Neto85082642018-03-24 06:55:20 -07003007 } else if (module_scope_constant_external_init) {
3008 // This module scope constant is initialized from a storage buffer with data
3009 // provided by the host at binding 0 of the next descriptor set.
David Neto78383442018-06-15 20:31:56 -04003010 const uint32_t descriptor_set = TakeDescriptorIndex(&M);
David Neto85082642018-03-24 06:55:20 -07003011
David Neto862b7d82018-06-14 18:48:37 -04003012 // Emit the intializer to the descriptor map file.
David Neto85082642018-03-24 06:55:20 -07003013 // Use "kind,buffer" to indicate storage buffer. We might want to expand
3014 // that later to other types, like uniform buffer.
alan-bakerf5e5f692018-11-27 08:33:24 -05003015 std::string hexbytes;
3016 llvm::raw_string_ostream str(hexbytes);
3017 clspv::ConstantEmitter(DL, str).Emit(GV.getInitializer());
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003018 version0::DescriptorMapEntry::ConstantData constant_data = {ArgKind::Buffer,
3019 str.str()};
3020 descriptorMapEntries->emplace_back(std::move(constant_data), descriptor_set,
3021 0);
David Neto85082642018-03-24 06:55:20 -07003022
3023 // Find Insert Point for OpDecorate.
3024 auto DecoInsertPoint =
3025 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
3026 [](SPIRVInstruction *Inst) -> bool {
3027 return Inst->getOpcode() != spv::OpDecorate &&
3028 Inst->getOpcode() != spv::OpMemberDecorate &&
3029 Inst->getOpcode() != spv::OpExtInstImport;
3030 });
3031
David Neto257c3892018-04-11 13:19:45 -04003032 // OpDecorate %var Binding <binding>
David Neto85082642018-03-24 06:55:20 -07003033 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04003034 DOps << MkId(var_id) << MkNum(spv::DecorationBinding) << MkNum(0);
3035 DecoInsertPoint = SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04003036 DecoInsertPoint, new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto85082642018-03-24 06:55:20 -07003037
3038 // OpDecorate %var DescriptorSet <descriptor_set>
3039 DOps.clear();
David Neto257c3892018-04-11 13:19:45 -04003040 DOps << MkId(var_id) << MkNum(spv::DecorationDescriptorSet)
3041 << MkNum(descriptor_set);
David Netoc6f3ab22018-04-06 18:02:31 -04003042 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04003043 new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto22f144c2017-06-12 14:26:21 -04003044 }
3045}
3046
David Netoc6f3ab22018-04-06 18:02:31 -04003047void SPIRVProducerPass::GenerateWorkgroupVars() {
3048 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
Alan Baker202c8c72018-08-13 13:47:44 -04003049 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
3050 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05003051 LocalArgInfo &info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04003052
3053 // Generate OpVariable.
3054 //
3055 // GIDOps[0] : Result Type ID
3056 // GIDOps[1] : Storage Class
3057 SPIRVOperandList Ops;
3058 Ops << MkId(info.ptr_array_type_id) << MkNum(spv::StorageClassWorkgroup);
3059
3060 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04003061 new SPIRVInstruction(spv::OpVariable, info.variable_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04003062 }
3063}
3064
David Neto862b7d82018-06-14 18:48:37 -04003065void SPIRVProducerPass::GenerateDescriptorMapInfo(const DataLayout &DL,
3066 Function &F) {
David Netoc5fb5242018-07-30 13:28:31 -04003067 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
3068 return;
3069 }
David Neto862b7d82018-06-14 18:48:37 -04003070 // Gather the list of resources that are used by this function's arguments.
3071 auto &resource_var_at_index = FunctionToResourceVarsMap[&F];
3072
alan-bakerf5e5f692018-11-27 08:33:24 -05003073 // TODO(alan-baker): This should become unnecessary by fixing the rest of the
3074 // flow to generate pod_ubo arguments earlier.
David Neto862b7d82018-06-14 18:48:37 -04003075 auto remap_arg_kind = [](StringRef argKind) {
alan-bakerf5e5f692018-11-27 08:33:24 -05003076 std::string kind =
3077 clspv::Option::PodArgsInUniformBuffer() && argKind.equals("pod")
3078 ? "pod_ubo"
3079 : argKind;
3080 return GetArgKindFromName(kind);
David Neto862b7d82018-06-14 18:48:37 -04003081 };
3082
3083 auto *fty = F.getType()->getPointerElementType();
3084 auto *func_ty = dyn_cast<FunctionType>(fty);
3085
alan-baker038e9242019-04-19 22:14:41 -04003086 // If we've clustered POD arguments, then argument details are in metadata.
David Neto862b7d82018-06-14 18:48:37 -04003087 // If an argument maps to a resource variable, then get descriptor set and
3088 // binding from the resoure variable. Other info comes from the metadata.
3089 const auto *arg_map = F.getMetadata("kernel_arg_map");
3090 if (arg_map) {
3091 for (const auto &arg : arg_map->operands()) {
3092 const MDNode *arg_node = dyn_cast<MDNode>(arg.get());
Kévin PETITa353c832018-03-20 23:21:21 +00003093 assert(arg_node->getNumOperands() == 7);
David Neto862b7d82018-06-14 18:48:37 -04003094 const auto name =
3095 dyn_cast<MDString>(arg_node->getOperand(0))->getString();
3096 const auto old_index =
3097 dyn_extract<ConstantInt>(arg_node->getOperand(1))->getZExtValue();
3098 // Remapped argument index
alan-bakerb6b09dc2018-11-08 16:59:28 -05003099 const size_t new_index = static_cast<size_t>(
3100 dyn_extract<ConstantInt>(arg_node->getOperand(2))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04003101 const auto offset =
3102 dyn_extract<ConstantInt>(arg_node->getOperand(3))->getZExtValue();
Kévin PETITa353c832018-03-20 23:21:21 +00003103 const auto arg_size =
3104 dyn_extract<ConstantInt>(arg_node->getOperand(4))->getZExtValue();
David Neto862b7d82018-06-14 18:48:37 -04003105 const auto argKind = remap_arg_kind(
Kévin PETITa353c832018-03-20 23:21:21 +00003106 dyn_cast<MDString>(arg_node->getOperand(5))->getString());
David Neto862b7d82018-06-14 18:48:37 -04003107 const auto spec_id =
Kévin PETITa353c832018-03-20 23:21:21 +00003108 dyn_extract<ConstantInt>(arg_node->getOperand(6))->getSExtValue();
alan-bakerf5e5f692018-11-27 08:33:24 -05003109
3110 uint32_t descriptor_set = 0;
3111 uint32_t binding = 0;
3112 version0::DescriptorMapEntry::KernelArgData kernel_data = {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003113 F.getName(), name, static_cast<uint32_t>(old_index), argKind,
alan-bakerf5e5f692018-11-27 08:33:24 -05003114 static_cast<uint32_t>(spec_id),
3115 // This will be set below for pointer-to-local args.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003116 0, static_cast<uint32_t>(offset), static_cast<uint32_t>(arg_size)};
David Neto862b7d82018-06-14 18:48:37 -04003117 if (spec_id > 0) {
alan-bakerf5e5f692018-11-27 08:33:24 -05003118 kernel_data.local_element_size = static_cast<uint32_t>(GetTypeAllocSize(
3119 func_ty->getParamType(unsigned(new_index))->getPointerElementType(),
3120 DL));
David Neto862b7d82018-06-14 18:48:37 -04003121 } else {
3122 auto *info = resource_var_at_index[new_index];
3123 assert(info);
alan-bakerf5e5f692018-11-27 08:33:24 -05003124 descriptor_set = info->descriptor_set;
3125 binding = info->binding;
David Neto862b7d82018-06-14 18:48:37 -04003126 }
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003127 descriptorMapEntries->emplace_back(std::move(kernel_data), descriptor_set,
3128 binding);
David Neto862b7d82018-06-14 18:48:37 -04003129 }
3130 } else {
3131 // There is no argument map.
3132 // Take descriptor info from the resource variable calls.
Kévin PETITa353c832018-03-20 23:21:21 +00003133 // Take argument name and size from the arguments list.
David Neto862b7d82018-06-14 18:48:37 -04003134
3135 SmallVector<Argument *, 4> arguments;
3136 for (auto &arg : F.args()) {
3137 arguments.push_back(&arg);
3138 }
3139
3140 unsigned arg_index = 0;
3141 for (auto *info : resource_var_at_index) {
3142 if (info) {
Kévin PETITa353c832018-03-20 23:21:21 +00003143 auto arg = arguments[arg_index];
alan-bakerb6b09dc2018-11-08 16:59:28 -05003144 unsigned arg_size = 0;
Kévin PETITa353c832018-03-20 23:21:21 +00003145 if (info->arg_kind == clspv::ArgKind::Pod) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05003146 arg_size = static_cast<uint32_t>(DL.getTypeStoreSize(arg->getType()));
Kévin PETITa353c832018-03-20 23:21:21 +00003147 }
3148
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003149 // Local pointer arguments are unused in this case. Offset is always
3150 // zero.
alan-bakerf5e5f692018-11-27 08:33:24 -05003151 version0::DescriptorMapEntry::KernelArgData kernel_data = {
3152 F.getName(), arg->getName(),
3153 arg_index, remap_arg_kind(clspv::GetArgKindName(info->arg_kind)),
3154 0, 0,
3155 0, arg_size};
3156 descriptorMapEntries->emplace_back(std::move(kernel_data),
3157 info->descriptor_set, info->binding);
David Neto862b7d82018-06-14 18:48:37 -04003158 }
3159 arg_index++;
3160 }
3161 // Generate mappings for pointer-to-local arguments.
3162 for (arg_index = 0; arg_index < arguments.size(); ++arg_index) {
3163 Argument *arg = arguments[arg_index];
Alan Baker202c8c72018-08-13 13:47:44 -04003164 auto where = LocalArgSpecIds.find(arg);
3165 if (where != LocalArgSpecIds.end()) {
3166 auto &local_arg_info = LocalSpecIdInfoMap[where->second];
alan-bakerf5e5f692018-11-27 08:33:24 -05003167 // Pod arguments members are unused in this case.
3168 version0::DescriptorMapEntry::KernelArgData kernel_data = {
3169 F.getName(),
3170 arg->getName(),
3171 arg_index,
3172 ArgKind::Local,
3173 static_cast<uint32_t>(local_arg_info.spec_id),
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003174 static_cast<uint32_t>(
3175 GetTypeAllocSize(local_arg_info.elem_type, DL)),
alan-bakerf5e5f692018-11-27 08:33:24 -05003176 0,
3177 0};
3178 // Pointer-to-local arguments do not utilize descriptor set and binding.
3179 descriptorMapEntries->emplace_back(std::move(kernel_data), 0, 0);
David Neto862b7d82018-06-14 18:48:37 -04003180 }
3181 }
3182 }
3183}
3184
David Neto22f144c2017-06-12 14:26:21 -04003185void SPIRVProducerPass::GenerateFuncPrologue(Function &F) {
3186 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3187 ValueMapType &VMap = getValueMap();
3188 EntryPointVecType &EntryPoints = getEntryPointVec();
David Neto22f144c2017-06-12 14:26:21 -04003189 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
3190 auto &GlobalConstArgSet = getGlobalConstArgSet();
3191
3192 FunctionType *FTy = F.getFunctionType();
3193
3194 //
David Neto22f144c2017-06-12 14:26:21 -04003195 // Generate OPFunction.
3196 //
3197
3198 // FOps[0] : Result Type ID
3199 // FOps[1] : Function Control
3200 // FOps[2] : Function Type ID
3201 SPIRVOperandList FOps;
3202
3203 // Find SPIRV instruction for return type.
David Neto257c3892018-04-11 13:19:45 -04003204 FOps << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04003205
3206 // Check function attributes for SPIRV Function Control.
3207 uint32_t FuncControl = spv::FunctionControlMaskNone;
3208 if (F.hasFnAttribute(Attribute::AlwaysInline)) {
3209 FuncControl |= spv::FunctionControlInlineMask;
3210 }
3211 if (F.hasFnAttribute(Attribute::NoInline)) {
3212 FuncControl |= spv::FunctionControlDontInlineMask;
3213 }
3214 // TODO: Check llvm attribute for Function Control Pure.
3215 if (F.hasFnAttribute(Attribute::ReadOnly)) {
3216 FuncControl |= spv::FunctionControlPureMask;
3217 }
3218 // TODO: Check llvm attribute for Function Control Const.
3219 if (F.hasFnAttribute(Attribute::ReadNone)) {
3220 FuncControl |= spv::FunctionControlConstMask;
3221 }
3222
David Neto257c3892018-04-11 13:19:45 -04003223 FOps << MkNum(FuncControl);
David Neto22f144c2017-06-12 14:26:21 -04003224
3225 uint32_t FTyID;
3226 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3227 SmallVector<Type *, 4> NewFuncParamTys;
3228 FunctionType *NewFTy =
3229 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
3230 FTyID = lookupType(NewFTy);
3231 } else {
David Neto9ed8e2f2018-03-24 06:47:24 -07003232 // Handle regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04003233 if (GlobalConstFuncTyMap.count(FTy)) {
3234 FTyID = lookupType(GlobalConstFuncTyMap[FTy].first);
3235 } else {
3236 FTyID = lookupType(FTy);
3237 }
3238 }
3239
David Neto257c3892018-04-11 13:19:45 -04003240 FOps << MkId(FTyID);
David Neto22f144c2017-06-12 14:26:21 -04003241
3242 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3243 EntryPoints.push_back(std::make_pair(&F, nextID));
3244 }
3245
3246 VMap[&F] = nextID;
3247
David Neto482550a2018-03-24 05:21:07 -07003248 if (clspv::Option::ShowIDs()) {
David Netob05675d2018-02-16 12:37:49 -05003249 errs() << "Function " << F.getName() << " is " << nextID << "\n";
3250 }
David Neto22f144c2017-06-12 14:26:21 -04003251 // Generate SPIRV instruction for function.
David Neto87846742018-04-11 17:36:22 -04003252 auto *FuncInst = new SPIRVInstruction(spv::OpFunction, nextID++, FOps);
David Neto22f144c2017-06-12 14:26:21 -04003253 SPIRVInstList.push_back(FuncInst);
3254
3255 //
3256 // Generate OpFunctionParameter for Normal function.
3257 //
3258
3259 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
alan-bakere9308012019-03-15 10:25:13 -04003260
3261 // Find Insert Point for OpDecorate.
3262 auto DecoInsertPoint =
3263 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
3264 [](SPIRVInstruction *Inst) -> bool {
3265 return Inst->getOpcode() != spv::OpDecorate &&
3266 Inst->getOpcode() != spv::OpMemberDecorate &&
3267 Inst->getOpcode() != spv::OpExtInstImport;
3268 });
3269
David Neto22f144c2017-06-12 14:26:21 -04003270 // Iterate Argument for name instead of param type from function type.
3271 unsigned ArgIdx = 0;
3272 for (Argument &Arg : F.args()) {
alan-bakere9308012019-03-15 10:25:13 -04003273 uint32_t param_id = nextID++;
3274 VMap[&Arg] = param_id;
3275
3276 if (CalledWithCoherentResource(Arg)) {
3277 // If the arg is passed a coherent resource ever, then decorate this
3278 // parameter with Coherent too.
3279 SPIRVOperandList decoration_ops;
3280 decoration_ops << MkId(param_id) << MkNum(spv::DecorationCoherent);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003281 SPIRVInstList.insert(
3282 DecoInsertPoint,
3283 new SPIRVInstruction(spv::OpDecorate, decoration_ops));
alan-bakere9308012019-03-15 10:25:13 -04003284 }
David Neto22f144c2017-06-12 14:26:21 -04003285
3286 // ParamOps[0] : Result Type ID
3287 SPIRVOperandList ParamOps;
3288
3289 // Find SPIRV instruction for parameter type.
3290 uint32_t ParamTyID = lookupType(Arg.getType());
3291 if (PointerType *PTy = dyn_cast<PointerType>(Arg.getType())) {
3292 if (GlobalConstFuncTyMap.count(FTy)) {
3293 if (ArgIdx == GlobalConstFuncTyMap[FTy].second) {
3294 Type *EleTy = PTy->getPointerElementType();
3295 Type *ArgTy =
3296 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
3297 ParamTyID = lookupType(ArgTy);
3298 GlobalConstArgSet.insert(&Arg);
3299 }
3300 }
3301 }
David Neto257c3892018-04-11 13:19:45 -04003302 ParamOps << MkId(ParamTyID);
David Neto22f144c2017-06-12 14:26:21 -04003303
3304 // Generate SPIRV instruction for parameter.
David Neto87846742018-04-11 17:36:22 -04003305 auto *ParamInst =
alan-bakere9308012019-03-15 10:25:13 -04003306 new SPIRVInstruction(spv::OpFunctionParameter, param_id, ParamOps);
David Neto22f144c2017-06-12 14:26:21 -04003307 SPIRVInstList.push_back(ParamInst);
3308
3309 ArgIdx++;
3310 }
3311 }
3312}
3313
alan-bakerb6b09dc2018-11-08 16:59:28 -05003314void SPIRVProducerPass::GenerateModuleInfo(Module &module) {
David Neto22f144c2017-06-12 14:26:21 -04003315 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3316 EntryPointVecType &EntryPoints = getEntryPointVec();
3317 ValueMapType &VMap = getValueMap();
3318 ValueList &EntryPointInterfaces = getEntryPointInterfacesVec();
3319 uint32_t &ExtInstImportID = getOpExtInstImportID();
3320 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
3321
3322 // Set up insert point.
3323 auto InsertPoint = SPIRVInstList.begin();
3324
3325 //
3326 // Generate OpCapability
3327 //
3328 // TODO: Which llvm information is mapped to SPIRV Capapbility?
3329
3330 // Ops[0] = Capability
3331 SPIRVOperandList Ops;
3332
David Neto87846742018-04-11 17:36:22 -04003333 auto *CapInst =
David Netoef5ba2b2019-12-20 08:35:54 -05003334 new SPIRVInstruction(spv::OpCapability, MkNum(spv::CapabilityShader));
David Neto22f144c2017-06-12 14:26:21 -04003335 SPIRVInstList.insert(InsertPoint, CapInst);
3336
alan-bakerf906d2b2019-12-10 11:26:23 -05003337 bool write_without_format = false;
3338 bool sampled_1d = false;
3339 bool image_1d = false;
David Neto22f144c2017-06-12 14:26:21 -04003340 for (Type *Ty : getTypeList()) {
alan-bakerb39c8262019-03-08 14:03:37 -05003341 if (clspv::Option::Int8Support() && Ty->isIntegerTy(8)) {
3342 // Generate OpCapability for i8 type.
David Netoef5ba2b2019-12-20 08:35:54 -05003343 SPIRVInstList.insert(
3344 InsertPoint,
3345 new SPIRVInstruction(spv::OpCapability, MkNum(spv::CapabilityInt8)));
alan-bakerb39c8262019-03-08 14:03:37 -05003346 } else if (Ty->isIntegerTy(16)) {
David Neto22f144c2017-06-12 14:26:21 -04003347 // Generate OpCapability for i16 type.
David Netoef5ba2b2019-12-20 08:35:54 -05003348 SPIRVInstList.insert(
3349 InsertPoint,
3350 new SPIRVInstruction(spv::OpCapability, MkNum(spv::CapabilityInt16)));
David Neto22f144c2017-06-12 14:26:21 -04003351 } else if (Ty->isIntegerTy(64)) {
3352 // Generate OpCapability for i64 type.
David Netoef5ba2b2019-12-20 08:35:54 -05003353 SPIRVInstList.insert(
3354 InsertPoint,
3355 new SPIRVInstruction(spv::OpCapability, MkNum(spv::CapabilityInt64)));
David Neto22f144c2017-06-12 14:26:21 -04003356 } else if (Ty->isHalfTy()) {
3357 // Generate OpCapability for half type.
David Netoef5ba2b2019-12-20 08:35:54 -05003358 SPIRVInstList.insert(InsertPoint,
3359 new SPIRVInstruction(spv::OpCapability,
3360 MkNum(spv::CapabilityFloat16)));
David Neto22f144c2017-06-12 14:26:21 -04003361 } else if (Ty->isDoubleTy()) {
3362 // Generate OpCapability for double type.
David Netoef5ba2b2019-12-20 08:35:54 -05003363 SPIRVInstList.insert(InsertPoint,
3364 new SPIRVInstruction(spv::OpCapability,
3365 MkNum(spv::CapabilityFloat64)));
David Neto22f144c2017-06-12 14:26:21 -04003366 } else if (auto *STy = dyn_cast<StructType>(Ty)) {
3367 if (STy->isOpaque()) {
alan-bakerf906d2b2019-12-10 11:26:23 -05003368 if (STy->getName().startswith("opencl.image1d_wo_t") ||
3369 STy->getName().startswith("opencl.image2d_wo_t") ||
alan-bakerf67468c2019-11-25 15:51:49 -05003370 STy->getName().startswith("opencl.image3d_wo_t")) {
alan-bakerf906d2b2019-12-10 11:26:23 -05003371 write_without_format = true;
3372 }
3373 if (STy->getName().startswith("opencl.image1d_ro_t") ||
3374 STy->getName().startswith("opencl.image1d_wo_t")) {
3375 if (STy->getName().contains(".sampled"))
3376 sampled_1d = true;
3377 else
3378 image_1d = true;
David Neto22f144c2017-06-12 14:26:21 -04003379 }
3380 }
3381 }
3382 }
3383
alan-bakerf906d2b2019-12-10 11:26:23 -05003384 if (write_without_format) {
3385 // Generate OpCapability for write only image type.
3386 SPIRVInstList.insert(
3387 InsertPoint,
3388 new SPIRVInstruction(
3389 spv::OpCapability,
3390 {MkNum(spv::CapabilityStorageImageWriteWithoutFormat)}));
3391 }
3392 if (image_1d) {
3393 // Generate OpCapability for unsampled 1D image type.
3394 SPIRVInstList.insert(InsertPoint,
3395 new SPIRVInstruction(spv::OpCapability,
3396 {MkNum(spv::CapabilityImage1D)}));
3397 } else if (sampled_1d) {
3398 // Generate OpCapability for sampled 1D image type.
3399 SPIRVInstList.insert(
3400 InsertPoint, new SPIRVInstruction(spv::OpCapability,
3401 {MkNum(spv::CapabilitySampled1D)}));
3402 }
3403
David Neto5c22a252018-03-15 16:07:41 -04003404 { // OpCapability ImageQuery
3405 bool hasImageQuery = false;
alan-bakerf67468c2019-11-25 15:51:49 -05003406 for (const auto &SymVal : module.getValueSymbolTable()) {
3407 if (auto F = dyn_cast<Function>(SymVal.getValue())) {
alan-bakerce179f12019-12-06 19:02:22 -05003408 if (clspv::IsImageQuery(F)) {
alan-bakerf67468c2019-11-25 15:51:49 -05003409 hasImageQuery = true;
3410 break;
3411 }
David Neto5c22a252018-03-15 16:07:41 -04003412 }
3413 }
alan-bakerf67468c2019-11-25 15:51:49 -05003414
David Neto5c22a252018-03-15 16:07:41 -04003415 if (hasImageQuery) {
David Neto87846742018-04-11 17:36:22 -04003416 auto *ImageQueryCapInst = new SPIRVInstruction(
3417 spv::OpCapability, {MkNum(spv::CapabilityImageQuery)});
David Neto5c22a252018-03-15 16:07:41 -04003418 SPIRVInstList.insert(InsertPoint, ImageQueryCapInst);
3419 }
3420 }
3421
David Neto22f144c2017-06-12 14:26:21 -04003422 if (hasVariablePointers()) {
3423 //
David Neto22f144c2017-06-12 14:26:21 -04003424 // Generate OpCapability.
3425 //
3426 // Ops[0] = Capability
3427 //
3428 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003429 Ops << MkNum(spv::CapabilityVariablePointers);
David Neto22f144c2017-06-12 14:26:21 -04003430
David Neto87846742018-04-11 17:36:22 -04003431 SPIRVInstList.insert(InsertPoint,
3432 new SPIRVInstruction(spv::OpCapability, Ops));
alan-baker5b86ed72019-02-15 08:26:50 -05003433 } else if (hasVariablePointersStorageBuffer()) {
3434 //
3435 // Generate OpCapability.
3436 //
3437 // Ops[0] = Capability
3438 //
3439 Ops.clear();
3440 Ops << MkNum(spv::CapabilityVariablePointersStorageBuffer);
David Neto22f144c2017-06-12 14:26:21 -04003441
alan-baker5b86ed72019-02-15 08:26:50 -05003442 SPIRVInstList.insert(InsertPoint,
3443 new SPIRVInstruction(spv::OpCapability, Ops));
3444 }
3445
3446 // Always add the storage buffer extension
3447 {
David Neto22f144c2017-06-12 14:26:21 -04003448 //
3449 // Generate OpExtension.
3450 //
3451 // Ops[0] = Name (Literal String)
3452 //
alan-baker5b86ed72019-02-15 08:26:50 -05003453 auto *ExtensionInst = new SPIRVInstruction(
3454 spv::OpExtension, {MkString("SPV_KHR_storage_buffer_storage_class")});
3455 SPIRVInstList.insert(InsertPoint, ExtensionInst);
3456 }
David Neto22f144c2017-06-12 14:26:21 -04003457
alan-baker5b86ed72019-02-15 08:26:50 -05003458 if (hasVariablePointers() || hasVariablePointersStorageBuffer()) {
3459 //
3460 // Generate OpExtension.
3461 //
3462 // Ops[0] = Name (Literal String)
3463 //
3464 auto *ExtensionInst = new SPIRVInstruction(
3465 spv::OpExtension, {MkString("SPV_KHR_variable_pointers")});
3466 SPIRVInstList.insert(InsertPoint, ExtensionInst);
David Neto22f144c2017-06-12 14:26:21 -04003467 }
3468
3469 if (ExtInstImportID) {
3470 ++InsertPoint;
3471 }
3472
3473 //
3474 // Generate OpMemoryModel
3475 //
3476 // Memory model for Vulkan will always be GLSL450.
3477
3478 // Ops[0] = Addressing Model
3479 // Ops[1] = Memory Model
3480 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003481 Ops << MkNum(spv::AddressingModelLogical) << MkNum(spv::MemoryModelGLSL450);
David Neto22f144c2017-06-12 14:26:21 -04003482
David Neto87846742018-04-11 17:36:22 -04003483 auto *MemModelInst = new SPIRVInstruction(spv::OpMemoryModel, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003484 SPIRVInstList.insert(InsertPoint, MemModelInst);
3485
3486 //
3487 // Generate OpEntryPoint
3488 //
3489 for (auto EntryPoint : EntryPoints) {
3490 // Ops[0] = Execution Model
3491 // Ops[1] = EntryPoint ID
3492 // Ops[2] = Name (Literal String)
3493 // ...
3494 //
3495 // TODO: Do we need to consider Interface ID for forward references???
3496 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05003497 const StringRef &name = EntryPoint.first->getName();
David Neto257c3892018-04-11 13:19:45 -04003498 Ops << MkNum(spv::ExecutionModelGLCompute) << MkId(EntryPoint.second)
3499 << MkString(name);
David Neto22f144c2017-06-12 14:26:21 -04003500
David Neto22f144c2017-06-12 14:26:21 -04003501 for (Value *Interface : EntryPointInterfaces) {
David Neto257c3892018-04-11 13:19:45 -04003502 Ops << MkId(VMap[Interface]);
David Neto22f144c2017-06-12 14:26:21 -04003503 }
3504
David Neto87846742018-04-11 17:36:22 -04003505 auto *EntryPointInst = new SPIRVInstruction(spv::OpEntryPoint, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003506 SPIRVInstList.insert(InsertPoint, EntryPointInst);
3507 }
3508
3509 for (auto EntryPoint : EntryPoints) {
3510 if (const MDNode *MD = dyn_cast<Function>(EntryPoint.first)
3511 ->getMetadata("reqd_work_group_size")) {
3512
3513 if (!BuiltinDimVec.empty()) {
3514 llvm_unreachable(
3515 "Kernels should have consistent work group size definition");
3516 }
3517
3518 //
3519 // Generate OpExecutionMode
3520 //
3521
3522 // Ops[0] = Entry Point ID
3523 // Ops[1] = Execution Mode
3524 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
3525 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05003526 Ops << MkId(EntryPoint.second) << MkNum(spv::ExecutionModeLocalSize);
David Neto22f144c2017-06-12 14:26:21 -04003527
3528 uint32_t XDim = static_cast<uint32_t>(
3529 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
3530 uint32_t YDim = static_cast<uint32_t>(
3531 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
3532 uint32_t ZDim = static_cast<uint32_t>(
3533 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
3534
David Neto257c3892018-04-11 13:19:45 -04003535 Ops << MkNum(XDim) << MkNum(YDim) << MkNum(ZDim);
David Neto22f144c2017-06-12 14:26:21 -04003536
David Neto87846742018-04-11 17:36:22 -04003537 auto *ExecModeInst = new SPIRVInstruction(spv::OpExecutionMode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003538 SPIRVInstList.insert(InsertPoint, ExecModeInst);
3539 }
3540 }
3541
3542 //
3543 // Generate OpSource.
3544 //
3545 // Ops[0] = SourceLanguage ID
3546 // Ops[1] = Version (LiteralNum)
3547 //
3548 Ops.clear();
Kévin Petit0fc88042019-04-09 23:25:02 +01003549 if (clspv::Option::CPlusPlus()) {
3550 Ops << MkNum(spv::SourceLanguageOpenCL_CPP) << MkNum(100);
3551 } else {
3552 Ops << MkNum(spv::SourceLanguageOpenCL_C) << MkNum(120);
3553 }
David Neto22f144c2017-06-12 14:26:21 -04003554
David Neto87846742018-04-11 17:36:22 -04003555 auto *OpenSourceInst = new SPIRVInstruction(spv::OpSource, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003556 SPIRVInstList.insert(InsertPoint, OpenSourceInst);
3557
3558 if (!BuiltinDimVec.empty()) {
3559 //
3560 // Generate OpDecorates for x/y/z dimension.
3561 //
3562 // Ops[0] = Target ID
3563 // Ops[1] = Decoration (SpecId)
David Neto257c3892018-04-11 13:19:45 -04003564 // Ops[2] = Specialization Constant ID (Literal Number)
David Neto22f144c2017-06-12 14:26:21 -04003565
3566 // X Dimension
3567 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003568 Ops << MkId(BuiltinDimVec[0]) << MkNum(spv::DecorationSpecId) << MkNum(0);
David Neto87846742018-04-11 17:36:22 -04003569 SPIRVInstList.insert(InsertPoint,
3570 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003571
3572 // Y Dimension
3573 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003574 Ops << MkId(BuiltinDimVec[1]) << MkNum(spv::DecorationSpecId) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04003575 SPIRVInstList.insert(InsertPoint,
3576 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003577
3578 // Z Dimension
3579 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003580 Ops << MkId(BuiltinDimVec[2]) << MkNum(spv::DecorationSpecId) << MkNum(2);
David Neto87846742018-04-11 17:36:22 -04003581 SPIRVInstList.insert(InsertPoint,
3582 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003583 }
3584}
3585
David Netob6e2e062018-04-25 10:32:06 -04003586void SPIRVProducerPass::GenerateEntryPointInitialStores() {
3587 // Work around a driver bug. Initializers on Private variables might not
3588 // work. So the start of the kernel should store the initializer value to the
3589 // variables. Yes, *every* entry point pays this cost if *any* entry point
3590 // uses this builtin. At this point I judge this to be an acceptable tradeoff
3591 // of complexity vs. runtime, for a broken driver.
alan-bakerb6b09dc2018-11-08 16:59:28 -05003592 // TODO(dneto): Remove this at some point once fixed drivers are widely
3593 // available.
David Netob6e2e062018-04-25 10:32:06 -04003594 if (WorkgroupSizeVarID) {
3595 assert(WorkgroupSizeValueID);
3596
3597 SPIRVOperandList Ops;
3598 Ops << MkId(WorkgroupSizeVarID) << MkId(WorkgroupSizeValueID);
3599
3600 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
3601 getSPIRVInstList().push_back(Inst);
3602 }
3603}
3604
David Neto22f144c2017-06-12 14:26:21 -04003605void SPIRVProducerPass::GenerateFuncBody(Function &F) {
3606 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3607 ValueMapType &VMap = getValueMap();
3608
David Netob6e2e062018-04-25 10:32:06 -04003609 const bool IsKernel = F.getCallingConv() == CallingConv::SPIR_KERNEL;
David Neto22f144c2017-06-12 14:26:21 -04003610
3611 for (BasicBlock &BB : F) {
3612 // Register BasicBlock to ValueMap.
3613 VMap[&BB] = nextID;
3614
3615 //
3616 // Generate OpLabel for Basic Block.
3617 //
3618 SPIRVOperandList Ops;
David Neto87846742018-04-11 17:36:22 -04003619 auto *Inst = new SPIRVInstruction(spv::OpLabel, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003620 SPIRVInstList.push_back(Inst);
3621
David Neto6dcd4712017-06-23 11:06:47 -04003622 // OpVariable instructions must come first.
3623 for (Instruction &I : BB) {
alan-baker5b86ed72019-02-15 08:26:50 -05003624 if (auto *alloca = dyn_cast<AllocaInst>(&I)) {
3625 // Allocating a pointer requires variable pointers.
3626 if (alloca->getAllocatedType()->isPointerTy()) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003627 setVariablePointersCapabilities(
3628 alloca->getAllocatedType()->getPointerAddressSpace());
alan-baker5b86ed72019-02-15 08:26:50 -05003629 }
David Neto6dcd4712017-06-23 11:06:47 -04003630 GenerateInstruction(I);
3631 }
3632 }
3633
David Neto22f144c2017-06-12 14:26:21 -04003634 if (&BB == &F.getEntryBlock() && IsKernel) {
David Netob6e2e062018-04-25 10:32:06 -04003635 if (clspv::Option::HackInitializers()) {
3636 GenerateEntryPointInitialStores();
3637 }
David Neto22f144c2017-06-12 14:26:21 -04003638 }
3639
3640 for (Instruction &I : BB) {
David Neto6dcd4712017-06-23 11:06:47 -04003641 if (!isa<AllocaInst>(I)) {
3642 GenerateInstruction(I);
3643 }
David Neto22f144c2017-06-12 14:26:21 -04003644 }
3645 }
3646}
3647
3648spv::Op SPIRVProducerPass::GetSPIRVCmpOpcode(CmpInst *I) {
3649 const std::map<CmpInst::Predicate, spv::Op> Map = {
3650 {CmpInst::ICMP_EQ, spv::OpIEqual},
3651 {CmpInst::ICMP_NE, spv::OpINotEqual},
3652 {CmpInst::ICMP_UGT, spv::OpUGreaterThan},
3653 {CmpInst::ICMP_UGE, spv::OpUGreaterThanEqual},
3654 {CmpInst::ICMP_ULT, spv::OpULessThan},
3655 {CmpInst::ICMP_ULE, spv::OpULessThanEqual},
3656 {CmpInst::ICMP_SGT, spv::OpSGreaterThan},
3657 {CmpInst::ICMP_SGE, spv::OpSGreaterThanEqual},
3658 {CmpInst::ICMP_SLT, spv::OpSLessThan},
3659 {CmpInst::ICMP_SLE, spv::OpSLessThanEqual},
3660 {CmpInst::FCMP_OEQ, spv::OpFOrdEqual},
3661 {CmpInst::FCMP_OGT, spv::OpFOrdGreaterThan},
3662 {CmpInst::FCMP_OGE, spv::OpFOrdGreaterThanEqual},
3663 {CmpInst::FCMP_OLT, spv::OpFOrdLessThan},
3664 {CmpInst::FCMP_OLE, spv::OpFOrdLessThanEqual},
3665 {CmpInst::FCMP_ONE, spv::OpFOrdNotEqual},
3666 {CmpInst::FCMP_UEQ, spv::OpFUnordEqual},
3667 {CmpInst::FCMP_UGT, spv::OpFUnordGreaterThan},
3668 {CmpInst::FCMP_UGE, spv::OpFUnordGreaterThanEqual},
3669 {CmpInst::FCMP_ULT, spv::OpFUnordLessThan},
3670 {CmpInst::FCMP_ULE, spv::OpFUnordLessThanEqual},
3671 {CmpInst::FCMP_UNE, spv::OpFUnordNotEqual}};
3672
3673 assert(0 != Map.count(I->getPredicate()));
3674
3675 return Map.at(I->getPredicate());
3676}
3677
3678spv::Op SPIRVProducerPass::GetSPIRVCastOpcode(Instruction &I) {
3679 const std::map<unsigned, spv::Op> Map{
3680 {Instruction::Trunc, spv::OpUConvert},
3681 {Instruction::ZExt, spv::OpUConvert},
3682 {Instruction::SExt, spv::OpSConvert},
3683 {Instruction::FPToUI, spv::OpConvertFToU},
3684 {Instruction::FPToSI, spv::OpConvertFToS},
3685 {Instruction::UIToFP, spv::OpConvertUToF},
3686 {Instruction::SIToFP, spv::OpConvertSToF},
3687 {Instruction::FPTrunc, spv::OpFConvert},
3688 {Instruction::FPExt, spv::OpFConvert},
3689 {Instruction::BitCast, spv::OpBitcast}};
3690
3691 assert(0 != Map.count(I.getOpcode()));
3692
3693 return Map.at(I.getOpcode());
3694}
3695
3696spv::Op SPIRVProducerPass::GetSPIRVBinaryOpcode(Instruction &I) {
Kévin Petit24272b62018-10-18 19:16:12 +00003697 if (I.getType()->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003698 switch (I.getOpcode()) {
3699 default:
3700 break;
3701 case Instruction::Or:
3702 return spv::OpLogicalOr;
3703 case Instruction::And:
3704 return spv::OpLogicalAnd;
3705 case Instruction::Xor:
3706 return spv::OpLogicalNotEqual;
3707 }
3708 }
3709
alan-bakerb6b09dc2018-11-08 16:59:28 -05003710 const std::map<unsigned, spv::Op> Map{
David Neto22f144c2017-06-12 14:26:21 -04003711 {Instruction::Add, spv::OpIAdd},
3712 {Instruction::FAdd, spv::OpFAdd},
3713 {Instruction::Sub, spv::OpISub},
3714 {Instruction::FSub, spv::OpFSub},
3715 {Instruction::Mul, spv::OpIMul},
3716 {Instruction::FMul, spv::OpFMul},
3717 {Instruction::UDiv, spv::OpUDiv},
3718 {Instruction::SDiv, spv::OpSDiv},
3719 {Instruction::FDiv, spv::OpFDiv},
3720 {Instruction::URem, spv::OpUMod},
3721 {Instruction::SRem, spv::OpSRem},
3722 {Instruction::FRem, spv::OpFRem},
3723 {Instruction::Or, spv::OpBitwiseOr},
3724 {Instruction::Xor, spv::OpBitwiseXor},
3725 {Instruction::And, spv::OpBitwiseAnd},
3726 {Instruction::Shl, spv::OpShiftLeftLogical},
3727 {Instruction::LShr, spv::OpShiftRightLogical},
3728 {Instruction::AShr, spv::OpShiftRightArithmetic}};
3729
3730 assert(0 != Map.count(I.getOpcode()));
3731
3732 return Map.at(I.getOpcode());
3733}
3734
3735void SPIRVProducerPass::GenerateInstruction(Instruction &I) {
3736 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3737 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04003738 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
3739 LLVMContext &Context = I.getParent()->getParent()->getParent()->getContext();
3740
3741 // Register Instruction to ValueMap.
3742 if (0 == VMap[&I]) {
3743 VMap[&I] = nextID;
3744 }
3745
3746 switch (I.getOpcode()) {
3747 default: {
3748 if (Instruction::isCast(I.getOpcode())) {
3749 //
3750 // Generate SPIRV instructions for cast operators.
3751 //
3752
David Netod2de94a2017-08-28 17:27:47 -04003753 auto Ty = I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003754 auto OpTy = I.getOperand(0)->getType();
David Netod2de94a2017-08-28 17:27:47 -04003755 auto toI8 = Ty == Type::getInt8Ty(Context);
3756 auto fromI32 = OpTy == Type::getInt32Ty(Context);
David Neto22f144c2017-06-12 14:26:21 -04003757 // Handle zext, sext and uitofp with i1 type specially.
3758 if ((I.getOpcode() == Instruction::ZExt ||
3759 I.getOpcode() == Instruction::SExt ||
3760 I.getOpcode() == Instruction::UIToFP) &&
alan-bakerb6b09dc2018-11-08 16:59:28 -05003761 OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003762 //
3763 // Generate OpSelect.
3764 //
3765
3766 // Ops[0] = Result Type ID
3767 // Ops[1] = Condition ID
3768 // Ops[2] = True Constant ID
3769 // Ops[3] = False Constant ID
3770 SPIRVOperandList Ops;
3771
David Neto257c3892018-04-11 13:19:45 -04003772 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003773
David Neto22f144c2017-06-12 14:26:21 -04003774 uint32_t CondID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003775 Ops << MkId(CondID);
David Neto22f144c2017-06-12 14:26:21 -04003776
3777 uint32_t TrueID = 0;
3778 if (I.getOpcode() == Instruction::ZExt) {
Kévin Petit7bfb8992019-02-26 13:45:08 +00003779 TrueID = VMap[ConstantInt::get(I.getType(), 1)];
David Neto22f144c2017-06-12 14:26:21 -04003780 } else if (I.getOpcode() == Instruction::SExt) {
Kévin Petit7bfb8992019-02-26 13:45:08 +00003781 TrueID = VMap[ConstantInt::getSigned(I.getType(), -1)];
David Neto22f144c2017-06-12 14:26:21 -04003782 } else {
3783 TrueID = VMap[ConstantFP::get(Context, APFloat(1.0f))];
3784 }
David Neto257c3892018-04-11 13:19:45 -04003785 Ops << MkId(TrueID);
David Neto22f144c2017-06-12 14:26:21 -04003786
3787 uint32_t FalseID = 0;
3788 if (I.getOpcode() == Instruction::ZExt) {
3789 FalseID = VMap[Constant::getNullValue(I.getType())];
3790 } else if (I.getOpcode() == Instruction::SExt) {
3791 FalseID = VMap[Constant::getNullValue(I.getType())];
3792 } else {
3793 FalseID = VMap[ConstantFP::get(Context, APFloat(0.0f))];
3794 }
David Neto257c3892018-04-11 13:19:45 -04003795 Ops << MkId(FalseID);
David Neto22f144c2017-06-12 14:26:21 -04003796
David Neto87846742018-04-11 17:36:22 -04003797 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003798 SPIRVInstList.push_back(Inst);
alan-bakerb39c8262019-03-08 14:03:37 -05003799 } else if (!clspv::Option::Int8Support() &&
3800 I.getOpcode() == Instruction::Trunc && fromI32 && toI8) {
David Netod2de94a2017-08-28 17:27:47 -04003801 // The SPIR-V target type is a 32-bit int. Keep only the bottom
3802 // 8 bits.
3803 // Before:
3804 // %result = trunc i32 %a to i8
3805 // After
3806 // %result = OpBitwiseAnd %uint %a %uint_255
3807
3808 SPIRVOperandList Ops;
3809
David Neto257c3892018-04-11 13:19:45 -04003810 Ops << MkId(lookupType(OpTy)) << MkId(VMap[I.getOperand(0)]);
David Netod2de94a2017-08-28 17:27:47 -04003811
3812 Type *UintTy = Type::getInt32Ty(Context);
3813 uint32_t MaskID = VMap[ConstantInt::get(UintTy, 255)];
David Neto257c3892018-04-11 13:19:45 -04003814 Ops << MkId(MaskID);
David Netod2de94a2017-08-28 17:27:47 -04003815
David Neto87846742018-04-11 17:36:22 -04003816 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Netod2de94a2017-08-28 17:27:47 -04003817 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04003818 } else {
3819 // Ops[0] = Result Type ID
3820 // Ops[1] = Source Value ID
3821 SPIRVOperandList Ops;
3822
David Neto257c3892018-04-11 13:19:45 -04003823 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003824
David Neto87846742018-04-11 17:36:22 -04003825 auto *Inst = new SPIRVInstruction(GetSPIRVCastOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003826 SPIRVInstList.push_back(Inst);
3827 }
3828 } else if (isa<BinaryOperator>(I)) {
3829 //
3830 // Generate SPIRV instructions for binary operators.
3831 //
3832
3833 // Handle xor with i1 type specially.
3834 if (I.getOpcode() == Instruction::Xor &&
3835 I.getType() == Type::getInt1Ty(Context) &&
Kévin Petit24272b62018-10-18 19:16:12 +00003836 ((isa<ConstantInt>(I.getOperand(0)) &&
3837 !cast<ConstantInt>(I.getOperand(0))->isZero()) ||
3838 (isa<ConstantInt>(I.getOperand(1)) &&
3839 !cast<ConstantInt>(I.getOperand(1))->isZero()))) {
David Neto22f144c2017-06-12 14:26:21 -04003840 //
3841 // Generate OpLogicalNot.
3842 //
3843 // Ops[0] = Result Type ID
3844 // Ops[1] = Operand
3845 SPIRVOperandList Ops;
3846
David Neto257c3892018-04-11 13:19:45 -04003847 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003848
3849 Value *CondV = I.getOperand(0);
3850 if (isa<Constant>(I.getOperand(0))) {
3851 CondV = I.getOperand(1);
3852 }
David Neto257c3892018-04-11 13:19:45 -04003853 Ops << MkId(VMap[CondV]);
David Neto22f144c2017-06-12 14:26:21 -04003854
David Neto87846742018-04-11 17:36:22 -04003855 auto *Inst = new SPIRVInstruction(spv::OpLogicalNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003856 SPIRVInstList.push_back(Inst);
3857 } else {
3858 // Ops[0] = Result Type ID
3859 // Ops[1] = Operand 0
3860 // Ops[2] = Operand 1
3861 SPIRVOperandList Ops;
3862
David Neto257c3892018-04-11 13:19:45 -04003863 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
3864 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003865
David Neto87846742018-04-11 17:36:22 -04003866 auto *Inst =
3867 new SPIRVInstruction(GetSPIRVBinaryOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003868 SPIRVInstList.push_back(Inst);
3869 }
alan-bakerc9c55ae2019-12-02 16:01:27 -05003870 } else if (I.getOpcode() == Instruction::FNeg) {
3871 // The only unary operator.
3872 //
3873 // Ops[0] = Result Type ID
3874 // Ops[1] = Operand 0
3875 SPIRVOperandList ops;
3876
3877 ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
3878 auto *Inst = new SPIRVInstruction(spv::OpFNegate, nextID++, ops);
3879 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04003880 } else {
3881 I.print(errs());
3882 llvm_unreachable("Unsupported instruction???");
3883 }
3884 break;
3885 }
3886 case Instruction::GetElementPtr: {
3887 auto &GlobalConstArgSet = getGlobalConstArgSet();
3888
3889 //
3890 // Generate OpAccessChain.
3891 //
3892 GetElementPtrInst *GEP = cast<GetElementPtrInst>(&I);
3893
3894 //
3895 // Generate OpAccessChain.
3896 //
3897
3898 // Ops[0] = Result Type ID
3899 // Ops[1] = Base ID
3900 // Ops[2] ... Ops[n] = Indexes ID
3901 SPIRVOperandList Ops;
3902
alan-bakerb6b09dc2018-11-08 16:59:28 -05003903 PointerType *ResultType = cast<PointerType>(GEP->getType());
David Neto22f144c2017-06-12 14:26:21 -04003904 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate ||
3905 GlobalConstArgSet.count(GEP->getPointerOperand())) {
3906 // Use pointer type with private address space for global constant.
3907 Type *EleTy = I.getType()->getPointerElementType();
David Neto1a1a0582017-07-07 12:01:44 -04003908 ResultType = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
David Neto22f144c2017-06-12 14:26:21 -04003909 }
David Neto257c3892018-04-11 13:19:45 -04003910
3911 Ops << MkId(lookupType(ResultType));
David Neto22f144c2017-06-12 14:26:21 -04003912
David Neto862b7d82018-06-14 18:48:37 -04003913 // Generate the base pointer.
3914 Ops << MkId(VMap[GEP->getPointerOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04003915
David Neto862b7d82018-06-14 18:48:37 -04003916 // TODO(dneto): Simplify the following?
David Neto22f144c2017-06-12 14:26:21 -04003917
3918 //
3919 // Follows below rules for gep.
3920 //
David Neto862b7d82018-06-14 18:48:37 -04003921 // 1. If gep's first index is 0 generate OpAccessChain and ignore gep's
3922 // first index.
David Neto22f144c2017-06-12 14:26:21 -04003923 // 2. If gep's first index is not 0, generate OpPtrAccessChain and use gep's
3924 // first index.
3925 // 3. If gep's first index is not constant, generate OpPtrAccessChain and
3926 // use gep's first index.
3927 // 4. If it is not above case 1, 2 and 3, generate OpAccessChain and use
3928 // gep's first index.
3929 //
3930 spv::Op Opcode = spv::OpAccessChain;
3931 unsigned offset = 0;
3932 if (ConstantInt *CstInt = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
David Neto862b7d82018-06-14 18:48:37 -04003933 if (CstInt->getZExtValue() == 0) {
David Neto22f144c2017-06-12 14:26:21 -04003934 offset = 1;
David Neto862b7d82018-06-14 18:48:37 -04003935 } else if (CstInt->getZExtValue() != 0) {
David Neto22f144c2017-06-12 14:26:21 -04003936 Opcode = spv::OpPtrAccessChain;
David Neto22f144c2017-06-12 14:26:21 -04003937 }
David Neto862b7d82018-06-14 18:48:37 -04003938 } else {
David Neto22f144c2017-06-12 14:26:21 -04003939 Opcode = spv::OpPtrAccessChain;
David Neto1a1a0582017-07-07 12:01:44 -04003940 }
3941
3942 if (Opcode == spv::OpPtrAccessChain) {
David Neto1a1a0582017-07-07 12:01:44 -04003943 // Do we need to generate ArrayStride? Check against the GEP result type
3944 // rather than the pointer type of the base because when indexing into
3945 // an OpenCL program-scope constant, we'll swap out the LLVM base pointer
3946 // for something else in the SPIR-V.
3947 // E.g. see test/PointerAccessChain/pointer_index_is_constant_1.cl
alan-baker5b86ed72019-02-15 08:26:50 -05003948 auto address_space = ResultType->getAddressSpace();
3949 setVariablePointersCapabilities(address_space);
3950 switch (GetStorageClass(address_space)) {
Alan Bakerfcda9482018-10-02 17:09:59 -04003951 case spv::StorageClassStorageBuffer:
3952 case spv::StorageClassUniform:
David Neto1a1a0582017-07-07 12:01:44 -04003953 // Save the need to generate an ArrayStride decoration. But defer
3954 // generation until later, so we only make one decoration.
David Neto85082642018-03-24 06:55:20 -07003955 getTypesNeedingArrayStride().insert(ResultType);
Alan Bakerfcda9482018-10-02 17:09:59 -04003956 break;
3957 default:
3958 break;
David Neto1a1a0582017-07-07 12:01:44 -04003959 }
David Neto22f144c2017-06-12 14:26:21 -04003960 }
3961
3962 for (auto II = GEP->idx_begin() + offset; II != GEP->idx_end(); II++) {
David Neto257c3892018-04-11 13:19:45 -04003963 Ops << MkId(VMap[*II]);
David Neto22f144c2017-06-12 14:26:21 -04003964 }
3965
David Neto87846742018-04-11 17:36:22 -04003966 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003967 SPIRVInstList.push_back(Inst);
3968 break;
3969 }
3970 case Instruction::ExtractValue: {
3971 ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
3972 // Ops[0] = Result Type ID
3973 // Ops[1] = Composite ID
3974 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3975 SPIRVOperandList Ops;
3976
David Neto257c3892018-04-11 13:19:45 -04003977 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003978
3979 uint32_t CompositeID = VMap[EVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003980 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003981
3982 for (auto &Index : EVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003983 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003984 }
3985
David Neto87846742018-04-11 17:36:22 -04003986 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003987 SPIRVInstList.push_back(Inst);
3988 break;
3989 }
3990 case Instruction::InsertValue: {
3991 InsertValueInst *IVI = cast<InsertValueInst>(&I);
3992 // Ops[0] = Result Type ID
3993 // Ops[1] = Object ID
3994 // Ops[2] = Composite ID
3995 // Ops[3] ... Ops[n] = Indexes (Literal Number)
3996 SPIRVOperandList Ops;
3997
3998 uint32_t ResTyID = lookupType(I.getType());
David Neto257c3892018-04-11 13:19:45 -04003999 Ops << MkId(ResTyID);
David Neto22f144c2017-06-12 14:26:21 -04004000
4001 uint32_t ObjectID = VMap[IVI->getInsertedValueOperand()];
David Neto257c3892018-04-11 13:19:45 -04004002 Ops << MkId(ObjectID);
David Neto22f144c2017-06-12 14:26:21 -04004003
4004 uint32_t CompositeID = VMap[IVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04004005 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04004006
4007 for (auto &Index : IVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04004008 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04004009 }
4010
David Neto87846742018-04-11 17:36:22 -04004011 auto *Inst = new SPIRVInstruction(spv::OpCompositeInsert, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004012 SPIRVInstList.push_back(Inst);
4013 break;
4014 }
4015 case Instruction::Select: {
4016 //
4017 // Generate OpSelect.
4018 //
4019
4020 // Ops[0] = Result Type ID
4021 // Ops[1] = Condition ID
4022 // Ops[2] = True Constant ID
4023 // Ops[3] = False Constant ID
4024 SPIRVOperandList Ops;
4025
4026 // Find SPIRV instruction for parameter type.
4027 auto Ty = I.getType();
4028 if (Ty->isPointerTy()) {
4029 auto PointeeTy = Ty->getPointerElementType();
4030 if (PointeeTy->isStructTy() &&
4031 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
4032 Ty = PointeeTy;
alan-baker5b86ed72019-02-15 08:26:50 -05004033 } else {
4034 // Selecting between pointers requires variable pointers.
4035 setVariablePointersCapabilities(Ty->getPointerAddressSpace());
4036 if (!hasVariablePointers() && !selectFromSameObject(&I)) {
4037 setVariablePointers(true);
4038 }
David Neto22f144c2017-06-12 14:26:21 -04004039 }
4040 }
4041
David Neto257c3892018-04-11 13:19:45 -04004042 Ops << MkId(lookupType(Ty)) << MkId(VMap[I.getOperand(0)])
4043 << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004044
David Neto87846742018-04-11 17:36:22 -04004045 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004046 SPIRVInstList.push_back(Inst);
4047 break;
4048 }
4049 case Instruction::ExtractElement: {
4050 // Handle <4 x i8> type manually.
4051 Type *CompositeTy = I.getOperand(0)->getType();
4052 if (is4xi8vec(CompositeTy)) {
4053 //
4054 // Generate OpShiftRightLogical and OpBitwiseAnd for extractelement with
4055 // <4 x i8>.
4056 //
4057
4058 //
4059 // Generate OpShiftRightLogical
4060 //
4061 // Ops[0] = Result Type ID
4062 // Ops[1] = Operand 0
4063 // Ops[2] = Operand 1
4064 //
4065 SPIRVOperandList Ops;
4066
David Neto257c3892018-04-11 13:19:45 -04004067 Ops << MkId(lookupType(CompositeTy));
David Neto22f144c2017-06-12 14:26:21 -04004068
4069 uint32_t Op0ID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04004070 Ops << MkId(Op0ID);
David Neto22f144c2017-06-12 14:26:21 -04004071
4072 uint32_t Op1ID = 0;
4073 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
4074 // Handle constant index.
4075 uint64_t Idx = CI->getZExtValue();
4076 Value *ShiftAmount =
4077 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
4078 Op1ID = VMap[ShiftAmount];
4079 } else {
4080 // Handle variable index.
4081 SPIRVOperandList TmpOps;
4082
David Neto257c3892018-04-11 13:19:45 -04004083 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
4084 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004085
4086 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04004087 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04004088
4089 Op1ID = nextID;
4090
David Neto87846742018-04-11 17:36:22 -04004091 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04004092 SPIRVInstList.push_back(TmpInst);
4093 }
David Neto257c3892018-04-11 13:19:45 -04004094 Ops << MkId(Op1ID);
David Neto22f144c2017-06-12 14:26:21 -04004095
4096 uint32_t ShiftID = nextID;
4097
David Neto87846742018-04-11 17:36:22 -04004098 auto *Inst =
4099 new SPIRVInstruction(spv::OpShiftRightLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004100 SPIRVInstList.push_back(Inst);
4101
4102 //
4103 // Generate OpBitwiseAnd
4104 //
4105 // Ops[0] = Result Type ID
4106 // Ops[1] = Operand 0
4107 // Ops[2] = Operand 1
4108 //
4109 Ops.clear();
4110
David Neto257c3892018-04-11 13:19:45 -04004111 Ops << MkId(lookupType(CompositeTy)) << MkId(ShiftID);
David Neto22f144c2017-06-12 14:26:21 -04004112
4113 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
David Neto257c3892018-04-11 13:19:45 -04004114 Ops << MkId(VMap[CstFF]);
David Neto22f144c2017-06-12 14:26:21 -04004115
David Neto9b2d6252017-09-06 15:47:37 -04004116 // Reset mapping for this value to the result of the bitwise and.
4117 VMap[&I] = nextID;
4118
David Neto87846742018-04-11 17:36:22 -04004119 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004120 SPIRVInstList.push_back(Inst);
4121 break;
4122 }
4123
4124 // Ops[0] = Result Type ID
4125 // Ops[1] = Composite ID
4126 // Ops[2] ... Ops[n] = Indexes (Literal Number)
4127 SPIRVOperandList Ops;
4128
David Neto257c3892018-04-11 13:19:45 -04004129 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004130
4131 spv::Op Opcode = spv::OpCompositeExtract;
4132 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
David Neto257c3892018-04-11 13:19:45 -04004133 Ops << MkNum(static_cast<uint32_t>(CI->getZExtValue()));
David Neto22f144c2017-06-12 14:26:21 -04004134 } else {
David Neto257c3892018-04-11 13:19:45 -04004135 Ops << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004136 Opcode = spv::OpVectorExtractDynamic;
4137 }
4138
David Neto87846742018-04-11 17:36:22 -04004139 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004140 SPIRVInstList.push_back(Inst);
4141 break;
4142 }
4143 case Instruction::InsertElement: {
4144 // Handle <4 x i8> type manually.
4145 Type *CompositeTy = I.getOperand(0)->getType();
4146 if (is4xi8vec(CompositeTy)) {
4147 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
4148 uint32_t CstFFID = VMap[CstFF];
4149
4150 uint32_t ShiftAmountID = 0;
4151 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
4152 // Handle constant index.
4153 uint64_t Idx = CI->getZExtValue();
4154 Value *ShiftAmount =
4155 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
4156 ShiftAmountID = VMap[ShiftAmount];
4157 } else {
4158 // Handle variable index.
4159 SPIRVOperandList TmpOps;
4160
David Neto257c3892018-04-11 13:19:45 -04004161 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
4162 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004163
4164 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04004165 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04004166
4167 ShiftAmountID = nextID;
4168
David Neto87846742018-04-11 17:36:22 -04004169 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04004170 SPIRVInstList.push_back(TmpInst);
4171 }
4172
4173 //
4174 // Generate mask operations.
4175 //
4176
4177 // ShiftLeft mask according to index of insertelement.
4178 SPIRVOperandList Ops;
4179
David Neto257c3892018-04-11 13:19:45 -04004180 const uint32_t ResTyID = lookupType(CompositeTy);
4181 Ops << MkId(ResTyID) << MkId(CstFFID) << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04004182
4183 uint32_t MaskID = nextID;
4184
David Neto87846742018-04-11 17:36:22 -04004185 auto *Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004186 SPIRVInstList.push_back(Inst);
4187
4188 // Inverse mask.
4189 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004190 Ops << MkId(ResTyID) << MkId(MaskID);
David Neto22f144c2017-06-12 14:26:21 -04004191
4192 uint32_t InvMaskID = nextID;
4193
David Neto87846742018-04-11 17:36:22 -04004194 Inst = new SPIRVInstruction(spv::OpNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004195 SPIRVInstList.push_back(Inst);
4196
4197 // Apply mask.
4198 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004199 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(0)]) << MkId(InvMaskID);
David Neto22f144c2017-06-12 14:26:21 -04004200
4201 uint32_t OrgValID = nextID;
4202
David Neto87846742018-04-11 17:36:22 -04004203 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004204 SPIRVInstList.push_back(Inst);
4205
4206 // Create correct value according to index of insertelement.
4207 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05004208 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(1)])
4209 << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04004210
4211 uint32_t InsertValID = nextID;
4212
David Neto87846742018-04-11 17:36:22 -04004213 Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004214 SPIRVInstList.push_back(Inst);
4215
4216 // Insert value to original value.
4217 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004218 Ops << MkId(ResTyID) << MkId(OrgValID) << MkId(InsertValID);
David Neto22f144c2017-06-12 14:26:21 -04004219
David Netoa394f392017-08-26 20:45:29 -04004220 VMap[&I] = nextID;
4221
David Neto87846742018-04-11 17:36:22 -04004222 Inst = new SPIRVInstruction(spv::OpBitwiseOr, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004223 SPIRVInstList.push_back(Inst);
4224
4225 break;
4226 }
4227
David Neto22f144c2017-06-12 14:26:21 -04004228 SPIRVOperandList Ops;
4229
James Priced26efea2018-06-09 23:28:32 +01004230 // Ops[0] = Result Type ID
4231 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004232
4233 spv::Op Opcode = spv::OpCompositeInsert;
4234 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
David Neto257c3892018-04-11 13:19:45 -04004235 const auto value = CI->getZExtValue();
4236 assert(value <= UINT32_MAX);
James Priced26efea2018-06-09 23:28:32 +01004237 // Ops[1] = Object ID
4238 // Ops[2] = Composite ID
4239 // Ops[3] ... Ops[n] = Indexes (Literal Number)
alan-bakerb6b09dc2018-11-08 16:59:28 -05004240 Ops << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(0)])
James Priced26efea2018-06-09 23:28:32 +01004241 << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004242 } else {
James Priced26efea2018-06-09 23:28:32 +01004243 // Ops[1] = Composite ID
4244 // Ops[2] = Object ID
4245 // Ops[3] ... Ops[n] = Indexes (Literal Number)
alan-bakerb6b09dc2018-11-08 16:59:28 -05004246 Ops << MkId(VMap[I.getOperand(0)]) << MkId(VMap[I.getOperand(1)])
James Priced26efea2018-06-09 23:28:32 +01004247 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004248 Opcode = spv::OpVectorInsertDynamic;
4249 }
4250
David Neto87846742018-04-11 17:36:22 -04004251 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004252 SPIRVInstList.push_back(Inst);
4253 break;
4254 }
4255 case Instruction::ShuffleVector: {
4256 // Ops[0] = Result Type ID
4257 // Ops[1] = Vector 1 ID
4258 // Ops[2] = Vector 2 ID
4259 // Ops[3] ... Ops[n] = Components (Literal Number)
4260 SPIRVOperandList Ops;
4261
David Neto257c3892018-04-11 13:19:45 -04004262 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
4263 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004264
4265 uint64_t NumElements = 0;
4266 if (Constant *Cst = dyn_cast<Constant>(I.getOperand(2))) {
4267 NumElements = cast<VectorType>(Cst->getType())->getNumElements();
4268
4269 if (Cst->isNullValue()) {
4270 for (unsigned i = 0; i < NumElements; i++) {
David Neto257c3892018-04-11 13:19:45 -04004271 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04004272 }
4273 } else if (const ConstantDataSequential *CDS =
4274 dyn_cast<ConstantDataSequential>(Cst)) {
4275 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
4276 std::vector<uint32_t> LiteralNum;
David Neto257c3892018-04-11 13:19:45 -04004277 const auto value = CDS->getElementAsInteger(i);
4278 assert(value <= UINT32_MAX);
4279 Ops << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004280 }
4281 } else if (const ConstantVector *CV = dyn_cast<ConstantVector>(Cst)) {
4282 for (unsigned i = 0; i < CV->getNumOperands(); i++) {
4283 auto Op = CV->getOperand(i);
4284
4285 uint32_t literal = 0;
4286
4287 if (auto CI = dyn_cast<ConstantInt>(Op)) {
4288 literal = static_cast<uint32_t>(CI->getZExtValue());
4289 } else if (auto UI = dyn_cast<UndefValue>(Op)) {
4290 literal = 0xFFFFFFFFu;
4291 } else {
4292 Op->print(errs());
4293 llvm_unreachable("Unsupported element in ConstantVector!");
4294 }
4295
David Neto257c3892018-04-11 13:19:45 -04004296 Ops << MkNum(literal);
David Neto22f144c2017-06-12 14:26:21 -04004297 }
4298 } else {
4299 Cst->print(errs());
4300 llvm_unreachable("Unsupported constant mask in ShuffleVector!");
4301 }
4302 }
4303
David Neto87846742018-04-11 17:36:22 -04004304 auto *Inst = new SPIRVInstruction(spv::OpVectorShuffle, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004305 SPIRVInstList.push_back(Inst);
4306 break;
4307 }
4308 case Instruction::ICmp:
4309 case Instruction::FCmp: {
4310 CmpInst *CmpI = cast<CmpInst>(&I);
4311
David Netod4ca2e62017-07-06 18:47:35 -04004312 // Pointer equality is invalid.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004313 Type *ArgTy = CmpI->getOperand(0)->getType();
David Netod4ca2e62017-07-06 18:47:35 -04004314 if (isa<PointerType>(ArgTy)) {
4315 CmpI->print(errs());
4316 std::string name = I.getParent()->getParent()->getName();
4317 errs()
4318 << "\nPointer equality test is not supported by SPIR-V for Vulkan, "
4319 << "in function " << name << "\n";
4320 llvm_unreachable("Pointer equality check is invalid");
4321 break;
4322 }
4323
David Neto257c3892018-04-11 13:19:45 -04004324 // Ops[0] = Result Type ID
4325 // Ops[1] = Operand 1 ID
4326 // Ops[2] = Operand 2 ID
4327 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04004328
David Neto257c3892018-04-11 13:19:45 -04004329 Ops << MkId(lookupType(CmpI->getType())) << MkId(VMap[CmpI->getOperand(0)])
4330 << MkId(VMap[CmpI->getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004331
4332 spv::Op Opcode = GetSPIRVCmpOpcode(CmpI);
David Neto87846742018-04-11 17:36:22 -04004333 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004334 SPIRVInstList.push_back(Inst);
4335 break;
4336 }
4337 case Instruction::Br: {
4338 // Branch instrucion is deferred because it needs label's ID. Record slot's
4339 // location on SPIRVInstructionList.
4340 DeferredInsts.push_back(
4341 std::make_tuple(&I, --SPIRVInstList.end(), 0 /* No id */));
4342 break;
4343 }
4344 case Instruction::Switch: {
4345 I.print(errs());
4346 llvm_unreachable("Unsupported instruction???");
4347 break;
4348 }
4349 case Instruction::IndirectBr: {
4350 I.print(errs());
4351 llvm_unreachable("Unsupported instruction???");
4352 break;
4353 }
4354 case Instruction::PHI: {
4355 // Branch instrucion is deferred because it needs label's ID. Record slot's
4356 // location on SPIRVInstructionList.
4357 DeferredInsts.push_back(
4358 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4359 break;
4360 }
4361 case Instruction::Alloca: {
4362 //
4363 // Generate OpVariable.
4364 //
4365 // Ops[0] : Result Type ID
4366 // Ops[1] : Storage Class
4367 SPIRVOperandList Ops;
4368
David Neto257c3892018-04-11 13:19:45 -04004369 Ops << MkId(lookupType(I.getType())) << MkNum(spv::StorageClassFunction);
David Neto22f144c2017-06-12 14:26:21 -04004370
David Neto87846742018-04-11 17:36:22 -04004371 auto *Inst = new SPIRVInstruction(spv::OpVariable, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004372 SPIRVInstList.push_back(Inst);
4373 break;
4374 }
4375 case Instruction::Load: {
4376 LoadInst *LD = cast<LoadInst>(&I);
4377 //
4378 // Generate OpLoad.
4379 //
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04004380
alan-baker5b86ed72019-02-15 08:26:50 -05004381 if (LD->getType()->isPointerTy()) {
4382 // Loading a pointer requires variable pointers.
4383 setVariablePointersCapabilities(LD->getType()->getPointerAddressSpace());
4384 }
David Neto22f144c2017-06-12 14:26:21 -04004385
David Neto0a2f98d2017-09-15 19:38:40 -04004386 uint32_t ResTyID = lookupType(LD->getType());
David Netoa60b00b2017-09-15 16:34:09 -04004387 uint32_t PointerID = VMap[LD->getPointerOperand()];
4388
4389 // This is a hack to work around what looks like a driver bug.
4390 // When we're loading from the special variable holding the WorkgroupSize
David Neto0a2f98d2017-09-15 19:38:40 -04004391 // builtin value, use an OpBitWiseAnd of the value's ID rather than
4392 // generating a load.
David Neto66cfe642018-03-24 06:13:56 -07004393 // TODO(dneto): Remove this awful hack once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -04004394 if (PointerID == WorkgroupSizeVarID) {
David Neto0a2f98d2017-09-15 19:38:40 -04004395 // Generate a bitwise-and of the original value with itself.
4396 // We should have been able to get away with just an OpCopyObject,
4397 // but we need something more complex to get past certain driver bugs.
4398 // This is ridiculous, but necessary.
4399 // TODO(dneto): Revisit this once drivers fix their bugs.
4400
4401 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004402 Ops << MkId(ResTyID) << MkId(WorkgroupSizeValueID)
4403 << MkId(WorkgroupSizeValueID);
David Neto0a2f98d2017-09-15 19:38:40 -04004404
David Neto87846742018-04-11 17:36:22 -04004405 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto0a2f98d2017-09-15 19:38:40 -04004406 SPIRVInstList.push_back(Inst);
David Netoa60b00b2017-09-15 16:34:09 -04004407 break;
4408 }
4409
4410 // This is the normal path. Generate a load.
4411
David Neto22f144c2017-06-12 14:26:21 -04004412 // Ops[0] = Result Type ID
4413 // Ops[1] = Pointer ID
4414 // Ops[2] ... Ops[n] = Optional Memory Access
4415 //
4416 // TODO: Do we need to implement Optional Memory Access???
David Neto0a2f98d2017-09-15 19:38:40 -04004417
David Neto22f144c2017-06-12 14:26:21 -04004418 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004419 Ops << MkId(ResTyID) << MkId(PointerID);
David Neto22f144c2017-06-12 14:26:21 -04004420
David Neto87846742018-04-11 17:36:22 -04004421 auto *Inst = new SPIRVInstruction(spv::OpLoad, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004422 SPIRVInstList.push_back(Inst);
4423 break;
4424 }
4425 case Instruction::Store: {
4426 StoreInst *ST = cast<StoreInst>(&I);
4427 //
4428 // Generate OpStore.
4429 //
4430
alan-baker5b86ed72019-02-15 08:26:50 -05004431 if (ST->getValueOperand()->getType()->isPointerTy()) {
4432 // Storing a pointer requires variable pointers.
4433 setVariablePointersCapabilities(
4434 ST->getValueOperand()->getType()->getPointerAddressSpace());
4435 }
4436
David Neto22f144c2017-06-12 14:26:21 -04004437 // Ops[0] = Pointer ID
4438 // Ops[1] = Object ID
4439 // Ops[2] ... Ops[n] = Optional Memory Access (later???)
4440 //
4441 // TODO: Do we need to implement Optional Memory Access???
David Neto257c3892018-04-11 13:19:45 -04004442 SPIRVOperandList Ops;
4443 Ops << MkId(VMap[ST->getPointerOperand()])
4444 << MkId(VMap[ST->getValueOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04004445
David Neto87846742018-04-11 17:36:22 -04004446 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004447 SPIRVInstList.push_back(Inst);
4448 break;
4449 }
4450 case Instruction::AtomicCmpXchg: {
4451 I.print(errs());
4452 llvm_unreachable("Unsupported instruction???");
4453 break;
4454 }
4455 case Instruction::AtomicRMW: {
Neil Henning39672102017-09-29 14:33:13 +01004456 AtomicRMWInst *AtomicRMW = dyn_cast<AtomicRMWInst>(&I);
4457
4458 spv::Op opcode;
4459
4460 switch (AtomicRMW->getOperation()) {
4461 default:
4462 I.print(errs());
4463 llvm_unreachable("Unsupported instruction???");
4464 case llvm::AtomicRMWInst::Add:
4465 opcode = spv::OpAtomicIAdd;
4466 break;
4467 case llvm::AtomicRMWInst::Sub:
4468 opcode = spv::OpAtomicISub;
4469 break;
4470 case llvm::AtomicRMWInst::Xchg:
4471 opcode = spv::OpAtomicExchange;
4472 break;
4473 case llvm::AtomicRMWInst::Min:
4474 opcode = spv::OpAtomicSMin;
4475 break;
4476 case llvm::AtomicRMWInst::Max:
4477 opcode = spv::OpAtomicSMax;
4478 break;
4479 case llvm::AtomicRMWInst::UMin:
4480 opcode = spv::OpAtomicUMin;
4481 break;
4482 case llvm::AtomicRMWInst::UMax:
4483 opcode = spv::OpAtomicUMax;
4484 break;
4485 case llvm::AtomicRMWInst::And:
4486 opcode = spv::OpAtomicAnd;
4487 break;
4488 case llvm::AtomicRMWInst::Or:
4489 opcode = spv::OpAtomicOr;
4490 break;
4491 case llvm::AtomicRMWInst::Xor:
4492 opcode = spv::OpAtomicXor;
4493 break;
4494 }
4495
4496 //
4497 // Generate OpAtomic*.
4498 //
4499 SPIRVOperandList Ops;
4500
David Neto257c3892018-04-11 13:19:45 -04004501 Ops << MkId(lookupType(I.getType()))
4502 << MkId(VMap[AtomicRMW->getPointerOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004503
4504 auto IntTy = Type::getInt32Ty(I.getContext());
Neil Henning39672102017-09-29 14:33:13 +01004505 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
David Neto257c3892018-04-11 13:19:45 -04004506 Ops << MkId(VMap[ConstantScopeDevice]);
Neil Henning39672102017-09-29 14:33:13 +01004507
4508 const auto ConstantMemorySemantics = ConstantInt::get(
4509 IntTy, spv::MemorySemanticsUniformMemoryMask |
4510 spv::MemorySemanticsSequentiallyConsistentMask);
David Neto257c3892018-04-11 13:19:45 -04004511 Ops << MkId(VMap[ConstantMemorySemantics]);
Neil Henning39672102017-09-29 14:33:13 +01004512
David Neto257c3892018-04-11 13:19:45 -04004513 Ops << MkId(VMap[AtomicRMW->getValOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004514
4515 VMap[&I] = nextID;
4516
David Neto87846742018-04-11 17:36:22 -04004517 auto *Inst = new SPIRVInstruction(opcode, nextID++, Ops);
Neil Henning39672102017-09-29 14:33:13 +01004518 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04004519 break;
4520 }
4521 case Instruction::Fence: {
4522 I.print(errs());
4523 llvm_unreachable("Unsupported instruction???");
4524 break;
4525 }
4526 case Instruction::Call: {
4527 CallInst *Call = dyn_cast<CallInst>(&I);
4528 Function *Callee = Call->getCalledFunction();
4529
Alan Baker202c8c72018-08-13 13:47:44 -04004530 if (Callee->getName().startswith(clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04004531 if (ResourceVarDeferredLoadCalls.count(Call) && Call->hasNUsesOrMore(1)) {
4532 // Generate an OpLoad
4533 SPIRVOperandList Ops;
4534 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004535
David Neto862b7d82018-06-14 18:48:37 -04004536 Ops << MkId(lookupType(Call->getType()->getPointerElementType()))
4537 << MkId(ResourceVarDeferredLoadCalls[Call]);
4538
4539 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
4540 SPIRVInstList.push_back(Inst);
4541 VMap[Call] = load_id;
4542 break;
4543
4544 } else {
4545 // This maps to an OpVariable we've already generated.
4546 // No code is generated for the call.
4547 }
4548 break;
alan-bakerb6b09dc2018-11-08 16:59:28 -05004549 } else if (Callee->getName().startswith(
4550 clspv::WorkgroupAccessorFunction())) {
Alan Baker202c8c72018-08-13 13:47:44 -04004551 // Don't codegen an instruction here, but instead map this call directly
4552 // to the workgroup variable id.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004553 int spec_id = static_cast<int>(
4554 cast<ConstantInt>(Call->getOperand(0))->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04004555 const auto &info = LocalSpecIdInfoMap[spec_id];
4556 VMap[Call] = info.variable_id;
4557 break;
David Neto862b7d82018-06-14 18:48:37 -04004558 }
4559
4560 // Sampler initializers become a load of the corresponding sampler.
4561
Kévin Petitdf71de32019-04-09 14:09:50 +01004562 if (Callee->getName().equals(clspv::LiteralSamplerFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04004563 // Map this to a load from the variable.
alan-baker09cb9802019-12-10 13:16:27 -05004564 const auto third_param = static_cast<unsigned>(
4565 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue());
4566 auto sampler_value = third_param;
4567 if (clspv::Option::UseSamplerMap()) {
4568 sampler_value = getSamplerMap()[third_param].first;
4569 }
David Neto862b7d82018-06-14 18:48:37 -04004570
4571 // Generate an OpLoad
David Neto22f144c2017-06-12 14:26:21 -04004572 SPIRVOperandList Ops;
David Neto862b7d82018-06-14 18:48:37 -04004573 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004574
David Neto257c3892018-04-11 13:19:45 -04004575 Ops << MkId(lookupType(SamplerTy->getPointerElementType()))
alan-baker09cb9802019-12-10 13:16:27 -05004576 << MkId(SamplerLiteralToIDMap[sampler_value]);
David Neto22f144c2017-06-12 14:26:21 -04004577
David Neto862b7d82018-06-14 18:48:37 -04004578 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004579 SPIRVInstList.push_back(Inst);
David Neto862b7d82018-06-14 18:48:37 -04004580 VMap[Call] = load_id;
David Neto22f144c2017-06-12 14:26:21 -04004581 break;
4582 }
4583
Kévin Petit349c9502019-03-28 17:24:14 +00004584 // Handle SPIR-V intrinsics
Kévin Petit9b340262019-06-19 18:31:11 +01004585 spv::Op opcode = StringSwitch<spv::Op>(Callee->getName())
4586 .Case("spirv.atomic_xor", spv::OpAtomicXor)
4587 .Default(spv::OpNop);
David Neto22f144c2017-06-12 14:26:21 -04004588
Kévin Petit617a76d2019-04-04 13:54:16 +01004589 // If the switch above didn't have an entry maybe the intrinsic
4590 // is using the name mangling logic.
4591 bool usesMangler = false;
4592 if (opcode == spv::OpNop) {
4593 if (Callee->getName().startswith(clspv::SPIRVOpIntrinsicFunction())) {
4594 auto OpCst = cast<ConstantInt>(Call->getOperand(0));
4595 opcode = static_cast<spv::Op>(OpCst->getZExtValue());
4596 usesMangler = true;
4597 }
4598 }
4599
Kévin Petit349c9502019-03-28 17:24:14 +00004600 if (opcode != spv::OpNop) {
4601
David Neto22f144c2017-06-12 14:26:21 -04004602 SPIRVOperandList Ops;
4603
Kévin Petit349c9502019-03-28 17:24:14 +00004604 if (!I.getType()->isVoidTy()) {
4605 Ops << MkId(lookupType(I.getType()));
4606 }
David Neto22f144c2017-06-12 14:26:21 -04004607
Kévin Petit617a76d2019-04-04 13:54:16 +01004608 unsigned firstOperand = usesMangler ? 1 : 0;
4609 for (unsigned i = firstOperand; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004610 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004611 }
4612
Kévin Petit349c9502019-03-28 17:24:14 +00004613 if (!I.getType()->isVoidTy()) {
4614 VMap[&I] = nextID;
Kévin Petit8a560882019-03-21 15:24:34 +00004615 }
4616
Kévin Petit349c9502019-03-28 17:24:14 +00004617 SPIRVInstruction *Inst;
4618 if (!I.getType()->isVoidTy()) {
4619 Inst = new SPIRVInstruction(opcode, nextID++, Ops);
4620 } else {
4621 Inst = new SPIRVInstruction(opcode, Ops);
4622 }
Kévin Petit8a560882019-03-21 15:24:34 +00004623 SPIRVInstList.push_back(Inst);
4624 break;
4625 }
4626
David Neto22f144c2017-06-12 14:26:21 -04004627 // spirv.copy_memory.* intrinsics become OpMemoryMemory's.
4628 if (Callee->getName().startswith("spirv.copy_memory")) {
4629 //
4630 // Generate OpCopyMemory.
4631 //
4632
4633 // Ops[0] = Dst ID
4634 // Ops[1] = Src ID
4635 // Ops[2] = Memory Access
4636 // Ops[3] = Alignment
4637
4638 auto IsVolatile =
4639 dyn_cast<ConstantInt>(Call->getArgOperand(3))->getZExtValue() != 0;
4640
4641 auto VolatileMemoryAccess = (IsVolatile) ? spv::MemoryAccessVolatileMask
4642 : spv::MemoryAccessMaskNone;
4643
4644 auto MemoryAccess = VolatileMemoryAccess | spv::MemoryAccessAlignedMask;
4645
4646 auto Alignment =
4647 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4648
David Neto257c3892018-04-11 13:19:45 -04004649 SPIRVOperandList Ops;
4650 Ops << MkId(VMap[Call->getArgOperand(0)])
4651 << MkId(VMap[Call->getArgOperand(1)]) << MkNum(MemoryAccess)
4652 << MkNum(static_cast<uint32_t>(Alignment));
David Neto22f144c2017-06-12 14:26:21 -04004653
David Neto87846742018-04-11 17:36:22 -04004654 auto *Inst = new SPIRVInstruction(spv::OpCopyMemory, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004655
4656 SPIRVInstList.push_back(Inst);
4657
4658 break;
4659 }
4660
David Neto22f144c2017-06-12 14:26:21 -04004661 // read_image is converted to OpSampledImage and OpImageSampleExplicitLod.
4662 // Additionally, OpTypeSampledImage is generated.
alan-bakerf67468c2019-11-25 15:51:49 -05004663 if (clspv::IsSampledImageRead(Callee)) {
David Neto22f144c2017-06-12 14:26:21 -04004664 //
4665 // Generate OpSampledImage.
4666 //
4667 // Ops[0] = Result Type ID
4668 // Ops[1] = Image ID
4669 // Ops[2] = Sampler ID
4670 //
4671 SPIRVOperandList Ops;
4672
4673 Value *Image = Call->getArgOperand(0);
4674 Value *Sampler = Call->getArgOperand(1);
4675 Value *Coordinate = Call->getArgOperand(2);
4676
4677 TypeMapType &OpImageTypeMap = getImageTypeMap();
4678 Type *ImageTy = Image->getType()->getPointerElementType();
4679 uint32_t ImageTyID = OpImageTypeMap[ImageTy];
David Neto22f144c2017-06-12 14:26:21 -04004680 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004681 uint32_t SamplerID = VMap[Sampler];
David Neto257c3892018-04-11 13:19:45 -04004682
4683 Ops << MkId(ImageTyID) << MkId(ImageID) << MkId(SamplerID);
David Neto22f144c2017-06-12 14:26:21 -04004684
4685 uint32_t SampledImageID = nextID;
4686
David Neto87846742018-04-11 17:36:22 -04004687 auto *Inst = new SPIRVInstruction(spv::OpSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004688 SPIRVInstList.push_back(Inst);
4689
4690 //
4691 // Generate OpImageSampleExplicitLod.
4692 //
4693 // Ops[0] = Result Type ID
4694 // Ops[1] = Sampled Image ID
4695 // Ops[2] = Coordinate ID
4696 // Ops[3] = Image Operands Type ID
4697 // Ops[4] ... Ops[n] = Operands ID
4698 //
4699 Ops.clear();
4700
alan-bakerf67468c2019-11-25 15:51:49 -05004701 const bool is_int_image = IsIntImageType(Image->getType());
4702 uint32_t result_type = 0;
4703 if (is_int_image) {
4704 result_type = v4int32ID;
4705 } else {
4706 result_type = lookupType(Call->getType());
4707 }
4708
4709 Ops << MkId(result_type) << MkId(SampledImageID) << MkId(VMap[Coordinate])
4710 << MkNum(spv::ImageOperandsLodMask);
David Neto22f144c2017-06-12 14:26:21 -04004711
4712 Constant *CstFP0 = ConstantFP::get(Context, APFloat(0.0f));
David Neto257c3892018-04-11 13:19:45 -04004713 Ops << MkId(VMap[CstFP0]);
David Neto22f144c2017-06-12 14:26:21 -04004714
alan-bakerf67468c2019-11-25 15:51:49 -05004715 uint32_t final_id = nextID++;
4716 VMap[&I] = final_id;
David Neto22f144c2017-06-12 14:26:21 -04004717
alan-bakerf67468c2019-11-25 15:51:49 -05004718 uint32_t image_id = final_id;
4719 if (is_int_image) {
4720 // Int image requires a bitcast from v4int to v4uint.
4721 image_id = nextID++;
4722 }
4723
4724 Inst = new SPIRVInstruction(spv::OpImageSampleExplicitLod, image_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004725 SPIRVInstList.push_back(Inst);
alan-bakerf67468c2019-11-25 15:51:49 -05004726
4727 if (is_int_image) {
4728 // Generate the bitcast.
4729 Ops.clear();
4730 Ops << MkId(lookupType(Call->getType())) << MkId(image_id);
4731 Inst = new SPIRVInstruction(spv::OpBitcast, final_id, Ops);
4732 SPIRVInstList.push_back(Inst);
4733 }
David Neto22f144c2017-06-12 14:26:21 -04004734 break;
4735 }
4736
alan-bakerf67468c2019-11-25 15:51:49 -05004737 // write_image is mapped to OpImageWrite.
4738 if (clspv::IsImageWrite(Callee)) {
David Neto22f144c2017-06-12 14:26:21 -04004739 //
4740 // Generate OpImageWrite.
4741 //
4742 // Ops[0] = Image ID
4743 // Ops[1] = Coordinate ID
4744 // Ops[2] = Texel ID
4745 // Ops[3] = (Optional) Image Operands Type (Literal Number)
4746 // Ops[4] ... Ops[n] = (Optional) Operands ID
4747 //
4748 SPIRVOperandList Ops;
4749
4750 Value *Image = Call->getArgOperand(0);
4751 Value *Coordinate = Call->getArgOperand(1);
4752 Value *Texel = Call->getArgOperand(2);
4753
4754 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004755 uint32_t CoordinateID = VMap[Coordinate];
David Neto22f144c2017-06-12 14:26:21 -04004756 uint32_t TexelID = VMap[Texel];
alan-bakerf67468c2019-11-25 15:51:49 -05004757
4758 const bool is_int_image = IsIntImageType(Image->getType());
4759 if (is_int_image) {
4760 // Generate a bitcast to v4int and use it as the texel value.
4761 uint32_t castID = nextID++;
4762 Ops << MkId(v4int32ID) << MkId(TexelID);
4763 auto cast = new SPIRVInstruction(spv::OpBitcast, castID, Ops);
4764 SPIRVInstList.push_back(cast);
4765 Ops.clear();
4766 TexelID = castID;
4767 }
David Neto257c3892018-04-11 13:19:45 -04004768 Ops << MkId(ImageID) << MkId(CoordinateID) << MkId(TexelID);
David Neto22f144c2017-06-12 14:26:21 -04004769
David Neto87846742018-04-11 17:36:22 -04004770 auto *Inst = new SPIRVInstruction(spv::OpImageWrite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004771 SPIRVInstList.push_back(Inst);
4772 break;
4773 }
4774
alan-bakerce179f12019-12-06 19:02:22 -05004775 // get_image_* is mapped to OpImageQuerySize or OpImageQuerySizeLod
4776 if (clspv::IsImageQuery(Callee)) {
David Neto5c22a252018-03-15 16:07:41 -04004777 //
alan-bakerce179f12019-12-06 19:02:22 -05004778 // Generate OpImageQuerySize[Lod]
David Neto5c22a252018-03-15 16:07:41 -04004779 //
4780 // Ops[0] = Image ID
4781 //
alan-bakerce179f12019-12-06 19:02:22 -05004782 // Result type has components equal to the dimensionality of the image,
4783 // plus 1 if the image is arrayed.
4784 //
alan-bakerf906d2b2019-12-10 11:26:23 -05004785 // %sizes = OpImageQuerySize[Lod] %uint[2|3|4] %im [%uint_0]
David Neto5c22a252018-03-15 16:07:41 -04004786 SPIRVOperandList Ops;
4787
4788 // Implement:
alan-bakerce179f12019-12-06 19:02:22 -05004789 // %sizes = OpImageQuerySize[Lod] %uint[2|3|4] %im [%uint_0]
4790 uint32_t SizesTypeID = 0;
4791
David Neto5c22a252018-03-15 16:07:41 -04004792 Value *Image = Call->getArgOperand(0);
alan-bakerce179f12019-12-06 19:02:22 -05004793 const uint32_t dim = ImageDimensionality(Image->getType());
alan-bakerf906d2b2019-12-10 11:26:23 -05004794 // TODO(alan-baker): fix component calculation when arrayed images are
4795 // supported.
alan-bakerce179f12019-12-06 19:02:22 -05004796 const uint32_t components = dim;
4797 if (components == 1) {
alan-bakerce179f12019-12-06 19:02:22 -05004798 SizesTypeID = TypeMap[Type::getInt32Ty(Context)];
4799 } else {
4800 SizesTypeID = TypeMap[VectorType::get(Type::getInt32Ty(Context), dim)];
4801 }
David Neto5c22a252018-03-15 16:07:41 -04004802 uint32_t ImageID = VMap[Image];
David Neto257c3892018-04-11 13:19:45 -04004803 Ops << MkId(SizesTypeID) << MkId(ImageID);
alan-bakerce179f12019-12-06 19:02:22 -05004804 spv::Op query_opcode = spv::OpImageQuerySize;
4805 if (clspv::IsSampledImageType(Image->getType())) {
4806 query_opcode = spv::OpImageQuerySizeLod;
4807 // Need explicit 0 for Lod operand.
4808 Constant *CstInt0 = ConstantInt::get(Context, APInt(32, 0));
4809 Ops << MkId(VMap[CstInt0]);
4810 }
David Neto5c22a252018-03-15 16:07:41 -04004811
4812 uint32_t SizesID = nextID++;
alan-bakerce179f12019-12-06 19:02:22 -05004813 auto *QueryInst = new SPIRVInstruction(query_opcode, SizesID, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004814 SPIRVInstList.push_back(QueryInst);
4815
alan-bakerce179f12019-12-06 19:02:22 -05004816 // May require an extra instruction to create the appropriate result of
4817 // the builtin function.
4818 if (clspv::IsGetImageDim(Callee)) {
4819 if (dim == 3) {
4820 // get_image_dim returns an int4 for 3D images.
4821 //
4822 // Reset value map entry since we generated an intermediate
4823 // instruction.
4824 VMap[&I] = nextID;
David Neto5c22a252018-03-15 16:07:41 -04004825
alan-bakerce179f12019-12-06 19:02:22 -05004826 // Implement:
4827 // %result = OpCompositeConstruct %uint4 %sizes %uint_0
4828 Ops.clear();
4829 Ops << MkId(lookupType(VectorType::get(Type::getInt32Ty(Context), 4)))
4830 << MkId(SizesID);
David Neto5c22a252018-03-15 16:07:41 -04004831
alan-bakerce179f12019-12-06 19:02:22 -05004832 Constant *CstInt0 = ConstantInt::get(Context, APInt(32, 0));
4833 Ops << MkId(VMap[CstInt0]);
David Neto5c22a252018-03-15 16:07:41 -04004834
alan-bakerce179f12019-12-06 19:02:22 -05004835 auto *Inst =
4836 new SPIRVInstruction(spv::OpCompositeConstruct, nextID++, Ops);
4837 SPIRVInstList.push_back(Inst);
4838 } else if (dim != components) {
4839 // get_image_dim return an int2 regardless of the arrayedness of the
4840 // image. If the image is arrayed an element must be dropped from the
4841 // query result.
4842 //
4843 // Reset value map entry since we generated an intermediate
4844 // instruction.
4845 VMap[&I] = nextID;
4846
4847 // Implement:
4848 // %result = OpVectorShuffle %uint2 %sizes %sizes 0 1
4849 Ops.clear();
4850 Ops << MkId(lookupType(VectorType::get(Type::getInt32Ty(Context), 2)))
4851 << MkId(SizesID) << MkId(SizesID) << MkNum(0) << MkNum(1);
4852
4853 auto *Inst =
4854 new SPIRVInstruction(spv::OpVectorShuffle, nextID++, Ops);
4855 SPIRVInstList.push_back(Inst);
4856 }
4857 } else if (components > 1) {
4858 // Reset value map entry since we generated an intermediate instruction.
4859 VMap[&I] = nextID;
4860
4861 // Implement:
4862 // %result = OpCompositeExtract %uint %sizes <component number>
4863 Ops.clear();
4864 Ops << MkId(TypeMap[I.getType()]) << MkId(SizesID);
4865
4866 uint32_t component = 0;
4867 if (IsGetImageHeight(Callee))
4868 component = 1;
4869 else if (IsGetImageDepth(Callee))
4870 component = 2;
4871 Ops << MkNum(component);
4872
4873 auto *Inst =
4874 new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
4875 SPIRVInstList.push_back(Inst);
4876 }
David Neto5c22a252018-03-15 16:07:41 -04004877 break;
4878 }
4879
David Neto22f144c2017-06-12 14:26:21 -04004880 // Call instrucion is deferred because it needs function's ID. Record
4881 // slot's location on SPIRVInstructionList.
4882 DeferredInsts.push_back(
4883 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4884
David Neto3fbb4072017-10-16 11:28:14 -04004885 // Check whether the implementation of this call uses an extended
4886 // instruction plus one more value-producing instruction. If so, then
4887 // reserve the id for the extra value-producing slot.
4888 glsl::ExtInst EInst = getIndirectExtInstEnum(Callee->getName());
4889 if (EInst != kGlslExtInstBad) {
4890 // Reserve a spot for the extra value.
David Neto4d02a532017-09-17 12:57:44 -04004891 // Increase nextID.
David Neto22f144c2017-06-12 14:26:21 -04004892 VMap[&I] = nextID;
4893 nextID++;
4894 }
4895 break;
4896 }
4897 case Instruction::Ret: {
4898 unsigned NumOps = I.getNumOperands();
4899 if (NumOps == 0) {
4900 //
4901 // Generate OpReturn.
4902 //
David Netoef5ba2b2019-12-20 08:35:54 -05004903 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpReturn));
David Neto22f144c2017-06-12 14:26:21 -04004904 } else {
4905 //
4906 // Generate OpReturnValue.
4907 //
4908
4909 // Ops[0] = Return Value ID
4910 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004911
4912 Ops << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004913
David Neto87846742018-04-11 17:36:22 -04004914 auto *Inst = new SPIRVInstruction(spv::OpReturnValue, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004915 SPIRVInstList.push_back(Inst);
4916 break;
4917 }
4918 break;
4919 }
4920 }
4921}
4922
4923void SPIRVProducerPass::GenerateFuncEpilogue() {
4924 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4925
4926 //
4927 // Generate OpFunctionEnd
4928 //
4929
David Netoef5ba2b2019-12-20 08:35:54 -05004930 auto *Inst = new SPIRVInstruction(spv::OpFunctionEnd);
David Neto22f144c2017-06-12 14:26:21 -04004931 SPIRVInstList.push_back(Inst);
4932}
4933
4934bool SPIRVProducerPass::is4xi8vec(Type *Ty) const {
alan-bakerb39c8262019-03-08 14:03:37 -05004935 // Don't specialize <4 x i8> if i8 is generally supported.
4936 if (clspv::Option::Int8Support())
4937 return false;
4938
David Neto22f144c2017-06-12 14:26:21 -04004939 LLVMContext &Context = Ty->getContext();
4940 if (Ty->isVectorTy()) {
4941 if (Ty->getVectorElementType() == Type::getInt8Ty(Context) &&
4942 Ty->getVectorNumElements() == 4) {
4943 return true;
4944 }
4945 }
4946
4947 return false;
4948}
4949
4950void SPIRVProducerPass::HandleDeferredInstruction() {
4951 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4952 ValueMapType &VMap = getValueMap();
4953 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
4954
4955 for (auto DeferredInst = DeferredInsts.rbegin();
4956 DeferredInst != DeferredInsts.rend(); ++DeferredInst) {
4957 Value *Inst = std::get<0>(*DeferredInst);
4958 SPIRVInstructionList::iterator InsertPoint = ++std::get<1>(*DeferredInst);
4959 if (InsertPoint != SPIRVInstList.end()) {
4960 while ((*InsertPoint)->getOpcode() == spv::OpPhi) {
4961 ++InsertPoint;
4962 }
4963 }
4964
4965 if (BranchInst *Br = dyn_cast<BranchInst>(Inst)) {
alan-baker06cad652019-12-03 17:56:47 -05004966 // Check whether this branch needs to be preceeded by merge instruction.
David Neto22f144c2017-06-12 14:26:21 -04004967 BasicBlock *BrBB = Br->getParent();
alan-baker06cad652019-12-03 17:56:47 -05004968 if (ContinueBlocks.count(BrBB)) {
David Neto22f144c2017-06-12 14:26:21 -04004969 //
4970 // Generate OpLoopMerge.
4971 //
4972 // Ops[0] = Merge Block ID
4973 // Ops[1] = Continue Target ID
4974 // Ops[2] = Selection Control
4975 SPIRVOperandList Ops;
4976
alan-baker06cad652019-12-03 17:56:47 -05004977 auto MergeBB = MergeBlocks[BrBB];
4978 auto ContinueBB = ContinueBlocks[BrBB];
David Neto22f144c2017-06-12 14:26:21 -04004979 uint32_t MergeBBID = VMap[MergeBB];
David Neto22f144c2017-06-12 14:26:21 -04004980 uint32_t ContinueBBID = VMap[ContinueBB];
David Neto257c3892018-04-11 13:19:45 -04004981 Ops << MkId(MergeBBID) << MkId(ContinueBBID)
alan-baker06cad652019-12-03 17:56:47 -05004982 << MkNum(spv::LoopControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04004983
David Neto87846742018-04-11 17:36:22 -04004984 auto *MergeInst = new SPIRVInstruction(spv::OpLoopMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004985 SPIRVInstList.insert(InsertPoint, MergeInst);
alan-baker06cad652019-12-03 17:56:47 -05004986 } else if (MergeBlocks.count(BrBB)) {
4987 //
4988 // Generate OpSelectionMerge.
4989 //
4990 // Ops[0] = Merge Block ID
4991 // Ops[1] = Selection Control
4992 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04004993
alan-baker06cad652019-12-03 17:56:47 -05004994 auto MergeBB = MergeBlocks[BrBB];
4995 uint32_t MergeBBID = VMap[MergeBB];
4996 Ops << MkId(MergeBBID) << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04004997
alan-baker06cad652019-12-03 17:56:47 -05004998 auto *MergeInst = new SPIRVInstruction(spv::OpSelectionMerge, Ops);
4999 SPIRVInstList.insert(InsertPoint, MergeInst);
David Neto22f144c2017-06-12 14:26:21 -04005000 }
5001
5002 if (Br->isConditional()) {
5003 //
5004 // Generate OpBranchConditional.
5005 //
5006 // Ops[0] = Condition ID
5007 // Ops[1] = True Label ID
5008 // Ops[2] = False Label ID
5009 // Ops[3] ... Ops[n] = Branch weights (Literal Number)
5010 SPIRVOperandList Ops;
5011
5012 uint32_t CondID = VMap[Br->getCondition()];
David Neto22f144c2017-06-12 14:26:21 -04005013 uint32_t TrueBBID = VMap[Br->getSuccessor(0)];
David Neto22f144c2017-06-12 14:26:21 -04005014 uint32_t FalseBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04005015
5016 Ops << MkId(CondID) << MkId(TrueBBID) << MkId(FalseBBID);
David Neto22f144c2017-06-12 14:26:21 -04005017
David Neto87846742018-04-11 17:36:22 -04005018 auto *BrInst = new SPIRVInstruction(spv::OpBranchConditional, Ops);
David Neto22f144c2017-06-12 14:26:21 -04005019 SPIRVInstList.insert(InsertPoint, BrInst);
5020 } else {
5021 //
5022 // Generate OpBranch.
5023 //
5024 // Ops[0] = Target Label ID
5025 SPIRVOperandList Ops;
5026
5027 uint32_t TargetID = VMap[Br->getSuccessor(0)];
David Neto257c3892018-04-11 13:19:45 -04005028 Ops << MkId(TargetID);
David Neto22f144c2017-06-12 14:26:21 -04005029
David Neto87846742018-04-11 17:36:22 -04005030 SPIRVInstList.insert(InsertPoint,
5031 new SPIRVInstruction(spv::OpBranch, Ops));
David Neto22f144c2017-06-12 14:26:21 -04005032 }
5033 } else if (PHINode *PHI = dyn_cast<PHINode>(Inst)) {
alan-baker5b86ed72019-02-15 08:26:50 -05005034 if (PHI->getType()->isPointerTy()) {
5035 // OpPhi on pointers requires variable pointers.
5036 setVariablePointersCapabilities(
5037 PHI->getType()->getPointerAddressSpace());
5038 if (!hasVariablePointers() && !selectFromSameObject(PHI)) {
5039 setVariablePointers(true);
5040 }
5041 }
5042
David Neto22f144c2017-06-12 14:26:21 -04005043 //
5044 // Generate OpPhi.
5045 //
5046 // Ops[0] = Result Type ID
5047 // Ops[1] ... Ops[n] = (Variable ID, Parent ID) pairs
5048 SPIRVOperandList Ops;
5049
David Neto257c3892018-04-11 13:19:45 -04005050 Ops << MkId(lookupType(PHI->getType()));
David Neto22f144c2017-06-12 14:26:21 -04005051
David Neto22f144c2017-06-12 14:26:21 -04005052 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
5053 uint32_t VarID = VMap[PHI->getIncomingValue(i)];
David Neto22f144c2017-06-12 14:26:21 -04005054 uint32_t ParentID = VMap[PHI->getIncomingBlock(i)];
David Neto257c3892018-04-11 13:19:45 -04005055 Ops << MkId(VarID) << MkId(ParentID);
David Neto22f144c2017-06-12 14:26:21 -04005056 }
5057
5058 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005059 InsertPoint,
5060 new SPIRVInstruction(spv::OpPhi, std::get<2>(*DeferredInst), Ops));
David Neto22f144c2017-06-12 14:26:21 -04005061 } else if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
5062 Function *Callee = Call->getCalledFunction();
David Neto3fbb4072017-10-16 11:28:14 -04005063 auto callee_name = Callee->getName();
5064 glsl::ExtInst EInst = getDirectOrIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04005065
5066 if (EInst) {
5067 uint32_t &ExtInstImportID = getOpExtInstImportID();
5068
5069 //
5070 // Generate OpExtInst.
5071 //
5072
5073 // Ops[0] = Result Type ID
5074 // Ops[1] = Set ID (OpExtInstImport ID)
5075 // Ops[2] = Instruction Number (Literal Number)
5076 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
5077 SPIRVOperandList Ops;
5078
David Neto862b7d82018-06-14 18:48:37 -04005079 Ops << MkId(lookupType(Call->getType())) << MkId(ExtInstImportID)
5080 << MkNum(EInst);
David Neto22f144c2017-06-12 14:26:21 -04005081
David Neto22f144c2017-06-12 14:26:21 -04005082 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5083 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
David Neto257c3892018-04-11 13:19:45 -04005084 Ops << MkId(VMap[Call->getOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04005085 }
5086
David Neto87846742018-04-11 17:36:22 -04005087 auto *ExtInst = new SPIRVInstruction(spv::OpExtInst,
5088 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04005089 SPIRVInstList.insert(InsertPoint, ExtInst);
5090
David Neto3fbb4072017-10-16 11:28:14 -04005091 const auto IndirectExtInst = getIndirectExtInstEnum(callee_name);
5092 if (IndirectExtInst != kGlslExtInstBad) {
5093 // Generate one more instruction that uses the result of the extended
5094 // instruction. Its result id is one more than the id of the
5095 // extended instruction.
David Neto22f144c2017-06-12 14:26:21 -04005096 LLVMContext &Context =
5097 Call->getParent()->getParent()->getParent()->getContext();
David Neto22f144c2017-06-12 14:26:21 -04005098
David Neto3fbb4072017-10-16 11:28:14 -04005099 auto generate_extra_inst = [this, &Context, &Call, &DeferredInst,
5100 &VMap, &SPIRVInstList, &InsertPoint](
5101 spv::Op opcode, Constant *constant) {
5102 //
5103 // Generate instruction like:
5104 // result = opcode constant <extinst-result>
5105 //
5106 // Ops[0] = Result Type ID
5107 // Ops[1] = Operand 0 ;; the constant, suitably splatted
5108 // Ops[2] = Operand 1 ;; the result of the extended instruction
5109 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04005110
David Neto3fbb4072017-10-16 11:28:14 -04005111 Type *resultTy = Call->getType();
David Neto257c3892018-04-11 13:19:45 -04005112 Ops << MkId(lookupType(resultTy));
David Neto3fbb4072017-10-16 11:28:14 -04005113
5114 if (auto *vectorTy = dyn_cast<VectorType>(resultTy)) {
5115 constant = ConstantVector::getSplat(
5116 static_cast<unsigned>(vectorTy->getNumElements()), constant);
5117 }
David Neto257c3892018-04-11 13:19:45 -04005118 Ops << MkId(VMap[constant]) << MkId(std::get<2>(*DeferredInst));
David Neto3fbb4072017-10-16 11:28:14 -04005119
5120 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005121 InsertPoint, new SPIRVInstruction(
5122 opcode, std::get<2>(*DeferredInst) + 1, Ops));
David Neto3fbb4072017-10-16 11:28:14 -04005123 };
5124
5125 switch (IndirectExtInst) {
5126 case glsl::ExtInstFindUMsb: // Implementing clz
5127 generate_extra_inst(
5128 spv::OpISub, ConstantInt::get(Type::getInt32Ty(Context), 31));
5129 break;
5130 case glsl::ExtInstAcos: // Implementing acospi
5131 case glsl::ExtInstAsin: // Implementing asinpi
Kévin Petiteb9f90a2018-09-29 12:29:34 +01005132 case glsl::ExtInstAtan: // Implementing atanpi
David Neto3fbb4072017-10-16 11:28:14 -04005133 case glsl::ExtInstAtan2: // Implementing atan2pi
5134 generate_extra_inst(
5135 spv::OpFMul,
5136 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
5137 break;
5138
5139 default:
5140 assert(false && "internally inconsistent");
David Neto4d02a532017-09-17 12:57:44 -04005141 }
David Neto22f144c2017-06-12 14:26:21 -04005142 }
David Neto3fbb4072017-10-16 11:28:14 -04005143
alan-bakerb39c8262019-03-08 14:03:37 -05005144 } else if (callee_name.startswith("_Z8popcount")) {
David Neto22f144c2017-06-12 14:26:21 -04005145 //
5146 // Generate OpBitCount
5147 //
5148 // Ops[0] = Result Type ID
5149 // Ops[1] = Base ID
David Neto257c3892018-04-11 13:19:45 -04005150 SPIRVOperandList Ops;
5151 Ops << MkId(lookupType(Call->getType()))
5152 << MkId(VMap[Call->getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04005153
5154 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005155 InsertPoint, new SPIRVInstruction(spv::OpBitCount,
David Neto22f144c2017-06-12 14:26:21 -04005156 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005157
David Neto862b7d82018-06-14 18:48:37 -04005158 } else if (callee_name.startswith(kCompositeConstructFunctionPrefix)) {
David Netoab03f432017-11-03 17:00:44 -04005159
5160 // Generate an OpCompositeConstruct
5161 SPIRVOperandList Ops;
5162
5163 // The result type.
David Neto257c3892018-04-11 13:19:45 -04005164 Ops << MkId(lookupType(Call->getType()));
David Netoab03f432017-11-03 17:00:44 -04005165
5166 for (Use &use : Call->arg_operands()) {
David Neto257c3892018-04-11 13:19:45 -04005167 Ops << MkId(VMap[use.get()]);
David Netoab03f432017-11-03 17:00:44 -04005168 }
5169
5170 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005171 InsertPoint, new SPIRVInstruction(spv::OpCompositeConstruct,
5172 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005173
Alan Baker202c8c72018-08-13 13:47:44 -04005174 } else if (callee_name.startswith(clspv::ResourceAccessorFunction())) {
5175
5176 // We have already mapped the call's result value to an ID.
5177 // Don't generate any code now.
5178
5179 } else if (callee_name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04005180
5181 // We have already mapped the call's result value to an ID.
5182 // Don't generate any code now.
5183
David Neto22f144c2017-06-12 14:26:21 -04005184 } else {
alan-baker5b86ed72019-02-15 08:26:50 -05005185 if (Call->getType()->isPointerTy()) {
5186 // Functions returning pointers require variable pointers.
5187 setVariablePointersCapabilities(
5188 Call->getType()->getPointerAddressSpace());
5189 }
5190
David Neto22f144c2017-06-12 14:26:21 -04005191 //
5192 // Generate OpFunctionCall.
5193 //
5194
5195 // Ops[0] = Result Type ID
5196 // Ops[1] = Callee Function ID
5197 // Ops[2] ... Ops[n] = Argument 0, ... , Argument n
5198 SPIRVOperandList Ops;
5199
David Neto862b7d82018-06-14 18:48:37 -04005200 Ops << MkId(lookupType(Call->getType()));
David Neto22f144c2017-06-12 14:26:21 -04005201
5202 uint32_t CalleeID = VMap[Callee];
David Neto43568eb2017-10-13 18:25:25 -04005203 if (CalleeID == 0) {
5204 errs() << "Can't translate function call. Missing builtin? "
David Neto862b7d82018-06-14 18:48:37 -04005205 << callee_name << " in: " << *Call << "\n";
David Neto43568eb2017-10-13 18:25:25 -04005206 // TODO(dneto): Can we error out? Enabling this llvm_unreachable
5207 // causes an infinite loop. Instead, go ahead and generate
5208 // the bad function call. A validator will catch the 0-Id.
5209 // llvm_unreachable("Can't translate function call");
5210 }
David Neto22f144c2017-06-12 14:26:21 -04005211
David Neto257c3892018-04-11 13:19:45 -04005212 Ops << MkId(CalleeID);
David Neto22f144c2017-06-12 14:26:21 -04005213
David Neto22f144c2017-06-12 14:26:21 -04005214 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5215 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
alan-baker5b86ed72019-02-15 08:26:50 -05005216 auto *operand = Call->getOperand(i);
alan-bakerd4d50652019-12-03 17:17:15 -05005217 auto *operand_type = operand->getType();
5218 // Images and samplers can be passed as function parameters without
5219 // variable pointers.
5220 if (operand_type->isPointerTy() && !IsImageType(operand_type) &&
5221 !IsSamplerType(operand_type)) {
alan-baker5b86ed72019-02-15 08:26:50 -05005222 auto sc =
5223 GetStorageClass(operand->getType()->getPointerAddressSpace());
5224 if (sc == spv::StorageClassStorageBuffer) {
5225 // Passing SSBO by reference requires variable pointers storage
5226 // buffer.
5227 setVariablePointersStorageBuffer(true);
5228 } else if (sc == spv::StorageClassWorkgroup) {
5229 // Workgroup references require variable pointers if they are not
5230 // memory object declarations.
5231 if (auto *operand_call = dyn_cast<CallInst>(operand)) {
5232 // Workgroup accessor represents a variable reference.
5233 if (!operand_call->getCalledFunction()->getName().startswith(
5234 clspv::WorkgroupAccessorFunction()))
5235 setVariablePointers(true);
5236 } else {
5237 // Arguments are function parameters.
5238 if (!isa<Argument>(operand))
5239 setVariablePointers(true);
5240 }
5241 }
5242 }
5243 Ops << MkId(VMap[operand]);
David Neto22f144c2017-06-12 14:26:21 -04005244 }
5245
David Neto87846742018-04-11 17:36:22 -04005246 auto *CallInst = new SPIRVInstruction(spv::OpFunctionCall,
5247 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04005248 SPIRVInstList.insert(InsertPoint, CallInst);
5249 }
5250 }
5251 }
5252}
5253
David Neto1a1a0582017-07-07 12:01:44 -04005254void SPIRVProducerPass::HandleDeferredDecorations(const DataLayout &DL) {
Alan Baker202c8c72018-08-13 13:47:44 -04005255 if (getTypesNeedingArrayStride().empty() && LocalArgSpecIds.empty()) {
David Neto1a1a0582017-07-07 12:01:44 -04005256 return;
David Netoc6f3ab22018-04-06 18:02:31 -04005257 }
David Neto1a1a0582017-07-07 12:01:44 -04005258
5259 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
David Neto1a1a0582017-07-07 12:01:44 -04005260
5261 // Find an iterator pointing just past the last decoration.
5262 bool seen_decorations = false;
5263 auto DecoInsertPoint =
5264 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
5265 [&seen_decorations](SPIRVInstruction *Inst) -> bool {
5266 const bool is_decoration =
5267 Inst->getOpcode() == spv::OpDecorate ||
5268 Inst->getOpcode() == spv::OpMemberDecorate;
5269 if (is_decoration) {
5270 seen_decorations = true;
5271 return false;
5272 } else {
5273 return seen_decorations;
5274 }
5275 });
5276
David Netoc6f3ab22018-04-06 18:02:31 -04005277 // Insert ArrayStride decorations on pointer types, due to OpPtrAccessChain
5278 // instructions we generated earlier.
David Neto85082642018-03-24 06:55:20 -07005279 for (auto *type : getTypesNeedingArrayStride()) {
5280 Type *elemTy = nullptr;
5281 if (auto *ptrTy = dyn_cast<PointerType>(type)) {
5282 elemTy = ptrTy->getElementType();
alan-bakerb6b09dc2018-11-08 16:59:28 -05005283 } else if (auto *arrayTy = dyn_cast<ArrayType>(type)) {
David Neto85082642018-03-24 06:55:20 -07005284 elemTy = arrayTy->getArrayElementType();
alan-bakerb6b09dc2018-11-08 16:59:28 -05005285 } else if (auto *seqTy = dyn_cast<SequentialType>(type)) {
David Neto85082642018-03-24 06:55:20 -07005286 elemTy = seqTy->getSequentialElementType();
5287 } else {
5288 errs() << "Unhandled strided type " << *type << "\n";
5289 llvm_unreachable("Unhandled strided type");
5290 }
David Neto1a1a0582017-07-07 12:01:44 -04005291
5292 // Ops[0] = Target ID
5293 // Ops[1] = Decoration (ArrayStride)
5294 // Ops[2] = Stride number (Literal Number)
5295 SPIRVOperandList Ops;
5296
David Neto85082642018-03-24 06:55:20 -07005297 // Same as DL.getIndexedOffsetInType( elemTy, { 1 } );
Alan Bakerfcda9482018-10-02 17:09:59 -04005298 const uint32_t stride = static_cast<uint32_t>(GetTypeAllocSize(elemTy, DL));
David Neto257c3892018-04-11 13:19:45 -04005299
5300 Ops << MkId(lookupType(type)) << MkNum(spv::DecorationArrayStride)
5301 << MkNum(stride);
David Neto1a1a0582017-07-07 12:01:44 -04005302
David Neto87846742018-04-11 17:36:22 -04005303 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto1a1a0582017-07-07 12:01:44 -04005304 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
5305 }
David Netoc6f3ab22018-04-06 18:02:31 -04005306
5307 // Emit SpecId decorations targeting the array size value.
Alan Baker202c8c72018-08-13 13:47:44 -04005308 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
5309 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05005310 LocalArgInfo &arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04005311 SPIRVOperandList Ops;
5312 Ops << MkId(arg_info.array_size_id) << MkNum(spv::DecorationSpecId)
5313 << MkNum(arg_info.spec_id);
5314 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04005315 new SPIRVInstruction(spv::OpDecorate, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04005316 }
David Neto1a1a0582017-07-07 12:01:44 -04005317}
5318
David Neto22f144c2017-06-12 14:26:21 -04005319glsl::ExtInst SPIRVProducerPass::getExtInstEnum(StringRef Name) {
5320 return StringSwitch<glsl::ExtInst>(Name)
alan-bakerb39c8262019-03-08 14:03:37 -05005321 .Case("_Z3absc", glsl::ExtInst::ExtInstSAbs)
5322 .Case("_Z3absDv2_c", glsl::ExtInst::ExtInstSAbs)
5323 .Case("_Z3absDv3_c", glsl::ExtInst::ExtInstSAbs)
5324 .Case("_Z3absDv4_c", glsl::ExtInst::ExtInstSAbs)
Kévin Petit2444e9b2018-11-09 14:14:37 +00005325 .Case("_Z3abss", glsl::ExtInst::ExtInstSAbs)
5326 .Case("_Z3absDv2_s", glsl::ExtInst::ExtInstSAbs)
5327 .Case("_Z3absDv3_s", glsl::ExtInst::ExtInstSAbs)
5328 .Case("_Z3absDv4_s", glsl::ExtInst::ExtInstSAbs)
David Neto22f144c2017-06-12 14:26:21 -04005329 .Case("_Z3absi", glsl::ExtInst::ExtInstSAbs)
5330 .Case("_Z3absDv2_i", glsl::ExtInst::ExtInstSAbs)
5331 .Case("_Z3absDv3_i", glsl::ExtInst::ExtInstSAbs)
5332 .Case("_Z3absDv4_i", glsl::ExtInst::ExtInstSAbs)
Kévin Petit2444e9b2018-11-09 14:14:37 +00005333 .Case("_Z3absl", glsl::ExtInst::ExtInstSAbs)
5334 .Case("_Z3absDv2_l", glsl::ExtInst::ExtInstSAbs)
5335 .Case("_Z3absDv3_l", glsl::ExtInst::ExtInstSAbs)
5336 .Case("_Z3absDv4_l", glsl::ExtInst::ExtInstSAbs)
alan-bakerb39c8262019-03-08 14:03:37 -05005337 .Case("_Z5clampccc", glsl::ExtInst::ExtInstSClamp)
5338 .Case("_Z5clampDv2_cS_S_", glsl::ExtInst::ExtInstSClamp)
5339 .Case("_Z5clampDv3_cS_S_", glsl::ExtInst::ExtInstSClamp)
5340 .Case("_Z5clampDv4_cS_S_", glsl::ExtInst::ExtInstSClamp)
5341 .Case("_Z5clamphhh", glsl::ExtInst::ExtInstUClamp)
5342 .Case("_Z5clampDv2_hS_S_", glsl::ExtInst::ExtInstUClamp)
5343 .Case("_Z5clampDv3_hS_S_", glsl::ExtInst::ExtInstUClamp)
5344 .Case("_Z5clampDv4_hS_S_", glsl::ExtInst::ExtInstUClamp)
Kévin Petit495255d2019-03-06 13:56:48 +00005345 .Case("_Z5clampsss", glsl::ExtInst::ExtInstSClamp)
5346 .Case("_Z5clampDv2_sS_S_", glsl::ExtInst::ExtInstSClamp)
5347 .Case("_Z5clampDv3_sS_S_", glsl::ExtInst::ExtInstSClamp)
5348 .Case("_Z5clampDv4_sS_S_", glsl::ExtInst::ExtInstSClamp)
5349 .Case("_Z5clampttt", glsl::ExtInst::ExtInstUClamp)
5350 .Case("_Z5clampDv2_tS_S_", glsl::ExtInst::ExtInstUClamp)
5351 .Case("_Z5clampDv3_tS_S_", glsl::ExtInst::ExtInstUClamp)
5352 .Case("_Z5clampDv4_tS_S_", glsl::ExtInst::ExtInstUClamp)
David Neto22f144c2017-06-12 14:26:21 -04005353 .Case("_Z5clampiii", glsl::ExtInst::ExtInstSClamp)
5354 .Case("_Z5clampDv2_iS_S_", glsl::ExtInst::ExtInstSClamp)
5355 .Case("_Z5clampDv3_iS_S_", glsl::ExtInst::ExtInstSClamp)
5356 .Case("_Z5clampDv4_iS_S_", glsl::ExtInst::ExtInstSClamp)
5357 .Case("_Z5clampjjj", glsl::ExtInst::ExtInstUClamp)
5358 .Case("_Z5clampDv2_jS_S_", glsl::ExtInst::ExtInstUClamp)
5359 .Case("_Z5clampDv3_jS_S_", glsl::ExtInst::ExtInstUClamp)
5360 .Case("_Z5clampDv4_jS_S_", glsl::ExtInst::ExtInstUClamp)
Kévin Petit495255d2019-03-06 13:56:48 +00005361 .Case("_Z5clamplll", glsl::ExtInst::ExtInstSClamp)
5362 .Case("_Z5clampDv2_lS_S_", glsl::ExtInst::ExtInstSClamp)
5363 .Case("_Z5clampDv3_lS_S_", glsl::ExtInst::ExtInstSClamp)
5364 .Case("_Z5clampDv4_lS_S_", glsl::ExtInst::ExtInstSClamp)
5365 .Case("_Z5clampmmm", glsl::ExtInst::ExtInstUClamp)
5366 .Case("_Z5clampDv2_mS_S_", glsl::ExtInst::ExtInstUClamp)
5367 .Case("_Z5clampDv3_mS_S_", glsl::ExtInst::ExtInstUClamp)
5368 .Case("_Z5clampDv4_mS_S_", glsl::ExtInst::ExtInstUClamp)
David Neto22f144c2017-06-12 14:26:21 -04005369 .Case("_Z5clampfff", glsl::ExtInst::ExtInstFClamp)
5370 .Case("_Z5clampDv2_fS_S_", glsl::ExtInst::ExtInstFClamp)
5371 .Case("_Z5clampDv3_fS_S_", glsl::ExtInst::ExtInstFClamp)
5372 .Case("_Z5clampDv4_fS_S_", glsl::ExtInst::ExtInstFClamp)
alan-bakerb39c8262019-03-08 14:03:37 -05005373 .Case("_Z3maxcc", glsl::ExtInst::ExtInstSMax)
5374 .Case("_Z3maxDv2_cS_", glsl::ExtInst::ExtInstSMax)
5375 .Case("_Z3maxDv3_cS_", glsl::ExtInst::ExtInstSMax)
5376 .Case("_Z3maxDv4_cS_", glsl::ExtInst::ExtInstSMax)
5377 .Case("_Z3maxhh", glsl::ExtInst::ExtInstUMax)
5378 .Case("_Z3maxDv2_hS_", glsl::ExtInst::ExtInstUMax)
5379 .Case("_Z3maxDv3_hS_", glsl::ExtInst::ExtInstUMax)
5380 .Case("_Z3maxDv4_hS_", glsl::ExtInst::ExtInstUMax)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005381 .Case("_Z3maxss", glsl::ExtInst::ExtInstSMax)
5382 .Case("_Z3maxDv2_sS_", glsl::ExtInst::ExtInstSMax)
5383 .Case("_Z3maxDv3_sS_", glsl::ExtInst::ExtInstSMax)
5384 .Case("_Z3maxDv4_sS_", glsl::ExtInst::ExtInstSMax)
5385 .Case("_Z3maxtt", glsl::ExtInst::ExtInstUMax)
5386 .Case("_Z3maxDv2_tS_", glsl::ExtInst::ExtInstUMax)
5387 .Case("_Z3maxDv3_tS_", glsl::ExtInst::ExtInstUMax)
5388 .Case("_Z3maxDv4_tS_", glsl::ExtInst::ExtInstUMax)
David Neto22f144c2017-06-12 14:26:21 -04005389 .Case("_Z3maxii", glsl::ExtInst::ExtInstSMax)
5390 .Case("_Z3maxDv2_iS_", glsl::ExtInst::ExtInstSMax)
5391 .Case("_Z3maxDv3_iS_", glsl::ExtInst::ExtInstSMax)
5392 .Case("_Z3maxDv4_iS_", glsl::ExtInst::ExtInstSMax)
5393 .Case("_Z3maxjj", glsl::ExtInst::ExtInstUMax)
5394 .Case("_Z3maxDv2_jS_", glsl::ExtInst::ExtInstUMax)
5395 .Case("_Z3maxDv3_jS_", glsl::ExtInst::ExtInstUMax)
5396 .Case("_Z3maxDv4_jS_", glsl::ExtInst::ExtInstUMax)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005397 .Case("_Z3maxll", glsl::ExtInst::ExtInstSMax)
5398 .Case("_Z3maxDv2_lS_", glsl::ExtInst::ExtInstSMax)
5399 .Case("_Z3maxDv3_lS_", glsl::ExtInst::ExtInstSMax)
5400 .Case("_Z3maxDv4_lS_", glsl::ExtInst::ExtInstSMax)
5401 .Case("_Z3maxmm", glsl::ExtInst::ExtInstUMax)
5402 .Case("_Z3maxDv2_mS_", glsl::ExtInst::ExtInstUMax)
5403 .Case("_Z3maxDv3_mS_", glsl::ExtInst::ExtInstUMax)
5404 .Case("_Z3maxDv4_mS_", glsl::ExtInst::ExtInstUMax)
David Neto22f144c2017-06-12 14:26:21 -04005405 .Case("_Z3maxff", glsl::ExtInst::ExtInstFMax)
5406 .Case("_Z3maxDv2_fS_", glsl::ExtInst::ExtInstFMax)
5407 .Case("_Z3maxDv3_fS_", glsl::ExtInst::ExtInstFMax)
5408 .Case("_Z3maxDv4_fS_", glsl::ExtInst::ExtInstFMax)
5409 .StartsWith("_Z4fmax", glsl::ExtInst::ExtInstFMax)
alan-bakerb39c8262019-03-08 14:03:37 -05005410 .Case("_Z3mincc", glsl::ExtInst::ExtInstSMin)
5411 .Case("_Z3minDv2_cS_", glsl::ExtInst::ExtInstSMin)
5412 .Case("_Z3minDv3_cS_", glsl::ExtInst::ExtInstSMin)
5413 .Case("_Z3minDv4_cS_", glsl::ExtInst::ExtInstSMin)
5414 .Case("_Z3minhh", glsl::ExtInst::ExtInstUMin)
5415 .Case("_Z3minDv2_hS_", glsl::ExtInst::ExtInstUMin)
5416 .Case("_Z3minDv3_hS_", glsl::ExtInst::ExtInstUMin)
5417 .Case("_Z3minDv4_hS_", glsl::ExtInst::ExtInstUMin)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005418 .Case("_Z3minss", glsl::ExtInst::ExtInstSMin)
5419 .Case("_Z3minDv2_sS_", glsl::ExtInst::ExtInstSMin)
5420 .Case("_Z3minDv3_sS_", glsl::ExtInst::ExtInstSMin)
5421 .Case("_Z3minDv4_sS_", glsl::ExtInst::ExtInstSMin)
5422 .Case("_Z3mintt", glsl::ExtInst::ExtInstUMin)
5423 .Case("_Z3minDv2_tS_", glsl::ExtInst::ExtInstUMin)
5424 .Case("_Z3minDv3_tS_", glsl::ExtInst::ExtInstUMin)
5425 .Case("_Z3minDv4_tS_", glsl::ExtInst::ExtInstUMin)
David Neto22f144c2017-06-12 14:26:21 -04005426 .Case("_Z3minii", glsl::ExtInst::ExtInstSMin)
5427 .Case("_Z3minDv2_iS_", glsl::ExtInst::ExtInstSMin)
5428 .Case("_Z3minDv3_iS_", glsl::ExtInst::ExtInstSMin)
5429 .Case("_Z3minDv4_iS_", glsl::ExtInst::ExtInstSMin)
5430 .Case("_Z3minjj", glsl::ExtInst::ExtInstUMin)
5431 .Case("_Z3minDv2_jS_", glsl::ExtInst::ExtInstUMin)
5432 .Case("_Z3minDv3_jS_", glsl::ExtInst::ExtInstUMin)
5433 .Case("_Z3minDv4_jS_", glsl::ExtInst::ExtInstUMin)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005434 .Case("_Z3minll", glsl::ExtInst::ExtInstSMin)
5435 .Case("_Z3minDv2_lS_", glsl::ExtInst::ExtInstSMin)
5436 .Case("_Z3minDv3_lS_", glsl::ExtInst::ExtInstSMin)
5437 .Case("_Z3minDv4_lS_", glsl::ExtInst::ExtInstSMin)
5438 .Case("_Z3minmm", glsl::ExtInst::ExtInstUMin)
5439 .Case("_Z3minDv2_mS_", glsl::ExtInst::ExtInstUMin)
5440 .Case("_Z3minDv3_mS_", glsl::ExtInst::ExtInstUMin)
5441 .Case("_Z3minDv4_mS_", glsl::ExtInst::ExtInstUMin)
David Neto22f144c2017-06-12 14:26:21 -04005442 .Case("_Z3minff", glsl::ExtInst::ExtInstFMin)
5443 .Case("_Z3minDv2_fS_", glsl::ExtInst::ExtInstFMin)
5444 .Case("_Z3minDv3_fS_", glsl::ExtInst::ExtInstFMin)
5445 .Case("_Z3minDv4_fS_", glsl::ExtInst::ExtInstFMin)
5446 .StartsWith("_Z4fmin", glsl::ExtInst::ExtInstFMin)
5447 .StartsWith("_Z7degrees", glsl::ExtInst::ExtInstDegrees)
5448 .StartsWith("_Z7radians", glsl::ExtInst::ExtInstRadians)
5449 .StartsWith("_Z3mix", glsl::ExtInst::ExtInstFMix)
5450 .StartsWith("_Z4acos", glsl::ExtInst::ExtInstAcos)
5451 .StartsWith("_Z5acosh", glsl::ExtInst::ExtInstAcosh)
5452 .StartsWith("_Z4asin", glsl::ExtInst::ExtInstAsin)
5453 .StartsWith("_Z5asinh", glsl::ExtInst::ExtInstAsinh)
5454 .StartsWith("_Z4atan", glsl::ExtInst::ExtInstAtan)
5455 .StartsWith("_Z5atan2", glsl::ExtInst::ExtInstAtan2)
5456 .StartsWith("_Z5atanh", glsl::ExtInst::ExtInstAtanh)
5457 .StartsWith("_Z4ceil", glsl::ExtInst::ExtInstCeil)
5458 .StartsWith("_Z3sin", glsl::ExtInst::ExtInstSin)
5459 .StartsWith("_Z4sinh", glsl::ExtInst::ExtInstSinh)
5460 .StartsWith("_Z8half_sin", glsl::ExtInst::ExtInstSin)
5461 .StartsWith("_Z10native_sin", glsl::ExtInst::ExtInstSin)
5462 .StartsWith("_Z3cos", glsl::ExtInst::ExtInstCos)
5463 .StartsWith("_Z4cosh", glsl::ExtInst::ExtInstCosh)
5464 .StartsWith("_Z8half_cos", glsl::ExtInst::ExtInstCos)
5465 .StartsWith("_Z10native_cos", glsl::ExtInst::ExtInstCos)
5466 .StartsWith("_Z3tan", glsl::ExtInst::ExtInstTan)
5467 .StartsWith("_Z4tanh", glsl::ExtInst::ExtInstTanh)
5468 .StartsWith("_Z8half_tan", glsl::ExtInst::ExtInstTan)
5469 .StartsWith("_Z10native_tan", glsl::ExtInst::ExtInstTan)
5470 .StartsWith("_Z3exp", glsl::ExtInst::ExtInstExp)
5471 .StartsWith("_Z8half_exp", glsl::ExtInst::ExtInstExp)
5472 .StartsWith("_Z10native_exp", glsl::ExtInst::ExtInstExp)
5473 .StartsWith("_Z4exp2", glsl::ExtInst::ExtInstExp2)
5474 .StartsWith("_Z9half_exp2", glsl::ExtInst::ExtInstExp2)
5475 .StartsWith("_Z11native_exp2", glsl::ExtInst::ExtInstExp2)
5476 .StartsWith("_Z3log", glsl::ExtInst::ExtInstLog)
5477 .StartsWith("_Z8half_log", glsl::ExtInst::ExtInstLog)
5478 .StartsWith("_Z10native_log", glsl::ExtInst::ExtInstLog)
5479 .StartsWith("_Z4log2", glsl::ExtInst::ExtInstLog2)
5480 .StartsWith("_Z9half_log2", glsl::ExtInst::ExtInstLog2)
5481 .StartsWith("_Z11native_log2", glsl::ExtInst::ExtInstLog2)
5482 .StartsWith("_Z4fabs", glsl::ExtInst::ExtInstFAbs)
kpet3458e942018-10-03 14:35:21 +01005483 .StartsWith("_Z3fma", glsl::ExtInst::ExtInstFma)
David Neto22f144c2017-06-12 14:26:21 -04005484 .StartsWith("_Z5floor", glsl::ExtInst::ExtInstFloor)
5485 .StartsWith("_Z5ldexp", glsl::ExtInst::ExtInstLdexp)
5486 .StartsWith("_Z3pow", glsl::ExtInst::ExtInstPow)
5487 .StartsWith("_Z4powr", glsl::ExtInst::ExtInstPow)
5488 .StartsWith("_Z9half_powr", glsl::ExtInst::ExtInstPow)
5489 .StartsWith("_Z11native_powr", glsl::ExtInst::ExtInstPow)
5490 .StartsWith("_Z5round", glsl::ExtInst::ExtInstRound)
5491 .StartsWith("_Z4sqrt", glsl::ExtInst::ExtInstSqrt)
5492 .StartsWith("_Z9half_sqrt", glsl::ExtInst::ExtInstSqrt)
5493 .StartsWith("_Z11native_sqrt", glsl::ExtInst::ExtInstSqrt)
5494 .StartsWith("_Z5rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5495 .StartsWith("_Z10half_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5496 .StartsWith("_Z12native_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5497 .StartsWith("_Z5trunc", glsl::ExtInst::ExtInstTrunc)
5498 .StartsWith("_Z5frexp", glsl::ExtInst::ExtInstFrexp)
5499 .StartsWith("_Z4sign", glsl::ExtInst::ExtInstFSign)
5500 .StartsWith("_Z6length", glsl::ExtInst::ExtInstLength)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005501 .StartsWith("_Z11fast_length", glsl::ExtInst::ExtInstLength)
David Neto22f144c2017-06-12 14:26:21 -04005502 .StartsWith("_Z8distance", glsl::ExtInst::ExtInstDistance)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005503 .StartsWith("_Z13fast_distance", glsl::ExtInst::ExtInstDistance)
David Netoe9a03512017-10-16 10:08:27 -04005504 .StartsWith("_Z4step", glsl::ExtInst::ExtInstStep)
kpet6fd2a262018-10-03 14:48:01 +01005505 .StartsWith("_Z10smoothstep", glsl::ExtInst::ExtInstSmoothStep)
David Neto22f144c2017-06-12 14:26:21 -04005506 .Case("_Z5crossDv3_fS_", glsl::ExtInst::ExtInstCross)
5507 .StartsWith("_Z9normalize", glsl::ExtInst::ExtInstNormalize)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005508 .StartsWith("_Z14fast_normalize", glsl::ExtInst::ExtInstNormalize)
David Neto22f144c2017-06-12 14:26:21 -04005509 .StartsWith("llvm.fmuladd.", glsl::ExtInst::ExtInstFma)
5510 .Case("spirv.unpack.v2f16", glsl::ExtInst::ExtInstUnpackHalf2x16)
5511 .Case("spirv.pack.v2f16", glsl::ExtInst::ExtInstPackHalf2x16)
David Neto62653202017-10-16 19:05:18 -04005512 .Case("clspv.fract.f", glsl::ExtInst::ExtInstFract)
5513 .Case("clspv.fract.v2f", glsl::ExtInst::ExtInstFract)
5514 .Case("clspv.fract.v3f", glsl::ExtInst::ExtInstFract)
5515 .Case("clspv.fract.v4f", glsl::ExtInst::ExtInstFract)
David Neto3fbb4072017-10-16 11:28:14 -04005516 .Default(kGlslExtInstBad);
5517}
5518
5519glsl::ExtInst SPIRVProducerPass::getIndirectExtInstEnum(StringRef Name) {
5520 // Check indirect cases.
5521 return StringSwitch<glsl::ExtInst>(Name)
5522 .StartsWith("_Z3clz", glsl::ExtInst::ExtInstFindUMsb)
5523 // Use exact match on float arg because these need a multiply
5524 // of a constant of the right floating point type.
5525 .Case("_Z6acospif", glsl::ExtInst::ExtInstAcos)
5526 .Case("_Z6acospiDv2_f", glsl::ExtInst::ExtInstAcos)
5527 .Case("_Z6acospiDv3_f", glsl::ExtInst::ExtInstAcos)
5528 .Case("_Z6acospiDv4_f", glsl::ExtInst::ExtInstAcos)
5529 .Case("_Z6asinpif", glsl::ExtInst::ExtInstAsin)
5530 .Case("_Z6asinpiDv2_f", glsl::ExtInst::ExtInstAsin)
5531 .Case("_Z6asinpiDv3_f", glsl::ExtInst::ExtInstAsin)
5532 .Case("_Z6asinpiDv4_f", glsl::ExtInst::ExtInstAsin)
Kévin Petiteb9f90a2018-09-29 12:29:34 +01005533 .Case("_Z6atanpif", glsl::ExtInst::ExtInstAtan)
5534 .Case("_Z6atanpiDv2_f", glsl::ExtInst::ExtInstAtan)
5535 .Case("_Z6atanpiDv3_f", glsl::ExtInst::ExtInstAtan)
5536 .Case("_Z6atanpiDv4_f", glsl::ExtInst::ExtInstAtan)
David Neto3fbb4072017-10-16 11:28:14 -04005537 .Case("_Z7atan2piff", glsl::ExtInst::ExtInstAtan2)
5538 .Case("_Z7atan2piDv2_fS_", glsl::ExtInst::ExtInstAtan2)
5539 .Case("_Z7atan2piDv3_fS_", glsl::ExtInst::ExtInstAtan2)
5540 .Case("_Z7atan2piDv4_fS_", glsl::ExtInst::ExtInstAtan2)
5541 .Default(kGlslExtInstBad);
5542}
5543
alan-bakerb6b09dc2018-11-08 16:59:28 -05005544glsl::ExtInst
5545SPIRVProducerPass::getDirectOrIndirectExtInstEnum(StringRef Name) {
David Neto3fbb4072017-10-16 11:28:14 -04005546 auto direct = getExtInstEnum(Name);
5547 if (direct != kGlslExtInstBad)
5548 return direct;
5549 return getIndirectExtInstEnum(Name);
David Neto22f144c2017-06-12 14:26:21 -04005550}
5551
David Neto22f144c2017-06-12 14:26:21 -04005552void SPIRVProducerPass::WriteOneWord(uint32_t Word) {
David Neto0676e6f2017-07-11 18:47:44 -04005553 binaryOut->write(reinterpret_cast<const char *>(&Word), sizeof(uint32_t));
David Neto22f144c2017-06-12 14:26:21 -04005554}
5555
5556void SPIRVProducerPass::WriteResultID(SPIRVInstruction *Inst) {
5557 WriteOneWord(Inst->getResultID());
5558}
5559
5560void SPIRVProducerPass::WriteWordCountAndOpcode(SPIRVInstruction *Inst) {
5561 // High 16 bit : Word Count
5562 // Low 16 bit : Opcode
5563 uint32_t Word = Inst->getOpcode();
David Netoee2660d2018-06-28 16:31:29 -04005564 const uint32_t count = Inst->getWordCount();
5565 if (count > 65535) {
5566 errs() << "Word count limit of 65535 exceeded: " << count << "\n";
5567 llvm_unreachable("Word count too high");
5568 }
David Neto22f144c2017-06-12 14:26:21 -04005569 Word |= Inst->getWordCount() << 16;
5570 WriteOneWord(Word);
5571}
5572
David Netoef5ba2b2019-12-20 08:35:54 -05005573void SPIRVProducerPass::WriteOperand(const std::unique_ptr<SPIRVOperand> &Op) {
David Neto22f144c2017-06-12 14:26:21 -04005574 SPIRVOperandType OpTy = Op->getType();
5575 switch (OpTy) {
5576 default: {
5577 llvm_unreachable("Unsupported SPIRV Operand Type???");
5578 break;
5579 }
5580 case SPIRVOperandType::NUMBERID: {
5581 WriteOneWord(Op->getNumID());
5582 break;
5583 }
5584 case SPIRVOperandType::LITERAL_STRING: {
5585 std::string Str = Op->getLiteralStr();
5586 const char *Data = Str.c_str();
5587 size_t WordSize = Str.size() / 4;
5588 for (unsigned Idx = 0; Idx < WordSize; Idx++) {
5589 WriteOneWord(*reinterpret_cast<const uint32_t *>(&Data[4 * Idx]));
5590 }
5591
5592 uint32_t Remainder = Str.size() % 4;
5593 uint32_t LastWord = 0;
5594 if (Remainder) {
5595 for (unsigned Idx = 0; Idx < Remainder; Idx++) {
5596 LastWord |= Data[4 * WordSize + Idx] << 8 * Idx;
5597 }
5598 }
5599
5600 WriteOneWord(LastWord);
5601 break;
5602 }
5603 case SPIRVOperandType::LITERAL_INTEGER:
5604 case SPIRVOperandType::LITERAL_FLOAT: {
5605 auto LiteralNum = Op->getLiteralNum();
5606 // TODO: Handle LiteranNum carefully.
5607 for (auto Word : LiteralNum) {
5608 WriteOneWord(Word);
5609 }
5610 break;
5611 }
5612 }
5613}
5614
5615void SPIRVProducerPass::WriteSPIRVBinary() {
5616 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
5617
5618 for (auto Inst : SPIRVInstList) {
David Netoef5ba2b2019-12-20 08:35:54 -05005619 const auto &Ops = Inst->getOperands();
David Neto22f144c2017-06-12 14:26:21 -04005620 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5621
5622 switch (Opcode) {
5623 default: {
David Neto5c22a252018-03-15 16:07:41 -04005624 errs() << "Unsupported SPIR-V instruction opcode " << int(Opcode) << "\n";
David Neto22f144c2017-06-12 14:26:21 -04005625 llvm_unreachable("Unsupported SPIRV instruction");
5626 break;
5627 }
5628 case spv::OpCapability:
5629 case spv::OpExtension:
5630 case spv::OpMemoryModel:
5631 case spv::OpEntryPoint:
5632 case spv::OpExecutionMode:
5633 case spv::OpSource:
5634 case spv::OpDecorate:
5635 case spv::OpMemberDecorate:
5636 case spv::OpBranch:
5637 case spv::OpBranchConditional:
5638 case spv::OpSelectionMerge:
5639 case spv::OpLoopMerge:
5640 case spv::OpStore:
5641 case spv::OpImageWrite:
5642 case spv::OpReturnValue:
5643 case spv::OpControlBarrier:
5644 case spv::OpMemoryBarrier:
5645 case spv::OpReturn:
5646 case spv::OpFunctionEnd:
5647 case spv::OpCopyMemory: {
5648 WriteWordCountAndOpcode(Inst);
5649 for (uint32_t i = 0; i < Ops.size(); i++) {
5650 WriteOperand(Ops[i]);
5651 }
5652 break;
5653 }
5654 case spv::OpTypeBool:
5655 case spv::OpTypeVoid:
5656 case spv::OpTypeSampler:
5657 case spv::OpLabel:
5658 case spv::OpExtInstImport:
5659 case spv::OpTypePointer:
5660 case spv::OpTypeRuntimeArray:
5661 case spv::OpTypeStruct:
5662 case spv::OpTypeImage:
5663 case spv::OpTypeSampledImage:
5664 case spv::OpTypeInt:
5665 case spv::OpTypeFloat:
5666 case spv::OpTypeArray:
5667 case spv::OpTypeVector:
5668 case spv::OpTypeFunction: {
5669 WriteWordCountAndOpcode(Inst);
5670 WriteResultID(Inst);
5671 for (uint32_t i = 0; i < Ops.size(); i++) {
5672 WriteOperand(Ops[i]);
5673 }
5674 break;
5675 }
5676 case spv::OpFunction:
5677 case spv::OpFunctionParameter:
5678 case spv::OpAccessChain:
5679 case spv::OpPtrAccessChain:
5680 case spv::OpInBoundsAccessChain:
5681 case spv::OpUConvert:
5682 case spv::OpSConvert:
5683 case spv::OpConvertFToU:
5684 case spv::OpConvertFToS:
5685 case spv::OpConvertUToF:
5686 case spv::OpConvertSToF:
5687 case spv::OpFConvert:
5688 case spv::OpConvertPtrToU:
5689 case spv::OpConvertUToPtr:
5690 case spv::OpBitcast:
alan-bakerc9c55ae2019-12-02 16:01:27 -05005691 case spv::OpFNegate:
David Neto22f144c2017-06-12 14:26:21 -04005692 case spv::OpIAdd:
5693 case spv::OpFAdd:
5694 case spv::OpISub:
5695 case spv::OpFSub:
5696 case spv::OpIMul:
5697 case spv::OpFMul:
5698 case spv::OpUDiv:
5699 case spv::OpSDiv:
5700 case spv::OpFDiv:
5701 case spv::OpUMod:
5702 case spv::OpSRem:
5703 case spv::OpFRem:
Kévin Petit8a560882019-03-21 15:24:34 +00005704 case spv::OpUMulExtended:
5705 case spv::OpSMulExtended:
David Neto22f144c2017-06-12 14:26:21 -04005706 case spv::OpBitwiseOr:
5707 case spv::OpBitwiseXor:
5708 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04005709 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04005710 case spv::OpShiftLeftLogical:
5711 case spv::OpShiftRightLogical:
5712 case spv::OpShiftRightArithmetic:
5713 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04005714 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04005715 case spv::OpCompositeExtract:
5716 case spv::OpVectorExtractDynamic:
5717 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04005718 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04005719 case spv::OpVectorInsertDynamic:
5720 case spv::OpVectorShuffle:
5721 case spv::OpIEqual:
5722 case spv::OpINotEqual:
5723 case spv::OpUGreaterThan:
5724 case spv::OpUGreaterThanEqual:
5725 case spv::OpULessThan:
5726 case spv::OpULessThanEqual:
5727 case spv::OpSGreaterThan:
5728 case spv::OpSGreaterThanEqual:
5729 case spv::OpSLessThan:
5730 case spv::OpSLessThanEqual:
5731 case spv::OpFOrdEqual:
5732 case spv::OpFOrdGreaterThan:
5733 case spv::OpFOrdGreaterThanEqual:
5734 case spv::OpFOrdLessThan:
5735 case spv::OpFOrdLessThanEqual:
5736 case spv::OpFOrdNotEqual:
5737 case spv::OpFUnordEqual:
5738 case spv::OpFUnordGreaterThan:
5739 case spv::OpFUnordGreaterThanEqual:
5740 case spv::OpFUnordLessThan:
5741 case spv::OpFUnordLessThanEqual:
5742 case spv::OpFUnordNotEqual:
5743 case spv::OpExtInst:
5744 case spv::OpIsInf:
5745 case spv::OpIsNan:
5746 case spv::OpAny:
5747 case spv::OpAll:
5748 case spv::OpUndef:
5749 case spv::OpConstantNull:
5750 case spv::OpLogicalOr:
5751 case spv::OpLogicalAnd:
5752 case spv::OpLogicalNot:
5753 case spv::OpLogicalNotEqual:
5754 case spv::OpConstantComposite:
5755 case spv::OpSpecConstantComposite:
5756 case spv::OpConstantTrue:
5757 case spv::OpConstantFalse:
5758 case spv::OpConstant:
5759 case spv::OpSpecConstant:
5760 case spv::OpVariable:
5761 case spv::OpFunctionCall:
5762 case spv::OpSampledImage:
5763 case spv::OpImageSampleExplicitLod:
David Neto5c22a252018-03-15 16:07:41 -04005764 case spv::OpImageQuerySize:
alan-bakerce179f12019-12-06 19:02:22 -05005765 case spv::OpImageQuerySizeLod:
David Neto22f144c2017-06-12 14:26:21 -04005766 case spv::OpSelect:
5767 case spv::OpPhi:
5768 case spv::OpLoad:
5769 case spv::OpAtomicIAdd:
5770 case spv::OpAtomicISub:
5771 case spv::OpAtomicExchange:
5772 case spv::OpAtomicIIncrement:
5773 case spv::OpAtomicIDecrement:
5774 case spv::OpAtomicCompareExchange:
5775 case spv::OpAtomicUMin:
5776 case spv::OpAtomicSMin:
5777 case spv::OpAtomicUMax:
5778 case spv::OpAtomicSMax:
5779 case spv::OpAtomicAnd:
5780 case spv::OpAtomicOr:
5781 case spv::OpAtomicXor:
5782 case spv::OpDot: {
5783 WriteWordCountAndOpcode(Inst);
5784 WriteOperand(Ops[0]);
5785 WriteResultID(Inst);
5786 for (uint32_t i = 1; i < Ops.size(); i++) {
5787 WriteOperand(Ops[i]);
5788 }
5789 break;
5790 }
5791 }
5792 }
5793}
Alan Baker9bf93fb2018-08-28 16:59:26 -04005794
alan-bakerb6b09dc2018-11-08 16:59:28 -05005795bool SPIRVProducerPass::IsTypeNullable(const Type *type) const {
Alan Baker9bf93fb2018-08-28 16:59:26 -04005796 switch (type->getTypeID()) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05005797 case Type::HalfTyID:
5798 case Type::FloatTyID:
5799 case Type::DoubleTyID:
5800 case Type::IntegerTyID:
5801 case Type::VectorTyID:
5802 return true;
5803 case Type::PointerTyID: {
5804 const PointerType *pointer_type = cast<PointerType>(type);
5805 if (pointer_type->getPointerAddressSpace() !=
5806 AddressSpace::UniformConstant) {
5807 auto pointee_type = pointer_type->getPointerElementType();
5808 if (pointee_type->isStructTy() &&
5809 cast<StructType>(pointee_type)->isOpaque()) {
5810 // Images and samplers are not nullable.
5811 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04005812 }
Alan Baker9bf93fb2018-08-28 16:59:26 -04005813 }
alan-bakerb6b09dc2018-11-08 16:59:28 -05005814 return true;
5815 }
5816 case Type::ArrayTyID:
5817 return IsTypeNullable(cast<CompositeType>(type)->getTypeAtIndex(0u));
5818 case Type::StructTyID: {
5819 const StructType *struct_type = cast<StructType>(type);
5820 // Images and samplers are not nullable.
5821 if (struct_type->isOpaque())
Alan Baker9bf93fb2018-08-28 16:59:26 -04005822 return false;
alan-bakerb6b09dc2018-11-08 16:59:28 -05005823 for (const auto element : struct_type->elements()) {
5824 if (!IsTypeNullable(element))
5825 return false;
5826 }
5827 return true;
5828 }
5829 default:
5830 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04005831 }
5832}
Alan Bakerfcda9482018-10-02 17:09:59 -04005833
5834void SPIRVProducerPass::PopulateUBOTypeMaps(Module &module) {
5835 if (auto *offsets_md =
5836 module.getNamedMetadata(clspv::RemappedTypeOffsetMetadataName())) {
5837 // Metdata is stored as key-value pair operands. The first element of each
5838 // operand is the type and the second is a vector of offsets.
5839 for (const auto *operand : offsets_md->operands()) {
5840 const auto *pair = cast<MDTuple>(operand);
5841 auto *type =
5842 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
5843 const auto *offset_vector = cast<MDTuple>(pair->getOperand(1));
5844 std::vector<uint32_t> offsets;
5845 for (const Metadata *offset_md : offset_vector->operands()) {
5846 const auto *constant_md = cast<ConstantAsMetadata>(offset_md);
alan-bakerb6b09dc2018-11-08 16:59:28 -05005847 offsets.push_back(static_cast<uint32_t>(
5848 cast<ConstantInt>(constant_md->getValue())->getZExtValue()));
Alan Bakerfcda9482018-10-02 17:09:59 -04005849 }
5850 RemappedUBOTypeOffsets.insert(std::make_pair(type, offsets));
5851 }
5852 }
5853
5854 if (auto *sizes_md =
5855 module.getNamedMetadata(clspv::RemappedTypeSizesMetadataName())) {
5856 // Metadata is stored as key-value pair operands. The first element of each
5857 // operand is the type and the second is a triple of sizes: type size in
5858 // bits, store size and alloc size.
5859 for (const auto *operand : sizes_md->operands()) {
5860 const auto *pair = cast<MDTuple>(operand);
5861 auto *type =
5862 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
5863 const auto *size_triple = cast<MDTuple>(pair->getOperand(1));
5864 uint64_t type_size_in_bits =
5865 cast<ConstantInt>(
5866 cast<ConstantAsMetadata>(size_triple->getOperand(0))->getValue())
5867 ->getZExtValue();
5868 uint64_t type_store_size =
5869 cast<ConstantInt>(
5870 cast<ConstantAsMetadata>(size_triple->getOperand(1))->getValue())
5871 ->getZExtValue();
5872 uint64_t type_alloc_size =
5873 cast<ConstantInt>(
5874 cast<ConstantAsMetadata>(size_triple->getOperand(2))->getValue())
5875 ->getZExtValue();
5876 RemappedUBOTypeSizes.insert(std::make_pair(
5877 type, std::make_tuple(type_size_in_bits, type_store_size,
5878 type_alloc_size)));
5879 }
5880 }
5881}
5882
5883uint64_t SPIRVProducerPass::GetTypeSizeInBits(Type *type,
5884 const DataLayout &DL) {
5885 auto iter = RemappedUBOTypeSizes.find(type);
5886 if (iter != RemappedUBOTypeSizes.end()) {
5887 return std::get<0>(iter->second);
5888 }
5889
5890 return DL.getTypeSizeInBits(type);
5891}
5892
5893uint64_t SPIRVProducerPass::GetTypeStoreSize(Type *type, const DataLayout &DL) {
5894 auto iter = RemappedUBOTypeSizes.find(type);
5895 if (iter != RemappedUBOTypeSizes.end()) {
5896 return std::get<1>(iter->second);
5897 }
5898
5899 return DL.getTypeStoreSize(type);
5900}
5901
5902uint64_t SPIRVProducerPass::GetTypeAllocSize(Type *type, const DataLayout &DL) {
5903 auto iter = RemappedUBOTypeSizes.find(type);
5904 if (iter != RemappedUBOTypeSizes.end()) {
5905 return std::get<2>(iter->second);
5906 }
5907
5908 return DL.getTypeAllocSize(type);
5909}
alan-baker5b86ed72019-02-15 08:26:50 -05005910
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04005911void SPIRVProducerPass::setVariablePointersCapabilities(
5912 unsigned address_space) {
alan-baker5b86ed72019-02-15 08:26:50 -05005913 if (GetStorageClass(address_space) == spv::StorageClassStorageBuffer) {
5914 setVariablePointersStorageBuffer(true);
5915 } else {
5916 setVariablePointers(true);
5917 }
5918}
5919
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04005920Value *SPIRVProducerPass::GetBasePointer(Value *v) {
alan-baker5b86ed72019-02-15 08:26:50 -05005921 if (auto *gep = dyn_cast<GetElementPtrInst>(v)) {
5922 return GetBasePointer(gep->getPointerOperand());
5923 }
5924
5925 // Conservatively return |v|.
5926 return v;
5927}
5928
5929bool SPIRVProducerPass::sameResource(Value *lhs, Value *rhs) const {
5930 if (auto *lhs_call = dyn_cast<CallInst>(lhs)) {
5931 if (auto *rhs_call = dyn_cast<CallInst>(rhs)) {
5932 if (lhs_call->getCalledFunction()->getName().startswith(
5933 clspv::ResourceAccessorFunction()) &&
5934 rhs_call->getCalledFunction()->getName().startswith(
5935 clspv::ResourceAccessorFunction())) {
5936 // For resource accessors, match descriptor set and binding.
5937 if (lhs_call->getOperand(0) == rhs_call->getOperand(0) &&
5938 lhs_call->getOperand(1) == rhs_call->getOperand(1))
5939 return true;
5940 } else if (lhs_call->getCalledFunction()->getName().startswith(
5941 clspv::WorkgroupAccessorFunction()) &&
5942 rhs_call->getCalledFunction()->getName().startswith(
5943 clspv::WorkgroupAccessorFunction())) {
5944 // For workgroup resources, match spec id.
5945 if (lhs_call->getOperand(0) == rhs_call->getOperand(0))
5946 return true;
5947 }
5948 }
5949 }
5950
5951 return false;
5952}
5953
5954bool SPIRVProducerPass::selectFromSameObject(Instruction *inst) {
5955 assert(inst->getType()->isPointerTy());
5956 assert(GetStorageClass(inst->getType()->getPointerAddressSpace()) ==
5957 spv::StorageClassStorageBuffer);
5958 const bool hack_undef = clspv::Option::HackUndef();
5959 if (auto *select = dyn_cast<SelectInst>(inst)) {
5960 auto *true_base = GetBasePointer(select->getTrueValue());
5961 auto *false_base = GetBasePointer(select->getFalseValue());
5962
5963 if (true_base == false_base)
5964 return true;
5965
5966 // If either the true or false operand is a null, then we satisfy the same
5967 // object constraint.
5968 if (auto *true_cst = dyn_cast<Constant>(true_base)) {
5969 if (true_cst->isNullValue() || (hack_undef && isa<UndefValue>(true_base)))
5970 return true;
5971 }
5972
5973 if (auto *false_cst = dyn_cast<Constant>(false_base)) {
5974 if (false_cst->isNullValue() ||
5975 (hack_undef && isa<UndefValue>(false_base)))
5976 return true;
5977 }
5978
5979 if (sameResource(true_base, false_base))
5980 return true;
5981 } else if (auto *phi = dyn_cast<PHINode>(inst)) {
5982 Value *value = nullptr;
5983 bool ok = true;
5984 for (unsigned i = 0; ok && i != phi->getNumIncomingValues(); ++i) {
5985 auto *base = GetBasePointer(phi->getIncomingValue(i));
5986 // Null values satisfy the constraint of selecting of selecting from the
5987 // same object.
5988 if (!value) {
5989 if (auto *cst = dyn_cast<Constant>(base)) {
5990 if (!cst->isNullValue() && !(hack_undef && isa<UndefValue>(base)))
5991 value = base;
5992 } else {
5993 value = base;
5994 }
5995 } else if (base != value) {
5996 if (auto *base_cst = dyn_cast<Constant>(base)) {
5997 if (base_cst->isNullValue() || (hack_undef && isa<UndefValue>(base)))
5998 continue;
5999 }
6000
6001 if (sameResource(value, base))
6002 continue;
6003
6004 // Values don't represent the same base.
6005 ok = false;
6006 }
6007 }
6008
6009 return ok;
6010 }
6011
6012 // Conservatively return false.
6013 return false;
6014}
alan-bakere9308012019-03-15 10:25:13 -04006015
6016bool SPIRVProducerPass::CalledWithCoherentResource(Argument &Arg) {
6017 if (!Arg.getType()->isPointerTy() ||
6018 Arg.getType()->getPointerAddressSpace() != clspv::AddressSpace::Global) {
6019 // Only SSBOs need to be annotated as coherent.
6020 return false;
6021 }
6022
6023 DenseSet<Value *> visited;
6024 std::vector<Value *> stack;
6025 for (auto *U : Arg.getParent()->users()) {
6026 if (auto *call = dyn_cast<CallInst>(U)) {
6027 stack.push_back(call->getOperand(Arg.getArgNo()));
6028 }
6029 }
6030
6031 while (!stack.empty()) {
6032 Value *v = stack.back();
6033 stack.pop_back();
6034
6035 if (!visited.insert(v).second)
6036 continue;
6037
6038 auto *resource_call = dyn_cast<CallInst>(v);
6039 if (resource_call &&
6040 resource_call->getCalledFunction()->getName().startswith(
6041 clspv::ResourceAccessorFunction())) {
6042 // If this is a resource accessor function, check if the coherent operand
6043 // is set.
6044 const auto coherent =
6045 unsigned(dyn_cast<ConstantInt>(resource_call->getArgOperand(5))
6046 ->getZExtValue());
6047 if (coherent == 1)
6048 return true;
6049 } else if (auto *arg = dyn_cast<Argument>(v)) {
6050 // If this is a function argument, trace through its callers.
alan-bakere98f3f92019-04-08 15:06:36 -04006051 for (auto U : arg->getParent()->users()) {
alan-bakere9308012019-03-15 10:25:13 -04006052 if (auto *call = dyn_cast<CallInst>(U)) {
6053 stack.push_back(call->getOperand(arg->getArgNo()));
6054 }
6055 }
6056 } else if (auto *user = dyn_cast<User>(v)) {
6057 // If this is a user, traverse all operands that could lead to resource
6058 // variables.
6059 for (unsigned i = 0; i != user->getNumOperands(); ++i) {
6060 Value *operand = user->getOperand(i);
6061 if (operand->getType()->isPointerTy() &&
6062 operand->getType()->getPointerAddressSpace() ==
6063 clspv::AddressSpace::Global) {
6064 stack.push_back(operand);
6065 }
6066 }
6067 }
6068 }
6069
6070 // No coherent resource variables encountered.
6071 return false;
6072}
alan-baker06cad652019-12-03 17:56:47 -05006073
6074void SPIRVProducerPass::PopulateStructuredCFGMaps(Module &module) {
6075 // First, track loop merges and continues.
6076 DenseSet<BasicBlock *> LoopMergesAndContinues;
6077 for (auto &F : module) {
6078 if (F.isDeclaration())
6079 continue;
6080
6081 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
6082 const LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>(F).getLoopInfo();
6083 std::deque<BasicBlock *> order;
6084 DenseSet<BasicBlock *> visited;
6085 clspv::ComputeStructuredOrder(&*F.begin(), &DT, LI, &order, &visited);
6086
6087 for (auto BB : order) {
6088 auto terminator = BB->getTerminator();
6089 auto branch = dyn_cast<BranchInst>(terminator);
6090 if (LI.isLoopHeader(BB)) {
6091 auto L = LI.getLoopFor(BB);
6092 BasicBlock *ContinueBB = nullptr;
6093 BasicBlock *MergeBB = nullptr;
6094
6095 MergeBB = L->getExitBlock();
6096 if (!MergeBB) {
6097 // StructurizeCFG pass converts CFG into triangle shape and the cfg
6098 // has regions with single entry/exit. As a result, loop should not
6099 // have multiple exits.
6100 llvm_unreachable("Loop has multiple exits???");
6101 }
6102
6103 if (L->isLoopLatch(BB)) {
6104 ContinueBB = BB;
6105 } else {
6106 // From SPIR-V spec 2.11, Continue Target must dominate that back-edge
6107 // block.
6108 BasicBlock *Header = L->getHeader();
6109 BasicBlock *Latch = L->getLoopLatch();
6110 for (auto *loop_block : L->blocks()) {
6111 if (loop_block == Header) {
6112 continue;
6113 }
6114
6115 // Check whether block dominates block with back-edge.
6116 // The loop latch is the single block with a back-edge. If it was
6117 // possible, StructurizeCFG made the loop conform to this
6118 // requirement, otherwise |Latch| is a nullptr.
6119 if (DT.dominates(loop_block, Latch)) {
6120 ContinueBB = loop_block;
6121 }
6122 }
6123
6124 if (!ContinueBB) {
6125 llvm_unreachable("Wrong continue block from loop");
6126 }
6127 }
6128
6129 // Record the continue and merge blocks.
6130 MergeBlocks[BB] = MergeBB;
6131 ContinueBlocks[BB] = ContinueBB;
6132 LoopMergesAndContinues.insert(MergeBB);
6133 LoopMergesAndContinues.insert(ContinueBB);
6134 } else if (branch && branch->isConditional()) {
6135 auto L = LI.getLoopFor(BB);
6136 bool HasBackedge = false;
6137 while (L && !HasBackedge) {
6138 if (L->isLoopLatch(BB)) {
6139 HasBackedge = true;
6140 }
6141 L = L->getParentLoop();
6142 }
6143
6144 if (!HasBackedge) {
6145 // Only need a merge if the branch doesn't include a loop break or
6146 // continue.
6147 auto true_bb = branch->getSuccessor(0);
6148 auto false_bb = branch->getSuccessor(1);
6149 if (!LoopMergesAndContinues.count(true_bb) &&
6150 !LoopMergesAndContinues.count(false_bb)) {
6151 // StructurizeCFG pass already manipulated CFG. Just use false block
6152 // of branch instruction as merge block.
6153 MergeBlocks[BB] = false_bb;
6154 }
6155 }
6156 }
6157 }
6158 }
6159}