blob: 3abdd19db35539bc804ce52f53652f7cde1c58ec [file] [log] [blame]
David Neto22f144c2017-06-12 14:26:21 -04001// Copyright 2017 The Clspv Authors. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#ifdef _MSC_VER
16#pragma warning(push, 0)
17#endif
18
David Neto156783e2017-07-05 15:39:41 -040019#include <cassert>
David Neto257c3892018-04-11 13:19:45 -040020#include <cstring>
David Neto118188e2018-08-24 11:27:54 -040021#include <iomanip>
22#include <list>
David Neto862b7d82018-06-14 18:48:37 -040023#include <memory>
David Neto118188e2018-08-24 11:27:54 -040024#include <set>
25#include <sstream>
26#include <string>
27#include <tuple>
28#include <unordered_set>
29#include <utility>
David Neto862b7d82018-06-14 18:48:37 -040030
David Neto118188e2018-08-24 11:27:54 -040031#include "llvm/ADT/StringSwitch.h"
32#include "llvm/ADT/UniqueVector.h"
33#include "llvm/Analysis/LoopInfo.h"
34#include "llvm/IR/Constants.h"
35#include "llvm/IR/Dominators.h"
36#include "llvm/IR/Instructions.h"
37#include "llvm/IR/Metadata.h"
38#include "llvm/IR/Module.h"
alan-bakerf67468c2019-11-25 15:51:49 -050039#include "llvm/IR/ValueSymbolTable.h"
David Neto118188e2018-08-24 11:27:54 -040040#include "llvm/Pass.h"
41#include "llvm/Support/CommandLine.h"
Kévin Petitbbbda972020-03-03 19:16:31 +000042#include "llvm/Support/MathExtras.h"
David Neto118188e2018-08-24 11:27:54 -040043#include "llvm/Support/raw_ostream.h"
44#include "llvm/Transforms/Utils/Cloning.h"
David Neto22f144c2017-06-12 14:26:21 -040045
SJWf93f5f32020-05-05 07:27:56 -050046// enable spv::HasResultAndType
47#define SPV_ENABLE_UTILITY_CODE
alan-bakere0902602020-03-23 08:43:40 -040048#include "spirv/unified1/spirv.hpp"
David Neto118188e2018-08-24 11:27:54 -040049
David Neto85082642018-03-24 06:55:20 -070050#include "clspv/AddressSpace.h"
alan-bakerf5e5f692018-11-27 08:33:24 -050051#include "clspv/DescriptorMap.h"
David Neto118188e2018-08-24 11:27:54 -040052#include "clspv/Option.h"
David Neto85082642018-03-24 06:55:20 -070053#include "clspv/spirv_c_strings.hpp"
54#include "clspv/spirv_glsl.hpp"
David Neto22f144c2017-06-12 14:26:21 -040055
David Neto4feb7a42017-10-06 17:29:42 -040056#include "ArgKind.h"
alan-bakerf67468c2019-11-25 15:51:49 -050057#include "Builtins.h"
alan-baker06cad652019-12-03 17:56:47 -050058#include "ComputeStructuredOrder.h"
David Neto85082642018-03-24 06:55:20 -070059#include "ConstantEmitter.h"
Alan Baker202c8c72018-08-13 13:47:44 -040060#include "Constants.h"
David Neto78383442018-06-15 20:31:56 -040061#include "DescriptorCounter.h"
alan-bakerc4579bb2020-04-29 14:15:50 -040062#include "Layout.h"
alan-baker56f7aff2019-05-22 08:06:42 -040063#include "NormalizeGlobalVariable.h"
Diego Novilloa4c44fa2019-04-11 10:56:15 -040064#include "Passes.h"
alan-bakera1be3322020-04-20 12:48:18 -040065#include "SpecConstant.h"
alan-bakerce179f12019-12-06 19:02:22 -050066#include "Types.h"
David Neto48f56a42017-10-06 16:44:25 -040067
David Neto22f144c2017-06-12 14:26:21 -040068#if defined(_MSC_VER)
69#pragma warning(pop)
70#endif
71
72using namespace llvm;
73using namespace clspv;
SJW173c7e92020-03-16 08:44:47 -050074using namespace clspv::Builtins;
SJW806a5d82020-07-15 12:51:38 -050075using namespace clspv::Option;
David Neto156783e2017-07-05 15:39:41 -040076using namespace mdconst;
David Neto22f144c2017-06-12 14:26:21 -040077
78namespace {
David Netocd8ca5f2017-10-02 23:34:11 -040079
David Neto862b7d82018-06-14 18:48:37 -040080cl::opt<bool> ShowResourceVars("show-rv", cl::init(false), cl::Hidden,
81 cl::desc("Show resource variable creation"));
82
alan-baker5ed87542020-03-23 11:05:22 -040083cl::opt<bool>
84 ShowProducerIR("show-producer-ir", cl::init(false), cl::ReallyHidden,
85 cl::desc("Dump the IR at the start of SPIRVProducer"));
86
David Neto862b7d82018-06-14 18:48:37 -040087// These hacks exist to help transition code generation algorithms
88// without making huge noise in detailed test output.
89const bool Hack_generate_runtime_array_stride_early = true;
90
David Neto3fbb4072017-10-16 11:28:14 -040091// The value of 1/pi. This value is from MSDN
92// https://msdn.microsoft.com/en-us/library/4hwaceh6.aspx
93const double kOneOverPi = 0.318309886183790671538;
94const glsl::ExtInst kGlslExtInstBad = static_cast<glsl::ExtInst>(0);
95
SJW69939d52020-04-16 07:29:07 -050096// SPIRV Module Sections (per 2.4 of the SPIRV spec)
97// These are used to collect SPIRVInstructions by type on-the-fly.
98enum SPIRVSection {
99 kCapabilities,
100 kExtensions,
101 kImports,
102 kMemoryModel,
103 kEntryPoints,
104 kExecutionModes,
105
106 kDebug,
107 kAnnotations,
108
109 kTypes,
110 kConstants = kTypes,
111 kGlobalVariables,
112
113 kFunctions,
114
115 kSectionCount
116};
117
SJW01901d92020-05-21 08:58:31 -0500118class SPIRVID {
119 uint32_t id;
120
121public:
122 SPIRVID(uint32_t _id = 0) : id(_id) {}
123 uint32_t get() const { return id; }
124 bool isValid() const { return id != 0; }
125 bool operator==(const SPIRVID &that) const { return id == that.id; }
SJW806a5d82020-07-15 12:51:38 -0500126 bool operator<(const SPIRVID &that) const { return id < that.id; }
SJW01901d92020-05-21 08:58:31 -0500127};
SJWf93f5f32020-05-05 07:27:56 -0500128
SJW88ed5fe2020-05-11 12:40:57 -0500129enum SPIRVOperandType { NUMBERID, LITERAL_WORD, LITERAL_DWORD, LITERAL_STRING };
David Neto22f144c2017-06-12 14:26:21 -0400130
131struct SPIRVOperand {
SJW88ed5fe2020-05-11 12:40:57 -0500132 explicit SPIRVOperand(SPIRVOperandType Ty, uint32_t Num) : Type(Ty) {
133 LiteralNum[0] = Num;
134 }
David Neto22f144c2017-06-12 14:26:21 -0400135 explicit SPIRVOperand(SPIRVOperandType Ty, const char *Str)
136 : Type(Ty), LiteralStr(Str) {}
137 explicit SPIRVOperand(SPIRVOperandType Ty, StringRef Str)
138 : Type(Ty), LiteralStr(Str) {}
SJW88ed5fe2020-05-11 12:40:57 -0500139 explicit SPIRVOperand(ArrayRef<uint32_t> NumVec) {
140 auto sz = NumVec.size();
141 assert(sz >= 1 && sz <= 2);
142 Type = sz == 1 ? LITERAL_WORD : LITERAL_DWORD;
143 LiteralNum[0] = NumVec[0];
144 if (sz == 2) {
145 LiteralNum[1] = NumVec[1];
146 }
147 }
David Neto22f144c2017-06-12 14:26:21 -0400148
James Price11010dc2019-12-19 13:53:09 -0500149 SPIRVOperandType getType() const { return Type; };
150 uint32_t getNumID() const { return LiteralNum[0]; };
151 std::string getLiteralStr() const { return LiteralStr; };
SJW88ed5fe2020-05-11 12:40:57 -0500152 const uint32_t *getLiteralNum() const { return LiteralNum; };
David Neto22f144c2017-06-12 14:26:21 -0400153
David Neto87846742018-04-11 17:36:22 -0400154 uint32_t GetNumWords() const {
155 switch (Type) {
156 case NUMBERID:
SJW88ed5fe2020-05-11 12:40:57 -0500157 case LITERAL_WORD:
David Neto87846742018-04-11 17:36:22 -0400158 return 1;
SJW88ed5fe2020-05-11 12:40:57 -0500159 case LITERAL_DWORD:
160 return 2;
David Neto87846742018-04-11 17:36:22 -0400161 case LITERAL_STRING:
162 // Account for the terminating null character.
David Netoee2660d2018-06-28 16:31:29 -0400163 return uint32_t((LiteralStr.size() + 4) / 4);
David Neto87846742018-04-11 17:36:22 -0400164 }
165 llvm_unreachable("Unhandled case in SPIRVOperand::GetNumWords()");
166 }
167
David Neto22f144c2017-06-12 14:26:21 -0400168private:
169 SPIRVOperandType Type;
170 std::string LiteralStr;
SJW88ed5fe2020-05-11 12:40:57 -0500171 uint32_t LiteralNum[2];
David Neto22f144c2017-06-12 14:26:21 -0400172};
173
SJW88ed5fe2020-05-11 12:40:57 -0500174typedef SmallVector<SPIRVOperand, 4> SPIRVOperandVec;
David Netoc6f3ab22018-04-06 18:02:31 -0400175
David Neto22f144c2017-06-12 14:26:21 -0400176struct SPIRVInstruction {
SJWf93f5f32020-05-05 07:27:56 -0500177 // Primary constructor must have Opcode, initializes WordCount based on ResID.
178 SPIRVInstruction(spv::Op Opc, SPIRVID ResID = 0)
179 : Opcode(static_cast<uint16_t>(Opc)) {
180 setResult(ResID);
David Neto87846742018-04-11 17:36:22 -0400181 }
David Neto22f144c2017-06-12 14:26:21 -0400182
SJWf93f5f32020-05-05 07:27:56 -0500183 // Creates an instruction with an opcode and no result ID, and with the given
184 // operands. This calls primary constructor to initialize Opcode, WordCount.
185 // Takes ownership of the operands and clears |Ops|.
186 SPIRVInstruction(spv::Op Opc, SPIRVOperandVec &Ops) : SPIRVInstruction(Opc) {
187 setOperands(Ops);
David Netoef5ba2b2019-12-20 08:35:54 -0500188 }
SJWf93f5f32020-05-05 07:27:56 -0500189 // Creates an instruction with an opcode and no result ID, and with the given
190 // operands. This calls primary constructor to initialize Opcode, WordCount.
191 // Takes ownership of the operands and clears |Ops|.
192 SPIRVInstruction(spv::Op Opc, SPIRVID ResID, SPIRVOperandVec &Ops)
193 : SPIRVInstruction(Opc, ResID) {
194 setOperands(Ops);
David Netoef5ba2b2019-12-20 08:35:54 -0500195 }
David Netoef5ba2b2019-12-20 08:35:54 -0500196
David Netoee2660d2018-06-28 16:31:29 -0400197 uint32_t getWordCount() const { return WordCount; }
David Neto22f144c2017-06-12 14:26:21 -0400198 uint16_t getOpcode() const { return Opcode; }
SJW88ed5fe2020-05-11 12:40:57 -0500199 SPIRVID getResultID() const { return ResultID; }
200 const SPIRVOperandVec &getOperands() const { return Operands; }
David Neto22f144c2017-06-12 14:26:21 -0400201
202private:
SJW01901d92020-05-21 08:58:31 -0500203 void setResult(SPIRVID ResID = 0) {
204 WordCount = 1 + (ResID.isValid() ? 1 : 0);
SJWf93f5f32020-05-05 07:27:56 -0500205 ResultID = ResID;
206 }
207
208 void setOperands(SPIRVOperandVec &Ops) {
209 assert(Operands.empty());
210 Operands = std::move(Ops);
211 for (auto &opd : Operands) {
SJW88ed5fe2020-05-11 12:40:57 -0500212 WordCount += uint16_t(opd.GetNumWords());
SJWf93f5f32020-05-05 07:27:56 -0500213 }
214 }
215
216private:
David Netoee2660d2018-06-28 16:31:29 -0400217 uint32_t WordCount; // Check the 16-bit bound at code generation time.
David Neto22f144c2017-06-12 14:26:21 -0400218 uint16_t Opcode;
SJW88ed5fe2020-05-11 12:40:57 -0500219 SPIRVID ResultID;
SJWf93f5f32020-05-05 07:27:56 -0500220 SPIRVOperandVec Operands;
David Neto22f144c2017-06-12 14:26:21 -0400221};
222
223struct SPIRVProducerPass final : public ModulePass {
SJW01901d92020-05-21 08:58:31 -0500224 typedef DenseMap<Type *, SPIRVID> TypeMapType;
David Neto22f144c2017-06-12 14:26:21 -0400225 typedef UniqueVector<Type *> TypeList;
SJW88ed5fe2020-05-11 12:40:57 -0500226 typedef DenseMap<Value *, SPIRVID> ValueMapType;
SJW806a5d82020-07-15 12:51:38 -0500227 typedef std::list<SPIRVID> SPIRVIDListType;
SJW01901d92020-05-21 08:58:31 -0500228 typedef std::vector<std::pair<Value *, SPIRVID>> EntryPointVecType;
229 typedef std::set<uint32_t> CapabilitySetType;
SJW88ed5fe2020-05-11 12:40:57 -0500230 typedef std::list<SPIRVInstruction> SPIRVInstructionList;
SJW806a5d82020-07-15 12:51:38 -0500231 typedef std::map<spv::BuiltIn, SPIRVID> BuiltinConstantMapType;
SJW88ed5fe2020-05-11 12:40:57 -0500232 // A vector of pairs, each of which is:
David Neto87846742018-04-11 17:36:22 -0400233 // - the LLVM instruction that we will later generate SPIR-V code for
SJW88ed5fe2020-05-11 12:40:57 -0500234 // - the SPIR-V instruction placeholder that will be replaced
235 typedef std::vector<std::pair<Value *, SPIRVInstruction *>>
David Neto22f144c2017-06-12 14:26:21 -0400236 DeferredInstVecType;
237 typedef DenseMap<FunctionType *, std::pair<FunctionType *, uint32_t>>
238 GlobalConstFuncMapType;
239
David Neto44795152017-07-13 15:45:28 -0400240 explicit SPIRVProducerPass(
alan-bakerf5e5f692018-11-27 08:33:24 -0500241 raw_pwrite_stream &out,
242 std::vector<clspv::version0::DescriptorMapEntry> *descriptor_map_entries,
alan-baker00e7a582019-06-07 12:54:21 -0400243 ArrayRef<std::pair<unsigned, std::string>> samplerMap,
David Neto44795152017-07-13 15:45:28 -0400244 bool outputCInitList)
SJW01901d92020-05-21 08:58:31 -0500245 : ModulePass(ID), module(nullptr), samplerMap(samplerMap), out(out),
David Neto0676e6f2017-07-11 18:47:44 -0400246 binaryTempOut(binaryTempUnderlyingVector), binaryOut(&out),
alan-baker00e7a582019-06-07 12:54:21 -0400247 descriptorMapEntries(descriptor_map_entries),
David Neto0676e6f2017-07-11 18:47:44 -0400248 outputCInitList(outputCInitList), patchBoundOffset(0), nextID(1),
alan-baker5b86ed72019-02-15 08:26:50 -0500249 OpExtInstImportID(0), HasVariablePointersStorageBuffer(false),
250 HasVariablePointers(false), SamplerTy(nullptr), WorkgroupSizeValueID(0),
SJW01901d92020-05-21 08:58:31 -0500251 WorkgroupSizeVarID(0) {
252 addCapability(spv::CapabilityShader);
253 Ptr = this;
254 }
David Neto22f144c2017-06-12 14:26:21 -0400255
James Price11010dc2019-12-19 13:53:09 -0500256 virtual ~SPIRVProducerPass() {
James Price11010dc2019-12-19 13:53:09 -0500257 }
258
David Neto22f144c2017-06-12 14:26:21 -0400259 void getAnalysisUsage(AnalysisUsage &AU) const override {
260 AU.addRequired<DominatorTreeWrapperPass>();
261 AU.addRequired<LoopInfoWrapperPass>();
262 }
263
264 virtual bool runOnModule(Module &module) override;
265
266 // output the SPIR-V header block
267 void outputHeader();
268
269 // patch the SPIR-V header block
270 void patchHeader();
271
SJW01901d92020-05-21 08:58:31 -0500272 CapabilitySetType &getCapabilitySet() { return CapabilitySet; }
David Neto22f144c2017-06-12 14:26:21 -0400273 TypeMapType &getImageTypeMap() { return ImageTypeMap; }
274 TypeList &getTypeList() { return Types; };
David Neto22f144c2017-06-12 14:26:21 -0400275 ValueMapType &getValueMap() { return ValueMap; }
SJW69939d52020-04-16 07:29:07 -0500276 SPIRVInstructionList &getSPIRVInstList(SPIRVSection Section) {
277 return SPIRVSections[Section];
278 };
David Neto22f144c2017-06-12 14:26:21 -0400279 EntryPointVecType &getEntryPointVec() { return EntryPointVec; };
280 DeferredInstVecType &getDeferredInstVec() { return DeferredInstVec; };
SJW806a5d82020-07-15 12:51:38 -0500281 SPIRVIDListType &getEntryPointInterfacesList() {
282 return EntryPointInterfacesList;
283 };
SJW01901d92020-05-21 08:58:31 -0500284 SPIRVID getOpExtInstImportID();
285 std::vector<SPIRVID> &getBuiltinDimVec() { return BuiltinDimensionVec; };
SJW2c317da2020-03-23 07:39:13 -0500286
alan-baker5b86ed72019-02-15 08:26:50 -0500287 bool hasVariablePointersStorageBuffer() {
288 return HasVariablePointersStorageBuffer;
289 }
SJW01901d92020-05-21 08:58:31 -0500290 void setVariablePointersStorageBuffer() {
291 if (!HasVariablePointersStorageBuffer) {
292 addCapability(spv::CapabilityVariablePointersStorageBuffer);
293 HasVariablePointersStorageBuffer = true;
294 }
alan-baker5b86ed72019-02-15 08:26:50 -0500295 }
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400296 bool hasVariablePointers() { return HasVariablePointers; };
SJW01901d92020-05-21 08:58:31 -0500297 void setVariablePointers() {
298 if (!HasVariablePointers) {
299 addCapability(spv::CapabilityVariablePointers);
300 HasVariablePointers = true;
301 }
302 };
alan-bakerb6b09dc2018-11-08 16:59:28 -0500303 ArrayRef<std::pair<unsigned, std::string>> &getSamplerMap() {
304 return samplerMap;
305 }
David Neto22f144c2017-06-12 14:26:21 -0400306 GlobalConstFuncMapType &getGlobalConstFuncTypeMap() {
307 return GlobalConstFuncTypeMap;
308 }
309 SmallPtrSet<Value *, 16> &getGlobalConstArgSet() {
310 return GlobalConstArgumentSet;
311 }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500312 TypeList &getTypesNeedingArrayStride() { return TypesNeedingArrayStride; }
David Neto22f144c2017-06-12 14:26:21 -0400313
SJW77b87ad2020-04-21 14:37:52 -0500314 void GenerateLLVMIRInfo();
alan-bakerb6b09dc2018-11-08 16:59:28 -0500315 // Populate GlobalConstFuncTypeMap. Also, if module-scope __constant will
316 // *not* be converted to a storage buffer, replace each such global variable
317 // with one in the storage class expecgted by SPIR-V.
SJW77b87ad2020-04-21 14:37:52 -0500318 void FindGlobalConstVars();
David Neto862b7d82018-06-14 18:48:37 -0400319 // Populate ResourceVarInfoList, FunctionToResourceVarsMap, and
320 // ModuleOrderedResourceVars.
SJW77b87ad2020-04-21 14:37:52 -0500321 void FindResourceVars();
David Neto22f144c2017-06-12 14:26:21 -0400322 void FindTypePerGlobalVar(GlobalVariable &GV);
323 void FindTypePerFunc(Function &F);
SJW77b87ad2020-04-21 14:37:52 -0500324 void FindTypesForSamplerMap();
325 void FindTypesForResourceVars();
alan-bakerb6b09dc2018-11-08 16:59:28 -0500326 // Inserts |Ty| and relevant sub-types into the |Types| member, indicating
327 // that |Ty| and its subtypes will need a corresponding SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400328 void FindType(Type *Ty);
SJWf93f5f32020-05-05 07:27:56 -0500329
330 // Lookup or create Types, Constants.
331 // Returns SPIRVID once it has been created.
332 SPIRVID getSPIRVType(Type *Ty);
333 SPIRVID getSPIRVConstant(Constant *Cst);
SJW806a5d82020-07-15 12:51:38 -0500334 SPIRVID getSPIRVInt32Constant(uint32_t CstVal);
SJWf93f5f32020-05-05 07:27:56 -0500335 // Lookup SPIRVID of llvm::Value, may create Constant.
336 SPIRVID getSPIRVValue(Value *V);
337
SJW806a5d82020-07-15 12:51:38 -0500338 SPIRVID getSPIRVBuiltin(spv::BuiltIn BID, spv::Capability Cap);
339
David Neto19a1bad2017-08-25 15:01:41 -0400340 // Generates instructions for SPIR-V types corresponding to the LLVM types
341 // saved in the |Types| member. A type follows its subtypes. IDs are
342 // allocated sequentially starting with the current value of nextID, and
343 // with a type following its subtypes. Also updates nextID to just beyond
344 // the last generated ID.
SJW77b87ad2020-04-21 14:37:52 -0500345 void GenerateSPIRVTypes();
SJW77b87ad2020-04-21 14:37:52 -0500346 void GenerateModuleInfo();
347 void GeneratePushConstantDescriptorMapEntries();
348 void GenerateSpecConstantDescriptorMapEntries();
David Neto22f144c2017-06-12 14:26:21 -0400349 void GenerateGlobalVar(GlobalVariable &GV);
SJW77b87ad2020-04-21 14:37:52 -0500350 void GenerateWorkgroupVars();
David Neto862b7d82018-06-14 18:48:37 -0400351 // Generate descriptor map entries for resource variables associated with
352 // arguments to F.
SJW77b87ad2020-04-21 14:37:52 -0500353 void GenerateDescriptorMapInfo(Function &F);
354 void GenerateSamplers();
David Neto862b7d82018-06-14 18:48:37 -0400355 // Generate OpVariables for %clspv.resource.var.* calls.
SJW77b87ad2020-04-21 14:37:52 -0500356 void GenerateResourceVars();
David Neto22f144c2017-06-12 14:26:21 -0400357 void GenerateFuncPrologue(Function &F);
358 void GenerateFuncBody(Function &F);
David Netob6e2e062018-04-25 10:32:06 -0400359 void GenerateEntryPointInitialStores();
David Neto22f144c2017-06-12 14:26:21 -0400360 spv::Op GetSPIRVCmpOpcode(CmpInst *CmpI);
361 spv::Op GetSPIRVCastOpcode(Instruction &I);
362 spv::Op GetSPIRVBinaryOpcode(Instruction &I);
SJW806a5d82020-07-15 12:51:38 -0500363 SPIRVID GenerateClspvInstruction(CallInst *Call,
364 const FunctionInfo &FuncInfo);
365 SPIRVID GenerateImageInstruction(CallInst *Call,
366 const FunctionInfo &FuncInfo);
367 SPIRVID GenerateSubgroupInstruction(CallInst *Call,
368 const FunctionInfo &FuncInfo);
369 SPIRVID GenerateInstructionFromCall(CallInst *Call);
David Neto22f144c2017-06-12 14:26:21 -0400370 void GenerateInstruction(Instruction &I);
371 void GenerateFuncEpilogue();
372 void HandleDeferredInstruction();
SJW77b87ad2020-04-21 14:37:52 -0500373 void HandleDeferredDecorations();
David Neto22f144c2017-06-12 14:26:21 -0400374 bool is4xi8vec(Type *Ty) const;
375 spv::StorageClass GetStorageClass(unsigned AddrSpace) const;
David Neto862b7d82018-06-14 18:48:37 -0400376 spv::StorageClass GetStorageClassForArgKind(clspv::ArgKind arg_kind) const;
David Neto22f144c2017-06-12 14:26:21 -0400377 spv::BuiltIn GetBuiltin(StringRef globalVarName) const;
David Neto3fbb4072017-10-16 11:28:14 -0400378 // Returns the GLSL extended instruction enum that the given function
379 // call maps to. If none, then returns the 0 value, i.e. GLSLstd4580Bad.
SJW61531372020-06-09 07:31:08 -0500380 glsl::ExtInst getExtInstEnum(const Builtins::FunctionInfo &func_info);
David Neto3fbb4072017-10-16 11:28:14 -0400381 // Returns the GLSL extended instruction enum indirectly used by the given
382 // function. That is, to implement the given function, we use an extended
383 // instruction plus one more instruction. If none, then returns the 0 value,
384 // i.e. GLSLstd4580Bad.
SJW61531372020-06-09 07:31:08 -0500385 glsl::ExtInst getIndirectExtInstEnum(const Builtins::FunctionInfo &func_info);
David Neto3fbb4072017-10-16 11:28:14 -0400386 // Returns the single GLSL extended instruction used directly or
387 // indirectly by the given function call.
SJW61531372020-06-09 07:31:08 -0500388 glsl::ExtInst
389 getDirectOrIndirectExtInstEnum(const Builtins::FunctionInfo &func_info);
David Neto22f144c2017-06-12 14:26:21 -0400390 void WriteOneWord(uint32_t Word);
SJW88ed5fe2020-05-11 12:40:57 -0500391 void WriteResultID(const SPIRVInstruction &Inst);
392 void WriteWordCountAndOpcode(const SPIRVInstruction &Inst);
393 void WriteOperand(const SPIRVOperand &Op);
David Neto22f144c2017-06-12 14:26:21 -0400394 void WriteSPIRVBinary();
SJW69939d52020-04-16 07:29:07 -0500395 void WriteSPIRVBinary(SPIRVInstructionList &SPIRVInstList);
David Neto22f144c2017-06-12 14:26:21 -0400396
Alan Baker9bf93fb2018-08-28 16:59:26 -0400397 // Returns true if |type| is compatible with OpConstantNull.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500398 bool IsTypeNullable(const Type *type) const;
Alan Baker9bf93fb2018-08-28 16:59:26 -0400399
Alan Bakerfcda9482018-10-02 17:09:59 -0400400 // Populate UBO remapped type maps.
SJW77b87ad2020-04-21 14:37:52 -0500401 void PopulateUBOTypeMaps();
Alan Bakerfcda9482018-10-02 17:09:59 -0400402
alan-baker06cad652019-12-03 17:56:47 -0500403 // Populate the merge and continue block maps.
SJW77b87ad2020-04-21 14:37:52 -0500404 void PopulateStructuredCFGMaps();
alan-baker06cad652019-12-03 17:56:47 -0500405
Alan Bakerfcda9482018-10-02 17:09:59 -0400406 // Wrapped methods of DataLayout accessors. If |type| was remapped for UBOs,
407 // uses the internal map, otherwise it falls back on the data layout.
408 uint64_t GetTypeSizeInBits(Type *type, const DataLayout &DL);
409 uint64_t GetTypeStoreSize(Type *type, const DataLayout &DL);
410 uint64_t GetTypeAllocSize(Type *type, const DataLayout &DL);
Kévin Petitbbbda972020-03-03 19:16:31 +0000411 uint32_t GetExplicitLayoutStructMemberOffset(StructType *type,
412 unsigned member,
413 const DataLayout &DL);
Alan Bakerfcda9482018-10-02 17:09:59 -0400414
alan-baker5b86ed72019-02-15 08:26:50 -0500415 // Returns the base pointer of |v|.
416 Value *GetBasePointer(Value *v);
417
SJW01901d92020-05-21 08:58:31 -0500418 // Add Capability if not already (e.g. CapabilityGroupNonUniformBroadcast)
419 void addCapability(uint32_t c) { CapabilitySet.emplace(c); }
420
alan-baker5b86ed72019-02-15 08:26:50 -0500421 // Sets |HasVariablePointersStorageBuffer| or |HasVariablePointers| base on
422 // |address_space|.
423 void setVariablePointersCapabilities(unsigned address_space);
424
425 // Returns true if |lhs| and |rhs| represent the same resource or workgroup
426 // variable.
427 bool sameResource(Value *lhs, Value *rhs) const;
428
429 // Returns true if |inst| is phi or select that selects from the same
430 // structure (or null).
431 bool selectFromSameObject(Instruction *inst);
432
alan-bakere9308012019-03-15 10:25:13 -0400433 // Returns true if |Arg| is called with a coherent resource.
434 bool CalledWithCoherentResource(Argument &Arg);
435
SJWf93f5f32020-05-05 07:27:56 -0500436 //
437 // Primary interface for adding SPIRVInstructions to a SPIRVSection.
438 template <enum SPIRVSection TSection = kFunctions>
439 SPIRVID addSPIRVInst(spv::Op Opcode, SPIRVOperandVec &Operands) {
440 bool has_result, has_result_type;
441 spv::HasResultAndType(Opcode, &has_result, &has_result_type);
442 SPIRVID RID = has_result ? incrNextID() : 0;
SJW88ed5fe2020-05-11 12:40:57 -0500443 SPIRVSections[TSection].emplace_back(Opcode, RID, Operands);
SJWf93f5f32020-05-05 07:27:56 -0500444 return RID;
445 }
446 template <enum SPIRVSection TSection = kFunctions>
447 SPIRVID addSPIRVInst(spv::Op Op) {
448 SPIRVOperandVec Ops;
449 return addSPIRVInst<TSection>(Op, Ops);
450 }
451 template <enum SPIRVSection TSection = kFunctions>
452 SPIRVID addSPIRVInst(spv::Op Op, uint32_t V) {
453 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -0500454 Ops.emplace_back(LITERAL_WORD, V);
SJWf93f5f32020-05-05 07:27:56 -0500455 return addSPIRVInst<TSection>(Op, Ops);
456 }
457 template <enum SPIRVSection TSection = kFunctions>
458 SPIRVID addSPIRVInst(spv::Op Op, const char *V) {
459 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -0500460 Ops.emplace_back(LITERAL_STRING, V);
SJWf93f5f32020-05-05 07:27:56 -0500461 return addSPIRVInst<TSection>(Op, Ops);
462 }
463
SJW88ed5fe2020-05-11 12:40:57 -0500464 //
465 // Add placeholder for llvm::Value that references future values.
466 // Must have result ID just in case final SPIRVInstruction requires.
467 SPIRVID addSPIRVPlaceholder(Value *I) {
468 SPIRVID RID = incrNextID();
469 SPIRVOperandVec Ops;
470 SPIRVSections[kFunctions].emplace_back(spv::OpExtInst, RID, Ops);
471 DeferredInstVec.push_back({I, &SPIRVSections[kFunctions].back()});
472 return RID;
473 }
474 // Replace placeholder with actual SPIRVInstruction on the final pass
475 // (HandleDeferredInstruction).
476 SPIRVID replaceSPIRVInst(SPIRVInstruction *I, spv::Op Opcode,
477 SPIRVOperandVec &Operands) {
478 bool has_result, has_result_type;
479 spv::HasResultAndType(Opcode, &has_result, &has_result_type);
480 SPIRVID RID = has_result ? I->getResultID() : 0;
481 *I = SPIRVInstruction(Opcode, RID, Operands);
482 return RID;
483 }
484
SJW806a5d82020-07-15 12:51:38 -0500485 //
486 // Add global variable and capture entry point interface
487 SPIRVID addSPIRVGlobalVariable(const SPIRVID &TypeID, spv::StorageClass SC,
488 const SPIRVID &InitID = SPIRVID());
489
David Neto22f144c2017-06-12 14:26:21 -0400490private:
491 static char ID;
SJW77b87ad2020-04-21 14:37:52 -0500492
493 Module *module;
494
SJW01901d92020-05-21 08:58:31 -0500495 // Set of Capabilities required
496 CapabilitySetType CapabilitySet;
497
SJW806a5d82020-07-15 12:51:38 -0500498 // Map from clspv::BuiltinType to SPIRV Global Variable
499 BuiltinConstantMapType BuiltinConstantMap;
500
David Neto44795152017-07-13 15:45:28 -0400501 ArrayRef<std::pair<unsigned, std::string>> samplerMap;
David Neto22f144c2017-06-12 14:26:21 -0400502 raw_pwrite_stream &out;
David Neto0676e6f2017-07-11 18:47:44 -0400503
504 // TODO(dneto): Wouldn't it be better to always just emit a binary, and then
505 // convert to other formats on demand?
506
507 // When emitting a C initialization list, the WriteSPIRVBinary method
508 // will actually write its words to this vector via binaryTempOut.
509 SmallVector<char, 100> binaryTempUnderlyingVector;
510 raw_svector_ostream binaryTempOut;
511
512 // Binary output writes to this stream, which might be |out| or
513 // |binaryTempOut|. It's the latter when we really want to write a C
514 // initializer list.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400515 raw_pwrite_stream *binaryOut;
alan-bakerf5e5f692018-11-27 08:33:24 -0500516 std::vector<version0::DescriptorMapEntry> *descriptorMapEntries;
David Neto0676e6f2017-07-11 18:47:44 -0400517 const bool outputCInitList; // If true, output look like {0x7023, ... , 5}
David Neto22f144c2017-06-12 14:26:21 -0400518 uint64_t patchBoundOffset;
519 uint32_t nextID;
520
SJWf93f5f32020-05-05 07:27:56 -0500521 SPIRVID incrNextID() { return nextID++; }
522
alan-bakerf67468c2019-11-25 15:51:49 -0500523 // ID for OpTypeInt 32 1.
SJW01901d92020-05-21 08:58:31 -0500524 SPIRVID int32ID;
alan-bakerf67468c2019-11-25 15:51:49 -0500525 // ID for OpTypeVector %int 4.
SJW01901d92020-05-21 08:58:31 -0500526 SPIRVID v4int32ID;
alan-bakerf67468c2019-11-25 15:51:49 -0500527
David Neto19a1bad2017-08-25 15:01:41 -0400528 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400529 TypeMapType TypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400530 // Maps an LLVM image type to its SPIR-V ID.
David Neto22f144c2017-06-12 14:26:21 -0400531 TypeMapType ImageTypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400532 // A unique-vector of LLVM types that map to a SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400533 TypeList Types;
David Neto19a1bad2017-08-25 15:01:41 -0400534 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400535 ValueMapType ValueMap;
SJW69939d52020-04-16 07:29:07 -0500536 SPIRVInstructionList SPIRVSections[kSectionCount];
David Neto862b7d82018-06-14 18:48:37 -0400537
David Neto22f144c2017-06-12 14:26:21 -0400538 EntryPointVecType EntryPointVec;
539 DeferredInstVecType DeferredInstVec;
SJW806a5d82020-07-15 12:51:38 -0500540 SPIRVIDListType EntryPointInterfacesList;
SJW01901d92020-05-21 08:58:31 -0500541 SPIRVID OpExtInstImportID;
542 std::vector<SPIRVID> BuiltinDimensionVec;
alan-baker5b86ed72019-02-15 08:26:50 -0500543 bool HasVariablePointersStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -0400544 bool HasVariablePointers;
545 Type *SamplerTy;
SJW01901d92020-05-21 08:58:31 -0500546 DenseMap<unsigned, SPIRVID> SamplerLiteralToIDMap;
David Netoc77d9e22018-03-24 06:30:28 -0700547
548 // If a function F has a pointer-to-__constant parameter, then this variable
David Neto9ed8e2f2018-03-24 06:47:24 -0700549 // will map F's type to (G, index of the parameter), where in a first phase
550 // G is F's type. During FindTypePerFunc, G will be changed to F's type
551 // but replacing the pointer-to-constant parameter with
552 // pointer-to-ModuleScopePrivate.
David Netoc77d9e22018-03-24 06:30:28 -0700553 // TODO(dneto): This doesn't seem general enough? A function might have
554 // more than one such parameter.
David Neto22f144c2017-06-12 14:26:21 -0400555 GlobalConstFuncMapType GlobalConstFuncTypeMap;
556 SmallPtrSet<Value *, 16> GlobalConstArgumentSet;
David Neto1a1a0582017-07-07 12:01:44 -0400557 // An ordered set of pointer types of Base arguments to OpPtrAccessChain,
David Neto85082642018-03-24 06:55:20 -0700558 // or array types, and which point into transparent memory (StorageBuffer
559 // storage class). These will require an ArrayStride decoration.
David Neto1a1a0582017-07-07 12:01:44 -0400560 // See SPV_KHR_variable_pointers rev 13.
David Neto85082642018-03-24 06:55:20 -0700561 TypeList TypesNeedingArrayStride;
David Netoa60b00b2017-09-15 16:34:09 -0400562
563 // This is truly ugly, but works around what look like driver bugs.
564 // For get_local_size, an earlier part of the flow has created a module-scope
565 // variable in Private address space to hold the value for the workgroup
566 // size. Its intializer is a uint3 value marked as builtin WorkgroupSize.
567 // When this is present, save the IDs of the initializer value and variable
568 // in these two variables. We only ever do a vector load from it, and
569 // when we see one of those, substitute just the value of the intializer.
570 // This mimics what Glslang does, and that's what drivers are used to.
David Neto66cfe642018-03-24 06:13:56 -0700571 // TODO(dneto): Remove this once drivers are fixed.
SJW01901d92020-05-21 08:58:31 -0500572 SPIRVID WorkgroupSizeValueID;
573 SPIRVID WorkgroupSizeVarID;
David Neto26aaf622017-10-23 18:11:53 -0400574
David Neto862b7d82018-06-14 18:48:37 -0400575 // Bookkeeping for mapping kernel arguments to resource variables.
576 struct ResourceVarInfo {
577 ResourceVarInfo(int index_arg, unsigned set_arg, unsigned binding_arg,
alan-bakere9308012019-03-15 10:25:13 -0400578 Function *fn, clspv::ArgKind arg_kind_arg, int coherent_arg)
David Neto862b7d82018-06-14 18:48:37 -0400579 : index(index_arg), descriptor_set(set_arg), binding(binding_arg),
alan-bakere9308012019-03-15 10:25:13 -0400580 var_fn(fn), arg_kind(arg_kind_arg), coherent(coherent_arg),
David Neto862b7d82018-06-14 18:48:37 -0400581 addr_space(fn->getReturnType()->getPointerAddressSpace()) {}
582 const int index; // Index into ResourceVarInfoList
583 const unsigned descriptor_set;
584 const unsigned binding;
585 Function *const var_fn; // The @clspv.resource.var.* function.
586 const clspv::ArgKind arg_kind;
alan-bakere9308012019-03-15 10:25:13 -0400587 const int coherent;
David Neto862b7d82018-06-14 18:48:37 -0400588 const unsigned addr_space; // The LLVM address space
589 // The SPIR-V ID of the OpVariable. Not populated at construction time.
SJW01901d92020-05-21 08:58:31 -0500590 SPIRVID var_id;
David Neto862b7d82018-06-14 18:48:37 -0400591 };
592 // A list of resource var info. Each one correponds to a module-scope
593 // resource variable we will have to create. Resource var indices are
594 // indices into this vector.
595 SmallVector<std::unique_ptr<ResourceVarInfo>, 8> ResourceVarInfoList;
596 // This is a vector of pointers of all the resource vars, but ordered by
597 // kernel function, and then by argument.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500598 UniqueVector<ResourceVarInfo *> ModuleOrderedResourceVars;
David Neto862b7d82018-06-14 18:48:37 -0400599 // Map a function to the ordered list of resource variables it uses, one for
600 // each argument. If an argument does not use a resource variable, it
601 // will have a null pointer entry.
602 using FunctionToResourceVarsMapType =
603 DenseMap<Function *, SmallVector<ResourceVarInfo *, 8>>;
604 FunctionToResourceVarsMapType FunctionToResourceVarsMap;
605
606 // What LLVM types map to SPIR-V types needing layout? These are the
607 // arrays and structures supporting storage buffers and uniform buffers.
608 TypeList TypesNeedingLayout;
609 // What LLVM struct types map to a SPIR-V struct type with Block decoration?
610 UniqueVector<StructType *> StructTypesNeedingBlock;
611 // For a call that represents a load from an opaque type (samplers, images),
612 // map it to the variable id it should load from.
SJW01901d92020-05-21 08:58:31 -0500613 DenseMap<CallInst *, SPIRVID> ResourceVarDeferredLoadCalls;
David Neto85082642018-03-24 06:55:20 -0700614
David Netoc6f3ab22018-04-06 18:02:31 -0400615 // An ordered list of the kernel arguments of type pointer-to-local.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500616 using LocalArgList = SmallVector<Argument *, 8>;
David Netoc6f3ab22018-04-06 18:02:31 -0400617 LocalArgList LocalArgs;
618 // Information about a pointer-to-local argument.
619 struct LocalArgInfo {
620 // The SPIR-V ID of the array variable.
SJW01901d92020-05-21 08:58:31 -0500621 SPIRVID variable_id;
David Netoc6f3ab22018-04-06 18:02:31 -0400622 // The element type of the
alan-bakerb6b09dc2018-11-08 16:59:28 -0500623 Type *elem_type;
David Netoc6f3ab22018-04-06 18:02:31 -0400624 // The ID of the array type.
SJW01901d92020-05-21 08:58:31 -0500625 SPIRVID array_size_id;
David Netoc6f3ab22018-04-06 18:02:31 -0400626 // The ID of the array type.
SJW01901d92020-05-21 08:58:31 -0500627 SPIRVID array_type_id;
David Netoc6f3ab22018-04-06 18:02:31 -0400628 // The ID of the pointer to the array type.
SJW01901d92020-05-21 08:58:31 -0500629 SPIRVID ptr_array_type_id;
David Netoc6f3ab22018-04-06 18:02:31 -0400630 // The specialization constant ID of the array size.
631 int spec_id;
632 };
Alan Baker202c8c72018-08-13 13:47:44 -0400633 // A mapping from Argument to its assigned SpecId.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500634 DenseMap<const Argument *, int> LocalArgSpecIds;
Alan Baker202c8c72018-08-13 13:47:44 -0400635 // A mapping from SpecId to its LocalArgInfo.
636 DenseMap<int, LocalArgInfo> LocalSpecIdInfoMap;
Alan Bakerfcda9482018-10-02 17:09:59 -0400637 // A mapping from a remapped type to its real offsets.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500638 DenseMap<Type *, std::vector<uint32_t>> RemappedUBOTypeOffsets;
Alan Bakerfcda9482018-10-02 17:09:59 -0400639 // A mapping from a remapped type to its real sizes.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500640 DenseMap<Type *, std::tuple<uint64_t, uint64_t, uint64_t>>
641 RemappedUBOTypeSizes;
alan-baker06cad652019-12-03 17:56:47 -0500642
643 // Maps basic block to its merge block.
644 DenseMap<BasicBlock *, BasicBlock *> MergeBlocks;
645 // Maps basic block to its continue block.
646 DenseMap<BasicBlock *, BasicBlock *> ContinueBlocks;
SJW01901d92020-05-21 08:58:31 -0500647
648public:
649 static SPIRVProducerPass *Ptr;
David Neto22f144c2017-06-12 14:26:21 -0400650};
651
652char SPIRVProducerPass::ID;
SJW01901d92020-05-21 08:58:31 -0500653SPIRVProducerPass *SPIRVProducerPass::Ptr = nullptr;
David Netoc6f3ab22018-04-06 18:02:31 -0400654
alan-bakerb6b09dc2018-11-08 16:59:28 -0500655} // namespace
David Neto22f144c2017-06-12 14:26:21 -0400656
657namespace clspv {
alan-bakerf5e5f692018-11-27 08:33:24 -0500658ModulePass *createSPIRVProducerPass(
659 raw_pwrite_stream &out,
660 std::vector<version0::DescriptorMapEntry> *descriptor_map_entries,
alan-baker00e7a582019-06-07 12:54:21 -0400661 ArrayRef<std::pair<unsigned, std::string>> samplerMap,
alan-bakerf5e5f692018-11-27 08:33:24 -0500662 bool outputCInitList) {
663 return new SPIRVProducerPass(out, descriptor_map_entries, samplerMap,
alan-baker00e7a582019-06-07 12:54:21 -0400664 outputCInitList);
David Neto22f144c2017-06-12 14:26:21 -0400665}
David Netoc2c368d2017-06-30 16:50:17 -0400666} // namespace clspv
David Neto22f144c2017-06-12 14:26:21 -0400667
SJW01901d92020-05-21 08:58:31 -0500668namespace {
669SPIRVOperandVec &operator<<(SPIRVOperandVec &list, uint32_t num) {
670 list.emplace_back(LITERAL_WORD, num);
671 return list;
672}
673
674SPIRVOperandVec &operator<<(SPIRVOperandVec &list, int32_t num) {
675 list.emplace_back(LITERAL_WORD, static_cast<uint32_t>(num));
676 return list;
677}
678
679SPIRVOperandVec &operator<<(SPIRVOperandVec &list, ArrayRef<uint32_t> num_vec) {
680 list.emplace_back(num_vec);
681 return list;
682}
683
684SPIRVOperandVec &operator<<(SPIRVOperandVec &list, StringRef str) {
685 list.emplace_back(LITERAL_STRING, str);
686 return list;
687}
688
689SPIRVOperandVec &operator<<(SPIRVOperandVec &list, Type *t) {
690 list.emplace_back(NUMBERID, SPIRVProducerPass::Ptr->getSPIRVType(t).get());
691 return list;
692}
693
694SPIRVOperandVec &operator<<(SPIRVOperandVec &list, Value *v) {
695 list.emplace_back(NUMBERID, SPIRVProducerPass::Ptr->getSPIRVValue(v).get());
696 return list;
697}
698
SJW806a5d82020-07-15 12:51:38 -0500699SPIRVOperandVec &operator<<(SPIRVOperandVec &list, const SPIRVID &v) {
SJW01901d92020-05-21 08:58:31 -0500700 list.emplace_back(NUMBERID, v.get());
701 return list;
702}
703} // namespace
704
SJW77b87ad2020-04-21 14:37:52 -0500705bool SPIRVProducerPass::runOnModule(Module &M) {
SJW01901d92020-05-21 08:58:31 -0500706 // TODO(sjw): Need to reset all data members for each Module, or better
707 // yet create a new SPIRVProducer for every module.. For now only
708 // allow 1 call.
709 assert(module == nullptr);
SJW77b87ad2020-04-21 14:37:52 -0500710 module = &M;
alan-baker5ed87542020-03-23 11:05:22 -0400711 if (ShowProducerIR) {
SJW77b87ad2020-04-21 14:37:52 -0500712 llvm::outs() << *module << "\n";
alan-baker5ed87542020-03-23 11:05:22 -0400713 }
David Neto0676e6f2017-07-11 18:47:44 -0400714 binaryOut = outputCInitList ? &binaryTempOut : &out;
715
SJW77b87ad2020-04-21 14:37:52 -0500716 PopulateUBOTypeMaps();
717 PopulateStructuredCFGMaps();
Alan Bakerfcda9482018-10-02 17:09:59 -0400718
David Neto22f144c2017-06-12 14:26:21 -0400719 // SPIR-V always begins with its header information
720 outputHeader();
721
722 // Gather information from the LLVM IR that we require.
SJW77b87ad2020-04-21 14:37:52 -0500723 GenerateLLVMIRInfo();
David Neto22f144c2017-06-12 14:26:21 -0400724
David Neto22f144c2017-06-12 14:26:21 -0400725 // Collect information on global variables too.
SJW77b87ad2020-04-21 14:37:52 -0500726 for (GlobalVariable &GV : module->globals()) {
David Neto22f144c2017-06-12 14:26:21 -0400727 // If the GV is one of our special __spirv_* variables, remove the
728 // initializer as it was only placed there to force LLVM to not throw the
729 // value away.
Kévin Petitbbbda972020-03-03 19:16:31 +0000730 if (GV.getName().startswith("__spirv_") ||
731 GV.getAddressSpace() == clspv::AddressSpace::PushConstant) {
David Neto22f144c2017-06-12 14:26:21 -0400732 GV.setInitializer(nullptr);
733 }
734
735 // Collect types' information from global variable.
736 FindTypePerGlobalVar(GV);
David Neto22f144c2017-06-12 14:26:21 -0400737 }
738
David Neto22f144c2017-06-12 14:26:21 -0400739 // Generate SPIRV instructions for types.
SJW77b87ad2020-04-21 14:37:52 -0500740 GenerateSPIRVTypes();
David Neto22f144c2017-06-12 14:26:21 -0400741
alan-baker09cb9802019-12-10 13:16:27 -0500742 // Generate literal samplers if necessary.
SJW77b87ad2020-04-21 14:37:52 -0500743 GenerateSamplers();
David Neto22f144c2017-06-12 14:26:21 -0400744
Kévin Petitbbbda972020-03-03 19:16:31 +0000745 // Generate descriptor map entries for all push constants
SJW77b87ad2020-04-21 14:37:52 -0500746 GeneratePushConstantDescriptorMapEntries();
Kévin Petitbbbda972020-03-03 19:16:31 +0000747
David Neto22f144c2017-06-12 14:26:21 -0400748 // Generate SPIRV variables.
SJW77b87ad2020-04-21 14:37:52 -0500749 for (GlobalVariable &GV : module->globals()) {
David Neto22f144c2017-06-12 14:26:21 -0400750 GenerateGlobalVar(GV);
751 }
SJW77b87ad2020-04-21 14:37:52 -0500752 GenerateResourceVars();
753 GenerateWorkgroupVars();
David Neto22f144c2017-06-12 14:26:21 -0400754
755 // Generate SPIRV instructions for each function.
SJW77b87ad2020-04-21 14:37:52 -0500756 for (Function &F : *module) {
David Neto22f144c2017-06-12 14:26:21 -0400757 if (F.isDeclaration()) {
758 continue;
759 }
760
SJW77b87ad2020-04-21 14:37:52 -0500761 GenerateDescriptorMapInfo(F);
David Neto862b7d82018-06-14 18:48:37 -0400762
David Neto22f144c2017-06-12 14:26:21 -0400763 // Generate Function Prologue.
764 GenerateFuncPrologue(F);
765
766 // Generate SPIRV instructions for function body.
767 GenerateFuncBody(F);
768
769 // Generate Function Epilogue.
770 GenerateFuncEpilogue();
771 }
772
773 HandleDeferredInstruction();
SJW77b87ad2020-04-21 14:37:52 -0500774 HandleDeferredDecorations();
alan-bakera1be3322020-04-20 12:48:18 -0400775
776 // Generate descriptor map entries for module scope specialization constants.
SJW77b87ad2020-04-21 14:37:52 -0500777 GenerateSpecConstantDescriptorMapEntries();
David Neto22f144c2017-06-12 14:26:21 -0400778
779 // Generate SPIRV module information.
SJW77b87ad2020-04-21 14:37:52 -0500780 GenerateModuleInfo();
David Neto22f144c2017-06-12 14:26:21 -0400781
alan-baker00e7a582019-06-07 12:54:21 -0400782 WriteSPIRVBinary();
David Neto22f144c2017-06-12 14:26:21 -0400783
784 // We need to patch the SPIR-V header to set bound correctly.
785 patchHeader();
David Neto0676e6f2017-07-11 18:47:44 -0400786
787 if (outputCInitList) {
788 bool first = true;
David Neto0676e6f2017-07-11 18:47:44 -0400789 std::ostringstream os;
790
David Neto57fb0b92017-08-04 15:35:09 -0400791 auto emit_word = [&os, &first](uint32_t word) {
David Neto0676e6f2017-07-11 18:47:44 -0400792 if (!first)
David Neto57fb0b92017-08-04 15:35:09 -0400793 os << ",\n";
794 os << word;
David Neto0676e6f2017-07-11 18:47:44 -0400795 first = false;
796 };
797
798 os << "{";
David Neto57fb0b92017-08-04 15:35:09 -0400799 const std::string str(binaryTempOut.str());
800 for (unsigned i = 0; i < str.size(); i += 4) {
801 const uint32_t a = static_cast<unsigned char>(str[i]);
802 const uint32_t b = static_cast<unsigned char>(str[i + 1]);
803 const uint32_t c = static_cast<unsigned char>(str[i + 2]);
804 const uint32_t d = static_cast<unsigned char>(str[i + 3]);
805 emit_word(a | (b << 8) | (c << 16) | (d << 24));
David Neto0676e6f2017-07-11 18:47:44 -0400806 }
807 os << "}\n";
808 out << os.str();
809 }
810
David Neto22f144c2017-06-12 14:26:21 -0400811 return false;
812}
813
814void SPIRVProducerPass::outputHeader() {
alan-baker00e7a582019-06-07 12:54:21 -0400815 binaryOut->write(reinterpret_cast<const char *>(&spv::MagicNumber),
816 sizeof(spv::MagicNumber));
SJW806a5d82020-07-15 12:51:38 -0500817 uint32_t minor = 0;
818 if (SpvVersion() == SPIRVVersion::SPIRV_1_3) {
819 minor = 3;
820 }
821 uint32_t version = (1 << 16) | (minor << 8);
822 binaryOut->write(reinterpret_cast<const char *>(&version), sizeof(version));
David Neto22f144c2017-06-12 14:26:21 -0400823
alan-baker0c18ab02019-06-12 10:23:21 -0400824 // use Google's vendor ID
825 const uint32_t vendor = 21 << 16;
alan-baker00e7a582019-06-07 12:54:21 -0400826 binaryOut->write(reinterpret_cast<const char *>(&vendor), sizeof(vendor));
David Neto22f144c2017-06-12 14:26:21 -0400827
alan-baker00e7a582019-06-07 12:54:21 -0400828 // we record where we need to come back to and patch in the bound value
829 patchBoundOffset = binaryOut->tell();
David Neto22f144c2017-06-12 14:26:21 -0400830
alan-baker00e7a582019-06-07 12:54:21 -0400831 // output a bad bound for now
832 binaryOut->write(reinterpret_cast<const char *>(&nextID), sizeof(nextID));
David Neto22f144c2017-06-12 14:26:21 -0400833
alan-baker00e7a582019-06-07 12:54:21 -0400834 // output the schema (reserved for use and must be 0)
835 const uint32_t schema = 0;
836 binaryOut->write(reinterpret_cast<const char *>(&schema), sizeof(schema));
David Neto22f144c2017-06-12 14:26:21 -0400837}
838
839void SPIRVProducerPass::patchHeader() {
alan-baker00e7a582019-06-07 12:54:21 -0400840 // for a binary we just write the value of nextID over bound
841 binaryOut->pwrite(reinterpret_cast<char *>(&nextID), sizeof(nextID),
842 patchBoundOffset);
David Neto22f144c2017-06-12 14:26:21 -0400843}
844
SJW77b87ad2020-04-21 14:37:52 -0500845void SPIRVProducerPass::GenerateLLVMIRInfo() {
David Neto22f144c2017-06-12 14:26:21 -0400846 // This function generates LLVM IR for function such as global variable for
847 // argument, constant and pointer type for argument access. These information
848 // is artificial one because we need Vulkan SPIR-V output. This function is
849 // executed ahead of FindType and FindConstant.
David Neto22f144c2017-06-12 14:26:21 -0400850
SJW77b87ad2020-04-21 14:37:52 -0500851 FindGlobalConstVars();
David Neto5c22a252018-03-15 16:07:41 -0400852
SJW77b87ad2020-04-21 14:37:52 -0500853 FindResourceVars();
David Neto22f144c2017-06-12 14:26:21 -0400854
855 bool HasWorkGroupBuiltin = false;
SJW77b87ad2020-04-21 14:37:52 -0500856 for (GlobalVariable &GV : module->globals()) {
David Neto22f144c2017-06-12 14:26:21 -0400857 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
858 if (spv::BuiltInWorkgroupSize == BuiltinType) {
859 HasWorkGroupBuiltin = true;
860 }
861 }
862
SJW77b87ad2020-04-21 14:37:52 -0500863 FindTypesForSamplerMap();
864 FindTypesForResourceVars();
David Neto22f144c2017-06-12 14:26:21 -0400865}
866
SJW77b87ad2020-04-21 14:37:52 -0500867void SPIRVProducerPass::FindGlobalConstVars() {
868 clspv::NormalizeGlobalVariables(*module);
869 const DataLayout &DL = module->getDataLayout();
alan-baker56f7aff2019-05-22 08:06:42 -0400870
David Neto862b7d82018-06-14 18:48:37 -0400871 SmallVector<GlobalVariable *, 8> GVList;
872 SmallVector<GlobalVariable *, 8> DeadGVList;
SJW77b87ad2020-04-21 14:37:52 -0500873 for (GlobalVariable &GV : module->globals()) {
David Neto862b7d82018-06-14 18:48:37 -0400874 if (GV.getType()->getAddressSpace() == AddressSpace::Constant) {
875 if (GV.use_empty()) {
876 DeadGVList.push_back(&GV);
877 } else {
878 GVList.push_back(&GV);
879 }
880 }
881 }
882
883 // Remove dead global __constant variables.
884 for (auto GV : DeadGVList) {
885 GV->eraseFromParent();
886 }
887 DeadGVList.clear();
888
889 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
890 // For now, we only support a single storage buffer.
891 if (GVList.size() > 0) {
892 assert(GVList.size() == 1);
893 const auto *GV = GVList[0];
894 const auto constants_byte_size =
Alan Bakerfcda9482018-10-02 17:09:59 -0400895 (GetTypeSizeInBits(GV->getInitializer()->getType(), DL)) / 8;
David Neto862b7d82018-06-14 18:48:37 -0400896 const size_t kConstantMaxSize = 65536;
897 if (constants_byte_size > kConstantMaxSize) {
898 outs() << "Max __constant capacity of " << kConstantMaxSize
899 << " bytes exceeded: " << constants_byte_size << " bytes used\n";
900 llvm_unreachable("Max __constant capacity exceeded");
901 }
902 }
903 } else {
904 // Change global constant variable's address space to ModuleScopePrivate.
905 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
906 for (auto GV : GVList) {
907 // Create new gv with ModuleScopePrivate address space.
908 Type *NewGVTy = GV->getType()->getPointerElementType();
909 GlobalVariable *NewGV = new GlobalVariable(
SJW77b87ad2020-04-21 14:37:52 -0500910 *module, NewGVTy, false, GV->getLinkage(), GV->getInitializer(), "",
David Neto862b7d82018-06-14 18:48:37 -0400911 nullptr, GV->getThreadLocalMode(), AddressSpace::ModuleScopePrivate);
912 NewGV->takeName(GV);
913
914 const SmallVector<User *, 8> GVUsers(GV->user_begin(), GV->user_end());
915 SmallVector<User *, 8> CandidateUsers;
916
917 auto record_called_function_type_as_user =
918 [&GlobalConstFuncTyMap](Value *gv, CallInst *call) {
919 // Find argument index.
920 unsigned index = 0;
921 for (unsigned i = 0; i < call->getNumArgOperands(); i++) {
922 if (gv == call->getOperand(i)) {
923 // TODO(dneto): Should we break here?
924 index = i;
925 }
926 }
927
928 // Record function type with global constant.
929 GlobalConstFuncTyMap[call->getFunctionType()] =
930 std::make_pair(call->getFunctionType(), index);
931 };
932
933 for (User *GVU : GVUsers) {
934 if (CallInst *Call = dyn_cast<CallInst>(GVU)) {
935 record_called_function_type_as_user(GV, Call);
936 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(GVU)) {
937 // Check GEP users.
938 for (User *GEPU : GEP->users()) {
939 if (CallInst *GEPCall = dyn_cast<CallInst>(GEPU)) {
940 record_called_function_type_as_user(GEP, GEPCall);
941 }
942 }
943 }
944
945 CandidateUsers.push_back(GVU);
946 }
947
948 for (User *U : CandidateUsers) {
949 // Update users of gv with new gv.
alan-bakered80f572019-02-11 17:28:26 -0500950 if (!isa<Constant>(U)) {
951 // #254: Can't change operands of a constant, but this shouldn't be
952 // something that sticks around in the module.
953 U->replaceUsesOfWith(GV, NewGV);
954 }
David Neto862b7d82018-06-14 18:48:37 -0400955 }
956
957 // Delete original gv.
958 GV->eraseFromParent();
959 }
960 }
961}
962
SJW77b87ad2020-04-21 14:37:52 -0500963void SPIRVProducerPass::FindResourceVars() {
David Neto862b7d82018-06-14 18:48:37 -0400964 ResourceVarInfoList.clear();
965 FunctionToResourceVarsMap.clear();
966 ModuleOrderedResourceVars.reset();
967 // Normally, there is one resource variable per clspv.resource.var.*
968 // function, since that is unique'd by arg type and index. By design,
969 // we can share these resource variables across kernels because all
970 // kernels use the same descriptor set.
971 //
972 // But if the user requested distinct descriptor sets per kernel, then
973 // the descriptor allocator has made different (set,binding) pairs for
974 // the same (type,arg_index) pair. Since we can decorate a resource
975 // variable with only exactly one DescriptorSet and Binding, we are
976 // forced in this case to make distinct resource variables whenever
Kévin Petitbbbda972020-03-03 19:16:31 +0000977 // the same clspv.resource.var.X function is seen with disintct
David Neto862b7d82018-06-14 18:48:37 -0400978 // (set,binding) values.
979 const bool always_distinct_sets =
980 clspv::Option::DistinctKernelDescriptorSets();
SJW77b87ad2020-04-21 14:37:52 -0500981 for (Function &F : *module) {
David Neto862b7d82018-06-14 18:48:37 -0400982 // Rely on the fact the resource var functions have a stable ordering
983 // in the module.
SJW61531372020-06-09 07:31:08 -0500984 if (Builtins::Lookup(&F) == Builtins::kClspvResource) {
David Neto862b7d82018-06-14 18:48:37 -0400985 // Find all calls to this function with distinct set and binding pairs.
986 // Save them in ResourceVarInfoList.
987
988 // Determine uniqueness of the (set,binding) pairs only withing this
989 // one resource-var builtin function.
990 using SetAndBinding = std::pair<unsigned, unsigned>;
991 // Maps set and binding to the resource var info.
992 DenseMap<SetAndBinding, ResourceVarInfo *> set_and_binding_map;
993 bool first_use = true;
994 for (auto &U : F.uses()) {
995 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
996 const auto set = unsigned(
997 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
998 const auto binding = unsigned(
999 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
1000 const auto arg_kind = clspv::ArgKind(
1001 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
1002 const auto arg_index = unsigned(
1003 dyn_cast<ConstantInt>(call->getArgOperand(3))->getZExtValue());
alan-bakere9308012019-03-15 10:25:13 -04001004 const auto coherent = unsigned(
1005 dyn_cast<ConstantInt>(call->getArgOperand(5))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04001006
1007 // Find or make the resource var info for this combination.
1008 ResourceVarInfo *rv = nullptr;
1009 if (always_distinct_sets) {
1010 // Make a new resource var any time we see a different
1011 // (set,binding) pair.
1012 SetAndBinding key{set, binding};
1013 auto where = set_and_binding_map.find(key);
1014 if (where == set_and_binding_map.end()) {
1015 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
alan-bakere9308012019-03-15 10:25:13 -04001016 binding, &F, arg_kind, coherent);
David Neto862b7d82018-06-14 18:48:37 -04001017 ResourceVarInfoList.emplace_back(rv);
1018 set_and_binding_map[key] = rv;
1019 } else {
1020 rv = where->second;
1021 }
1022 } else {
1023 // The default is to make exactly one resource for each
1024 // clspv.resource.var.* function.
1025 if (first_use) {
1026 first_use = false;
1027 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
alan-bakere9308012019-03-15 10:25:13 -04001028 binding, &F, arg_kind, coherent);
David Neto862b7d82018-06-14 18:48:37 -04001029 ResourceVarInfoList.emplace_back(rv);
1030 } else {
1031 rv = ResourceVarInfoList.back().get();
1032 }
1033 }
1034
1035 // Now populate FunctionToResourceVarsMap.
1036 auto &mapping =
1037 FunctionToResourceVarsMap[call->getParent()->getParent()];
1038 while (mapping.size() <= arg_index) {
1039 mapping.push_back(nullptr);
1040 }
1041 mapping[arg_index] = rv;
1042 }
1043 }
1044 }
1045 }
1046
1047 // Populate ModuleOrderedResourceVars.
SJW77b87ad2020-04-21 14:37:52 -05001048 for (Function &F : *module) {
David Neto862b7d82018-06-14 18:48:37 -04001049 auto where = FunctionToResourceVarsMap.find(&F);
1050 if (where != FunctionToResourceVarsMap.end()) {
1051 for (auto &rv : where->second) {
1052 if (rv != nullptr) {
1053 ModuleOrderedResourceVars.insert(rv);
1054 }
1055 }
1056 }
1057 }
1058 if (ShowResourceVars) {
1059 for (auto *info : ModuleOrderedResourceVars) {
1060 outs() << "MORV index " << info->index << " (" << info->descriptor_set
1061 << "," << info->binding << ") " << *(info->var_fn->getReturnType())
1062 << "\n";
1063 }
1064 }
1065}
1066
David Neto22f144c2017-06-12 14:26:21 -04001067void SPIRVProducerPass::FindTypePerGlobalVar(GlobalVariable &GV) {
1068 // Investigate global variable's type.
1069 FindType(GV.getType());
1070}
1071
1072void SPIRVProducerPass::FindTypePerFunc(Function &F) {
1073 // Investigate function's type.
1074 FunctionType *FTy = F.getFunctionType();
1075
1076 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
1077 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
David Neto9ed8e2f2018-03-24 06:47:24 -07001078 // Handle a regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04001079 if (GlobalConstFuncTyMap.count(FTy)) {
1080 uint32_t GVCstArgIdx = GlobalConstFuncTypeMap[FTy].second;
1081 SmallVector<Type *, 4> NewFuncParamTys;
1082 for (unsigned i = 0; i < FTy->getNumParams(); i++) {
1083 Type *ParamTy = FTy->getParamType(i);
1084 if (i == GVCstArgIdx) {
1085 Type *EleTy = ParamTy->getPointerElementType();
1086 ParamTy = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1087 }
1088
1089 NewFuncParamTys.push_back(ParamTy);
1090 }
1091
1092 FunctionType *NewFTy =
1093 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1094 GlobalConstFuncTyMap[FTy] = std::make_pair(NewFTy, GVCstArgIdx);
1095 FTy = NewFTy;
1096 }
1097
1098 FindType(FTy);
1099 } else {
1100 // As kernel functions do not have parameters, create new function type and
1101 // add it to type map.
1102 SmallVector<Type *, 4> NewFuncParamTys;
1103 FunctionType *NewFTy =
1104 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1105 FindType(NewFTy);
1106 }
1107
1108 // Investigate instructions' type in function body.
1109 for (BasicBlock &BB : F) {
1110 for (Instruction &I : BB) {
1111 if (isa<ShuffleVectorInst>(I)) {
1112 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1113 // Ignore type for mask of shuffle vector instruction.
1114 if (i == 2) {
1115 continue;
1116 }
1117
1118 Value *Op = I.getOperand(i);
1119 if (!isa<MetadataAsValue>(Op)) {
1120 FindType(Op->getType());
1121 }
1122 }
1123
1124 FindType(I.getType());
1125 continue;
1126 }
1127
David Neto862b7d82018-06-14 18:48:37 -04001128 CallInst *Call = dyn_cast<CallInst>(&I);
1129
SJW61531372020-06-09 07:31:08 -05001130 if (Call) {
1131 auto &func_info = Builtins::Lookup(Call->getCalledFunction());
1132 if (func_info.getType() == Builtins::kClspvResource ||
1133 func_info.getType() == Builtins::kClspvLocal) {
1134 // This is a fake call representing access to a resource/workgroup
1135 // variable. We handle that elsewhere.
1136 continue;
1137 }
Alan Baker202c8c72018-08-13 13:47:44 -04001138 }
1139
alan-bakerf083bed2020-01-29 08:15:42 -05001140 // #497: InsertValue and ExtractValue map to OpCompositeInsert and
1141 // OpCompositeExtract which takes literal values for indices. As a result
1142 // don't map the type of indices.
1143 if (I.getOpcode() == Instruction::ExtractValue) {
1144 FindType(I.getOperand(0)->getType());
1145 continue;
1146 }
1147 if (I.getOpcode() == Instruction::InsertValue) {
1148 FindType(I.getOperand(0)->getType());
1149 FindType(I.getOperand(1)->getType());
1150 continue;
1151 }
1152
1153 // #497: InsertElement and ExtractElement map to OpCompositeExtract if
1154 // the index is a constant. In such a case don't map the index type.
1155 if (I.getOpcode() == Instruction::ExtractElement) {
1156 FindType(I.getOperand(0)->getType());
1157 Value *op1 = I.getOperand(1);
1158 if (!isa<Constant>(op1) || isa<GlobalValue>(op1)) {
1159 FindType(op1->getType());
1160 }
1161 continue;
1162 }
1163 if (I.getOpcode() == Instruction::InsertElement) {
1164 FindType(I.getOperand(0)->getType());
1165 FindType(I.getOperand(1)->getType());
1166 Value *op2 = I.getOperand(2);
1167 if (!isa<Constant>(op2) || isa<GlobalValue>(op2)) {
1168 FindType(op2->getType());
1169 }
1170 continue;
1171 }
1172
David Neto22f144c2017-06-12 14:26:21 -04001173 // Work through the operands of the instruction.
1174 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1175 Value *const Op = I.getOperand(i);
1176 // If any of the operands is a constant, find the type!
1177 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1178 FindType(Op->getType());
1179 }
1180 }
1181
1182 for (Use &Op : I.operands()) {
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001183 if (isa<CallInst>(&I)) {
David Neto22f144c2017-06-12 14:26:21 -04001184 // Avoid to check call instruction's type.
1185 break;
1186 }
Alan Baker202c8c72018-08-13 13:47:44 -04001187 if (CallInst *OpCall = dyn_cast<CallInst>(Op)) {
SJW61531372020-06-09 07:31:08 -05001188 if (Builtins::Lookup(OpCall->getCalledFunction()) ==
1189 Builtins::kClspvLocal) {
Alan Baker202c8c72018-08-13 13:47:44 -04001190 // This is a fake call representing access to a workgroup variable.
1191 // We handle that elsewhere.
1192 continue;
1193 }
1194 }
David Neto22f144c2017-06-12 14:26:21 -04001195 if (!isa<MetadataAsValue>(&Op)) {
1196 FindType(Op->getType());
1197 continue;
1198 }
1199 }
1200
David Neto22f144c2017-06-12 14:26:21 -04001201 // We don't want to track the type of this call as we are going to replace
1202 // it.
SJW61531372020-06-09 07:31:08 -05001203 if (Call && Builtins::Lookup(Call->getCalledFunction()) ==
1204 Builtins::kClspvSamplerVarLiteral) {
David Neto22f144c2017-06-12 14:26:21 -04001205 continue;
1206 }
1207
1208 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
1209 // If gep's base operand has ModuleScopePrivate address space, make gep
1210 // return ModuleScopePrivate address space.
1211 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate) {
1212 // Add pointer type with private address space for global constant to
1213 // type list.
1214 Type *EleTy = I.getType()->getPointerElementType();
1215 Type *NewPTy =
1216 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1217
1218 FindType(NewPTy);
1219 continue;
1220 }
1221 }
1222
1223 FindType(I.getType());
1224 }
1225 }
1226}
1227
SJW77b87ad2020-04-21 14:37:52 -05001228void SPIRVProducerPass::FindTypesForSamplerMap() {
David Neto862b7d82018-06-14 18:48:37 -04001229 // If we are using a sampler map, find the type of the sampler.
SJW77b87ad2020-04-21 14:37:52 -05001230 if (module->getFunction(clspv::LiteralSamplerFunction()) ||
David Neto862b7d82018-06-14 18:48:37 -04001231 0 < getSamplerMap().size()) {
SJW77b87ad2020-04-21 14:37:52 -05001232 auto SamplerStructTy = module->getTypeByName("opencl.sampler_t");
David Neto862b7d82018-06-14 18:48:37 -04001233 if (!SamplerStructTy) {
SJW77b87ad2020-04-21 14:37:52 -05001234 SamplerStructTy =
1235 StructType::create(module->getContext(), "opencl.sampler_t");
David Neto862b7d82018-06-14 18:48:37 -04001236 }
1237
1238 SamplerTy = SamplerStructTy->getPointerTo(AddressSpace::UniformConstant);
1239
1240 FindType(SamplerTy);
1241 }
1242}
1243
SJW77b87ad2020-04-21 14:37:52 -05001244void SPIRVProducerPass::FindTypesForResourceVars() {
David Neto862b7d82018-06-14 18:48:37 -04001245 // Record types so they are generated.
1246 TypesNeedingLayout.reset();
1247 StructTypesNeedingBlock.reset();
1248
1249 // To match older clspv codegen, generate the float type first if required
1250 // for images.
1251 for (const auto *info : ModuleOrderedResourceVars) {
1252 if (info->arg_kind == clspv::ArgKind::ReadOnlyImage ||
1253 info->arg_kind == clspv::ArgKind::WriteOnlyImage) {
alan-bakerf67468c2019-11-25 15:51:49 -05001254 if (IsIntImageType(info->var_fn->getReturnType())) {
1255 // Nothing for now...
1256 } else if (IsUintImageType(info->var_fn->getReturnType())) {
SJW77b87ad2020-04-21 14:37:52 -05001257 FindType(Type::getInt32Ty(module->getContext()));
alan-bakerf67468c2019-11-25 15:51:49 -05001258 }
1259
1260 // We need "float" either for the sampled type or for the Lod operand.
SJW77b87ad2020-04-21 14:37:52 -05001261 FindType(Type::getFloatTy(module->getContext()));
David Neto862b7d82018-06-14 18:48:37 -04001262 }
1263 }
1264
1265 for (const auto *info : ModuleOrderedResourceVars) {
1266 Type *type = info->var_fn->getReturnType();
1267
1268 switch (info->arg_kind) {
1269 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04001270 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04001271 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1272 StructTypesNeedingBlock.insert(sty);
1273 } else {
1274 errs() << *type << "\n";
1275 llvm_unreachable("Buffer arguments must map to structures!");
1276 }
1277 break;
1278 case clspv::ArgKind::Pod:
alan-baker9b0ec3c2020-04-06 14:45:34 -04001279 case clspv::ArgKind::PodUBO:
1280 case clspv::ArgKind::PodPushConstant:
David Neto862b7d82018-06-14 18:48:37 -04001281 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1282 StructTypesNeedingBlock.insert(sty);
1283 } else {
1284 errs() << *type << "\n";
1285 llvm_unreachable("POD arguments must map to structures!");
1286 }
1287 break;
1288 case clspv::ArgKind::ReadOnlyImage:
1289 case clspv::ArgKind::WriteOnlyImage:
1290 case clspv::ArgKind::Sampler:
1291 // Sampler and image types map to the pointee type but
1292 // in the uniform constant address space.
1293 type = PointerType::get(type->getPointerElementType(),
1294 clspv::AddressSpace::UniformConstant);
1295 break;
1296 default:
1297 break;
1298 }
1299
1300 // The converted type is the type of the OpVariable we will generate.
1301 // If the pointee type is an array of size zero, FindType will convert it
1302 // to a runtime array.
1303 FindType(type);
1304 }
1305
alan-bakerdcd97412019-09-16 15:32:30 -04001306 // If module constants are clustered in a storage buffer then that struct
1307 // needs layout decorations.
1308 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
SJW77b87ad2020-04-21 14:37:52 -05001309 for (GlobalVariable &GV : module->globals()) {
alan-bakerdcd97412019-09-16 15:32:30 -04001310 PointerType *PTy = cast<PointerType>(GV.getType());
1311 const auto AS = PTy->getAddressSpace();
1312 const bool module_scope_constant_external_init =
1313 (AS == AddressSpace::Constant) && GV.hasInitializer();
1314 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
1315 if (module_scope_constant_external_init &&
1316 spv::BuiltInMax == BuiltinType) {
1317 StructTypesNeedingBlock.insert(
1318 cast<StructType>(PTy->getPointerElementType()));
1319 }
1320 }
1321 }
1322
SJW77b87ad2020-04-21 14:37:52 -05001323 for (const GlobalVariable &GV : module->globals()) {
Kévin Petitbbbda972020-03-03 19:16:31 +00001324 if (GV.getAddressSpace() == clspv::AddressSpace::PushConstant) {
1325 auto Ty = cast<PointerType>(GV.getType())->getPointerElementType();
1326 assert(Ty->isStructTy() && "Push constants have to be structures.");
1327 auto STy = cast<StructType>(Ty);
1328 StructTypesNeedingBlock.insert(STy);
1329 }
1330 }
1331
David Neto862b7d82018-06-14 18:48:37 -04001332 // Traverse the arrays and structures underneath each Block, and
1333 // mark them as needing layout.
1334 std::vector<Type *> work_list(StructTypesNeedingBlock.begin(),
1335 StructTypesNeedingBlock.end());
1336 while (!work_list.empty()) {
1337 Type *type = work_list.back();
1338 work_list.pop_back();
1339 TypesNeedingLayout.insert(type);
1340 switch (type->getTypeID()) {
1341 case Type::ArrayTyID:
1342 work_list.push_back(type->getArrayElementType());
1343 if (!Hack_generate_runtime_array_stride_early) {
1344 // Remember this array type for deferred decoration.
1345 TypesNeedingArrayStride.insert(type);
1346 }
1347 break;
1348 case Type::StructTyID:
1349 for (auto *elem_ty : cast<StructType>(type)->elements()) {
1350 work_list.push_back(elem_ty);
1351 }
1352 default:
1353 // This type and its contained types don't get layout.
1354 break;
1355 }
1356 }
1357}
1358
SJWf93f5f32020-05-05 07:27:56 -05001359void SPIRVProducerPass::GenerateWorkgroupVars() {
Alan Baker202c8c72018-08-13 13:47:44 -04001360 // The SpecId assignment for pointer-to-local arguments is recorded in
1361 // module-level metadata. Translate that information into local argument
1362 // information.
SJWf93f5f32020-05-05 07:27:56 -05001363 LLVMContext &Context = module->getContext();
SJW77b87ad2020-04-21 14:37:52 -05001364 NamedMDNode *nmd = module->getNamedMetadata(clspv::LocalSpecIdMetadataName());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001365 if (!nmd)
1366 return;
Alan Baker202c8c72018-08-13 13:47:44 -04001367 for (auto operand : nmd->operands()) {
1368 MDTuple *tuple = cast<MDTuple>(operand);
1369 ValueAsMetadata *fn_md = cast<ValueAsMetadata>(tuple->getOperand(0));
1370 Function *func = cast<Function>(fn_md->getValue());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001371 ConstantAsMetadata *arg_index_md =
1372 cast<ConstantAsMetadata>(tuple->getOperand(1));
1373 int arg_index = static_cast<int>(
1374 cast<ConstantInt>(arg_index_md->getValue())->getSExtValue());
1375 Argument *arg = &*(func->arg_begin() + arg_index);
Alan Baker202c8c72018-08-13 13:47:44 -04001376
1377 ConstantAsMetadata *spec_id_md =
1378 cast<ConstantAsMetadata>(tuple->getOperand(2));
alan-bakerb6b09dc2018-11-08 16:59:28 -05001379 int spec_id = static_cast<int>(
1380 cast<ConstantInt>(spec_id_md->getValue())->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04001381
Alan Baker202c8c72018-08-13 13:47:44 -04001382 LocalArgSpecIds[arg] = spec_id;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001383 if (LocalSpecIdInfoMap.count(spec_id))
1384 continue;
Alan Baker202c8c72018-08-13 13:47:44 -04001385
SJWf93f5f32020-05-05 07:27:56 -05001386 // Generate the spec constant.
1387 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05001388 Ops << Type::getInt32Ty(Context) << 1;
SJWf93f5f32020-05-05 07:27:56 -05001389 SPIRVID ArraySizeID = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
Alan Baker202c8c72018-08-13 13:47:44 -04001390
SJWf93f5f32020-05-05 07:27:56 -05001391 // Generate the array type.
1392 Type *ElemTy = arg->getType()->getPointerElementType();
1393 Ops.clear();
1394 // The element type must have been created.
SJW01901d92020-05-21 08:58:31 -05001395 Ops << ElemTy << ArraySizeID;
SJWf93f5f32020-05-05 07:27:56 -05001396
1397 SPIRVID ArrayTypeID = addSPIRVInst<kTypes>(spv::OpTypeArray, Ops);
1398
1399 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05001400 Ops << spv::StorageClassWorkgroup << ArrayTypeID;
SJWf93f5f32020-05-05 07:27:56 -05001401 SPIRVID PtrArrayTypeID = addSPIRVInst<kTypes>(spv::OpTypePointer, Ops);
1402
1403 // Generate OpVariable.
1404 //
1405 // Ops[0] : Result Type ID
1406 // Ops[1] : Storage Class
SJW806a5d82020-07-15 12:51:38 -05001407 SPIRVID VariableID =
1408 addSPIRVGlobalVariable(PtrArrayTypeID, spv::StorageClassWorkgroup);
SJWf93f5f32020-05-05 07:27:56 -05001409
1410 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05001411 Ops << ArraySizeID << spv::DecorationSpecId << spec_id;
SJWf93f5f32020-05-05 07:27:56 -05001412 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
1413
1414 LocalArgInfo info{VariableID, ElemTy, ArraySizeID,
1415 ArrayTypeID, PtrArrayTypeID, spec_id};
1416 LocalSpecIdInfoMap[spec_id] = info;
Alan Baker202c8c72018-08-13 13:47:44 -04001417 }
1418}
1419
David Neto22f144c2017-06-12 14:26:21 -04001420void SPIRVProducerPass::FindType(Type *Ty) {
1421 TypeList &TyList = getTypeList();
1422
1423 if (0 != TyList.idFor(Ty)) {
1424 return;
1425 }
1426
1427 if (Ty->isPointerTy()) {
1428 auto AddrSpace = Ty->getPointerAddressSpace();
1429 if ((AddressSpace::Constant == AddrSpace) ||
1430 (AddressSpace::Global == AddrSpace)) {
1431 auto PointeeTy = Ty->getPointerElementType();
1432
1433 if (PointeeTy->isStructTy() &&
1434 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1435 FindType(PointeeTy);
1436 auto ActualPointerTy =
1437 PointeeTy->getPointerTo(AddressSpace::UniformConstant);
1438 FindType(ActualPointerTy);
1439 return;
1440 }
1441 }
1442 }
1443
David Neto862b7d82018-06-14 18:48:37 -04001444 // By convention, LLVM array type with 0 elements will map to
1445 // OpTypeRuntimeArray. Otherwise, it will map to OpTypeArray, which
1446 // has a constant number of elements. We need to support type of the
1447 // constant.
1448 if (auto *arrayTy = dyn_cast<ArrayType>(Ty)) {
1449 if (arrayTy->getNumElements() > 0) {
1450 LLVMContext &Context = Ty->getContext();
1451 FindType(Type::getInt32Ty(Context));
1452 }
David Neto22f144c2017-06-12 14:26:21 -04001453 }
1454
1455 for (Type *SubTy : Ty->subtypes()) {
1456 FindType(SubTy);
1457 }
1458
1459 TyList.insert(Ty);
1460}
1461
David Neto22f144c2017-06-12 14:26:21 -04001462spv::StorageClass SPIRVProducerPass::GetStorageClass(unsigned AddrSpace) const {
1463 switch (AddrSpace) {
1464 default:
1465 llvm_unreachable("Unsupported OpenCL address space");
1466 case AddressSpace::Private:
1467 return spv::StorageClassFunction;
1468 case AddressSpace::Global:
David Neto22f144c2017-06-12 14:26:21 -04001469 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001470 case AddressSpace::Constant:
1471 return clspv::Option::ConstantArgsInUniformBuffer()
1472 ? spv::StorageClassUniform
1473 : spv::StorageClassStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -04001474 case AddressSpace::Input:
1475 return spv::StorageClassInput;
1476 case AddressSpace::Local:
1477 return spv::StorageClassWorkgroup;
1478 case AddressSpace::UniformConstant:
1479 return spv::StorageClassUniformConstant;
David Neto9ed8e2f2018-03-24 06:47:24 -07001480 case AddressSpace::Uniform:
David Netoe439d702018-03-23 13:14:08 -07001481 return spv::StorageClassUniform;
David Neto22f144c2017-06-12 14:26:21 -04001482 case AddressSpace::ModuleScopePrivate:
1483 return spv::StorageClassPrivate;
Kévin Petitbbbda972020-03-03 19:16:31 +00001484 case AddressSpace::PushConstant:
1485 return spv::StorageClassPushConstant;
David Neto22f144c2017-06-12 14:26:21 -04001486 }
1487}
1488
David Neto862b7d82018-06-14 18:48:37 -04001489spv::StorageClass
1490SPIRVProducerPass::GetStorageClassForArgKind(clspv::ArgKind arg_kind) const {
1491 switch (arg_kind) {
1492 case clspv::ArgKind::Buffer:
1493 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001494 case clspv::ArgKind::BufferUBO:
1495 return spv::StorageClassUniform;
David Neto862b7d82018-06-14 18:48:37 -04001496 case clspv::ArgKind::Pod:
alan-baker9b0ec3c2020-04-06 14:45:34 -04001497 return spv::StorageClassStorageBuffer;
1498 case clspv::ArgKind::PodUBO:
1499 return spv::StorageClassUniform;
1500 case clspv::ArgKind::PodPushConstant:
1501 return spv::StorageClassPushConstant;
David Neto862b7d82018-06-14 18:48:37 -04001502 case clspv::ArgKind::Local:
1503 return spv::StorageClassWorkgroup;
1504 case clspv::ArgKind::ReadOnlyImage:
1505 case clspv::ArgKind::WriteOnlyImage:
1506 case clspv::ArgKind::Sampler:
1507 return spv::StorageClassUniformConstant;
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001508 default:
1509 llvm_unreachable("Unsupported storage class for argument kind");
David Neto862b7d82018-06-14 18:48:37 -04001510 }
1511}
1512
David Neto22f144c2017-06-12 14:26:21 -04001513spv::BuiltIn SPIRVProducerPass::GetBuiltin(StringRef Name) const {
1514 return StringSwitch<spv::BuiltIn>(Name)
1515 .Case("__spirv_GlobalInvocationId", spv::BuiltInGlobalInvocationId)
1516 .Case("__spirv_LocalInvocationId", spv::BuiltInLocalInvocationId)
1517 .Case("__spirv_WorkgroupSize", spv::BuiltInWorkgroupSize)
1518 .Case("__spirv_NumWorkgroups", spv::BuiltInNumWorkgroups)
1519 .Case("__spirv_WorkgroupId", spv::BuiltInWorkgroupId)
alan-bakerbed3a882020-04-21 14:42:41 -04001520 .Case("__spirv_WorkDim", spv::BuiltInWorkDim)
alan-bakere1996972020-05-04 08:38:12 -04001521 .Case("__spirv_GlobalOffset", spv::BuiltInGlobalOffset)
David Neto22f144c2017-06-12 14:26:21 -04001522 .Default(spv::BuiltInMax);
1523}
1524
SJW01901d92020-05-21 08:58:31 -05001525SPIRVID SPIRVProducerPass::getOpExtInstImportID() {
1526 if (OpExtInstImportID == 0) {
1527 //
1528 // Generate OpExtInstImport.
1529 //
1530 // Ops[0] ... Ops[n] = Name (Literal String)
David Neto22f144c2017-06-12 14:26:21 -04001531
SJW01901d92020-05-21 08:58:31 -05001532 OpExtInstImportID =
1533 addSPIRVInst<kImports>(spv::OpExtInstImport, "GLSL.std.450");
1534 }
1535 return OpExtInstImportID;
SJWf93f5f32020-05-05 07:27:56 -05001536}
1537
SJW806a5d82020-07-15 12:51:38 -05001538SPIRVID SPIRVProducerPass::addSPIRVGlobalVariable(const SPIRVID &TypeID,
1539 spv::StorageClass SC,
1540 const SPIRVID &InitID) {
1541 // Generate OpVariable.
1542 //
1543 // Ops[0] : Result Type ID
1544 // Ops[1] : Storage Class
1545 // Ops[2] : Initialization Value ID (optional)
1546
1547 SPIRVOperandVec Ops;
1548 Ops << TypeID << SC;
1549 if (InitID.isValid()) {
1550 Ops << InitID;
1551 }
1552
1553 SPIRVID VID = addSPIRVInst<kGlobalVariables>(spv::OpVariable, Ops);
1554
1555 if (SC == spv::StorageClassInput) {
1556 getEntryPointInterfacesList().push_back(VID);
1557 }
1558
1559 return VID;
1560}
1561
SJW01901d92020-05-21 08:58:31 -05001562SPIRVID SPIRVProducerPass::getSPIRVType(Type *Ty) {
SJWf93f5f32020-05-05 07:27:56 -05001563 auto TI = TypeMap.find(Ty);
1564 if (TI != TypeMap.end()) {
SJW01901d92020-05-21 08:58:31 -05001565 assert(TI->second.isValid());
SJWf93f5f32020-05-05 07:27:56 -05001566 return TI->second;
1567 }
1568
1569 const auto &DL = module->getDataLayout();
1570
SJW01901d92020-05-21 08:58:31 -05001571 SPIRVID RID;
SJWf93f5f32020-05-05 07:27:56 -05001572
1573 switch (Ty->getTypeID()) {
1574 default: {
1575 Ty->print(errs());
1576 llvm_unreachable("Unsupported type???");
1577 break;
1578 }
1579 case Type::MetadataTyID:
1580 case Type::LabelTyID: {
1581 // Ignore these types.
1582 break;
1583 }
1584 case Type::PointerTyID: {
1585 PointerType *PTy = cast<PointerType>(Ty);
1586 unsigned AddrSpace = PTy->getAddressSpace();
1587
1588 if (AddrSpace != AddressSpace::UniformConstant) {
1589 auto PointeeTy = PTy->getElementType();
1590 if (PointeeTy->isStructTy() &&
1591 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1592 // TODO(sjw): assert always an image?
1593 RID = getSPIRVType(PointeeTy);
1594 break;
1595 }
1596 }
1597
1598 // For the purposes of our Vulkan SPIR-V type system, constant and global
1599 // are conflated.
1600 if (AddressSpace::Constant == AddrSpace) {
1601 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1602 AddrSpace = AddressSpace::Global;
1603 // Check to see if we already created this type (for instance, if we
1604 // had a constant <type>* and a global <type>*, the type would be
1605 // created by one of these types, and shared by both).
1606 auto GlobalTy = PTy->getPointerElementType()->getPointerTo(AddrSpace);
1607 if (0 < TypeMap.count(GlobalTy)) {
1608 RID = TypeMap[GlobalTy];
1609 break;
1610 }
1611 }
1612 } else if (AddressSpace::Global == AddrSpace) {
1613 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1614 AddrSpace = AddressSpace::Constant;
1615
1616 // Check to see if we already created this type (for instance, if we
1617 // had a constant <type>* and a global <type>*, the type would be
1618 // created by one of these types, and shared by both).
1619 auto ConstantTy = PTy->getPointerElementType()->getPointerTo(AddrSpace);
1620 if (0 < TypeMap.count(ConstantTy)) {
1621 RID = TypeMap[ConstantTy];
1622 break;
1623 }
1624 }
1625 }
1626
1627 //
1628 // Generate OpTypePointer.
1629 //
1630
1631 // OpTypePointer
1632 // Ops[0] = Storage Class
1633 // Ops[1] = Element Type ID
1634 SPIRVOperandVec Ops;
1635
SJW01901d92020-05-21 08:58:31 -05001636 Ops << GetStorageClass(AddrSpace) << PTy->getElementType();
SJWf93f5f32020-05-05 07:27:56 -05001637
1638 RID = addSPIRVInst<kTypes>(spv::OpTypePointer, Ops);
1639 break;
1640 }
1641 case Type::StructTyID: {
1642 StructType *STy = cast<StructType>(Ty);
1643
1644 // Handle sampler type.
1645 if (STy->isOpaque()) {
1646 if (STy->getName().equals("opencl.sampler_t")) {
1647 //
1648 // Generate OpTypeSampler
1649 //
1650 // Empty Ops.
1651
1652 RID = addSPIRVInst<kTypes>(spv::OpTypeSampler);
1653 break;
1654 } else if (STy->getName().startswith("opencl.image1d_ro_t") ||
1655 STy->getName().startswith("opencl.image1d_wo_t") ||
1656 STy->getName().startswith("opencl.image1d_array_ro_t") ||
1657 STy->getName().startswith("opencl.image1d_array_wo_t") ||
1658 STy->getName().startswith("opencl.image2d_ro_t") ||
1659 STy->getName().startswith("opencl.image2d_wo_t") ||
1660 STy->getName().startswith("opencl.image2d_array_ro_t") ||
1661 STy->getName().startswith("opencl.image2d_array_wo_t") ||
1662 STy->getName().startswith("opencl.image3d_ro_t") ||
1663 STy->getName().startswith("opencl.image3d_wo_t")) {
SJW01901d92020-05-21 08:58:31 -05001664
1665 if (STy->getName().contains("_wo_t")) {
1666 addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
1667 }
1668 if (STy->getName().startswith("opencl.image1d_")) {
1669 if (STy->getName().contains(".sampled"))
1670 addCapability(spv::CapabilitySampled1D);
1671 else
1672 addCapability(spv::CapabilityImage1D);
1673 }
1674
SJWf93f5f32020-05-05 07:27:56 -05001675 //
1676 // Generate OpTypeImage
1677 //
1678 // Ops[0] = Sampled Type ID
1679 // Ops[1] = Dim ID
1680 // Ops[2] = Depth (Literal Number)
1681 // Ops[3] = Arrayed (Literal Number)
1682 // Ops[4] = MS (Literal Number)
1683 // Ops[5] = Sampled (Literal Number)
1684 // Ops[6] = Image Format ID
1685 //
1686 SPIRVOperandVec Ops;
1687
SJW01901d92020-05-21 08:58:31 -05001688 SPIRVID SampledTyID;
SJWf93f5f32020-05-05 07:27:56 -05001689 if (STy->getName().contains(".float")) {
1690 SampledTyID = getSPIRVType(Type::getFloatTy(Ty->getContext()));
1691 } else if (STy->getName().contains(".uint")) {
1692 SampledTyID = getSPIRVType(Type::getInt32Ty(Ty->getContext()));
1693 } else if (STy->getName().contains(".int")) {
1694 // Generate a signed 32-bit integer if necessary.
1695 if (int32ID == 0) {
1696 SPIRVOperandVec intOps;
SJW01901d92020-05-21 08:58:31 -05001697 intOps << 32 << 1;
SJWf93f5f32020-05-05 07:27:56 -05001698 int32ID = addSPIRVInst<kTypes>(spv::OpTypeInt, intOps);
1699 }
1700 SampledTyID = int32ID;
1701
1702 // Generate a vec4 of the signed int if necessary.
1703 if (v4int32ID == 0) {
1704 SPIRVOperandVec vecOps;
SJW01901d92020-05-21 08:58:31 -05001705 vecOps << int32ID << 4;
SJWf93f5f32020-05-05 07:27:56 -05001706 v4int32ID = addSPIRVInst<kTypes>(spv::OpTypeVector, vecOps);
1707 }
1708 } else {
1709 // This was likely an UndefValue.
1710 SampledTyID = getSPIRVType(Type::getFloatTy(Ty->getContext()));
1711 }
SJW01901d92020-05-21 08:58:31 -05001712 Ops << SampledTyID;
SJWf93f5f32020-05-05 07:27:56 -05001713
1714 spv::Dim DimID = spv::Dim2D;
1715 if (STy->getName().startswith("opencl.image1d_ro_t") ||
1716 STy->getName().startswith("opencl.image1d_wo_t") ||
1717 STy->getName().startswith("opencl.image1d_array_ro_t") ||
1718 STy->getName().startswith("opencl.image1d_array_wo_t")) {
1719 DimID = spv::Dim1D;
1720 } else if (STy->getName().startswith("opencl.image3d_ro_t") ||
1721 STy->getName().startswith("opencl.image3d_wo_t")) {
1722 DimID = spv::Dim3D;
1723 }
SJW01901d92020-05-21 08:58:31 -05001724 Ops << DimID;
SJWf93f5f32020-05-05 07:27:56 -05001725
1726 // TODO: Set up Depth.
SJW01901d92020-05-21 08:58:31 -05001727 Ops << 0;
SJWf93f5f32020-05-05 07:27:56 -05001728
1729 uint32_t arrayed = STy->getName().contains("_array_") ? 1 : 0;
SJW01901d92020-05-21 08:58:31 -05001730 Ops << arrayed;
SJWf93f5f32020-05-05 07:27:56 -05001731
1732 // TODO: Set up MS.
SJW01901d92020-05-21 08:58:31 -05001733 Ops << 0;
SJWf93f5f32020-05-05 07:27:56 -05001734
1735 // Set up Sampled.
1736 //
1737 // From Spec
1738 //
1739 // 0 indicates this is only known at run time, not at compile time
1740 // 1 indicates will be used with sampler
1741 // 2 indicates will be used without a sampler (a storage image)
1742 uint32_t Sampled = 1;
1743 if (!STy->getName().contains(".sampled")) {
1744 Sampled = 2;
1745 }
SJW01901d92020-05-21 08:58:31 -05001746 Ops << Sampled;
SJWf93f5f32020-05-05 07:27:56 -05001747
1748 // TODO: Set up Image Format.
SJW01901d92020-05-21 08:58:31 -05001749 Ops << spv::ImageFormatUnknown;
SJWf93f5f32020-05-05 07:27:56 -05001750
1751 RID = addSPIRVInst<kTypes>(spv::OpTypeImage, Ops);
1752
1753 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05001754 Ops << RID;
SJWf93f5f32020-05-05 07:27:56 -05001755
1756 getImageTypeMap()[Ty] =
1757 addSPIRVInst<kTypes>(spv::OpTypeSampledImage, Ops);
1758 break;
1759 }
1760 }
1761
1762 //
1763 // Generate OpTypeStruct
1764 //
1765 // Ops[0] ... Ops[n] = Member IDs
1766 SPIRVOperandVec Ops;
1767
1768 for (auto *EleTy : STy->elements()) {
SJW01901d92020-05-21 08:58:31 -05001769 Ops << EleTy;
SJWf93f5f32020-05-05 07:27:56 -05001770 }
1771
1772 RID = addSPIRVInst<kTypes>(spv::OpTypeStruct, Ops);
1773
1774 // Generate OpMemberDecorate.
1775 if (TypesNeedingLayout.idFor(STy)) {
1776 for (unsigned MemberIdx = 0; MemberIdx < STy->getNumElements();
1777 MemberIdx++) {
1778 // Ops[0] = Structure Type ID
1779 // Ops[1] = Member Index(Literal Number)
1780 // Ops[2] = Decoration (Offset)
1781 // Ops[3] = Byte Offset (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05001782 const auto ByteOffset =
1783 GetExplicitLayoutStructMemberOffset(STy, MemberIdx, DL);
1784
SJW01901d92020-05-21 08:58:31 -05001785 Ops.clear();
1786 Ops << RID << MemberIdx << spv::DecorationOffset << ByteOffset;
SJWf93f5f32020-05-05 07:27:56 -05001787
1788 addSPIRVInst<kAnnotations>(spv::OpMemberDecorate, Ops);
1789 }
1790 }
1791
1792 // Generate OpDecorate.
1793 if (StructTypesNeedingBlock.idFor(STy)) {
1794 Ops.clear();
1795 // Use Block decorations with StorageBuffer storage class.
SJW01901d92020-05-21 08:58:31 -05001796 Ops << RID << spv::DecorationBlock;
SJWf93f5f32020-05-05 07:27:56 -05001797
1798 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
1799 }
1800 break;
1801 }
1802 case Type::IntegerTyID: {
alan-bakere2a62752020-07-09 22:53:23 -04001803 uint32_t bit_width = static_cast<uint32_t>(Ty->getPrimitiveSizeInBits());
SJWf93f5f32020-05-05 07:27:56 -05001804
alan-bakere2a62752020-07-09 22:53:23 -04001805 if (clspv::Option::Int8Support() && bit_width == 8) {
SJW01901d92020-05-21 08:58:31 -05001806 addCapability(spv::CapabilityInt8);
alan-bakere2a62752020-07-09 22:53:23 -04001807 } else if (bit_width == 16) {
SJW01901d92020-05-21 08:58:31 -05001808 addCapability(spv::CapabilityInt16);
alan-bakere2a62752020-07-09 22:53:23 -04001809 } else if (bit_width == 64) {
SJW01901d92020-05-21 08:58:31 -05001810 addCapability(spv::CapabilityInt64);
1811 }
1812
alan-bakere2a62752020-07-09 22:53:23 -04001813 if (bit_width == 1) {
SJWf93f5f32020-05-05 07:27:56 -05001814 RID = addSPIRVInst<kTypes>(spv::OpTypeBool);
1815 } else {
alan-bakere2a62752020-07-09 22:53:23 -04001816 if (!clspv::Option::Int8Support() && bit_width == 8) {
SJWf93f5f32020-05-05 07:27:56 -05001817 // i8 is added to TypeMap as i32.
1818 RID = getSPIRVType(Type::getIntNTy(Ty->getContext(), 32));
1819 } else {
1820 SPIRVOperandVec Ops;
alan-bakere2a62752020-07-09 22:53:23 -04001821 Ops << bit_width << 0 /* not signed */;
SJWf93f5f32020-05-05 07:27:56 -05001822 RID = addSPIRVInst<kTypes>(spv::OpTypeInt, Ops);
1823 }
1824 }
1825 break;
1826 }
1827 case Type::HalfTyID:
1828 case Type::FloatTyID:
1829 case Type::DoubleTyID: {
alan-bakere2a62752020-07-09 22:53:23 -04001830 uint32_t bit_width = static_cast<uint32_t>(Ty->getPrimitiveSizeInBits());
1831 if (bit_width == 16) {
SJW01901d92020-05-21 08:58:31 -05001832 addCapability(spv::CapabilityFloat16);
alan-bakere2a62752020-07-09 22:53:23 -04001833 } else if (bit_width == 64) {
SJW01901d92020-05-21 08:58:31 -05001834 addCapability(spv::CapabilityFloat64);
1835 }
1836
SJWf93f5f32020-05-05 07:27:56 -05001837 SPIRVOperandVec Ops;
alan-bakere2a62752020-07-09 22:53:23 -04001838 Ops << bit_width;
SJWf93f5f32020-05-05 07:27:56 -05001839
1840 RID = addSPIRVInst<kTypes>(spv::OpTypeFloat, Ops);
1841 break;
1842 }
1843 case Type::ArrayTyID: {
1844 ArrayType *ArrTy = cast<ArrayType>(Ty);
1845 const uint64_t Length = ArrTy->getArrayNumElements();
1846 if (Length == 0) {
1847 // By convention, map it to a RuntimeArray.
1848
1849 Type *EleTy = ArrTy->getArrayElementType();
1850
1851 //
1852 // Generate OpTypeRuntimeArray.
1853 //
1854 // OpTypeRuntimeArray
1855 // Ops[0] = Element Type ID
1856 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05001857 Ops << EleTy;
SJWf93f5f32020-05-05 07:27:56 -05001858
1859 RID = addSPIRVInst<kTypes>(spv::OpTypeRuntimeArray, Ops);
1860
1861 if (Hack_generate_runtime_array_stride_early) {
1862 // Generate OpDecorate.
1863
1864 // Ops[0] = Target ID
1865 // Ops[1] = Decoration (ArrayStride)
1866 // Ops[2] = Stride Number(Literal Number)
1867 Ops.clear();
1868
SJW01901d92020-05-21 08:58:31 -05001869 Ops << RID << spv::DecorationArrayStride
1870 << static_cast<uint32_t>(GetTypeAllocSize(EleTy, DL));
SJWf93f5f32020-05-05 07:27:56 -05001871
1872 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
1873 }
1874
1875 } else {
1876
1877 //
1878 // Generate OpConstant and OpTypeArray.
1879 //
1880
1881 //
1882 // Generate OpConstant for array length.
1883 //
1884 // Add constant for length to constant list.
1885 Constant *CstLength =
1886 ConstantInt::get(Type::getInt32Ty(module->getContext()), Length);
SJWf93f5f32020-05-05 07:27:56 -05001887
1888 // Remember to generate ArrayStride later
1889 getTypesNeedingArrayStride().insert(Ty);
1890
1891 //
1892 // Generate OpTypeArray.
1893 //
1894 // Ops[0] = Element Type ID
1895 // Ops[1] = Array Length Constant ID
1896 SPIRVOperandVec Ops;
1897
SJW01901d92020-05-21 08:58:31 -05001898 Ops << ArrTy->getElementType() << CstLength;
SJWf93f5f32020-05-05 07:27:56 -05001899
1900 RID = addSPIRVInst<kTypes>(spv::OpTypeArray, Ops);
1901 }
1902 break;
1903 }
1904 case Type::FixedVectorTyID: {
1905 auto VecTy = cast<VectorType>(Ty);
1906 // <4 x i8> is changed to i32 if i8 is not generally supported.
1907 if (!clspv::Option::Int8Support() &&
1908 VecTy->getElementType() == Type::getInt8Ty(module->getContext())) {
1909 if (VecTy->getNumElements() == 4) {
1910 RID = getSPIRVType(VecTy->getElementType());
1911 break;
1912 } else {
1913 Ty->print(errs());
1914 llvm_unreachable("Support above i8 vector type");
1915 }
1916 }
1917
1918 // Ops[0] = Component Type ID
1919 // Ops[1] = Component Count (Literal Number)
1920 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05001921 Ops << VecTy->getElementType() << VecTy->getNumElements();
SJWf93f5f32020-05-05 07:27:56 -05001922
1923 RID = addSPIRVInst<kTypes>(spv::OpTypeVector, Ops);
1924 break;
1925 }
1926 case Type::VoidTyID: {
1927 RID = addSPIRVInst<kTypes>(spv::OpTypeVoid);
1928 break;
1929 }
1930 case Type::FunctionTyID: {
1931 // Generate SPIRV instruction for function type.
1932 FunctionType *FTy = cast<FunctionType>(Ty);
1933
1934 // Ops[0] = Return Type ID
1935 // Ops[1] ... Ops[n] = Parameter Type IDs
1936 SPIRVOperandVec Ops;
1937
1938 // Find SPIRV instruction for return type
SJW01901d92020-05-21 08:58:31 -05001939 Ops << FTy->getReturnType();
SJWf93f5f32020-05-05 07:27:56 -05001940
1941 // Find SPIRV instructions for parameter types
1942 for (unsigned k = 0; k < FTy->getNumParams(); k++) {
1943 // Find SPIRV instruction for parameter type.
1944 auto ParamTy = FTy->getParamType(k);
1945 if (ParamTy->isPointerTy()) {
1946 auto PointeeTy = ParamTy->getPointerElementType();
1947 if (PointeeTy->isStructTy() &&
1948 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1949 ParamTy = PointeeTy;
1950 }
1951 }
1952
SJW01901d92020-05-21 08:58:31 -05001953 Ops << ParamTy;
SJWf93f5f32020-05-05 07:27:56 -05001954 }
1955
1956 RID = addSPIRVInst<kTypes>(spv::OpTypeFunction, Ops);
1957 break;
1958 }
1959 }
1960
SJW01901d92020-05-21 08:58:31 -05001961 if (RID.isValid()) {
SJWf93f5f32020-05-05 07:27:56 -05001962 TypeMap[Ty] = RID;
1963 }
1964 return RID;
David Neto22f144c2017-06-12 14:26:21 -04001965}
1966
SJW77b87ad2020-04-21 14:37:52 -05001967void SPIRVProducerPass::GenerateSPIRVTypes() {
David Neto22f144c2017-06-12 14:26:21 -04001968 for (Type *Ty : getTypeList()) {
SJWf93f5f32020-05-05 07:27:56 -05001969 getSPIRVType(Ty);
David Netoc6f3ab22018-04-06 18:02:31 -04001970 }
David Neto22f144c2017-06-12 14:26:21 -04001971}
1972
SJW806a5d82020-07-15 12:51:38 -05001973SPIRVID SPIRVProducerPass::getSPIRVInt32Constant(uint32_t CstVal) {
1974 Type *i32 = Type::getInt32Ty(module->getContext());
1975 Constant *Cst = ConstantInt::get(i32, CstVal);
1976 return getSPIRVValue(Cst);
1977}
1978
SJWf93f5f32020-05-05 07:27:56 -05001979SPIRVID SPIRVProducerPass::getSPIRVConstant(Constant *Cst) {
David Neto22f144c2017-06-12 14:26:21 -04001980 ValueMapType &VMap = getValueMap();
David Neto482550a2018-03-24 05:21:07 -07001981 const bool hack_undef = clspv::Option::HackUndef();
David Neto22f144c2017-06-12 14:26:21 -04001982
SJW01901d92020-05-21 08:58:31 -05001983 SPIRVID RID;
David Neto22f144c2017-06-12 14:26:21 -04001984
SJWf93f5f32020-05-05 07:27:56 -05001985 //
1986 // Generate OpConstant.
1987 //
1988 // Ops[0] = Result Type ID
1989 // Ops[1] .. Ops[n] = Values LiteralNumber
1990 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04001991
SJW01901d92020-05-21 08:58:31 -05001992 Ops << Cst->getType();
David Neto22f144c2017-06-12 14:26:21 -04001993
SJWf93f5f32020-05-05 07:27:56 -05001994 std::vector<uint32_t> LiteralNum;
1995 spv::Op Opcode = spv::OpNop;
David Neto22f144c2017-06-12 14:26:21 -04001996
SJWf93f5f32020-05-05 07:27:56 -05001997 if (isa<UndefValue>(Cst)) {
David Neto22f144c2017-06-12 14:26:21 -04001998 // Ops[0] = Result Type ID
SJWf93f5f32020-05-05 07:27:56 -05001999 Opcode = spv::OpUndef;
2000 if (hack_undef && IsTypeNullable(Cst->getType())) {
2001 Opcode = spv::OpConstantNull;
2002 }
2003 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(Cst)) {
alan-bakere2a62752020-07-09 22:53:23 -04002004 unsigned bit_width = CI->getBitWidth();
2005 if (bit_width == 1) {
SJWf93f5f32020-05-05 07:27:56 -05002006 // If the bitwidth of constant is 1, generate OpConstantTrue or
2007 // OpConstantFalse.
2008 if (CI->getZExtValue()) {
2009 // Ops[0] = Result Type ID
2010 Opcode = spv::OpConstantTrue;
David Neto22f144c2017-06-12 14:26:21 -04002011 } else {
SJWf93f5f32020-05-05 07:27:56 -05002012 // Ops[0] = Result Type ID
2013 Opcode = spv::OpConstantFalse;
David Neto22f144c2017-06-12 14:26:21 -04002014 }
SJWf93f5f32020-05-05 07:27:56 -05002015 } else {
2016 auto V = CI->getZExtValue();
2017 LiteralNum.push_back(V & 0xFFFFFFFF);
2018
alan-bakere2a62752020-07-09 22:53:23 -04002019 if (bit_width > 32) {
SJWf93f5f32020-05-05 07:27:56 -05002020 LiteralNum.push_back(V >> 32);
David Neto22f144c2017-06-12 14:26:21 -04002021 }
2022
2023 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002024
SJW01901d92020-05-21 08:58:31 -05002025 Ops << LiteralNum;
SJWf93f5f32020-05-05 07:27:56 -05002026 }
2027 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Cst)) {
2028 uint64_t FPVal = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
2029 Type *CFPTy = CFP->getType();
2030 if (CFPTy->isFloatTy()) {
2031 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
2032 } else if (CFPTy->isDoubleTy()) {
2033 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
2034 LiteralNum.push_back(FPVal >> 32);
2035 } else if (CFPTy->isHalfTy()) {
2036 LiteralNum.push_back(FPVal & 0xFFFF);
2037 } else {
2038 CFPTy->print(errs());
2039 llvm_unreachable("Implement this ConstantFP Type");
2040 }
David Neto22f144c2017-06-12 14:26:21 -04002041
SJWf93f5f32020-05-05 07:27:56 -05002042 Opcode = spv::OpConstant;
David Neto49351ac2017-08-26 17:32:20 -04002043
SJW01901d92020-05-21 08:58:31 -05002044 Ops << LiteralNum;
SJWf93f5f32020-05-05 07:27:56 -05002045 } else if (isa<ConstantDataSequential>(Cst) &&
2046 cast<ConstantDataSequential>(Cst)->isString()) {
2047 Cst->print(errs());
2048 llvm_unreachable("Implement this Constant");
David Neto49351ac2017-08-26 17:32:20 -04002049
SJWf93f5f32020-05-05 07:27:56 -05002050 } else if (const ConstantDataSequential *CDS =
2051 dyn_cast<ConstantDataSequential>(Cst)) {
2052 // Let's convert <4 x i8> constant to int constant specially.
2053 // This case occurs when all the values are specified as constant
2054 // ints.
2055 Type *CstTy = Cst->getType();
2056 if (is4xi8vec(CstTy)) {
SJWf93f5f32020-05-05 07:27:56 -05002057 //
2058 // Generate OpConstant with OpTypeInt 32 0.
2059 //
2060 uint32_t IntValue = 0;
2061 for (unsigned k = 0; k < 4; k++) {
2062 const uint64_t Val = CDS->getElementAsInteger(k);
2063 IntValue = (IntValue << 8) | (Val & 0xffu);
David Neto49351ac2017-08-26 17:32:20 -04002064 }
2065
SJW806a5d82020-07-15 12:51:38 -05002066 RID = getSPIRVInt32Constant(IntValue);
SJWf93f5f32020-05-05 07:27:56 -05002067 } else {
2068
David Neto49351ac2017-08-26 17:32:20 -04002069 // A normal constant-data-sequential case.
David Neto22f144c2017-06-12 14:26:21 -04002070 for (unsigned k = 0; k < CDS->getNumElements(); k++) {
SJW01901d92020-05-21 08:58:31 -05002071 Ops << CDS->getElementAsConstant(k);
David Neto22f144c2017-06-12 14:26:21 -04002072 }
2073
2074 Opcode = spv::OpConstantComposite;
SJWf93f5f32020-05-05 07:27:56 -05002075 }
2076 } else if (const ConstantAggregate *CA = dyn_cast<ConstantAggregate>(Cst)) {
2077 // Let's convert <4 x i8> constant to int constant specially.
2078 // This case occurs when at least one of the values is an undef.
2079 Type *CstTy = Cst->getType();
2080 if (is4xi8vec(CstTy)) {
SJWf93f5f32020-05-05 07:27:56 -05002081 //
2082 // Generate OpConstant with OpTypeInt 32 0.
2083 //
2084 uint32_t IntValue = 0;
2085 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end();
2086 I != E; ++I) {
2087 uint64_t Val = 0;
2088 const Value *CV = *I;
2089 if (auto *CI2 = dyn_cast<ConstantInt>(CV)) {
2090 Val = CI2->getZExtValue();
David Neto22f144c2017-06-12 14:26:21 -04002091 }
SJWf93f5f32020-05-05 07:27:56 -05002092 IntValue = (IntValue << 8) | (Val & 0xffu);
David Neto22f144c2017-06-12 14:26:21 -04002093 }
2094
SJW806a5d82020-07-15 12:51:38 -05002095 RID = getSPIRVInt32Constant(IntValue);
SJWf93f5f32020-05-05 07:27:56 -05002096 } else {
2097
David Neto22f144c2017-06-12 14:26:21 -04002098 // We use a constant composite in SPIR-V for our constant aggregate in
2099 // LLVM.
2100 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002101
2102 for (unsigned k = 0; k < CA->getNumOperands(); k++) {
David Neto22f144c2017-06-12 14:26:21 -04002103 // And add an operand to the composite we are constructing
SJW01901d92020-05-21 08:58:31 -05002104 Ops << CA->getAggregateElement(k);
David Neto22f144c2017-06-12 14:26:21 -04002105 }
David Neto22f144c2017-06-12 14:26:21 -04002106 }
SJWf93f5f32020-05-05 07:27:56 -05002107 } else if (Cst->isNullValue()) {
2108 Opcode = spv::OpConstantNull;
2109 } else {
2110 Cst->print(errs());
2111 llvm_unreachable("Unsupported Constant???");
2112 }
David Neto22f144c2017-06-12 14:26:21 -04002113
SJWf93f5f32020-05-05 07:27:56 -05002114 if (Opcode == spv::OpConstantNull && Cst->getType()->isPointerTy()) {
2115 // Null pointer requires variable pointers.
2116 setVariablePointersCapabilities(Cst->getType()->getPointerAddressSpace());
2117 }
alan-baker5b86ed72019-02-15 08:26:50 -05002118
SJWf93f5f32020-05-05 07:27:56 -05002119 if (RID == 0) {
2120 RID = addSPIRVInst<kConstants>(Opcode, Ops);
2121 }
2122
2123 VMap[Cst] = RID;
2124
2125 return RID;
2126}
2127
2128SPIRVID SPIRVProducerPass::getSPIRVValue(Value *V) {
2129 auto II = ValueMap.find(V);
2130 if (II != ValueMap.end()) {
SJW01901d92020-05-21 08:58:31 -05002131 assert(II->second.isValid());
SJWf93f5f32020-05-05 07:27:56 -05002132 return II->second;
2133 }
2134 if (Constant *Cst = dyn_cast<Constant>(V)) {
2135 return getSPIRVConstant(Cst);
2136 } else {
2137 llvm_unreachable("Variable not found");
2138 }
2139}
2140
SJW77b87ad2020-04-21 14:37:52 -05002141void SPIRVProducerPass::GenerateSamplers() {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002142 auto &sampler_map = getSamplerMap();
alan-baker09cb9802019-12-10 13:16:27 -05002143 SamplerLiteralToIDMap.clear();
David Neto862b7d82018-06-14 18:48:37 -04002144 DenseMap<unsigned, unsigned> SamplerLiteralToDescriptorSetMap;
2145 DenseMap<unsigned, unsigned> SamplerLiteralToBindingMap;
David Neto22f144c2017-06-12 14:26:21 -04002146
David Neto862b7d82018-06-14 18:48:37 -04002147 // We might have samplers in the sampler map that are not used
2148 // in the translation unit. We need to allocate variables
2149 // for them and bindings too.
2150 DenseSet<unsigned> used_bindings;
David Neto22f144c2017-06-12 14:26:21 -04002151
SJW77b87ad2020-04-21 14:37:52 -05002152 auto *var_fn = module->getFunction(clspv::LiteralSamplerFunction());
alan-baker09cb9802019-12-10 13:16:27 -05002153 // Return if there are no literal samplers.
alan-bakerb6b09dc2018-11-08 16:59:28 -05002154 if (!var_fn)
2155 return;
alan-baker09cb9802019-12-10 13:16:27 -05002156
David Neto862b7d82018-06-14 18:48:37 -04002157 for (auto user : var_fn->users()) {
2158 // Populate SamplerLiteralToDescriptorSetMap and
2159 // SamplerLiteralToBindingMap.
2160 //
2161 // Look for calls like
2162 // call %opencl.sampler_t addrspace(2)*
2163 // @clspv.sampler.var.literal(
2164 // i32 descriptor,
2165 // i32 binding,
alan-baker09cb9802019-12-10 13:16:27 -05002166 // i32 (index-into-sampler-map|sampler_mask))
alan-bakerb6b09dc2018-11-08 16:59:28 -05002167 if (auto *call = dyn_cast<CallInst>(user)) {
alan-baker09cb9802019-12-10 13:16:27 -05002168 const auto third_param = static_cast<unsigned>(
alan-bakerb6b09dc2018-11-08 16:59:28 -05002169 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
alan-baker09cb9802019-12-10 13:16:27 -05002170 auto sampler_value = third_param;
2171 if (clspv::Option::UseSamplerMap()) {
2172 if (third_param >= sampler_map.size()) {
2173 errs() << "Out of bounds index to sampler map: " << third_param;
2174 llvm_unreachable("bad sampler init: out of bounds");
2175 }
2176 sampler_value = sampler_map[third_param].first;
David Neto862b7d82018-06-14 18:48:37 -04002177 }
2178
David Neto862b7d82018-06-14 18:48:37 -04002179 const auto descriptor_set = static_cast<unsigned>(
2180 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
2181 const auto binding = static_cast<unsigned>(
2182 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
2183
2184 SamplerLiteralToDescriptorSetMap[sampler_value] = descriptor_set;
2185 SamplerLiteralToBindingMap[sampler_value] = binding;
2186 used_bindings.insert(binding);
2187 }
2188 }
2189
alan-baker09cb9802019-12-10 13:16:27 -05002190 DenseSet<size_t> seen;
2191 for (auto user : var_fn->users()) {
2192 if (!isa<CallInst>(user))
2193 continue;
2194
2195 auto call = cast<CallInst>(user);
2196 const unsigned third_param = static_cast<unsigned>(
2197 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
2198
2199 // Already allocated a variable for this value.
2200 if (!seen.insert(third_param).second)
2201 continue;
2202
2203 auto sampler_value = third_param;
2204 if (clspv::Option::UseSamplerMap()) {
2205 sampler_value = sampler_map[third_param].first;
2206 }
2207
SJW806a5d82020-07-15 12:51:38 -05002208 auto sampler_var_id = addSPIRVGlobalVariable(
2209 getSPIRVType(SamplerTy), spv::StorageClassUniformConstant);
David Neto22f144c2017-06-12 14:26:21 -04002210
alan-baker09cb9802019-12-10 13:16:27 -05002211 SamplerLiteralToIDMap[sampler_value] = sampler_var_id;
David Neto22f144c2017-06-12 14:26:21 -04002212
David Neto862b7d82018-06-14 18:48:37 -04002213 unsigned descriptor_set;
2214 unsigned binding;
alan-baker09cb9802019-12-10 13:16:27 -05002215 if (SamplerLiteralToBindingMap.find(sampler_value) ==
alan-bakerb6b09dc2018-11-08 16:59:28 -05002216 SamplerLiteralToBindingMap.end()) {
David Neto862b7d82018-06-14 18:48:37 -04002217 // This sampler is not actually used. Find the next one.
2218 for (binding = 0; used_bindings.count(binding); binding++)
2219 ;
2220 descriptor_set = 0; // Literal samplers always use descriptor set 0.
2221 used_bindings.insert(binding);
2222 } else {
alan-baker09cb9802019-12-10 13:16:27 -05002223 descriptor_set = SamplerLiteralToDescriptorSetMap[sampler_value];
2224 binding = SamplerLiteralToBindingMap[sampler_value];
alan-bakercff80152019-06-15 00:38:00 -04002225
alan-baker09cb9802019-12-10 13:16:27 -05002226 version0::DescriptorMapEntry::SamplerData sampler_data = {sampler_value};
alan-bakercff80152019-06-15 00:38:00 -04002227 descriptorMapEntries->emplace_back(std::move(sampler_data),
2228 descriptor_set, binding);
David Neto862b7d82018-06-14 18:48:37 -04002229 }
2230
SJW69939d52020-04-16 07:29:07 -05002231 // Ops[0] = Target ID
2232 // Ops[1] = Decoration (DescriptorSet)
2233 // Ops[2] = LiteralNumber according to Decoration
SJW806a5d82020-07-15 12:51:38 -05002234 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05002235 Ops << sampler_var_id << spv::DecorationDescriptorSet << descriptor_set;
David Neto22f144c2017-06-12 14:26:21 -04002236
SJWf93f5f32020-05-05 07:27:56 -05002237 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002238
2239 // Ops[0] = Target ID
2240 // Ops[1] = Decoration (Binding)
2241 // Ops[2] = LiteralNumber according to Decoration
2242 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002243 Ops << sampler_var_id << spv::DecorationBinding << binding;
David Neto22f144c2017-06-12 14:26:21 -04002244
SJWf93f5f32020-05-05 07:27:56 -05002245 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002246 }
David Neto862b7d82018-06-14 18:48:37 -04002247}
David Neto22f144c2017-06-12 14:26:21 -04002248
SJW77b87ad2020-04-21 14:37:52 -05002249void SPIRVProducerPass::GenerateResourceVars() {
David Neto862b7d82018-06-14 18:48:37 -04002250 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04002251
David Neto862b7d82018-06-14 18:48:37 -04002252 // Generate variables. Make one for each of resource var info object.
2253 for (auto *info : ModuleOrderedResourceVars) {
2254 Type *type = info->var_fn->getReturnType();
2255 // Remap the address space for opaque types.
2256 switch (info->arg_kind) {
2257 case clspv::ArgKind::Sampler:
2258 case clspv::ArgKind::ReadOnlyImage:
2259 case clspv::ArgKind::WriteOnlyImage:
2260 type = PointerType::get(type->getPointerElementType(),
2261 clspv::AddressSpace::UniformConstant);
2262 break;
2263 default:
2264 break;
2265 }
David Neto22f144c2017-06-12 14:26:21 -04002266
David Neto862b7d82018-06-14 18:48:37 -04002267 const auto sc = GetStorageClassForArgKind(info->arg_kind);
David Neto22f144c2017-06-12 14:26:21 -04002268
SJW806a5d82020-07-15 12:51:38 -05002269 info->var_id = addSPIRVGlobalVariable(getSPIRVType(type), sc);
David Neto862b7d82018-06-14 18:48:37 -04002270
2271 // Map calls to the variable-builtin-function.
2272 for (auto &U : info->var_fn->uses()) {
2273 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
2274 const auto set = unsigned(
2275 dyn_cast<ConstantInt>(call->getOperand(0))->getZExtValue());
2276 const auto binding = unsigned(
2277 dyn_cast<ConstantInt>(call->getOperand(1))->getZExtValue());
2278 if (set == info->descriptor_set && binding == info->binding) {
2279 switch (info->arg_kind) {
2280 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002281 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002282 case clspv::ArgKind::Pod:
alan-baker9b0ec3c2020-04-06 14:45:34 -04002283 case clspv::ArgKind::PodUBO:
2284 case clspv::ArgKind::PodPushConstant:
David Neto862b7d82018-06-14 18:48:37 -04002285 // The call maps to the variable directly.
2286 VMap[call] = info->var_id;
2287 break;
2288 case clspv::ArgKind::Sampler:
2289 case clspv::ArgKind::ReadOnlyImage:
2290 case clspv::ArgKind::WriteOnlyImage:
2291 // The call maps to a load we generate later.
2292 ResourceVarDeferredLoadCalls[call] = info->var_id;
2293 break;
2294 default:
2295 llvm_unreachable("Unhandled arg kind");
2296 }
2297 }
David Neto22f144c2017-06-12 14:26:21 -04002298 }
David Neto862b7d82018-06-14 18:48:37 -04002299 }
2300 }
David Neto22f144c2017-06-12 14:26:21 -04002301
David Neto862b7d82018-06-14 18:48:37 -04002302 // Generate associated decorations.
SJWf93f5f32020-05-05 07:27:56 -05002303 SPIRVOperandVec Ops;
David Neto862b7d82018-06-14 18:48:37 -04002304 for (auto *info : ModuleOrderedResourceVars) {
alan-baker9b0ec3c2020-04-06 14:45:34 -04002305 // Push constants don't need descriptor set or binding decorations.
2306 if (info->arg_kind == clspv::ArgKind::PodPushConstant)
2307 continue;
2308
David Neto862b7d82018-06-14 18:48:37 -04002309 // Decorate with DescriptorSet and Binding.
2310 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002311 Ops << info->var_id << spv::DecorationDescriptorSet << info->descriptor_set;
SJWf93f5f32020-05-05 07:27:56 -05002312 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto862b7d82018-06-14 18:48:37 -04002313
2314 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002315 Ops << info->var_id << spv::DecorationBinding << info->binding;
SJWf93f5f32020-05-05 07:27:56 -05002316 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto862b7d82018-06-14 18:48:37 -04002317
alan-bakere9308012019-03-15 10:25:13 -04002318 if (info->coherent) {
2319 // Decorate with Coherent if required for the variable.
2320 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002321 Ops << info->var_id << spv::DecorationCoherent;
SJWf93f5f32020-05-05 07:27:56 -05002322 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
alan-bakere9308012019-03-15 10:25:13 -04002323 }
2324
David Neto862b7d82018-06-14 18:48:37 -04002325 // Generate NonWritable and NonReadable
2326 switch (info->arg_kind) {
2327 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002328 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002329 if (info->var_fn->getReturnType()->getPointerAddressSpace() ==
2330 clspv::AddressSpace::Constant) {
2331 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002332 Ops << info->var_id << spv::DecorationNonWritable;
SJWf93f5f32020-05-05 07:27:56 -05002333 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002334 }
David Neto862b7d82018-06-14 18:48:37 -04002335 break;
David Neto862b7d82018-06-14 18:48:37 -04002336 case clspv::ArgKind::WriteOnlyImage:
2337 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002338 Ops << info->var_id << spv::DecorationNonReadable;
SJWf93f5f32020-05-05 07:27:56 -05002339 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto862b7d82018-06-14 18:48:37 -04002340 break;
2341 default:
2342 break;
David Neto22f144c2017-06-12 14:26:21 -04002343 }
2344 }
2345}
2346
SJW77b87ad2020-04-21 14:37:52 -05002347void SPIRVProducerPass::GeneratePushConstantDescriptorMapEntries() {
Kévin Petitbbbda972020-03-03 19:16:31 +00002348
SJW77b87ad2020-04-21 14:37:52 -05002349 if (auto GV = module->getGlobalVariable(clspv::PushConstantsVariableName())) {
2350 auto const &DL = module->getDataLayout();
Kévin Petitbbbda972020-03-03 19:16:31 +00002351 auto MD = GV->getMetadata(clspv::PushConstantsMetadataName());
2352 auto STy = cast<StructType>(GV->getValueType());
2353
2354 for (unsigned i = 0; i < STy->getNumElements(); i++) {
2355 auto pc = static_cast<clspv::PushConstant>(
2356 mdconst::extract<ConstantInt>(MD->getOperand(i))->getZExtValue());
alan-baker6a3930b2020-05-21 10:09:11 -04002357 if (pc != clspv::PushConstant::KernelArgument) {
2358 auto memberType = STy->getElementType(i);
2359 auto offset = GetExplicitLayoutStructMemberOffset(STy, i, DL);
2360 unsigned previousOffset = 0;
2361 if (i > 0) {
2362 previousOffset = GetExplicitLayoutStructMemberOffset(STy, i - 1, DL);
2363 }
2364 auto size =
2365 static_cast<uint32_t>(GetTypeSizeInBits(memberType, DL)) / 8;
2366 assert(isValidExplicitLayout(*module, STy, i,
2367 spv::StorageClassPushConstant, offset,
2368 previousOffset));
2369 version0::DescriptorMapEntry::PushConstantData data = {pc, offset,
2370 size};
2371 descriptorMapEntries->emplace_back(std::move(data));
Kévin Petitbbbda972020-03-03 19:16:31 +00002372 }
Kévin Petitbbbda972020-03-03 19:16:31 +00002373 }
2374 }
2375}
2376
SJW77b87ad2020-04-21 14:37:52 -05002377void SPIRVProducerPass::GenerateSpecConstantDescriptorMapEntries() {
2378 for (auto pair : clspv::GetSpecConstants(module)) {
alan-bakera1be3322020-04-20 12:48:18 -04002379 auto kind = pair.first;
2380 auto id = pair.second;
2381
2382 // Local memory size is only used for kernel arguments.
2383 if (kind == SpecConstant::kLocalMemorySize)
2384 continue;
2385
2386 version0::DescriptorMapEntry::SpecConstantData data = {kind, id};
2387 descriptorMapEntries->emplace_back(std::move(data));
2388 }
2389}
2390
David Neto22f144c2017-06-12 14:26:21 -04002391void SPIRVProducerPass::GenerateGlobalVar(GlobalVariable &GV) {
David Neto22f144c2017-06-12 14:26:21 -04002392 ValueMapType &VMap = getValueMap();
SJW01901d92020-05-21 08:58:31 -05002393 std::vector<SPIRVID> &BuiltinDimVec = getBuiltinDimVec();
David Neto85082642018-03-24 06:55:20 -07002394 const DataLayout &DL = GV.getParent()->getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04002395
2396 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
2397 Type *Ty = GV.getType();
2398 PointerType *PTy = cast<PointerType>(Ty);
2399
SJW01901d92020-05-21 08:58:31 -05002400 SPIRVID InitializerID;
David Neto22f144c2017-06-12 14:26:21 -04002401
2402 // Workgroup size is handled differently (it goes into a constant)
2403 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2404 std::vector<bool> HasMDVec;
2405 uint32_t PrevXDimCst = 0xFFFFFFFF;
2406 uint32_t PrevYDimCst = 0xFFFFFFFF;
2407 uint32_t PrevZDimCst = 0xFFFFFFFF;
2408 for (Function &Func : *GV.getParent()) {
2409 if (Func.isDeclaration()) {
2410 continue;
2411 }
2412
2413 // We only need to check kernels.
2414 if (Func.getCallingConv() != CallingConv::SPIR_KERNEL) {
2415 continue;
2416 }
2417
2418 if (const MDNode *MD =
2419 dyn_cast<Function>(&Func)->getMetadata("reqd_work_group_size")) {
2420 uint32_t CurXDimCst = static_cast<uint32_t>(
2421 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
2422 uint32_t CurYDimCst = static_cast<uint32_t>(
2423 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
2424 uint32_t CurZDimCst = static_cast<uint32_t>(
2425 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
2426
2427 if (PrevXDimCst == 0xFFFFFFFF && PrevYDimCst == 0xFFFFFFFF &&
2428 PrevZDimCst == 0xFFFFFFFF) {
2429 PrevXDimCst = CurXDimCst;
2430 PrevYDimCst = CurYDimCst;
2431 PrevZDimCst = CurZDimCst;
2432 } else if (CurXDimCst != PrevXDimCst || CurYDimCst != PrevYDimCst ||
2433 CurZDimCst != PrevZDimCst) {
2434 llvm_unreachable(
2435 "reqd_work_group_size must be the same across all kernels");
2436 } else {
2437 continue;
2438 }
2439
2440 //
2441 // Generate OpConstantComposite.
2442 //
2443 // Ops[0] : Result Type ID
2444 // Ops[1] : Constant size for x dimension.
2445 // Ops[2] : Constant size for y dimension.
2446 // Ops[3] : Constant size for z dimension.
SJWf93f5f32020-05-05 07:27:56 -05002447 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04002448
SJW01901d92020-05-21 08:58:31 -05002449 SPIRVID XDimCstID =
SJWf93f5f32020-05-05 07:27:56 -05002450 getSPIRVValue(mdconst::extract<ConstantInt>(MD->getOperand(0)));
SJW01901d92020-05-21 08:58:31 -05002451 SPIRVID YDimCstID =
SJWf93f5f32020-05-05 07:27:56 -05002452 getSPIRVValue(mdconst::extract<ConstantInt>(MD->getOperand(1)));
SJW01901d92020-05-21 08:58:31 -05002453 SPIRVID ZDimCstID =
SJWf93f5f32020-05-05 07:27:56 -05002454 getSPIRVValue(mdconst::extract<ConstantInt>(MD->getOperand(2)));
David Neto22f144c2017-06-12 14:26:21 -04002455
SJW01901d92020-05-21 08:58:31 -05002456 Ops << Ty->getPointerElementType() << XDimCstID << YDimCstID
2457 << ZDimCstID;
David Neto22f144c2017-06-12 14:26:21 -04002458
SJWf93f5f32020-05-05 07:27:56 -05002459 InitializerID =
2460 addSPIRVInst<kGlobalVariables>(spv::OpConstantComposite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002461
2462 HasMDVec.push_back(true);
2463 } else {
2464 HasMDVec.push_back(false);
2465 }
2466 }
2467
2468 // Check all kernels have same definitions for work_group_size.
2469 bool HasMD = false;
2470 if (!HasMDVec.empty()) {
2471 HasMD = HasMDVec[0];
2472 for (uint32_t i = 1; i < HasMDVec.size(); i++) {
2473 if (HasMD != HasMDVec[i]) {
2474 llvm_unreachable(
2475 "Kernels should have consistent work group size definition");
2476 }
2477 }
2478 }
2479
2480 // If all kernels do not have metadata for reqd_work_group_size, generate
2481 // OpSpecConstants for x/y/z dimension.
Kévin Petit21c23c62020-04-29 01:38:28 +01002482 if (!HasMD || clspv::Option::NonUniformNDRangeSupported()) {
David Neto22f144c2017-06-12 14:26:21 -04002483 //
2484 // Generate OpSpecConstants for x/y/z dimension.
2485 //
2486 // Ops[0] : Result Type ID
2487 // Ops[1] : Constant size for x/y/z dimension (Literal Number).
David Neto22f144c2017-06-12 14:26:21 -04002488
alan-bakera1be3322020-04-20 12:48:18 -04002489 // Allocate spec constants for workgroup size.
SJW77b87ad2020-04-21 14:37:52 -05002490 clspv::AddWorkgroupSpecConstants(module);
alan-bakera1be3322020-04-20 12:48:18 -04002491
SJWf93f5f32020-05-05 07:27:56 -05002492 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05002493 SPIRVID result_type_id = getSPIRVType(
SJWf93f5f32020-05-05 07:27:56 -05002494 dyn_cast<VectorType>(Ty->getPointerElementType())->getElementType());
David Neto22f144c2017-06-12 14:26:21 -04002495
David Neto257c3892018-04-11 13:19:45 -04002496 // X Dimension
SJW01901d92020-05-21 08:58:31 -05002497 Ops << result_type_id << 1;
2498 SPIRVID XDimCstID = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002499
2500 // Y Dimension
2501 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002502 Ops << result_type_id << 1;
2503 SPIRVID YDimCstID = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002504
2505 // Z Dimension
2506 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002507 Ops << result_type_id << 1;
2508 SPIRVID ZDimCstID = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002509
David Neto257c3892018-04-11 13:19:45 -04002510 BuiltinDimVec.push_back(XDimCstID);
2511 BuiltinDimVec.push_back(YDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002512 BuiltinDimVec.push_back(ZDimCstID);
2513
David Neto22f144c2017-06-12 14:26:21 -04002514 //
2515 // Generate OpSpecConstantComposite.
2516 //
2517 // Ops[0] : Result Type ID
2518 // Ops[1] : Constant size for x dimension.
2519 // Ops[2] : Constant size for y dimension.
2520 // Ops[3] : Constant size for z dimension.
David Neto22f144c2017-06-12 14:26:21 -04002521 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002522 Ops << Ty->getPointerElementType() << XDimCstID << YDimCstID << ZDimCstID;
David Neto22f144c2017-06-12 14:26:21 -04002523
SJWf93f5f32020-05-05 07:27:56 -05002524 InitializerID =
2525 addSPIRVInst<kConstants>(spv::OpSpecConstantComposite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002526 }
alan-bakerbed3a882020-04-21 14:42:41 -04002527 } else if (BuiltinType == spv::BuiltInWorkDim) {
2528 // 1. Generate a specialization constant with a default of 3.
2529 // 2. Allocate and annotate a SpecId for the constant.
2530 // 3. Use the spec constant as the initializer for the variable.
SJWf93f5f32020-05-05 07:27:56 -05002531 SPIRVOperandVec Ops;
alan-bakerbed3a882020-04-21 14:42:41 -04002532
2533 //
2534 // Generate OpSpecConstant.
2535 //
2536 // Ops[0] : Result Type ID
2537 // Ops[1] : Default literal value
alan-bakerbed3a882020-04-21 14:42:41 -04002538
SJW01901d92020-05-21 08:58:31 -05002539 Ops << IntegerType::get(GV.getContext(), 32) << 3;
alan-bakerbed3a882020-04-21 14:42:41 -04002540
SJWf93f5f32020-05-05 07:27:56 -05002541 InitializerID = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
alan-bakerbed3a882020-04-21 14:42:41 -04002542
2543 //
2544 // Generate SpecId decoration.
2545 //
2546 // Ops[0] : target
2547 // Ops[1] : decoration
2548 // Ops[2] : SpecId
Alan Baker75ccc252020-04-21 17:11:52 -04002549 auto spec_id = AllocateSpecConstant(module, SpecConstant::kWorkDim);
alan-bakerbed3a882020-04-21 14:42:41 -04002550 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002551 Ops << InitializerID << spv::DecorationSpecId << spec_id;
alan-bakerbed3a882020-04-21 14:42:41 -04002552
SJWf93f5f32020-05-05 07:27:56 -05002553 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002554 } else if (BuiltinType == spv::BuiltInGlobalOffset) {
2555 // 1. Generate a spec constant with a default of {0, 0, 0}.
2556 // 2. Allocate and annotate SpecIds for the constants.
2557 // 3. Use the spec constant as the initializer for the variable.
SJWf93f5f32020-05-05 07:27:56 -05002558 SPIRVOperandVec Ops;
alan-bakere1996972020-05-04 08:38:12 -04002559
2560 //
2561 // Generate OpSpecConstant for each dimension.
2562 //
2563 // Ops[0] : Result Type ID
2564 // Ops[1] : Default literal value
2565 //
SJW01901d92020-05-21 08:58:31 -05002566 Ops << IntegerType::get(GV.getContext(), 32) << 0;
2567 SPIRVID x_id = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002568
alan-bakere1996972020-05-04 08:38:12 -04002569 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002570 Ops << IntegerType::get(GV.getContext(), 32) << 0;
2571 SPIRVID y_id = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002572
alan-bakere1996972020-05-04 08:38:12 -04002573 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002574 Ops << IntegerType::get(GV.getContext(), 32) << 0;
2575 SPIRVID z_id = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002576
2577 //
2578 // Generate SpecId decoration for each dimension.
2579 //
2580 // Ops[0] : target
2581 // Ops[1] : decoration
2582 // Ops[2] : SpecId
2583 //
2584 auto spec_id = AllocateSpecConstant(module, SpecConstant::kGlobalOffsetX);
2585 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002586 Ops << x_id << spv::DecorationSpecId << spec_id;
SJWf93f5f32020-05-05 07:27:56 -05002587 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002588
2589 spec_id = AllocateSpecConstant(module, SpecConstant::kGlobalOffsetY);
2590 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002591 Ops << y_id << spv::DecorationSpecId << spec_id;
SJWf93f5f32020-05-05 07:27:56 -05002592 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002593
2594 spec_id = AllocateSpecConstant(module, SpecConstant::kGlobalOffsetZ);
2595 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002596 Ops << z_id << spv::DecorationSpecId << spec_id;
SJWf93f5f32020-05-05 07:27:56 -05002597 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002598
2599 //
2600 // Generate OpSpecConstantComposite.
2601 //
2602 // Ops[0] : type id
2603 // Ops[1..n-1] : elements
2604 //
alan-bakere1996972020-05-04 08:38:12 -04002605 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002606 Ops << GV.getType()->getPointerElementType() << x_id << y_id << z_id;
SJWf93f5f32020-05-05 07:27:56 -05002607 InitializerID = addSPIRVInst<kConstants>(spv::OpSpecConstantComposite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002608 }
2609
David Neto85082642018-03-24 06:55:20 -07002610 const auto AS = PTy->getAddressSpace();
SJW806a5d82020-07-15 12:51:38 -05002611 const auto spvSC = GetStorageClass(AS);
David Neto22f144c2017-06-12 14:26:21 -04002612
David Neto85082642018-03-24 06:55:20 -07002613 const bool module_scope_constant_external_init =
David Neto862b7d82018-06-14 18:48:37 -04002614 (AS == AddressSpace::Constant) && GV.hasInitializer() &&
David Neto85082642018-03-24 06:55:20 -07002615 clspv::Option::ModuleConstantsInStorageBuffer();
2616
Kévin Petit23d5f182019-08-13 16:21:29 +01002617 if (GV.hasInitializer()) {
2618 auto GVInit = GV.getInitializer();
2619 if (!isa<UndefValue>(GVInit) && !module_scope_constant_external_init) {
SJWf93f5f32020-05-05 07:27:56 -05002620 InitializerID = getSPIRVValue(GVInit);
David Neto85082642018-03-24 06:55:20 -07002621 }
2622 }
Kévin Petit23d5f182019-08-13 16:21:29 +01002623
SJW806a5d82020-07-15 12:51:38 -05002624 SPIRVID var_id =
2625 addSPIRVGlobalVariable(getSPIRVType(Ty), spvSC, InitializerID);
David Neto85082642018-03-24 06:55:20 -07002626
SJWf93f5f32020-05-05 07:27:56 -05002627 VMap[&GV] = var_id;
David Neto22f144c2017-06-12 14:26:21 -04002628
alan-bakere1996972020-05-04 08:38:12 -04002629 auto IsOpenCLBuiltin = [](spv::BuiltIn builtin) {
2630 return builtin == spv::BuiltInWorkDim ||
2631 builtin == spv::BuiltInGlobalOffset;
2632 };
2633
alan-bakere1996972020-05-04 08:38:12 -04002634 // If we have a builtin (not an OpenCL builtin).
2635 if (spv::BuiltInMax != BuiltinType && !IsOpenCLBuiltin(BuiltinType)) {
David Neto22f144c2017-06-12 14:26:21 -04002636 //
2637 // Generate OpDecorate.
2638 //
2639 // DOps[0] = Target ID
2640 // DOps[1] = Decoration (Builtin)
2641 // DOps[2] = BuiltIn ID
SJW01901d92020-05-21 08:58:31 -05002642 SPIRVID ResultID;
David Neto22f144c2017-06-12 14:26:21 -04002643
2644 // WorkgroupSize is different, we decorate the constant composite that has
2645 // its value, rather than the variable that we use to access the value.
2646 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2647 ResultID = InitializerID;
David Netoa60b00b2017-09-15 16:34:09 -04002648 // Save both the value and variable IDs for later.
2649 WorkgroupSizeValueID = InitializerID;
SJWf93f5f32020-05-05 07:27:56 -05002650 WorkgroupSizeVarID = getSPIRVValue(&GV);
David Neto22f144c2017-06-12 14:26:21 -04002651 } else {
SJWf93f5f32020-05-05 07:27:56 -05002652 ResultID = getSPIRVValue(&GV);
David Neto22f144c2017-06-12 14:26:21 -04002653 }
2654
SJW806a5d82020-07-15 12:51:38 -05002655 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05002656 Ops << ResultID << spv::DecorationBuiltIn << BuiltinType;
David Neto22f144c2017-06-12 14:26:21 -04002657
SJW01901d92020-05-21 08:58:31 -05002658 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto85082642018-03-24 06:55:20 -07002659 } else if (module_scope_constant_external_init) {
2660 // This module scope constant is initialized from a storage buffer with data
2661 // provided by the host at binding 0 of the next descriptor set.
SJW77b87ad2020-04-21 14:37:52 -05002662 const uint32_t descriptor_set = TakeDescriptorIndex(module);
David Neto85082642018-03-24 06:55:20 -07002663
David Neto862b7d82018-06-14 18:48:37 -04002664 // Emit the intializer to the descriptor map file.
David Neto85082642018-03-24 06:55:20 -07002665 // Use "kind,buffer" to indicate storage buffer. We might want to expand
2666 // that later to other types, like uniform buffer.
alan-bakerf5e5f692018-11-27 08:33:24 -05002667 std::string hexbytes;
2668 llvm::raw_string_ostream str(hexbytes);
2669 clspv::ConstantEmitter(DL, str).Emit(GV.getInitializer());
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002670 version0::DescriptorMapEntry::ConstantData constant_data = {ArgKind::Buffer,
2671 str.str()};
2672 descriptorMapEntries->emplace_back(std::move(constant_data), descriptor_set,
2673 0);
David Neto85082642018-03-24 06:55:20 -07002674
David Neto85082642018-03-24 06:55:20 -07002675 // OpDecorate %var DescriptorSet <descriptor_set>
SJW806a5d82020-07-15 12:51:38 -05002676 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05002677 Ops << var_id << spv::DecorationDescriptorSet << descriptor_set;
2678 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
SJW69939d52020-04-16 07:29:07 -05002679
2680 // OpDecorate %var Binding <binding>
SJW01901d92020-05-21 08:58:31 -05002681 Ops.clear();
2682 Ops << var_id << spv::DecorationBinding << 0;
2683 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Netoc6f3ab22018-04-06 18:02:31 -04002684 }
2685}
2686
SJW77b87ad2020-04-21 14:37:52 -05002687void SPIRVProducerPass::GenerateDescriptorMapInfo(Function &F) {
2688 const auto &DL = module->getDataLayout();
David Netoc5fb5242018-07-30 13:28:31 -04002689 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
2690 return;
2691 }
Kévin Petit717f8572020-04-06 17:31:53 +01002692 // Add entries for each kernel
2693 version0::DescriptorMapEntry::KernelDeclData kernel_decl_data = {
2694 F.getName().str()};
2695 descriptorMapEntries->emplace_back(std::move(kernel_decl_data));
2696
David Neto862b7d82018-06-14 18:48:37 -04002697 // Gather the list of resources that are used by this function's arguments.
2698 auto &resource_var_at_index = FunctionToResourceVarsMap[&F];
2699
David Neto862b7d82018-06-14 18:48:37 -04002700 auto *fty = F.getType()->getPointerElementType();
2701 auto *func_ty = dyn_cast<FunctionType>(fty);
2702
alan-baker038e9242019-04-19 22:14:41 -04002703 // If we've clustered POD arguments, then argument details are in metadata.
David Neto862b7d82018-06-14 18:48:37 -04002704 // If an argument maps to a resource variable, then get descriptor set and
2705 // binding from the resoure variable. Other info comes from the metadata.
alan-bakerff6c9292020-05-04 08:32:09 -04002706 const auto *arg_map = F.getMetadata(clspv::KernelArgMapMetadataName());
2707 auto local_spec_id_md =
2708 module->getNamedMetadata(clspv::LocalSpecIdMetadataName());
David Neto862b7d82018-06-14 18:48:37 -04002709 if (arg_map) {
2710 for (const auto &arg : arg_map->operands()) {
2711 const MDNode *arg_node = dyn_cast<MDNode>(arg.get());
alan-bakerff6c9292020-05-04 08:32:09 -04002712 assert(arg_node->getNumOperands() == 6);
David Neto862b7d82018-06-14 18:48:37 -04002713 const auto name =
2714 dyn_cast<MDString>(arg_node->getOperand(0))->getString();
2715 const auto old_index =
2716 dyn_extract<ConstantInt>(arg_node->getOperand(1))->getZExtValue();
2717 // Remapped argument index
alan-baker6a3930b2020-05-21 10:09:11 -04002718 const int new_index = static_cast<int>(
2719 dyn_extract<ConstantInt>(arg_node->getOperand(2))->getSExtValue());
David Neto862b7d82018-06-14 18:48:37 -04002720 const auto offset =
2721 dyn_extract<ConstantInt>(arg_node->getOperand(3))->getZExtValue();
Kévin PETITa353c832018-03-20 23:21:21 +00002722 const auto arg_size =
2723 dyn_extract<ConstantInt>(arg_node->getOperand(4))->getZExtValue();
alan-bakerc4579bb2020-04-29 14:15:50 -04002724 const auto argKind = clspv::GetArgKindFromName(
2725 dyn_cast<MDString>(arg_node->getOperand(5))->getString().str());
alan-bakerf5e5f692018-11-27 08:33:24 -05002726
alan-bakerff6c9292020-05-04 08:32:09 -04002727 // If this is a local memory argument, find the right spec id for this
2728 // argument.
2729 int64_t spec_id = -1;
2730 if (argKind == clspv::ArgKind::Local) {
2731 for (auto spec_id_arg : local_spec_id_md->operands()) {
2732 if ((&F == dyn_cast<Function>(
2733 dyn_cast<ValueAsMetadata>(spec_id_arg->getOperand(0))
2734 ->getValue())) &&
alan-baker6a3930b2020-05-21 10:09:11 -04002735 (static_cast<uint64_t>(new_index) ==
alan-bakerff6c9292020-05-04 08:32:09 -04002736 mdconst::extract<ConstantInt>(spec_id_arg->getOperand(1))
2737 ->getZExtValue())) {
2738 spec_id = mdconst::extract<ConstantInt>(spec_id_arg->getOperand(2))
2739 ->getSExtValue();
2740 break;
2741 }
2742 }
2743 }
alan-bakerf5e5f692018-11-27 08:33:24 -05002744 uint32_t descriptor_set = 0;
2745 uint32_t binding = 0;
2746 version0::DescriptorMapEntry::KernelArgData kernel_data = {
alan-baker21574d32020-01-29 16:00:31 -05002747 F.getName().str(), name.str(), static_cast<uint32_t>(old_index),
2748 argKind, static_cast<uint32_t>(spec_id),
alan-bakerf5e5f692018-11-27 08:33:24 -05002749 // This will be set below for pointer-to-local args.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002750 0, static_cast<uint32_t>(offset), static_cast<uint32_t>(arg_size)};
David Neto862b7d82018-06-14 18:48:37 -04002751 if (spec_id > 0) {
alan-bakerf5e5f692018-11-27 08:33:24 -05002752 kernel_data.local_element_size = static_cast<uint32_t>(GetTypeAllocSize(
2753 func_ty->getParamType(unsigned(new_index))->getPointerElementType(),
2754 DL));
alan-baker6a3930b2020-05-21 10:09:11 -04002755 } else if (new_index >= 0) {
David Neto862b7d82018-06-14 18:48:37 -04002756 auto *info = resource_var_at_index[new_index];
2757 assert(info);
alan-bakerf5e5f692018-11-27 08:33:24 -05002758 descriptor_set = info->descriptor_set;
2759 binding = info->binding;
David Neto862b7d82018-06-14 18:48:37 -04002760 }
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002761 descriptorMapEntries->emplace_back(std::move(kernel_data), descriptor_set,
2762 binding);
David Neto862b7d82018-06-14 18:48:37 -04002763 }
2764 } else {
2765 // There is no argument map.
2766 // Take descriptor info from the resource variable calls.
Kévin PETITa353c832018-03-20 23:21:21 +00002767 // Take argument name and size from the arguments list.
David Neto862b7d82018-06-14 18:48:37 -04002768
2769 SmallVector<Argument *, 4> arguments;
2770 for (auto &arg : F.args()) {
2771 arguments.push_back(&arg);
2772 }
2773
2774 unsigned arg_index = 0;
2775 for (auto *info : resource_var_at_index) {
2776 if (info) {
Kévin PETITa353c832018-03-20 23:21:21 +00002777 auto arg = arguments[arg_index];
alan-bakerb6b09dc2018-11-08 16:59:28 -05002778 unsigned arg_size = 0;
alan-baker9b0ec3c2020-04-06 14:45:34 -04002779 if (info->arg_kind == clspv::ArgKind::Pod ||
2780 info->arg_kind == clspv::ArgKind::PodUBO ||
2781 info->arg_kind == clspv::ArgKind::PodPushConstant) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002782 arg_size = static_cast<uint32_t>(DL.getTypeStoreSize(arg->getType()));
Kévin PETITa353c832018-03-20 23:21:21 +00002783 }
2784
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002785 // Local pointer arguments are unused in this case. Offset is always
2786 // zero.
alan-bakerf5e5f692018-11-27 08:33:24 -05002787 version0::DescriptorMapEntry::KernelArgData kernel_data = {
alan-baker21574d32020-01-29 16:00:31 -05002788 F.getName().str(),
2789 arg->getName().str(),
2790 arg_index,
alan-bakerc4579bb2020-04-29 14:15:50 -04002791 info->arg_kind,
alan-baker21574d32020-01-29 16:00:31 -05002792 0,
2793 0,
2794 0,
2795 arg_size};
alan-bakerf5e5f692018-11-27 08:33:24 -05002796 descriptorMapEntries->emplace_back(std::move(kernel_data),
2797 info->descriptor_set, info->binding);
David Neto862b7d82018-06-14 18:48:37 -04002798 }
2799 arg_index++;
2800 }
2801 // Generate mappings for pointer-to-local arguments.
2802 for (arg_index = 0; arg_index < arguments.size(); ++arg_index) {
2803 Argument *arg = arguments[arg_index];
Alan Baker202c8c72018-08-13 13:47:44 -04002804 auto where = LocalArgSpecIds.find(arg);
2805 if (where != LocalArgSpecIds.end()) {
2806 auto &local_arg_info = LocalSpecIdInfoMap[where->second];
alan-bakerf5e5f692018-11-27 08:33:24 -05002807 // Pod arguments members are unused in this case.
2808 version0::DescriptorMapEntry::KernelArgData kernel_data = {
alan-baker21574d32020-01-29 16:00:31 -05002809 F.getName().str(),
2810 arg->getName().str(),
alan-bakerf5e5f692018-11-27 08:33:24 -05002811 arg_index,
2812 ArgKind::Local,
2813 static_cast<uint32_t>(local_arg_info.spec_id),
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002814 static_cast<uint32_t>(
2815 GetTypeAllocSize(local_arg_info.elem_type, DL)),
alan-bakerf5e5f692018-11-27 08:33:24 -05002816 0,
2817 0};
2818 // Pointer-to-local arguments do not utilize descriptor set and binding.
2819 descriptorMapEntries->emplace_back(std::move(kernel_data), 0, 0);
David Neto862b7d82018-06-14 18:48:37 -04002820 }
2821 }
2822 }
2823}
2824
David Neto22f144c2017-06-12 14:26:21 -04002825void SPIRVProducerPass::GenerateFuncPrologue(Function &F) {
David Neto22f144c2017-06-12 14:26:21 -04002826 ValueMapType &VMap = getValueMap();
2827 EntryPointVecType &EntryPoints = getEntryPointVec();
David Neto22f144c2017-06-12 14:26:21 -04002828 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
2829 auto &GlobalConstArgSet = getGlobalConstArgSet();
2830
2831 FunctionType *FTy = F.getFunctionType();
2832
2833 //
David Neto22f144c2017-06-12 14:26:21 -04002834 // Generate OPFunction.
2835 //
2836
2837 // FOps[0] : Result Type ID
2838 // FOps[1] : Function Control
2839 // FOps[2] : Function Type ID
SJWf93f5f32020-05-05 07:27:56 -05002840 SPIRVOperandVec FOps;
David Neto22f144c2017-06-12 14:26:21 -04002841
2842 // Find SPIRV instruction for return type.
SJW01901d92020-05-21 08:58:31 -05002843 FOps << FTy->getReturnType();
David Neto22f144c2017-06-12 14:26:21 -04002844
2845 // Check function attributes for SPIRV Function Control.
2846 uint32_t FuncControl = spv::FunctionControlMaskNone;
2847 if (F.hasFnAttribute(Attribute::AlwaysInline)) {
2848 FuncControl |= spv::FunctionControlInlineMask;
2849 }
2850 if (F.hasFnAttribute(Attribute::NoInline)) {
2851 FuncControl |= spv::FunctionControlDontInlineMask;
2852 }
2853 // TODO: Check llvm attribute for Function Control Pure.
2854 if (F.hasFnAttribute(Attribute::ReadOnly)) {
2855 FuncControl |= spv::FunctionControlPureMask;
2856 }
2857 // TODO: Check llvm attribute for Function Control Const.
2858 if (F.hasFnAttribute(Attribute::ReadNone)) {
2859 FuncControl |= spv::FunctionControlConstMask;
2860 }
2861
SJW01901d92020-05-21 08:58:31 -05002862 FOps << FuncControl;
David Neto22f144c2017-06-12 14:26:21 -04002863
SJW01901d92020-05-21 08:58:31 -05002864 SPIRVID FTyID;
David Neto22f144c2017-06-12 14:26:21 -04002865 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
2866 SmallVector<Type *, 4> NewFuncParamTys;
2867 FunctionType *NewFTy =
2868 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
SJWf93f5f32020-05-05 07:27:56 -05002869 FTyID = getSPIRVType(NewFTy);
David Neto22f144c2017-06-12 14:26:21 -04002870 } else {
David Neto9ed8e2f2018-03-24 06:47:24 -07002871 // Handle regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04002872 if (GlobalConstFuncTyMap.count(FTy)) {
SJWf93f5f32020-05-05 07:27:56 -05002873 FTyID = getSPIRVType(GlobalConstFuncTyMap[FTy].first);
David Neto22f144c2017-06-12 14:26:21 -04002874 } else {
SJWf93f5f32020-05-05 07:27:56 -05002875 FTyID = getSPIRVType(FTy);
David Neto22f144c2017-06-12 14:26:21 -04002876 }
2877 }
2878
SJW01901d92020-05-21 08:58:31 -05002879 FOps << FTyID;
David Neto22f144c2017-06-12 14:26:21 -04002880
SJWf93f5f32020-05-05 07:27:56 -05002881 // Generate SPIRV instruction for function.
2882 SPIRVID FID = addSPIRVInst(spv::OpFunction, FOps);
2883 VMap[&F] = FID;
David Neto22f144c2017-06-12 14:26:21 -04002884
SJWf93f5f32020-05-05 07:27:56 -05002885 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
2886 EntryPoints.push_back(std::make_pair(&F, FID));
2887 }
David Neto22f144c2017-06-12 14:26:21 -04002888
David Neto482550a2018-03-24 05:21:07 -07002889 if (clspv::Option::ShowIDs()) {
SJW01901d92020-05-21 08:58:31 -05002890 errs() << "Function " << F.getName() << " is " << FID.get() << "\n";
David Netob05675d2018-02-16 12:37:49 -05002891 }
David Neto22f144c2017-06-12 14:26:21 -04002892
2893 //
2894 // Generate OpFunctionParameter for Normal function.
2895 //
2896
2897 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
alan-bakere9308012019-03-15 10:25:13 -04002898
David Neto22f144c2017-06-12 14:26:21 -04002899 // Iterate Argument for name instead of param type from function type.
2900 unsigned ArgIdx = 0;
2901 for (Argument &Arg : F.args()) {
David Neto22f144c2017-06-12 14:26:21 -04002902 // ParamOps[0] : Result Type ID
SJW01901d92020-05-21 08:58:31 -05002903 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04002904
2905 // Find SPIRV instruction for parameter type.
SJW01901d92020-05-21 08:58:31 -05002906 SPIRVID ParamTyID = getSPIRVType(Arg.getType());
David Neto22f144c2017-06-12 14:26:21 -04002907 if (PointerType *PTy = dyn_cast<PointerType>(Arg.getType())) {
2908 if (GlobalConstFuncTyMap.count(FTy)) {
2909 if (ArgIdx == GlobalConstFuncTyMap[FTy].second) {
2910 Type *EleTy = PTy->getPointerElementType();
2911 Type *ArgTy =
2912 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
SJWf93f5f32020-05-05 07:27:56 -05002913 ParamTyID = getSPIRVType(ArgTy);
David Neto22f144c2017-06-12 14:26:21 -04002914 GlobalConstArgSet.insert(&Arg);
2915 }
2916 }
2917 }
SJW01901d92020-05-21 08:58:31 -05002918 Ops << ParamTyID;
David Neto22f144c2017-06-12 14:26:21 -04002919
2920 // Generate SPIRV instruction for parameter.
SJW01901d92020-05-21 08:58:31 -05002921 SPIRVID param_id = addSPIRVInst(spv::OpFunctionParameter, Ops);
SJWf93f5f32020-05-05 07:27:56 -05002922 VMap[&Arg] = param_id;
2923
2924 if (CalledWithCoherentResource(Arg)) {
2925 // If the arg is passed a coherent resource ever, then decorate this
2926 // parameter with Coherent too.
SJW01901d92020-05-21 08:58:31 -05002927 Ops.clear();
2928 Ops << param_id << spv::DecorationCoherent;
2929 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
SJWf93f5f32020-05-05 07:27:56 -05002930 }
David Neto22f144c2017-06-12 14:26:21 -04002931
2932 ArgIdx++;
2933 }
2934 }
2935}
2936
SJW77b87ad2020-04-21 14:37:52 -05002937void SPIRVProducerPass::GenerateModuleInfo() {
David Neto22f144c2017-06-12 14:26:21 -04002938 EntryPointVecType &EntryPoints = getEntryPointVec();
SJW806a5d82020-07-15 12:51:38 -05002939 auto &EntryPointInterfaces = getEntryPointInterfacesList();
SJW01901d92020-05-21 08:58:31 -05002940 std::vector<SPIRVID> &BuiltinDimVec = getBuiltinDimVec();
David Neto22f144c2017-06-12 14:26:21 -04002941
SJWf93f5f32020-05-05 07:27:56 -05002942 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04002943
SJW01901d92020-05-21 08:58:31 -05002944 for (auto Capability : CapabilitySet) {
David Neto22f144c2017-06-12 14:26:21 -04002945 //
SJW01901d92020-05-21 08:58:31 -05002946 // Generate OpCapability
David Neto22f144c2017-06-12 14:26:21 -04002947 //
2948 // Ops[0] = Capability
SJW01901d92020-05-21 08:58:31 -05002949 addSPIRVInst<kCapabilities>(spv::OpCapability, Capability);
alan-baker5b86ed72019-02-15 08:26:50 -05002950 }
2951
2952 // Always add the storage buffer extension
2953 {
David Neto22f144c2017-06-12 14:26:21 -04002954 //
2955 // Generate OpExtension.
2956 //
2957 // Ops[0] = Name (Literal String)
2958 //
SJWf93f5f32020-05-05 07:27:56 -05002959 addSPIRVInst<kExtensions>(spv::OpExtension,
2960 "SPV_KHR_storage_buffer_storage_class");
alan-baker5b86ed72019-02-15 08:26:50 -05002961 }
David Neto22f144c2017-06-12 14:26:21 -04002962
alan-baker5b86ed72019-02-15 08:26:50 -05002963 if (hasVariablePointers() || hasVariablePointersStorageBuffer()) {
2964 //
2965 // Generate OpExtension.
2966 //
2967 // Ops[0] = Name (Literal String)
2968 //
SJWf93f5f32020-05-05 07:27:56 -05002969 addSPIRVInst<kExtensions>(spv::OpExtension, "SPV_KHR_variable_pointers");
David Neto22f144c2017-06-12 14:26:21 -04002970 }
2971
2972 //
2973 // Generate OpMemoryModel
2974 //
2975 // Memory model for Vulkan will always be GLSL450.
2976
2977 // Ops[0] = Addressing Model
2978 // Ops[1] = Memory Model
2979 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002980 Ops << spv::AddressingModelLogical << spv::MemoryModelGLSL450;
David Neto22f144c2017-06-12 14:26:21 -04002981
SJWf93f5f32020-05-05 07:27:56 -05002982 addSPIRVInst<kMemoryModel>(spv::OpMemoryModel, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002983
2984 //
2985 // Generate OpEntryPoint
2986 //
2987 for (auto EntryPoint : EntryPoints) {
2988 // Ops[0] = Execution Model
2989 // Ops[1] = EntryPoint ID
2990 // Ops[2] = Name (Literal String)
2991 // ...
2992 //
2993 // TODO: Do we need to consider Interface ID for forward references???
2994 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05002995 const StringRef &name = EntryPoint.first->getName();
SJW01901d92020-05-21 08:58:31 -05002996 Ops << spv::ExecutionModelGLCompute << EntryPoint.second << name;
David Neto22f144c2017-06-12 14:26:21 -04002997
SJW806a5d82020-07-15 12:51:38 -05002998 for (auto &Interface : EntryPointInterfaces) {
SJW01901d92020-05-21 08:58:31 -05002999 Ops << Interface;
David Neto22f144c2017-06-12 14:26:21 -04003000 }
3001
SJWf93f5f32020-05-05 07:27:56 -05003002 addSPIRVInst<kEntryPoints>(spv::OpEntryPoint, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003003 }
3004
3005 for (auto EntryPoint : EntryPoints) {
Kévin Petit21c23c62020-04-29 01:38:28 +01003006 const MDNode *MD = dyn_cast<Function>(EntryPoint.first)
3007 ->getMetadata("reqd_work_group_size");
3008 if ((MD != nullptr) && !clspv::Option::NonUniformNDRangeSupported()) {
David Neto22f144c2017-06-12 14:26:21 -04003009
3010 if (!BuiltinDimVec.empty()) {
3011 llvm_unreachable(
3012 "Kernels should have consistent work group size definition");
3013 }
3014
3015 //
3016 // Generate OpExecutionMode
3017 //
3018
3019 // Ops[0] = Entry Point ID
3020 // Ops[1] = Execution Mode
3021 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
3022 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05003023 Ops << EntryPoint.second << spv::ExecutionModeLocalSize;
David Neto22f144c2017-06-12 14:26:21 -04003024
3025 uint32_t XDim = static_cast<uint32_t>(
3026 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
3027 uint32_t YDim = static_cast<uint32_t>(
3028 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
3029 uint32_t ZDim = static_cast<uint32_t>(
3030 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
3031
SJW01901d92020-05-21 08:58:31 -05003032 Ops << XDim << YDim << ZDim;
David Neto22f144c2017-06-12 14:26:21 -04003033
SJWf93f5f32020-05-05 07:27:56 -05003034 addSPIRVInst<kExecutionModes>(spv::OpExecutionMode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003035 }
3036 }
3037
3038 //
3039 // Generate OpSource.
3040 //
3041 // Ops[0] = SourceLanguage ID
3042 // Ops[1] = Version (LiteralNum)
3043 //
SJW01901d92020-05-21 08:58:31 -05003044 uint32_t LangID = spv::SourceLanguageUnknown;
3045 uint32_t LangVer = 0;
Kévin Petitf0515712020-01-07 18:29:20 +00003046 switch (clspv::Option::Language()) {
3047 case clspv::Option::SourceLanguage::OpenCL_C_10:
SJW01901d92020-05-21 08:58:31 -05003048 LangID = spv::SourceLanguageOpenCL_C;
3049 LangVer = 100;
Kévin Petitf0515712020-01-07 18:29:20 +00003050 break;
3051 case clspv::Option::SourceLanguage::OpenCL_C_11:
SJW01901d92020-05-21 08:58:31 -05003052 LangID = spv::SourceLanguageOpenCL_C;
3053 LangVer = 110;
Kévin Petitf0515712020-01-07 18:29:20 +00003054 break;
3055 case clspv::Option::SourceLanguage::OpenCL_C_12:
SJW01901d92020-05-21 08:58:31 -05003056 LangID = spv::SourceLanguageOpenCL_C;
3057 LangVer = 120;
Kévin Petitf0515712020-01-07 18:29:20 +00003058 break;
3059 case clspv::Option::SourceLanguage::OpenCL_C_20:
SJW01901d92020-05-21 08:58:31 -05003060 LangID = spv::SourceLanguageOpenCL_C;
3061 LangVer = 200;
Kévin Petitf0515712020-01-07 18:29:20 +00003062 break;
3063 case clspv::Option::SourceLanguage::OpenCL_CPP:
SJW01901d92020-05-21 08:58:31 -05003064 LangID = spv::SourceLanguageOpenCL_CPP;
3065 LangVer = 100;
Kévin Petitf0515712020-01-07 18:29:20 +00003066 break;
3067 default:
Kévin Petitf0515712020-01-07 18:29:20 +00003068 break;
Kévin Petit0fc88042019-04-09 23:25:02 +01003069 }
David Neto22f144c2017-06-12 14:26:21 -04003070
SJW01901d92020-05-21 08:58:31 -05003071 Ops.clear();
3072 Ops << LangID << LangVer;
SJWf93f5f32020-05-05 07:27:56 -05003073 addSPIRVInst<kDebug>(spv::OpSource, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003074
3075 if (!BuiltinDimVec.empty()) {
3076 //
3077 // Generate OpDecorates for x/y/z dimension.
3078 //
3079 // Ops[0] = Target ID
3080 // Ops[1] = Decoration (SpecId)
David Neto257c3892018-04-11 13:19:45 -04003081 // Ops[2] = Specialization Constant ID (Literal Number)
David Neto22f144c2017-06-12 14:26:21 -04003082
3083 // X Dimension
3084 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05003085 Ops << BuiltinDimVec[0] << spv::DecorationSpecId << 0;
SJWf93f5f32020-05-05 07:27:56 -05003086 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003087
3088 // Y Dimension
3089 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05003090 Ops << BuiltinDimVec[1] << spv::DecorationSpecId << 1;
SJWf93f5f32020-05-05 07:27:56 -05003091 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003092
3093 // Z Dimension
3094 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05003095 Ops << BuiltinDimVec[2] << spv::DecorationSpecId << 2;
SJWf93f5f32020-05-05 07:27:56 -05003096 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003097 }
3098}
3099
David Netob6e2e062018-04-25 10:32:06 -04003100void SPIRVProducerPass::GenerateEntryPointInitialStores() {
3101 // Work around a driver bug. Initializers on Private variables might not
3102 // work. So the start of the kernel should store the initializer value to the
3103 // variables. Yes, *every* entry point pays this cost if *any* entry point
3104 // uses this builtin. At this point I judge this to be an acceptable tradeoff
3105 // of complexity vs. runtime, for a broken driver.
alan-bakerb6b09dc2018-11-08 16:59:28 -05003106 // TODO(dneto): Remove this at some point once fixed drivers are widely
3107 // available.
SJW01901d92020-05-21 08:58:31 -05003108 if (WorkgroupSizeVarID.isValid()) {
3109 assert(WorkgroupSizeValueID.isValid());
David Netob6e2e062018-04-25 10:32:06 -04003110
SJWf93f5f32020-05-05 07:27:56 -05003111 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05003112 Ops << WorkgroupSizeVarID << WorkgroupSizeValueID;
David Netob6e2e062018-04-25 10:32:06 -04003113
SJWf93f5f32020-05-05 07:27:56 -05003114 addSPIRVInst(spv::OpStore, Ops);
David Netob6e2e062018-04-25 10:32:06 -04003115 }
3116}
3117
David Neto22f144c2017-06-12 14:26:21 -04003118void SPIRVProducerPass::GenerateFuncBody(Function &F) {
David Neto22f144c2017-06-12 14:26:21 -04003119 ValueMapType &VMap = getValueMap();
3120
David Netob6e2e062018-04-25 10:32:06 -04003121 const bool IsKernel = F.getCallingConv() == CallingConv::SPIR_KERNEL;
David Neto22f144c2017-06-12 14:26:21 -04003122
3123 for (BasicBlock &BB : F) {
3124 // Register BasicBlock to ValueMap.
David Neto22f144c2017-06-12 14:26:21 -04003125
3126 //
3127 // Generate OpLabel for Basic Block.
3128 //
SJWf93f5f32020-05-05 07:27:56 -05003129 VMap[&BB] = addSPIRVInst(spv::OpLabel);
David Neto22f144c2017-06-12 14:26:21 -04003130
David Neto6dcd4712017-06-23 11:06:47 -04003131 // OpVariable instructions must come first.
3132 for (Instruction &I : BB) {
alan-baker5b86ed72019-02-15 08:26:50 -05003133 if (auto *alloca = dyn_cast<AllocaInst>(&I)) {
3134 // Allocating a pointer requires variable pointers.
3135 if (alloca->getAllocatedType()->isPointerTy()) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003136 setVariablePointersCapabilities(
3137 alloca->getAllocatedType()->getPointerAddressSpace());
alan-baker5b86ed72019-02-15 08:26:50 -05003138 }
David Neto6dcd4712017-06-23 11:06:47 -04003139 GenerateInstruction(I);
3140 }
3141 }
3142
David Neto22f144c2017-06-12 14:26:21 -04003143 if (&BB == &F.getEntryBlock() && IsKernel) {
David Netob6e2e062018-04-25 10:32:06 -04003144 if (clspv::Option::HackInitializers()) {
3145 GenerateEntryPointInitialStores();
3146 }
David Neto22f144c2017-06-12 14:26:21 -04003147 }
3148
3149 for (Instruction &I : BB) {
David Neto6dcd4712017-06-23 11:06:47 -04003150 if (!isa<AllocaInst>(I)) {
3151 GenerateInstruction(I);
3152 }
David Neto22f144c2017-06-12 14:26:21 -04003153 }
3154 }
3155}
3156
3157spv::Op SPIRVProducerPass::GetSPIRVCmpOpcode(CmpInst *I) {
3158 const std::map<CmpInst::Predicate, spv::Op> Map = {
3159 {CmpInst::ICMP_EQ, spv::OpIEqual},
3160 {CmpInst::ICMP_NE, spv::OpINotEqual},
3161 {CmpInst::ICMP_UGT, spv::OpUGreaterThan},
3162 {CmpInst::ICMP_UGE, spv::OpUGreaterThanEqual},
3163 {CmpInst::ICMP_ULT, spv::OpULessThan},
3164 {CmpInst::ICMP_ULE, spv::OpULessThanEqual},
3165 {CmpInst::ICMP_SGT, spv::OpSGreaterThan},
3166 {CmpInst::ICMP_SGE, spv::OpSGreaterThanEqual},
3167 {CmpInst::ICMP_SLT, spv::OpSLessThan},
3168 {CmpInst::ICMP_SLE, spv::OpSLessThanEqual},
3169 {CmpInst::FCMP_OEQ, spv::OpFOrdEqual},
3170 {CmpInst::FCMP_OGT, spv::OpFOrdGreaterThan},
3171 {CmpInst::FCMP_OGE, spv::OpFOrdGreaterThanEqual},
3172 {CmpInst::FCMP_OLT, spv::OpFOrdLessThan},
3173 {CmpInst::FCMP_OLE, spv::OpFOrdLessThanEqual},
3174 {CmpInst::FCMP_ONE, spv::OpFOrdNotEqual},
3175 {CmpInst::FCMP_UEQ, spv::OpFUnordEqual},
3176 {CmpInst::FCMP_UGT, spv::OpFUnordGreaterThan},
3177 {CmpInst::FCMP_UGE, spv::OpFUnordGreaterThanEqual},
3178 {CmpInst::FCMP_ULT, spv::OpFUnordLessThan},
3179 {CmpInst::FCMP_ULE, spv::OpFUnordLessThanEqual},
3180 {CmpInst::FCMP_UNE, spv::OpFUnordNotEqual}};
3181
3182 assert(0 != Map.count(I->getPredicate()));
3183
3184 return Map.at(I->getPredicate());
3185}
3186
3187spv::Op SPIRVProducerPass::GetSPIRVCastOpcode(Instruction &I) {
3188 const std::map<unsigned, spv::Op> Map{
3189 {Instruction::Trunc, spv::OpUConvert},
3190 {Instruction::ZExt, spv::OpUConvert},
3191 {Instruction::SExt, spv::OpSConvert},
3192 {Instruction::FPToUI, spv::OpConvertFToU},
3193 {Instruction::FPToSI, spv::OpConvertFToS},
3194 {Instruction::UIToFP, spv::OpConvertUToF},
3195 {Instruction::SIToFP, spv::OpConvertSToF},
3196 {Instruction::FPTrunc, spv::OpFConvert},
3197 {Instruction::FPExt, spv::OpFConvert},
3198 {Instruction::BitCast, spv::OpBitcast}};
3199
3200 assert(0 != Map.count(I.getOpcode()));
3201
3202 return Map.at(I.getOpcode());
3203}
3204
3205spv::Op SPIRVProducerPass::GetSPIRVBinaryOpcode(Instruction &I) {
Kévin Petit24272b62018-10-18 19:16:12 +00003206 if (I.getType()->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003207 switch (I.getOpcode()) {
3208 default:
3209 break;
3210 case Instruction::Or:
3211 return spv::OpLogicalOr;
3212 case Instruction::And:
3213 return spv::OpLogicalAnd;
3214 case Instruction::Xor:
3215 return spv::OpLogicalNotEqual;
3216 }
3217 }
3218
alan-bakerb6b09dc2018-11-08 16:59:28 -05003219 const std::map<unsigned, spv::Op> Map{
David Neto22f144c2017-06-12 14:26:21 -04003220 {Instruction::Add, spv::OpIAdd},
3221 {Instruction::FAdd, spv::OpFAdd},
3222 {Instruction::Sub, spv::OpISub},
3223 {Instruction::FSub, spv::OpFSub},
3224 {Instruction::Mul, spv::OpIMul},
3225 {Instruction::FMul, spv::OpFMul},
3226 {Instruction::UDiv, spv::OpUDiv},
3227 {Instruction::SDiv, spv::OpSDiv},
3228 {Instruction::FDiv, spv::OpFDiv},
3229 {Instruction::URem, spv::OpUMod},
3230 {Instruction::SRem, spv::OpSRem},
3231 {Instruction::FRem, spv::OpFRem},
3232 {Instruction::Or, spv::OpBitwiseOr},
3233 {Instruction::Xor, spv::OpBitwiseXor},
3234 {Instruction::And, spv::OpBitwiseAnd},
3235 {Instruction::Shl, spv::OpShiftLeftLogical},
3236 {Instruction::LShr, spv::OpShiftRightLogical},
3237 {Instruction::AShr, spv::OpShiftRightArithmetic}};
3238
3239 assert(0 != Map.count(I.getOpcode()));
3240
3241 return Map.at(I.getOpcode());
3242}
3243
SJW806a5d82020-07-15 12:51:38 -05003244SPIRVID SPIRVProducerPass::getSPIRVBuiltin(spv::BuiltIn BID,
3245 spv::Capability Cap) {
3246 SPIRVID RID;
3247
3248 auto ii = BuiltinConstantMap.find(BID);
3249
3250 if (ii != BuiltinConstantMap.end()) {
3251 return ii->second;
3252 } else {
3253
3254 addCapability(Cap);
3255
3256 Type *type = PointerType::get(IntegerType::get(module->getContext(), 32),
3257 AddressSpace::Input);
3258
3259 RID = addSPIRVGlobalVariable(getSPIRVType(type), spv::StorageClassInput);
3260
3261 BuiltinConstantMap[BID] = RID;
3262
3263 //
3264 // Generate OpDecorate.
3265 //
3266 // Ops[0] : target
3267 // Ops[1] : decoration
3268 // Ops[2] : SpecId
3269 SPIRVOperandVec Ops;
3270 Ops << RID << spv::DecorationBuiltIn << static_cast<int>(BID);
3271
3272 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
3273 }
3274
3275 return RID;
3276}
3277
3278SPIRVID
3279SPIRVProducerPass::GenerateClspvInstruction(CallInst *Call,
3280 const FunctionInfo &FuncInfo) {
3281 SPIRVID RID;
3282
3283 switch (FuncInfo.getType()) {
3284 case Builtins::kClspvCompositeConstruct:
3285 RID = addSPIRVPlaceholder(Call);
3286 break;
3287 case Builtins::kClspvResource: {
3288 if (ResourceVarDeferredLoadCalls.count(Call) && Call->hasNUsesOrMore(1)) {
3289 // Generate an OpLoad
3290 SPIRVOperandVec Ops;
3291
3292 Ops << Call->getType()->getPointerElementType()
3293 << ResourceVarDeferredLoadCalls[Call];
3294
3295 RID = addSPIRVInst(spv::OpLoad, Ops);
3296
3297 } else {
3298 // This maps to an OpVariable we've already generated.
3299 // No code is generated for the call.
3300 }
3301 break;
3302 }
3303 case Builtins::kClspvLocal: {
3304 // Don't codegen an instruction here, but instead map this call directly
3305 // to the workgroup variable id.
3306 int spec_id = static_cast<int>(
3307 cast<ConstantInt>(Call->getOperand(0))->getSExtValue());
3308 const auto &info = LocalSpecIdInfoMap[spec_id];
3309 RID = info.variable_id;
3310 break;
3311 }
3312 case Builtins::kClspvSamplerVarLiteral: {
3313 // Sampler initializers become a load of the corresponding sampler.
3314 // Map this to a load from the variable.
3315 const auto third_param = static_cast<unsigned>(
3316 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue());
3317 auto sampler_value = third_param;
3318 if (clspv::Option::UseSamplerMap()) {
3319 sampler_value = getSamplerMap()[third_param].first;
3320 }
3321
3322 // Generate an OpLoad
3323 SPIRVOperandVec Ops;
3324
3325 Ops << SamplerTy->getPointerElementType()
3326 << SamplerLiteralToIDMap[sampler_value];
3327
3328 RID = addSPIRVInst(spv::OpLoad, Ops);
3329 break;
3330 }
3331 case Builtins::kSpirvAtomicXor: {
3332 // Handle SPIR-V intrinsics
3333 SPIRVOperandVec Ops;
3334
3335 if (!Call->getType()->isVoidTy()) {
3336 Ops << Call->getType();
3337 }
3338
3339 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
3340 Ops << Call->getArgOperand(i);
3341 }
3342
3343 RID = addSPIRVInst(spv::OpAtomicXor, Ops);
3344 break;
3345 }
3346 case Builtins::kSpirvOp: {
3347 // Handle SPIR-V intrinsics
3348 auto *arg0 = dyn_cast<ConstantInt>(Call->getArgOperand(0));
3349 spv::Op opcode = static_cast<spv::Op>(arg0->getZExtValue());
3350 if (opcode != spv::OpNop) {
3351 SPIRVOperandVec Ops;
3352
3353 if (!Call->getType()->isVoidTy()) {
3354 Ops << Call->getType();
3355 }
3356
3357 for (unsigned i = 1; i < Call->getNumArgOperands(); i++) {
3358 Ops << Call->getArgOperand(i);
3359 }
3360
3361 RID = addSPIRVInst(opcode, Ops);
3362 }
3363 break;
3364 }
3365 case Builtins::kSpirvCopyMemory: {
3366 //
3367 // Generate OpCopyMemory.
3368 //
3369
3370 // Ops[0] = Dst ID
3371 // Ops[1] = Src ID
3372 // Ops[2] = Memory Access
3373 // Ops[3] = Alignment
3374
3375 auto IsVolatile =
3376 dyn_cast<ConstantInt>(Call->getArgOperand(3))->getZExtValue() != 0;
3377
3378 auto VolatileMemoryAccess = (IsVolatile) ? spv::MemoryAccessVolatileMask
3379 : spv::MemoryAccessMaskNone;
3380
3381 auto MemoryAccess = VolatileMemoryAccess | spv::MemoryAccessAlignedMask;
3382
3383 auto Alignment =
3384 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
3385
3386 SPIRVOperandVec Ops;
3387 Ops << Call->getArgOperand(0) << Call->getArgOperand(1) << MemoryAccess
3388 << static_cast<uint32_t>(Alignment);
3389
3390 RID = addSPIRVInst(spv::OpCopyMemory, Ops);
3391 break;
3392 }
3393 default:
3394 llvm_unreachable("Unknown CLSPV Instruction");
3395 break;
3396 }
3397 return RID;
3398}
3399
3400SPIRVID
3401SPIRVProducerPass::GenerateImageInstruction(CallInst *Call,
3402 const FunctionInfo &FuncInfo) {
3403 SPIRVID RID;
3404
3405 LLVMContext &Context = module->getContext();
3406 switch (FuncInfo.getType()) {
3407 case Builtins::kReadImagef:
3408 case Builtins::kReadImageh:
3409 case Builtins::kReadImagei:
3410 case Builtins::kReadImageui: {
3411 // read_image is converted to OpSampledImage and OpImageSampleExplicitLod.
3412 // Additionally, OpTypeSampledImage is generated.
3413 const auto &pi = FuncInfo.getParameter(1);
3414 if (pi.isSampler()) {
3415 //
3416 // Generate OpSampledImage.
3417 //
3418 // Ops[0] = Result Type ID
3419 // Ops[1] = Image ID
3420 // Ops[2] = Sampler ID
3421 //
3422 SPIRVOperandVec Ops;
3423
3424 Value *Image = Call->getArgOperand(0);
3425 Value *Sampler = Call->getArgOperand(1);
3426 Value *Coordinate = Call->getArgOperand(2);
3427
3428 TypeMapType &OpImageTypeMap = getImageTypeMap();
3429 Type *ImageTy = Image->getType()->getPointerElementType();
3430 SPIRVID ImageTyID = OpImageTypeMap[ImageTy];
3431
3432 Ops << ImageTyID << Image << Sampler;
3433
3434 SPIRVID SampledImageID = addSPIRVInst(spv::OpSampledImage, Ops);
3435
3436 //
3437 // Generate OpImageSampleExplicitLod.
3438 //
3439 // Ops[0] = Result Type ID
3440 // Ops[1] = Sampled Image ID
3441 // Ops[2] = Coordinate ID
3442 // Ops[3] = Image Operands Type ID
3443 // Ops[4] ... Ops[n] = Operands ID
3444 //
3445 Ops.clear();
3446
3447 const bool is_int_image = IsIntImageType(Image->getType());
3448 SPIRVID result_type;
3449 if (is_int_image) {
3450 result_type = v4int32ID;
3451 } else {
3452 result_type = getSPIRVType(Call->getType());
3453 }
3454
3455 Constant *CstFP0 = ConstantFP::get(Context, APFloat(0.0f));
3456 Ops << result_type << SampledImageID << Coordinate
3457 << spv::ImageOperandsLodMask << CstFP0;
3458
3459 RID = addSPIRVInst(spv::OpImageSampleExplicitLod, Ops);
3460
3461 if (is_int_image) {
3462 // Generate the bitcast.
3463 Ops.clear();
3464 Ops << Call->getType() << RID;
3465 RID = addSPIRVInst(spv::OpBitcast, Ops);
3466 }
3467 } else {
3468
3469 // read_image (without a sampler) is mapped to OpImageFetch.
3470 Value *Image = Call->getArgOperand(0);
3471 Value *Coordinate = Call->getArgOperand(1);
3472
3473 //
3474 // Generate OpImageFetch
3475 //
3476 // Ops[0] = Result Type ID
3477 // Ops[1] = Image ID
3478 // Ops[2] = Coordinate ID
3479 // Ops[3] = Lod
3480 // Ops[4] = 0
3481 //
3482 SPIRVOperandVec Ops;
3483
3484 const bool is_int_image = IsIntImageType(Image->getType());
3485 SPIRVID result_type;
3486 if (is_int_image) {
3487 result_type = v4int32ID;
3488 } else {
3489 result_type = getSPIRVType(Call->getType());
3490 }
3491
3492 Ops << result_type << Image << Coordinate << spv::ImageOperandsLodMask
3493 << getSPIRVInt32Constant(0);
3494
3495 RID = addSPIRVInst(spv::OpImageFetch, Ops);
3496
3497 if (is_int_image) {
3498 // Generate the bitcast.
3499 Ops.clear();
3500 Ops << Call->getType() << RID;
3501 RID = addSPIRVInst(spv::OpBitcast, Ops);
3502 }
3503 }
3504 break;
3505 }
3506
3507 case Builtins::kWriteImagef:
3508 case Builtins::kWriteImageh:
3509 case Builtins::kWriteImagei:
3510 case Builtins::kWriteImageui: {
3511 // write_image is mapped to OpImageWrite.
3512 //
3513 // Generate OpImageWrite.
3514 //
3515 // Ops[0] = Image ID
3516 // Ops[1] = Coordinate ID
3517 // Ops[2] = Texel ID
3518 // Ops[3] = (Optional) Image Operands Type (Literal Number)
3519 // Ops[4] ... Ops[n] = (Optional) Operands ID
3520 //
3521 SPIRVOperandVec Ops;
3522
3523 Value *Image = Call->getArgOperand(0);
3524 Value *Coordinate = Call->getArgOperand(1);
3525 Value *Texel = Call->getArgOperand(2);
3526
3527 SPIRVID TexelID = getSPIRVValue(Texel);
3528
3529 const bool is_int_image = IsIntImageType(Image->getType());
3530 if (is_int_image) {
3531 // Generate a bitcast to v4int and use it as the texel value.
3532 Ops << v4int32ID << TexelID;
3533 TexelID = addSPIRVInst(spv::OpBitcast, Ops);
3534 Ops.clear();
3535 }
3536 Ops << Image << Coordinate << TexelID;
3537
3538 RID = addSPIRVInst(spv::OpImageWrite, Ops);
3539 break;
3540 }
3541
3542 case Builtins::kGetImageHeight:
3543 case Builtins::kGetImageWidth:
3544 case Builtins::kGetImageDepth:
3545 case Builtins::kGetImageDim: {
3546 // get_image_* is mapped to OpImageQuerySize or OpImageQuerySizeLod
3547 addCapability(spv::CapabilityImageQuery);
3548
3549 //
3550 // Generate OpImageQuerySize[Lod]
3551 //
3552 // Ops[0] = Image ID
3553 //
3554 // Result type has components equal to the dimensionality of the image,
3555 // plus 1 if the image is arrayed.
3556 //
3557 // %sizes = OpImageQuerySize[Lod] %uint[2|3|4] %im [%uint_0]
3558 SPIRVOperandVec Ops;
3559
3560 // Implement:
3561 // %sizes = OpImageQuerySize[Lod] %uint[2|3|4] %im [%uint_0]
3562 SPIRVID SizesTypeID;
3563
3564 Value *Image = Call->getArgOperand(0);
3565 const uint32_t dim = ImageDimensionality(Image->getType());
3566 const uint32_t components =
3567 dim + (IsArrayImageType(Image->getType()) ? 1 : 0);
3568 if (components == 1) {
3569 SizesTypeID = getSPIRVType(Type::getInt32Ty(Context));
3570 } else {
3571 SizesTypeID = getSPIRVType(
3572 FixedVectorType::get(Type::getInt32Ty(Context), components));
3573 }
3574 Ops << SizesTypeID << Image;
3575 spv::Op query_opcode = spv::OpImageQuerySize;
3576 if (IsSampledImageType(Image->getType())) {
3577 query_opcode = spv::OpImageQuerySizeLod;
3578 // Need explicit 0 for Lod operand.
3579 Ops << getSPIRVInt32Constant(0);
3580 }
3581
3582 RID = addSPIRVInst(query_opcode, Ops);
3583
3584 // May require an extra instruction to create the appropriate result of
3585 // the builtin function.
3586 if (FuncInfo.getType() == Builtins::kGetImageDim) {
3587 if (dim == 3) {
3588 // get_image_dim returns an int4 for 3D images.
3589 //
3590
3591 // Implement:
3592 // %result = OpCompositeConstruct %uint4 %sizes %uint_0
3593 Ops.clear();
3594 Ops << FixedVectorType::get(Type::getInt32Ty(Context), 4) << RID
3595 << getSPIRVInt32Constant(0);
3596
3597 RID = addSPIRVInst(spv::OpCompositeConstruct, Ops);
3598 } else if (dim != components) {
3599 // get_image_dim return an int2 regardless of the arrayedness of the
3600 // image. If the image is arrayed an element must be dropped from the
3601 // query result.
3602 //
3603
3604 // Implement:
3605 // %result = OpVectorShuffle %uint2 %sizes %sizes 0 1
3606 Ops.clear();
3607 Ops << FixedVectorType::get(Type::getInt32Ty(Context), 2) << RID << RID
3608 << 0 << 1;
3609
3610 RID = addSPIRVInst(spv::OpVectorShuffle, Ops);
3611 }
3612 } else if (components > 1) {
3613 // Implement:
3614 // %result = OpCompositeExtract %uint %sizes <component number>
3615 Ops.clear();
3616 Ops << Call->getType() << RID;
3617
3618 uint32_t component = 0;
3619 if (FuncInfo.getType() == Builtins::kGetImageHeight)
3620 component = 1;
3621 else if (FuncInfo.getType() == Builtins::kGetImageDepth)
3622 component = 2;
3623 Ops << component;
3624
3625 RID = addSPIRVInst(spv::OpCompositeExtract, Ops);
3626 }
3627 break;
3628 }
3629 default:
3630 llvm_unreachable("Unsupported Image builtin");
3631 }
3632
3633 return RID;
3634}
3635
3636SPIRVID
3637SPIRVProducerPass::GenerateSubgroupInstruction(CallInst *Call,
3638 const FunctionInfo &FuncInfo) {
3639 SPIRVID RID;
3640
3641 // requires SPIRV version 1.3 or greater
3642 if (SpvVersion() != SPIRVVersion::SPIRV_1_3) {
3643 // llvm_unreachable("SubGroups extension requires SPIRV 1.3 or greater");
3644 // TODO(sjw): error out gracefully
3645 }
3646
3647 auto loadBuiltin = [this, Call](spv::BuiltIn spvBI,
3648 spv::Capability spvCap =
3649 spv::CapabilityGroupNonUniform) {
3650 SPIRVOperandVec Ops;
3651 Ops << Call->getType() << this->getSPIRVBuiltin(spvBI, spvCap);
3652
3653 return addSPIRVInst(spv::OpLoad, Ops);
3654 };
3655
3656 spv::Op op = spv::OpNop;
3657 switch (FuncInfo.getType()) {
3658 case Builtins::kGetSubGroupSize:
3659 return loadBuiltin(spv::BuiltInSubgroupSize);
3660 case Builtins::kGetNumSubGroups:
3661 return loadBuiltin(spv::BuiltInNumSubgroups);
3662 case Builtins::kGetSubGroupId:
3663 return loadBuiltin(spv::BuiltInSubgroupId);
3664 case Builtins::kGetSubGroupLocalId:
3665 return loadBuiltin(spv::BuiltInSubgroupLocalInvocationId);
3666
3667 case Builtins::kSubGroupBroadcast:
3668 if (SpvVersion() < SPIRVVersion::SPIRV_1_5 &&
3669 !dyn_cast<ConstantInt>(Call->getOperand(1))) {
3670 llvm_unreachable("sub_group_broadcast requires constant lane Id for "
3671 "SPIRV version < 1.5");
3672 }
3673 addCapability(spv::CapabilityGroupNonUniformBallot);
3674 op = spv::OpGroupNonUniformBroadcast;
3675 break;
3676
3677 case Builtins::kSubGroupAll:
3678 addCapability(spv::CapabilityGroupNonUniformVote);
3679 op = spv::OpGroupNonUniformAll;
3680 break;
3681 case Builtins::kSubGroupAny:
3682 addCapability(spv::CapabilityGroupNonUniformVote);
3683 op = spv::OpGroupNonUniformAny;
3684 break;
3685 case Builtins::kSubGroupReduceAdd:
3686 case Builtins::kSubGroupScanExclusiveAdd:
3687 case Builtins::kSubGroupScanInclusiveAdd: {
3688 addCapability(spv::CapabilityGroupNonUniformArithmetic);
3689 if (FuncInfo.getParameter(0).type_id == Type::IntegerTyID) {
3690 op = spv::OpGroupNonUniformIAdd;
3691 } else {
3692 op = spv::OpGroupNonUniformFAdd;
3693 }
3694 break;
3695 }
3696 case Builtins::kSubGroupReduceMin:
3697 case Builtins::kSubGroupScanExclusiveMin:
3698 case Builtins::kSubGroupScanInclusiveMin: {
3699 addCapability(spv::CapabilityGroupNonUniformArithmetic);
3700 auto &param = FuncInfo.getParameter(0);
3701 if (param.type_id == Type::IntegerTyID) {
3702 op = param.is_signed ? spv::OpGroupNonUniformSMin
3703 : spv::OpGroupNonUniformUMin;
3704 } else {
3705 op = spv::OpGroupNonUniformFMin;
3706 }
3707 break;
3708 }
3709 case Builtins::kSubGroupReduceMax:
3710 case Builtins::kSubGroupScanExclusiveMax:
3711 case Builtins::kSubGroupScanInclusiveMax: {
3712 addCapability(spv::CapabilityGroupNonUniformArithmetic);
3713 auto &param = FuncInfo.getParameter(0);
3714 if (param.type_id == Type::IntegerTyID) {
3715 op = param.is_signed ? spv::OpGroupNonUniformSMax
3716 : spv::OpGroupNonUniformUMax;
3717 } else {
3718 op = spv::OpGroupNonUniformFMax;
3719 }
3720 break;
3721 }
3722
3723 case Builtins::kGetEnqueuedNumSubGroups:
3724 // TODO(sjw): requires CapabilityKernel (incompatible with Shader)
3725 case Builtins::kGetMaxSubGroupSize:
3726 // TODO(sjw): use SpecConstant, capability Kernel (incompatible with Shader)
3727 case Builtins::kSubGroupBarrier:
3728 case Builtins::kSubGroupReserveReadPipe:
3729 case Builtins::kSubGroupReserveWritePipe:
3730 case Builtins::kSubGroupCommitReadPipe:
3731 case Builtins::kSubGroupCommitWritePipe:
3732 case Builtins::kGetKernelSubGroupCountForNdrange:
3733 case Builtins::kGetKernelMaxSubGroupSizeForNdrange:
3734 default:
3735 Call->print(errs());
3736 llvm_unreachable("Unsupported sub_group operation");
3737 break;
3738 }
3739
3740 assert(op != spv::OpNop);
3741
3742 SPIRVOperandVec Operands;
3743
3744 //
3745 // Generate OpGroupNonUniform*
3746 //
3747 // Ops[0] = Result Type ID
3748 // Ops[1] = ScopeSubgroup
3749 // Ops[2] = Value ID
3750 // Ops[3] = Local ID
3751
3752 // The result type.
3753 Operands << Call->getType();
3754
3755 // Subgroup Scope
3756 Operands << getSPIRVInt32Constant(spv::ScopeSubgroup);
3757
3758 switch (FuncInfo.getType()) {
3759 case Builtins::kSubGroupReduceAdd:
3760 case Builtins::kSubGroupReduceMin:
3761 case Builtins::kSubGroupReduceMax:
3762 Operands << spv::GroupOperationReduce;
3763 break;
3764 case Builtins::kSubGroupScanExclusiveAdd:
3765 case Builtins::kSubGroupScanExclusiveMin:
3766 case Builtins::kSubGroupScanExclusiveMax:
3767 Operands << spv::GroupOperationExclusiveScan;
3768 break;
3769 case Builtins::kSubGroupScanInclusiveAdd:
3770 case Builtins::kSubGroupScanInclusiveMin:
3771 case Builtins::kSubGroupScanInclusiveMax:
3772 Operands << spv::GroupOperationInclusiveScan;
3773 break;
3774 default:
3775 break;
3776 }
3777
3778 for (Use &use : Call->arg_operands()) {
3779 Operands << use.get();
3780 }
3781
3782 return addSPIRVInst(op, Operands);
3783}
3784
3785SPIRVID SPIRVProducerPass::GenerateInstructionFromCall(CallInst *Call) {
3786 LLVMContext &Context = module->getContext();
3787
3788 auto &func_info = Builtins::Lookup(Call->getCalledFunction());
3789 auto func_type = func_info.getType();
3790
3791 if (BUILTIN_IN_GROUP(func_type, Clspv)) {
3792 return GenerateClspvInstruction(Call, func_info);
3793 } else if (BUILTIN_IN_GROUP(func_type, Image)) {
3794 return GenerateImageInstruction(Call, func_info);
3795 } else if (BUILTIN_IN_GROUP(func_type, SubgroupsKHR)) {
3796 return GenerateSubgroupInstruction(Call, func_info);
3797 }
3798
3799 SPIRVID RID;
3800
3801 switch (func_type) {
3802 case Builtins::kPopcount: {
3803 //
3804 // Generate OpBitCount
3805 //
3806 // Ops[0] = Result Type ID
3807 // Ops[1] = Base ID
3808 SPIRVOperandVec Ops;
3809 Ops << Call->getType() << Call->getOperand(0);
3810
3811 RID = addSPIRVInst(spv::OpBitCount, Ops);
3812 break;
3813 }
3814 default: {
3815 glsl::ExtInst EInst = getDirectOrIndirectExtInstEnum(func_info);
3816
3817 if (EInst) {
3818 SPIRVID ExtInstImportID = getOpExtInstImportID();
3819
3820 //
3821 // Generate OpExtInst.
3822 //
3823
3824 // Ops[0] = Result Type ID
3825 // Ops[1] = Set ID (OpExtInstImport ID)
3826 // Ops[2] = Instruction Number (Literal Number)
3827 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
3828 SPIRVOperandVec Ops;
3829
3830 Ops << Call->getType() << ExtInstImportID << EInst;
3831
3832 for (auto &use : Call->arg_operands()) {
3833 Ops << use.get();
3834 }
3835
3836 RID = addSPIRVInst(spv::OpExtInst, Ops);
3837
3838 const auto IndirectExtInst = getIndirectExtInstEnum(func_info);
3839 if (IndirectExtInst != kGlslExtInstBad) {
3840
3841 // Generate one more instruction that uses the result of the extended
3842 // instruction. Its result id is one more than the id of the
3843 // extended instruction.
3844 auto generate_extra_inst = [this, &Context, &Call,
3845 &RID](spv::Op opcode, Constant *constant) {
3846 //
3847 // Generate instruction like:
3848 // result = opcode constant <extinst-result>
3849 //
3850 // Ops[0] = Result Type ID
3851 // Ops[1] = Operand 0 ;; the constant, suitably splatted
3852 // Ops[2] = Operand 1 ;; the result of the extended instruction
3853 SPIRVOperandVec Ops;
3854
3855 Type *resultTy = Call->getType();
3856
3857 if (auto *vectorTy = dyn_cast<VectorType>(resultTy)) {
3858 constant = ConstantVector::getSplat(
3859 {static_cast<unsigned>(vectorTy->getNumElements()), false},
3860 constant);
3861 }
3862 Ops << resultTy << constant << RID;
3863
3864 RID = addSPIRVInst(opcode, Ops);
3865 };
3866
3867 auto IntTy = Type::getInt32Ty(Context);
3868 switch (IndirectExtInst) {
3869 case glsl::ExtInstFindUMsb: // Implementing clz
3870 generate_extra_inst(spv::OpISub, ConstantInt::get(IntTy, 31));
3871 break;
3872 case glsl::ExtInstAcos: // Implementing acospi
3873 case glsl::ExtInstAsin: // Implementing asinpi
3874 case glsl::ExtInstAtan: // Implementing atanpi
3875 case glsl::ExtInstAtan2: // Implementing atan2pi
3876 generate_extra_inst(
3877 spv::OpFMul,
3878 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
3879 break;
3880
3881 default:
3882 assert(false && "internally inconsistent");
3883 }
3884 }
3885 } else {
3886
3887 // A real function call (not builtin)
3888 // Call instruction is deferred because it needs function's ID.
3889 RID = addSPIRVPlaceholder(Call);
3890 }
3891
3892 break;
3893 }
3894 }
3895
3896 return RID;
3897}
3898
David Neto22f144c2017-06-12 14:26:21 -04003899void SPIRVProducerPass::GenerateInstruction(Instruction &I) {
David Neto22f144c2017-06-12 14:26:21 -04003900 ValueMapType &VMap = getValueMap();
SJW806a5d82020-07-15 12:51:38 -05003901 LLVMContext &Context = module->getContext();
David Neto22f144c2017-06-12 14:26:21 -04003902
SJW806a5d82020-07-15 12:51:38 -05003903 SPIRVID RID;
David Neto22f144c2017-06-12 14:26:21 -04003904
3905 switch (I.getOpcode()) {
3906 default: {
3907 if (Instruction::isCast(I.getOpcode())) {
3908 //
3909 // Generate SPIRV instructions for cast operators.
3910 //
3911
David Netod2de94a2017-08-28 17:27:47 -04003912 auto Ty = I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003913 auto OpTy = I.getOperand(0)->getType();
David Netod2de94a2017-08-28 17:27:47 -04003914 auto toI8 = Ty == Type::getInt8Ty(Context);
3915 auto fromI32 = OpTy == Type::getInt32Ty(Context);
David Neto22f144c2017-06-12 14:26:21 -04003916 // Handle zext, sext and uitofp with i1 type specially.
3917 if ((I.getOpcode() == Instruction::ZExt ||
3918 I.getOpcode() == Instruction::SExt ||
3919 I.getOpcode() == Instruction::UIToFP) &&
alan-bakerb6b09dc2018-11-08 16:59:28 -05003920 OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003921 //
3922 // Generate OpSelect.
3923 //
3924
3925 // Ops[0] = Result Type ID
3926 // Ops[1] = Condition ID
3927 // Ops[2] = True Constant ID
3928 // Ops[3] = False Constant ID
SJWf93f5f32020-05-05 07:27:56 -05003929 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04003930
SJW01901d92020-05-21 08:58:31 -05003931 Ops << I.getType() << I.getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04003932
David Neto22f144c2017-06-12 14:26:21 -04003933 if (I.getOpcode() == Instruction::ZExt) {
SJW01901d92020-05-21 08:58:31 -05003934 Ops << ConstantInt::get(I.getType(), 1);
David Neto22f144c2017-06-12 14:26:21 -04003935 } else if (I.getOpcode() == Instruction::SExt) {
SJW01901d92020-05-21 08:58:31 -05003936 Ops << ConstantInt::getSigned(I.getType(), -1);
David Neto22f144c2017-06-12 14:26:21 -04003937 } else {
SJW01901d92020-05-21 08:58:31 -05003938 Ops << ConstantFP::get(Context, APFloat(1.0f));
David Neto22f144c2017-06-12 14:26:21 -04003939 }
David Neto22f144c2017-06-12 14:26:21 -04003940
David Neto22f144c2017-06-12 14:26:21 -04003941 if (I.getOpcode() == Instruction::ZExt) {
SJW01901d92020-05-21 08:58:31 -05003942 Ops << Constant::getNullValue(I.getType());
David Neto22f144c2017-06-12 14:26:21 -04003943 } else if (I.getOpcode() == Instruction::SExt) {
SJW01901d92020-05-21 08:58:31 -05003944 Ops << Constant::getNullValue(I.getType());
David Neto22f144c2017-06-12 14:26:21 -04003945 } else {
SJW01901d92020-05-21 08:58:31 -05003946 Ops << ConstantFP::get(Context, APFloat(0.0f));
David Neto22f144c2017-06-12 14:26:21 -04003947 }
David Neto22f144c2017-06-12 14:26:21 -04003948
SJWf93f5f32020-05-05 07:27:56 -05003949 RID = addSPIRVInst(spv::OpSelect, Ops);
alan-bakerb39c8262019-03-08 14:03:37 -05003950 } else if (!clspv::Option::Int8Support() &&
3951 I.getOpcode() == Instruction::Trunc && fromI32 && toI8) {
David Netod2de94a2017-08-28 17:27:47 -04003952 // The SPIR-V target type is a 32-bit int. Keep only the bottom
3953 // 8 bits.
3954 // Before:
3955 // %result = trunc i32 %a to i8
3956 // After
3957 // %result = OpBitwiseAnd %uint %a %uint_255
3958
SJWf93f5f32020-05-05 07:27:56 -05003959 SPIRVOperandVec Ops;
David Netod2de94a2017-08-28 17:27:47 -04003960
SJW806a5d82020-07-15 12:51:38 -05003961 Ops << OpTy << I.getOperand(0) << getSPIRVInt32Constant(255);
David Netod2de94a2017-08-28 17:27:47 -04003962
SJWf93f5f32020-05-05 07:27:56 -05003963 RID = addSPIRVInst(spv::OpBitwiseAnd, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003964 } else {
3965 // Ops[0] = Result Type ID
3966 // Ops[1] = Source Value ID
SJWf93f5f32020-05-05 07:27:56 -05003967 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04003968
SJW01901d92020-05-21 08:58:31 -05003969 Ops << I.getType() << I.getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04003970
SJWf93f5f32020-05-05 07:27:56 -05003971 RID = addSPIRVInst(GetSPIRVCastOpcode(I), Ops);
David Neto22f144c2017-06-12 14:26:21 -04003972 }
3973 } else if (isa<BinaryOperator>(I)) {
3974 //
3975 // Generate SPIRV instructions for binary operators.
3976 //
3977
3978 // Handle xor with i1 type specially.
3979 if (I.getOpcode() == Instruction::Xor &&
3980 I.getType() == Type::getInt1Ty(Context) &&
Kévin Petit24272b62018-10-18 19:16:12 +00003981 ((isa<ConstantInt>(I.getOperand(0)) &&
3982 !cast<ConstantInt>(I.getOperand(0))->isZero()) ||
3983 (isa<ConstantInt>(I.getOperand(1)) &&
3984 !cast<ConstantInt>(I.getOperand(1))->isZero()))) {
David Neto22f144c2017-06-12 14:26:21 -04003985 //
3986 // Generate OpLogicalNot.
3987 //
3988 // Ops[0] = Result Type ID
3989 // Ops[1] = Operand
SJWf93f5f32020-05-05 07:27:56 -05003990 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04003991
SJW01901d92020-05-21 08:58:31 -05003992 Ops << I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003993
3994 Value *CondV = I.getOperand(0);
3995 if (isa<Constant>(I.getOperand(0))) {
3996 CondV = I.getOperand(1);
3997 }
SJW01901d92020-05-21 08:58:31 -05003998 Ops << CondV;
David Neto22f144c2017-06-12 14:26:21 -04003999
SJWf93f5f32020-05-05 07:27:56 -05004000 RID = addSPIRVInst(spv::OpLogicalNot, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004001 } else {
4002 // Ops[0] = Result Type ID
4003 // Ops[1] = Operand 0
4004 // Ops[2] = Operand 1
SJWf93f5f32020-05-05 07:27:56 -05004005 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004006
SJW01901d92020-05-21 08:58:31 -05004007 Ops << I.getType() << I.getOperand(0) << I.getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04004008
SJWf93f5f32020-05-05 07:27:56 -05004009 RID = addSPIRVInst(GetSPIRVBinaryOpcode(I), Ops);
David Neto22f144c2017-06-12 14:26:21 -04004010 }
alan-bakerc9c55ae2019-12-02 16:01:27 -05004011 } else if (I.getOpcode() == Instruction::FNeg) {
4012 // The only unary operator.
4013 //
4014 // Ops[0] = Result Type ID
4015 // Ops[1] = Operand 0
SJW01901d92020-05-21 08:58:31 -05004016 SPIRVOperandVec Ops;
alan-bakerc9c55ae2019-12-02 16:01:27 -05004017
SJW01901d92020-05-21 08:58:31 -05004018 Ops << I.getType() << I.getOperand(0);
4019 RID = addSPIRVInst(spv::OpFNegate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004020 } else {
4021 I.print(errs());
4022 llvm_unreachable("Unsupported instruction???");
4023 }
4024 break;
4025 }
4026 case Instruction::GetElementPtr: {
4027 auto &GlobalConstArgSet = getGlobalConstArgSet();
4028
4029 //
4030 // Generate OpAccessChain.
4031 //
4032 GetElementPtrInst *GEP = cast<GetElementPtrInst>(&I);
4033
4034 //
4035 // Generate OpAccessChain.
4036 //
4037
4038 // Ops[0] = Result Type ID
4039 // Ops[1] = Base ID
4040 // Ops[2] ... Ops[n] = Indexes ID
SJWf93f5f32020-05-05 07:27:56 -05004041 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004042
alan-bakerb6b09dc2018-11-08 16:59:28 -05004043 PointerType *ResultType = cast<PointerType>(GEP->getType());
David Neto22f144c2017-06-12 14:26:21 -04004044 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate ||
4045 GlobalConstArgSet.count(GEP->getPointerOperand())) {
4046 // Use pointer type with private address space for global constant.
4047 Type *EleTy = I.getType()->getPointerElementType();
David Neto1a1a0582017-07-07 12:01:44 -04004048 ResultType = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
David Neto22f144c2017-06-12 14:26:21 -04004049 }
David Neto257c3892018-04-11 13:19:45 -04004050
SJW01901d92020-05-21 08:58:31 -05004051 Ops << ResultType;
David Neto22f144c2017-06-12 14:26:21 -04004052
David Neto862b7d82018-06-14 18:48:37 -04004053 // Generate the base pointer.
SJW01901d92020-05-21 08:58:31 -05004054 Ops << GEP->getPointerOperand();
David Neto22f144c2017-06-12 14:26:21 -04004055
David Neto862b7d82018-06-14 18:48:37 -04004056 // TODO(dneto): Simplify the following?
David Neto22f144c2017-06-12 14:26:21 -04004057
4058 //
4059 // Follows below rules for gep.
4060 //
David Neto862b7d82018-06-14 18:48:37 -04004061 // 1. If gep's first index is 0 generate OpAccessChain and ignore gep's
4062 // first index.
David Neto22f144c2017-06-12 14:26:21 -04004063 // 2. If gep's first index is not 0, generate OpPtrAccessChain and use gep's
4064 // first index.
4065 // 3. If gep's first index is not constant, generate OpPtrAccessChain and
4066 // use gep's first index.
4067 // 4. If it is not above case 1, 2 and 3, generate OpAccessChain and use
4068 // gep's first index.
4069 //
4070 spv::Op Opcode = spv::OpAccessChain;
4071 unsigned offset = 0;
4072 if (ConstantInt *CstInt = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
David Neto862b7d82018-06-14 18:48:37 -04004073 if (CstInt->getZExtValue() == 0) {
David Neto22f144c2017-06-12 14:26:21 -04004074 offset = 1;
David Neto862b7d82018-06-14 18:48:37 -04004075 } else if (CstInt->getZExtValue() != 0) {
David Neto22f144c2017-06-12 14:26:21 -04004076 Opcode = spv::OpPtrAccessChain;
David Neto22f144c2017-06-12 14:26:21 -04004077 }
David Neto862b7d82018-06-14 18:48:37 -04004078 } else {
David Neto22f144c2017-06-12 14:26:21 -04004079 Opcode = spv::OpPtrAccessChain;
David Neto1a1a0582017-07-07 12:01:44 -04004080 }
4081
4082 if (Opcode == spv::OpPtrAccessChain) {
David Neto1a1a0582017-07-07 12:01:44 -04004083 // Do we need to generate ArrayStride? Check against the GEP result type
4084 // rather than the pointer type of the base because when indexing into
4085 // an OpenCL program-scope constant, we'll swap out the LLVM base pointer
4086 // for something else in the SPIR-V.
4087 // E.g. see test/PointerAccessChain/pointer_index_is_constant_1.cl
alan-baker5b86ed72019-02-15 08:26:50 -05004088 auto address_space = ResultType->getAddressSpace();
4089 setVariablePointersCapabilities(address_space);
4090 switch (GetStorageClass(address_space)) {
Alan Bakerfcda9482018-10-02 17:09:59 -04004091 case spv::StorageClassStorageBuffer:
4092 case spv::StorageClassUniform:
David Neto1a1a0582017-07-07 12:01:44 -04004093 // Save the need to generate an ArrayStride decoration. But defer
4094 // generation until later, so we only make one decoration.
David Neto85082642018-03-24 06:55:20 -07004095 getTypesNeedingArrayStride().insert(ResultType);
Alan Bakerfcda9482018-10-02 17:09:59 -04004096 break;
4097 default:
4098 break;
David Neto1a1a0582017-07-07 12:01:44 -04004099 }
David Neto22f144c2017-06-12 14:26:21 -04004100 }
4101
4102 for (auto II = GEP->idx_begin() + offset; II != GEP->idx_end(); II++) {
SJW01901d92020-05-21 08:58:31 -05004103 Ops << *II;
David Neto22f144c2017-06-12 14:26:21 -04004104 }
4105
SJWf93f5f32020-05-05 07:27:56 -05004106 RID = addSPIRVInst(Opcode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004107 break;
4108 }
4109 case Instruction::ExtractValue: {
4110 ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
4111 // Ops[0] = Result Type ID
4112 // Ops[1] = Composite ID
4113 // Ops[2] ... Ops[n] = Indexes (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05004114 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004115
SJW01901d92020-05-21 08:58:31 -05004116 Ops << I.getType();
David Neto22f144c2017-06-12 14:26:21 -04004117
SJW01901d92020-05-21 08:58:31 -05004118 Ops << EVI->getAggregateOperand();
David Neto22f144c2017-06-12 14:26:21 -04004119
4120 for (auto &Index : EVI->indices()) {
SJW01901d92020-05-21 08:58:31 -05004121 Ops << Index;
David Neto22f144c2017-06-12 14:26:21 -04004122 }
4123
SJWf93f5f32020-05-05 07:27:56 -05004124 RID = addSPIRVInst(spv::OpCompositeExtract, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004125 break;
4126 }
4127 case Instruction::InsertValue: {
4128 InsertValueInst *IVI = cast<InsertValueInst>(&I);
4129 // Ops[0] = Result Type ID
4130 // Ops[1] = Object ID
4131 // Ops[2] = Composite ID
4132 // Ops[3] ... Ops[n] = Indexes (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05004133 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004134
SJW01901d92020-05-21 08:58:31 -05004135 Ops << I.getType() << IVI->getInsertedValueOperand()
4136 << IVI->getAggregateOperand();
David Neto22f144c2017-06-12 14:26:21 -04004137
4138 for (auto &Index : IVI->indices()) {
SJW01901d92020-05-21 08:58:31 -05004139 Ops << Index;
David Neto22f144c2017-06-12 14:26:21 -04004140 }
4141
SJWf93f5f32020-05-05 07:27:56 -05004142 RID = addSPIRVInst(spv::OpCompositeInsert, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004143 break;
4144 }
4145 case Instruction::Select: {
4146 //
4147 // Generate OpSelect.
4148 //
4149
4150 // Ops[0] = Result Type ID
4151 // Ops[1] = Condition ID
4152 // Ops[2] = True Constant ID
4153 // Ops[3] = False Constant ID
SJWf93f5f32020-05-05 07:27:56 -05004154 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004155
4156 // Find SPIRV instruction for parameter type.
4157 auto Ty = I.getType();
4158 if (Ty->isPointerTy()) {
4159 auto PointeeTy = Ty->getPointerElementType();
4160 if (PointeeTy->isStructTy() &&
4161 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
4162 Ty = PointeeTy;
alan-baker5b86ed72019-02-15 08:26:50 -05004163 } else {
4164 // Selecting between pointers requires variable pointers.
4165 setVariablePointersCapabilities(Ty->getPointerAddressSpace());
4166 if (!hasVariablePointers() && !selectFromSameObject(&I)) {
SJW01901d92020-05-21 08:58:31 -05004167 setVariablePointers();
alan-baker5b86ed72019-02-15 08:26:50 -05004168 }
David Neto22f144c2017-06-12 14:26:21 -04004169 }
4170 }
4171
SJW01901d92020-05-21 08:58:31 -05004172 Ops << Ty << I.getOperand(0) << I.getOperand(1) << I.getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04004173
SJWf93f5f32020-05-05 07:27:56 -05004174 RID = addSPIRVInst(spv::OpSelect, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004175 break;
4176 }
4177 case Instruction::ExtractElement: {
4178 // Handle <4 x i8> type manually.
4179 Type *CompositeTy = I.getOperand(0)->getType();
4180 if (is4xi8vec(CompositeTy)) {
4181 //
4182 // Generate OpShiftRightLogical and OpBitwiseAnd for extractelement with
4183 // <4 x i8>.
4184 //
4185
4186 //
4187 // Generate OpShiftRightLogical
4188 //
4189 // Ops[0] = Result Type ID
4190 // Ops[1] = Operand 0
4191 // Ops[2] = Operand 1
4192 //
SJWf93f5f32020-05-05 07:27:56 -05004193 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004194
SJW01901d92020-05-21 08:58:31 -05004195 Ops << CompositeTy << I.getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04004196
SJW01901d92020-05-21 08:58:31 -05004197 SPIRVID Op1ID = 0;
David Neto22f144c2017-06-12 14:26:21 -04004198 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
4199 // Handle constant index.
SJW806a5d82020-07-15 12:51:38 -05004200 uint32_t Idx = static_cast<uint32_t>(CI->getZExtValue());
4201 Op1ID = getSPIRVInt32Constant(Idx * 8);
David Neto22f144c2017-06-12 14:26:21 -04004202 } else {
4203 // Handle variable index.
SJWf93f5f32020-05-05 07:27:56 -05004204 SPIRVOperandVec TmpOps;
David Neto22f144c2017-06-12 14:26:21 -04004205
SJW806a5d82020-07-15 12:51:38 -05004206 TmpOps << Type::getInt32Ty(Context) << I.getOperand(1)
4207 << getSPIRVInt32Constant(8);
David Neto22f144c2017-06-12 14:26:21 -04004208
SJWf93f5f32020-05-05 07:27:56 -05004209 Op1ID = addSPIRVInst(spv::OpIMul, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04004210 }
SJW01901d92020-05-21 08:58:31 -05004211 Ops << Op1ID;
David Neto22f144c2017-06-12 14:26:21 -04004212
SJW01901d92020-05-21 08:58:31 -05004213 SPIRVID ShiftID = addSPIRVInst(spv::OpShiftRightLogical, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004214
4215 //
4216 // Generate OpBitwiseAnd
4217 //
4218 // Ops[0] = Result Type ID
4219 // Ops[1] = Operand 0
4220 // Ops[2] = Operand 1
4221 //
4222 Ops.clear();
4223
SJW806a5d82020-07-15 12:51:38 -05004224 Ops << CompositeTy << ShiftID << getSPIRVInt32Constant(0xFF);
David Neto22f144c2017-06-12 14:26:21 -04004225
SJWf93f5f32020-05-05 07:27:56 -05004226 RID = addSPIRVInst(spv::OpBitwiseAnd, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004227 break;
4228 }
4229
4230 // Ops[0] = Result Type ID
4231 // Ops[1] = Composite ID
4232 // Ops[2] ... Ops[n] = Indexes (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05004233 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004234
SJW01901d92020-05-21 08:58:31 -05004235 Ops << I.getType() << I.getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04004236
4237 spv::Op Opcode = spv::OpCompositeExtract;
4238 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
SJW01901d92020-05-21 08:58:31 -05004239 Ops << static_cast<uint32_t>(CI->getZExtValue());
David Neto22f144c2017-06-12 14:26:21 -04004240 } else {
SJW01901d92020-05-21 08:58:31 -05004241 Ops << I.getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04004242 Opcode = spv::OpVectorExtractDynamic;
4243 }
4244
SJWf93f5f32020-05-05 07:27:56 -05004245 RID = addSPIRVInst(Opcode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004246 break;
4247 }
4248 case Instruction::InsertElement: {
4249 // Handle <4 x i8> type manually.
4250 Type *CompositeTy = I.getOperand(0)->getType();
4251 if (is4xi8vec(CompositeTy)) {
SJW806a5d82020-07-15 12:51:38 -05004252 SPIRVID CstFFID = getSPIRVInt32Constant(0xFF);
David Neto22f144c2017-06-12 14:26:21 -04004253
SJW01901d92020-05-21 08:58:31 -05004254 SPIRVID ShiftAmountID = 0;
David Neto22f144c2017-06-12 14:26:21 -04004255 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
4256 // Handle constant index.
SJW806a5d82020-07-15 12:51:38 -05004257 uint32_t Idx = static_cast<uint32_t>(CI->getZExtValue());
4258 ShiftAmountID = getSPIRVInt32Constant(Idx * 8);
David Neto22f144c2017-06-12 14:26:21 -04004259 } else {
4260 // Handle variable index.
SJWf93f5f32020-05-05 07:27:56 -05004261 SPIRVOperandVec TmpOps;
David Neto22f144c2017-06-12 14:26:21 -04004262
SJW806a5d82020-07-15 12:51:38 -05004263 TmpOps << Type::getInt32Ty(Context) << I.getOperand(2)
4264 << getSPIRVInt32Constant(8);
David Neto22f144c2017-06-12 14:26:21 -04004265
SJWf93f5f32020-05-05 07:27:56 -05004266 ShiftAmountID = addSPIRVInst(spv::OpIMul, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04004267 }
4268
4269 //
4270 // Generate mask operations.
4271 //
4272
4273 // ShiftLeft mask according to index of insertelement.
SJWf93f5f32020-05-05 07:27:56 -05004274 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004275
SJW01901d92020-05-21 08:58:31 -05004276 Ops << CompositeTy << CstFFID << ShiftAmountID;
David Neto22f144c2017-06-12 14:26:21 -04004277
SJW01901d92020-05-21 08:58:31 -05004278 SPIRVID MaskID = addSPIRVInst(spv::OpShiftLeftLogical, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004279
4280 // Inverse mask.
4281 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05004282 Ops << CompositeTy << MaskID;
David Neto22f144c2017-06-12 14:26:21 -04004283
SJW01901d92020-05-21 08:58:31 -05004284 SPIRVID InvMaskID = addSPIRVInst(spv::OpNot, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004285
4286 // Apply mask.
4287 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05004288 Ops << CompositeTy << I.getOperand(0) << InvMaskID;
David Neto22f144c2017-06-12 14:26:21 -04004289
SJW01901d92020-05-21 08:58:31 -05004290 SPIRVID OrgValID = addSPIRVInst(spv::OpBitwiseAnd, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004291
4292 // Create correct value according to index of insertelement.
4293 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05004294 Ops << CompositeTy << I.getOperand(1) << ShiftAmountID;
David Neto22f144c2017-06-12 14:26:21 -04004295
SJW01901d92020-05-21 08:58:31 -05004296 SPIRVID InsertValID = addSPIRVInst(spv::OpShiftLeftLogical, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004297
4298 // Insert value to original value.
4299 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05004300 Ops << CompositeTy << OrgValID << InsertValID;
David Neto22f144c2017-06-12 14:26:21 -04004301
SJWf93f5f32020-05-05 07:27:56 -05004302 RID = addSPIRVInst(spv::OpBitwiseOr, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004303 break;
4304 }
4305
SJWf93f5f32020-05-05 07:27:56 -05004306 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004307
James Priced26efea2018-06-09 23:28:32 +01004308 // Ops[0] = Result Type ID
SJW01901d92020-05-21 08:58:31 -05004309 Ops << I.getType();
David Neto22f144c2017-06-12 14:26:21 -04004310
4311 spv::Op Opcode = spv::OpCompositeInsert;
4312 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
David Neto257c3892018-04-11 13:19:45 -04004313 const auto value = CI->getZExtValue();
4314 assert(value <= UINT32_MAX);
James Priced26efea2018-06-09 23:28:32 +01004315 // Ops[1] = Object ID
4316 // Ops[2] = Composite ID
4317 // Ops[3] ... Ops[n] = Indexes (Literal Number)
SJW01901d92020-05-21 08:58:31 -05004318 Ops << I.getOperand(1) << I.getOperand(0) << static_cast<uint32_t>(value);
David Neto22f144c2017-06-12 14:26:21 -04004319 } else {
James Priced26efea2018-06-09 23:28:32 +01004320 // Ops[1] = Composite ID
4321 // Ops[2] = Object ID
4322 // Ops[3] ... Ops[n] = Indexes (Literal Number)
SJW01901d92020-05-21 08:58:31 -05004323 Ops << I.getOperand(0) << I.getOperand(1) << I.getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04004324 Opcode = spv::OpVectorInsertDynamic;
4325 }
4326
SJWf93f5f32020-05-05 07:27:56 -05004327 RID = addSPIRVInst(Opcode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004328 break;
4329 }
4330 case Instruction::ShuffleVector: {
4331 // Ops[0] = Result Type ID
4332 // Ops[1] = Vector 1 ID
4333 // Ops[2] = Vector 2 ID
4334 // Ops[3] ... Ops[n] = Components (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05004335 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004336
SJW01901d92020-05-21 08:58:31 -05004337 Ops << I.getType() << I.getOperand(0) << I.getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04004338
alan-bakerc9666712020-04-01 16:31:21 -04004339 auto shuffle = cast<ShuffleVectorInst>(&I);
4340 SmallVector<int, 4> mask;
4341 shuffle->getShuffleMask(mask);
4342 for (auto i : mask) {
4343 if (i == UndefMaskElem) {
4344 if (clspv::Option::HackUndef())
4345 // Use 0 instead of undef.
SJW01901d92020-05-21 08:58:31 -05004346 Ops << 0;
alan-bakerc9666712020-04-01 16:31:21 -04004347 else
4348 // Undef for shuffle in SPIR-V.
SJW01901d92020-05-21 08:58:31 -05004349 Ops << 0xffffffff;
David Neto22f144c2017-06-12 14:26:21 -04004350 } else {
SJW01901d92020-05-21 08:58:31 -05004351 Ops << i;
David Neto22f144c2017-06-12 14:26:21 -04004352 }
4353 }
4354
SJWf93f5f32020-05-05 07:27:56 -05004355 RID = addSPIRVInst(spv::OpVectorShuffle, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004356 break;
4357 }
4358 case Instruction::ICmp:
4359 case Instruction::FCmp: {
4360 CmpInst *CmpI = cast<CmpInst>(&I);
4361
David Netod4ca2e62017-07-06 18:47:35 -04004362 // Pointer equality is invalid.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004363 Type *ArgTy = CmpI->getOperand(0)->getType();
David Netod4ca2e62017-07-06 18:47:35 -04004364 if (isa<PointerType>(ArgTy)) {
4365 CmpI->print(errs());
alan-baker21574d32020-01-29 16:00:31 -05004366 std::string name = I.getParent()->getParent()->getName().str();
David Netod4ca2e62017-07-06 18:47:35 -04004367 errs()
4368 << "\nPointer equality test is not supported by SPIR-V for Vulkan, "
4369 << "in function " << name << "\n";
4370 llvm_unreachable("Pointer equality check is invalid");
4371 break;
4372 }
4373
David Neto257c3892018-04-11 13:19:45 -04004374 // Ops[0] = Result Type ID
4375 // Ops[1] = Operand 1 ID
4376 // Ops[2] = Operand 2 ID
SJWf93f5f32020-05-05 07:27:56 -05004377 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004378
SJW01901d92020-05-21 08:58:31 -05004379 Ops << CmpI->getType() << CmpI->getOperand(0) << CmpI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04004380
4381 spv::Op Opcode = GetSPIRVCmpOpcode(CmpI);
SJWf93f5f32020-05-05 07:27:56 -05004382 RID = addSPIRVInst(Opcode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004383 break;
4384 }
4385 case Instruction::Br: {
SJW88ed5fe2020-05-11 12:40:57 -05004386 // Branch instruction is deferred because it needs label's ID.
4387 BasicBlock *BrBB = I.getParent();
4388 if (ContinueBlocks.count(BrBB) || MergeBlocks.count(BrBB)) {
4389 // Placeholder for Merge operation
4390 RID = addSPIRVPlaceholder(&I);
4391 }
4392 RID = addSPIRVPlaceholder(&I);
David Neto22f144c2017-06-12 14:26:21 -04004393 break;
4394 }
4395 case Instruction::Switch: {
4396 I.print(errs());
4397 llvm_unreachable("Unsupported instruction???");
4398 break;
4399 }
4400 case Instruction::IndirectBr: {
4401 I.print(errs());
4402 llvm_unreachable("Unsupported instruction???");
4403 break;
4404 }
4405 case Instruction::PHI: {
SJW88ed5fe2020-05-11 12:40:57 -05004406 // PHI instruction is deferred because it needs label's ID.
4407 RID = addSPIRVPlaceholder(&I);
David Neto22f144c2017-06-12 14:26:21 -04004408 break;
4409 }
4410 case Instruction::Alloca: {
4411 //
4412 // Generate OpVariable.
4413 //
4414 // Ops[0] : Result Type ID
4415 // Ops[1] : Storage Class
SJWf93f5f32020-05-05 07:27:56 -05004416 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004417
SJW01901d92020-05-21 08:58:31 -05004418 Ops << I.getType() << spv::StorageClassFunction;
David Neto22f144c2017-06-12 14:26:21 -04004419
SJWf93f5f32020-05-05 07:27:56 -05004420 RID = addSPIRVInst(spv::OpVariable, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004421 break;
4422 }
4423 case Instruction::Load: {
4424 LoadInst *LD = cast<LoadInst>(&I);
4425 //
4426 // Generate OpLoad.
4427 //
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04004428
alan-baker5b86ed72019-02-15 08:26:50 -05004429 if (LD->getType()->isPointerTy()) {
4430 // Loading a pointer requires variable pointers.
4431 setVariablePointersCapabilities(LD->getType()->getPointerAddressSpace());
4432 }
David Neto22f144c2017-06-12 14:26:21 -04004433
SJW01901d92020-05-21 08:58:31 -05004434 SPIRVID PointerID = getSPIRVValue(LD->getPointerOperand());
David Netoa60b00b2017-09-15 16:34:09 -04004435 // This is a hack to work around what looks like a driver bug.
4436 // When we're loading from the special variable holding the WorkgroupSize
David Neto0a2f98d2017-09-15 19:38:40 -04004437 // builtin value, use an OpBitWiseAnd of the value's ID rather than
4438 // generating a load.
David Neto66cfe642018-03-24 06:13:56 -07004439 // TODO(dneto): Remove this awful hack once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -04004440 if (PointerID == WorkgroupSizeVarID) {
David Neto0a2f98d2017-09-15 19:38:40 -04004441 // Generate a bitwise-and of the original value with itself.
4442 // We should have been able to get away with just an OpCopyObject,
4443 // but we need something more complex to get past certain driver bugs.
4444 // This is ridiculous, but necessary.
4445 // TODO(dneto): Revisit this once drivers fix their bugs.
4446
SJWf93f5f32020-05-05 07:27:56 -05004447 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05004448 Ops << LD->getType() << WorkgroupSizeValueID << WorkgroupSizeValueID;
David Neto0a2f98d2017-09-15 19:38:40 -04004449
SJWf93f5f32020-05-05 07:27:56 -05004450 RID = addSPIRVInst(spv::OpBitwiseAnd, Ops);
David Netoa60b00b2017-09-15 16:34:09 -04004451 break;
4452 }
4453
4454 // This is the normal path. Generate a load.
4455
David Neto22f144c2017-06-12 14:26:21 -04004456 // Ops[0] = Result Type ID
4457 // Ops[1] = Pointer ID
4458 // Ops[2] ... Ops[n] = Optional Memory Access
4459 //
4460 // TODO: Do we need to implement Optional Memory Access???
David Neto0a2f98d2017-09-15 19:38:40 -04004461
SJWf93f5f32020-05-05 07:27:56 -05004462 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05004463 Ops << LD->getType() << LD->getPointerOperand();
David Neto22f144c2017-06-12 14:26:21 -04004464
SJWf93f5f32020-05-05 07:27:56 -05004465 RID = addSPIRVInst(spv::OpLoad, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004466 break;
4467 }
4468 case Instruction::Store: {
4469 StoreInst *ST = cast<StoreInst>(&I);
4470 //
4471 // Generate OpStore.
4472 //
4473
alan-baker5b86ed72019-02-15 08:26:50 -05004474 if (ST->getValueOperand()->getType()->isPointerTy()) {
4475 // Storing a pointer requires variable pointers.
4476 setVariablePointersCapabilities(
4477 ST->getValueOperand()->getType()->getPointerAddressSpace());
4478 }
4479
David Neto22f144c2017-06-12 14:26:21 -04004480 // Ops[0] = Pointer ID
4481 // Ops[1] = Object ID
4482 // Ops[2] ... Ops[n] = Optional Memory Access (later???)
4483 //
4484 // TODO: Do we need to implement Optional Memory Access???
SJWf93f5f32020-05-05 07:27:56 -05004485 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05004486 Ops << ST->getPointerOperand() << ST->getValueOperand();
David Neto22f144c2017-06-12 14:26:21 -04004487
SJWf93f5f32020-05-05 07:27:56 -05004488 RID = addSPIRVInst(spv::OpStore, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004489 break;
4490 }
4491 case Instruction::AtomicCmpXchg: {
4492 I.print(errs());
4493 llvm_unreachable("Unsupported instruction???");
4494 break;
4495 }
4496 case Instruction::AtomicRMW: {
Neil Henning39672102017-09-29 14:33:13 +01004497 AtomicRMWInst *AtomicRMW = dyn_cast<AtomicRMWInst>(&I);
4498
4499 spv::Op opcode;
4500
4501 switch (AtomicRMW->getOperation()) {
4502 default:
4503 I.print(errs());
4504 llvm_unreachable("Unsupported instruction???");
4505 case llvm::AtomicRMWInst::Add:
4506 opcode = spv::OpAtomicIAdd;
4507 break;
4508 case llvm::AtomicRMWInst::Sub:
4509 opcode = spv::OpAtomicISub;
4510 break;
4511 case llvm::AtomicRMWInst::Xchg:
4512 opcode = spv::OpAtomicExchange;
4513 break;
4514 case llvm::AtomicRMWInst::Min:
4515 opcode = spv::OpAtomicSMin;
4516 break;
4517 case llvm::AtomicRMWInst::Max:
4518 opcode = spv::OpAtomicSMax;
4519 break;
4520 case llvm::AtomicRMWInst::UMin:
4521 opcode = spv::OpAtomicUMin;
4522 break;
4523 case llvm::AtomicRMWInst::UMax:
4524 opcode = spv::OpAtomicUMax;
4525 break;
4526 case llvm::AtomicRMWInst::And:
4527 opcode = spv::OpAtomicAnd;
4528 break;
4529 case llvm::AtomicRMWInst::Or:
4530 opcode = spv::OpAtomicOr;
4531 break;
4532 case llvm::AtomicRMWInst::Xor:
4533 opcode = spv::OpAtomicXor;
4534 break;
4535 }
4536
4537 //
4538 // Generate OpAtomic*.
4539 //
SJWf93f5f32020-05-05 07:27:56 -05004540 SPIRVOperandVec Ops;
Neil Henning39672102017-09-29 14:33:13 +01004541
SJW01901d92020-05-21 08:58:31 -05004542 Ops << I.getType() << AtomicRMW->getPointerOperand();
Neil Henning39672102017-09-29 14:33:13 +01004543
SJW806a5d82020-07-15 12:51:38 -05004544 const auto ConstantScopeDevice = getSPIRVInt32Constant(spv::ScopeDevice);
SJW01901d92020-05-21 08:58:31 -05004545 Ops << ConstantScopeDevice;
Neil Henning39672102017-09-29 14:33:13 +01004546
SJW806a5d82020-07-15 12:51:38 -05004547 const auto ConstantMemorySemantics =
4548 getSPIRVInt32Constant(spv::MemorySemanticsUniformMemoryMask |
4549 spv::MemorySemanticsSequentiallyConsistentMask);
SJW01901d92020-05-21 08:58:31 -05004550 Ops << ConstantMemorySemantics << AtomicRMW->getValOperand();
Neil Henning39672102017-09-29 14:33:13 +01004551
SJWf93f5f32020-05-05 07:27:56 -05004552 RID = addSPIRVInst(opcode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004553 break;
4554 }
4555 case Instruction::Fence: {
4556 I.print(errs());
4557 llvm_unreachable("Unsupported instruction???");
4558 break;
4559 }
4560 case Instruction::Call: {
4561 CallInst *Call = dyn_cast<CallInst>(&I);
SJW806a5d82020-07-15 12:51:38 -05004562 RID = GenerateInstructionFromCall(Call);
David Neto22f144c2017-06-12 14:26:21 -04004563 break;
4564 }
4565 case Instruction::Ret: {
4566 unsigned NumOps = I.getNumOperands();
4567 if (NumOps == 0) {
4568 //
4569 // Generate OpReturn.
4570 //
SJWf93f5f32020-05-05 07:27:56 -05004571 RID = addSPIRVInst(spv::OpReturn);
David Neto22f144c2017-06-12 14:26:21 -04004572 } else {
4573 //
4574 // Generate OpReturnValue.
4575 //
4576
4577 // Ops[0] = Return Value ID
SJWf93f5f32020-05-05 07:27:56 -05004578 SPIRVOperandVec Ops;
David Neto257c3892018-04-11 13:19:45 -04004579
SJW01901d92020-05-21 08:58:31 -05004580 Ops << I.getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04004581
SJWf93f5f32020-05-05 07:27:56 -05004582 RID = addSPIRVInst(spv::OpReturnValue, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004583 break;
4584 }
4585 break;
4586 }
4587 }
SJWf93f5f32020-05-05 07:27:56 -05004588
4589 // Register Instruction to ValueMap.
SJW01901d92020-05-21 08:58:31 -05004590 if (RID.isValid()) {
SJWf93f5f32020-05-05 07:27:56 -05004591 VMap[&I] = RID;
4592 }
David Neto22f144c2017-06-12 14:26:21 -04004593}
4594
4595void SPIRVProducerPass::GenerateFuncEpilogue() {
David Neto22f144c2017-06-12 14:26:21 -04004596
4597 //
4598 // Generate OpFunctionEnd
4599 //
SJWf93f5f32020-05-05 07:27:56 -05004600 addSPIRVInst(spv::OpFunctionEnd);
David Neto22f144c2017-06-12 14:26:21 -04004601}
4602
4603bool SPIRVProducerPass::is4xi8vec(Type *Ty) const {
alan-bakerb39c8262019-03-08 14:03:37 -05004604 // Don't specialize <4 x i8> if i8 is generally supported.
4605 if (clspv::Option::Int8Support())
4606 return false;
4607
David Neto22f144c2017-06-12 14:26:21 -04004608 LLVMContext &Context = Ty->getContext();
James Pricecf53df42020-04-20 14:41:24 -04004609 if (auto VecTy = dyn_cast<VectorType>(Ty)) {
4610 if (VecTy->getElementType() == Type::getInt8Ty(Context) &&
4611 VecTy->getNumElements() == 4) {
David Neto22f144c2017-06-12 14:26:21 -04004612 return true;
4613 }
4614 }
4615
4616 return false;
4617}
4618
4619void SPIRVProducerPass::HandleDeferredInstruction() {
David Neto22f144c2017-06-12 14:26:21 -04004620 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
4621
SJW88ed5fe2020-05-11 12:40:57 -05004622 for (size_t i = 0; i < DeferredInsts.size(); ++i) {
4623 Value *Inst = DeferredInsts[i].first;
4624 SPIRVInstruction *Placeholder = DeferredInsts[i].second;
4625 SPIRVOperandVec Operands;
4626
4627 auto nextDeferred = [&i, &Inst, &DeferredInsts, &Placeholder]() {
4628 ++i;
4629 assert(DeferredInsts.size() > i);
4630 assert(Inst == DeferredInsts[i].first);
4631 Placeholder = DeferredInsts[i].second;
4632 };
David Neto22f144c2017-06-12 14:26:21 -04004633
4634 if (BranchInst *Br = dyn_cast<BranchInst>(Inst)) {
alan-baker06cad652019-12-03 17:56:47 -05004635 // Check whether this branch needs to be preceeded by merge instruction.
David Neto22f144c2017-06-12 14:26:21 -04004636 BasicBlock *BrBB = Br->getParent();
alan-baker06cad652019-12-03 17:56:47 -05004637 if (ContinueBlocks.count(BrBB)) {
David Neto22f144c2017-06-12 14:26:21 -04004638 //
4639 // Generate OpLoopMerge.
4640 //
4641 // Ops[0] = Merge Block ID
4642 // Ops[1] = Continue Target ID
4643 // Ops[2] = Selection Control
SJWf93f5f32020-05-05 07:27:56 -05004644 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004645
SJW01901d92020-05-21 08:58:31 -05004646 Ops << MergeBlocks[BrBB] << ContinueBlocks[BrBB]
4647 << spv::LoopControlMaskNone;
David Neto22f144c2017-06-12 14:26:21 -04004648
SJW88ed5fe2020-05-11 12:40:57 -05004649 replaceSPIRVInst(Placeholder, spv::OpLoopMerge, Ops);
4650
4651 nextDeferred();
4652
alan-baker06cad652019-12-03 17:56:47 -05004653 } else if (MergeBlocks.count(BrBB)) {
4654 //
4655 // Generate OpSelectionMerge.
4656 //
4657 // Ops[0] = Merge Block ID
4658 // Ops[1] = Selection Control
SJWf93f5f32020-05-05 07:27:56 -05004659 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004660
alan-baker06cad652019-12-03 17:56:47 -05004661 auto MergeBB = MergeBlocks[BrBB];
SJW01901d92020-05-21 08:58:31 -05004662 Ops << MergeBB << spv::SelectionControlMaskNone;
David Neto22f144c2017-06-12 14:26:21 -04004663
SJW88ed5fe2020-05-11 12:40:57 -05004664 replaceSPIRVInst(Placeholder, spv::OpSelectionMerge, Ops);
4665
4666 nextDeferred();
David Neto22f144c2017-06-12 14:26:21 -04004667 }
4668
4669 if (Br->isConditional()) {
4670 //
4671 // Generate OpBranchConditional.
4672 //
4673 // Ops[0] = Condition ID
4674 // Ops[1] = True Label ID
4675 // Ops[2] = False Label ID
4676 // Ops[3] ... Ops[n] = Branch weights (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05004677 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004678
SJW01901d92020-05-21 08:58:31 -05004679 Ops << Br->getCondition() << Br->getSuccessor(0) << Br->getSuccessor(1);
David Neto22f144c2017-06-12 14:26:21 -04004680
SJW88ed5fe2020-05-11 12:40:57 -05004681 replaceSPIRVInst(Placeholder, spv::OpBranchConditional, Ops);
4682
David Neto22f144c2017-06-12 14:26:21 -04004683 } else {
4684 //
4685 // Generate OpBranch.
4686 //
4687 // Ops[0] = Target Label ID
SJWf93f5f32020-05-05 07:27:56 -05004688 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004689
SJW01901d92020-05-21 08:58:31 -05004690 Ops << Br->getSuccessor(0);
David Neto22f144c2017-06-12 14:26:21 -04004691
SJW88ed5fe2020-05-11 12:40:57 -05004692 replaceSPIRVInst(Placeholder, spv::OpBranch, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004693 }
4694 } else if (PHINode *PHI = dyn_cast<PHINode>(Inst)) {
alan-baker5ed87542020-03-23 11:05:22 -04004695 if (PHI->getType()->isPointerTy() && !IsSamplerType(PHI->getType()) &&
4696 !IsImageType(PHI->getType())) {
alan-baker5b86ed72019-02-15 08:26:50 -05004697 // OpPhi on pointers requires variable pointers.
4698 setVariablePointersCapabilities(
4699 PHI->getType()->getPointerAddressSpace());
4700 if (!hasVariablePointers() && !selectFromSameObject(PHI)) {
SJW01901d92020-05-21 08:58:31 -05004701 setVariablePointers();
alan-baker5b86ed72019-02-15 08:26:50 -05004702 }
4703 }
4704
David Neto22f144c2017-06-12 14:26:21 -04004705 //
4706 // Generate OpPhi.
4707 //
4708 // Ops[0] = Result Type ID
4709 // Ops[1] ... Ops[n] = (Variable ID, Parent ID) pairs
SJWf93f5f32020-05-05 07:27:56 -05004710 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004711
SJW01901d92020-05-21 08:58:31 -05004712 Ops << PHI->getType();
David Neto22f144c2017-06-12 14:26:21 -04004713
SJW88ed5fe2020-05-11 12:40:57 -05004714 for (unsigned j = 0; j < PHI->getNumIncomingValues(); j++) {
SJW01901d92020-05-21 08:58:31 -05004715 Ops << PHI->getIncomingValue(j) << PHI->getIncomingBlock(j);
David Neto22f144c2017-06-12 14:26:21 -04004716 }
4717
SJW88ed5fe2020-05-11 12:40:57 -05004718 replaceSPIRVInst(Placeholder, spv::OpPhi, Ops);
4719
David Neto22f144c2017-06-12 14:26:21 -04004720 } else if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
4721 Function *Callee = Call->getCalledFunction();
David Neto3fbb4072017-10-16 11:28:14 -04004722 auto callee_name = Callee->getName();
David Neto22f144c2017-06-12 14:26:21 -04004723
SJW61531372020-06-09 07:31:08 -05004724 if (Builtins::Lookup(Callee) == Builtins::kClspvCompositeConstruct) {
David Netoab03f432017-11-03 17:00:44 -04004725
4726 // Generate an OpCompositeConstruct
SJWf93f5f32020-05-05 07:27:56 -05004727 SPIRVOperandVec Ops;
David Netoab03f432017-11-03 17:00:44 -04004728
4729 // The result type.
SJW01901d92020-05-21 08:58:31 -05004730 Ops << Call->getType();
David Netoab03f432017-11-03 17:00:44 -04004731
4732 for (Use &use : Call->arg_operands()) {
SJW01901d92020-05-21 08:58:31 -05004733 Ops << use.get();
David Netoab03f432017-11-03 17:00:44 -04004734 }
4735
SJW88ed5fe2020-05-11 12:40:57 -05004736 replaceSPIRVInst(Placeholder, spv::OpCompositeConstruct, Ops);
David Netoab03f432017-11-03 17:00:44 -04004737
David Neto22f144c2017-06-12 14:26:21 -04004738 } else {
alan-baker5b86ed72019-02-15 08:26:50 -05004739 if (Call->getType()->isPointerTy()) {
4740 // Functions returning pointers require variable pointers.
4741 setVariablePointersCapabilities(
4742 Call->getType()->getPointerAddressSpace());
4743 }
4744
David Neto22f144c2017-06-12 14:26:21 -04004745 //
4746 // Generate OpFunctionCall.
4747 //
4748
4749 // Ops[0] = Result Type ID
4750 // Ops[1] = Callee Function ID
4751 // Ops[2] ... Ops[n] = Argument 0, ... , Argument n
SJWf93f5f32020-05-05 07:27:56 -05004752 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004753
SJW01901d92020-05-21 08:58:31 -05004754 Ops << Call->getType();
David Neto22f144c2017-06-12 14:26:21 -04004755
SJW01901d92020-05-21 08:58:31 -05004756 SPIRVID CalleeID = getSPIRVValue(Callee);
SJW806a5d82020-07-15 12:51:38 -05004757 if (!CalleeID.isValid()) {
David Neto43568eb2017-10-13 18:25:25 -04004758 errs() << "Can't translate function call. Missing builtin? "
David Neto862b7d82018-06-14 18:48:37 -04004759 << callee_name << " in: " << *Call << "\n";
David Neto43568eb2017-10-13 18:25:25 -04004760 // TODO(dneto): Can we error out? Enabling this llvm_unreachable
4761 // causes an infinite loop. Instead, go ahead and generate
4762 // the bad function call. A validator will catch the 0-Id.
4763 // llvm_unreachable("Can't translate function call");
4764 }
David Neto22f144c2017-06-12 14:26:21 -04004765
SJW01901d92020-05-21 08:58:31 -05004766 Ops << CalleeID;
David Neto22f144c2017-06-12 14:26:21 -04004767
David Neto22f144c2017-06-12 14:26:21 -04004768 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
SJW88ed5fe2020-05-11 12:40:57 -05004769 for (unsigned j = 0; j < CalleeFTy->getNumParams(); j++) {
4770 auto *operand = Call->getOperand(j);
alan-bakerd4d50652019-12-03 17:17:15 -05004771 auto *operand_type = operand->getType();
4772 // Images and samplers can be passed as function parameters without
4773 // variable pointers.
4774 if (operand_type->isPointerTy() && !IsImageType(operand_type) &&
4775 !IsSamplerType(operand_type)) {
alan-baker5b86ed72019-02-15 08:26:50 -05004776 auto sc =
4777 GetStorageClass(operand->getType()->getPointerAddressSpace());
4778 if (sc == spv::StorageClassStorageBuffer) {
4779 // Passing SSBO by reference requires variable pointers storage
4780 // buffer.
SJW01901d92020-05-21 08:58:31 -05004781 setVariablePointersStorageBuffer();
alan-baker5b86ed72019-02-15 08:26:50 -05004782 } else if (sc == spv::StorageClassWorkgroup) {
4783 // Workgroup references require variable pointers if they are not
4784 // memory object declarations.
4785 if (auto *operand_call = dyn_cast<CallInst>(operand)) {
4786 // Workgroup accessor represents a variable reference.
SJW61531372020-06-09 07:31:08 -05004787 if (Builtins::Lookup(operand_call->getCalledFunction()) !=
4788 Builtins::kClspvLocal)
SJW01901d92020-05-21 08:58:31 -05004789 setVariablePointers();
alan-baker5b86ed72019-02-15 08:26:50 -05004790 } else {
4791 // Arguments are function parameters.
4792 if (!isa<Argument>(operand))
SJW01901d92020-05-21 08:58:31 -05004793 setVariablePointers();
alan-baker5b86ed72019-02-15 08:26:50 -05004794 }
4795 }
4796 }
SJW01901d92020-05-21 08:58:31 -05004797 Ops << operand;
David Neto22f144c2017-06-12 14:26:21 -04004798 }
4799
SJW88ed5fe2020-05-11 12:40:57 -05004800 replaceSPIRVInst(Placeholder, spv::OpFunctionCall, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004801 }
4802 }
4803 }
4804}
4805
SJW77b87ad2020-04-21 14:37:52 -05004806void SPIRVProducerPass::HandleDeferredDecorations() {
4807 const auto &DL = module->getDataLayout();
Alan Baker202c8c72018-08-13 13:47:44 -04004808 if (getTypesNeedingArrayStride().empty() && LocalArgSpecIds.empty()) {
David Neto1a1a0582017-07-07 12:01:44 -04004809 return;
David Netoc6f3ab22018-04-06 18:02:31 -04004810 }
David Neto1a1a0582017-07-07 12:01:44 -04004811
David Netoc6f3ab22018-04-06 18:02:31 -04004812 // Insert ArrayStride decorations on pointer types, due to OpPtrAccessChain
4813 // instructions we generated earlier.
David Neto85082642018-03-24 06:55:20 -07004814 for (auto *type : getTypesNeedingArrayStride()) {
4815 Type *elemTy = nullptr;
4816 if (auto *ptrTy = dyn_cast<PointerType>(type)) {
4817 elemTy = ptrTy->getElementType();
alan-bakerb6b09dc2018-11-08 16:59:28 -05004818 } else if (auto *arrayTy = dyn_cast<ArrayType>(type)) {
alan-baker8eb435a2020-04-08 00:42:06 -04004819 elemTy = arrayTy->getElementType();
4820 } else if (auto *vecTy = dyn_cast<VectorType>(type)) {
4821 elemTy = vecTy->getElementType();
David Neto85082642018-03-24 06:55:20 -07004822 } else {
4823 errs() << "Unhandled strided type " << *type << "\n";
4824 llvm_unreachable("Unhandled strided type");
4825 }
David Neto1a1a0582017-07-07 12:01:44 -04004826
4827 // Ops[0] = Target ID
4828 // Ops[1] = Decoration (ArrayStride)
4829 // Ops[2] = Stride number (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05004830 SPIRVOperandVec Ops;
David Neto1a1a0582017-07-07 12:01:44 -04004831
David Neto85082642018-03-24 06:55:20 -07004832 // Same as DL.getIndexedOffsetInType( elemTy, { 1 } );
Alan Bakerfcda9482018-10-02 17:09:59 -04004833 const uint32_t stride = static_cast<uint32_t>(GetTypeAllocSize(elemTy, DL));
David Neto257c3892018-04-11 13:19:45 -04004834
SJW01901d92020-05-21 08:58:31 -05004835 Ops << type << spv::DecorationArrayStride << stride;
David Neto1a1a0582017-07-07 12:01:44 -04004836
SJWf93f5f32020-05-05 07:27:56 -05004837 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Netoc6f3ab22018-04-06 18:02:31 -04004838 }
David Neto1a1a0582017-07-07 12:01:44 -04004839}
4840
SJW61531372020-06-09 07:31:08 -05004841glsl::ExtInst
4842SPIRVProducerPass::getExtInstEnum(const Builtins::FunctionInfo &func_info) {
SJW2c317da2020-03-23 07:39:13 -05004843
SJW61531372020-06-09 07:31:08 -05004844 switch (func_info.getType()) {
SJW2c317da2020-03-23 07:39:13 -05004845 case Builtins::kClamp: {
SJW61531372020-06-09 07:31:08 -05004846 auto param_type = func_info.getParameter(0);
SJW2c317da2020-03-23 07:39:13 -05004847 if (param_type.type_id == Type::FloatTyID) {
4848 return glsl::ExtInst::ExtInstFClamp;
4849 }
4850 return param_type.is_signed ? glsl::ExtInst::ExtInstSClamp
4851 : glsl::ExtInst::ExtInstUClamp;
4852 }
4853 case Builtins::kMax: {
SJW61531372020-06-09 07:31:08 -05004854 auto param_type = func_info.getParameter(0);
SJW2c317da2020-03-23 07:39:13 -05004855 if (param_type.type_id == Type::FloatTyID) {
4856 return glsl::ExtInst::ExtInstFMax;
4857 }
4858 return param_type.is_signed ? glsl::ExtInst::ExtInstSMax
4859 : glsl::ExtInst::ExtInstUMax;
4860 }
4861 case Builtins::kMin: {
SJW61531372020-06-09 07:31:08 -05004862 auto param_type = func_info.getParameter(0);
SJW2c317da2020-03-23 07:39:13 -05004863 if (param_type.type_id == Type::FloatTyID) {
4864 return glsl::ExtInst::ExtInstFMin;
4865 }
4866 return param_type.is_signed ? glsl::ExtInst::ExtInstSMin
4867 : glsl::ExtInst::ExtInstUMin;
4868 }
4869 case Builtins::kAbs:
4870 return glsl::ExtInst::ExtInstSAbs;
4871 case Builtins::kFmax:
Marco Antognini55d51862020-07-21 17:50:07 +01004872 return glsl::ExtInst::ExtInstNMax;
SJW2c317da2020-03-23 07:39:13 -05004873 case Builtins::kFmin:
Marco Antognini55d51862020-07-21 17:50:07 +01004874 return glsl::ExtInst::ExtInstNMin;
SJW2c317da2020-03-23 07:39:13 -05004875 case Builtins::kDegrees:
4876 return glsl::ExtInst::ExtInstDegrees;
4877 case Builtins::kRadians:
4878 return glsl::ExtInst::ExtInstRadians;
4879 case Builtins::kMix:
4880 return glsl::ExtInst::ExtInstFMix;
4881 case Builtins::kAcos:
4882 case Builtins::kAcospi:
4883 return glsl::ExtInst::ExtInstAcos;
4884 case Builtins::kAcosh:
4885 return glsl::ExtInst::ExtInstAcosh;
4886 case Builtins::kAsin:
4887 case Builtins::kAsinpi:
4888 return glsl::ExtInst::ExtInstAsin;
4889 case Builtins::kAsinh:
4890 return glsl::ExtInst::ExtInstAsinh;
4891 case Builtins::kAtan:
4892 case Builtins::kAtanpi:
4893 return glsl::ExtInst::ExtInstAtan;
4894 case Builtins::kAtanh:
4895 return glsl::ExtInst::ExtInstAtanh;
4896 case Builtins::kAtan2:
4897 case Builtins::kAtan2pi:
4898 return glsl::ExtInst::ExtInstAtan2;
4899 case Builtins::kCeil:
4900 return glsl::ExtInst::ExtInstCeil;
4901 case Builtins::kSin:
4902 case Builtins::kHalfSin:
4903 case Builtins::kNativeSin:
4904 return glsl::ExtInst::ExtInstSin;
4905 case Builtins::kSinh:
4906 return glsl::ExtInst::ExtInstSinh;
4907 case Builtins::kCos:
4908 case Builtins::kHalfCos:
4909 case Builtins::kNativeCos:
4910 return glsl::ExtInst::ExtInstCos;
4911 case Builtins::kCosh:
4912 return glsl::ExtInst::ExtInstCosh;
4913 case Builtins::kTan:
4914 case Builtins::kHalfTan:
4915 case Builtins::kNativeTan:
4916 return glsl::ExtInst::ExtInstTan;
4917 case Builtins::kTanh:
4918 return glsl::ExtInst::ExtInstTanh;
4919 case Builtins::kExp:
4920 case Builtins::kHalfExp:
4921 case Builtins::kNativeExp:
4922 return glsl::ExtInst::ExtInstExp;
4923 case Builtins::kExp2:
4924 case Builtins::kHalfExp2:
4925 case Builtins::kNativeExp2:
4926 return glsl::ExtInst::ExtInstExp2;
4927 case Builtins::kLog:
4928 case Builtins::kHalfLog:
4929 case Builtins::kNativeLog:
4930 return glsl::ExtInst::ExtInstLog;
4931 case Builtins::kLog2:
4932 case Builtins::kHalfLog2:
4933 case Builtins::kNativeLog2:
4934 return glsl::ExtInst::ExtInstLog2;
4935 case Builtins::kFabs:
4936 return glsl::ExtInst::ExtInstFAbs;
4937 case Builtins::kFma:
4938 return glsl::ExtInst::ExtInstFma;
4939 case Builtins::kFloor:
4940 return glsl::ExtInst::ExtInstFloor;
4941 case Builtins::kLdexp:
4942 return glsl::ExtInst::ExtInstLdexp;
4943 case Builtins::kPow:
4944 case Builtins::kPowr:
4945 case Builtins::kHalfPowr:
4946 case Builtins::kNativePowr:
4947 return glsl::ExtInst::ExtInstPow;
4948 case Builtins::kRound:
4949 return glsl::ExtInst::ExtInstRound;
4950 case Builtins::kSqrt:
4951 case Builtins::kHalfSqrt:
4952 case Builtins::kNativeSqrt:
4953 return glsl::ExtInst::ExtInstSqrt;
4954 case Builtins::kRsqrt:
4955 case Builtins::kHalfRsqrt:
4956 case Builtins::kNativeRsqrt:
4957 return glsl::ExtInst::ExtInstInverseSqrt;
4958 case Builtins::kTrunc:
4959 return glsl::ExtInst::ExtInstTrunc;
4960 case Builtins::kFrexp:
4961 return glsl::ExtInst::ExtInstFrexp;
SJW61531372020-06-09 07:31:08 -05004962 case Builtins::kClspvFract:
SJW2c317da2020-03-23 07:39:13 -05004963 case Builtins::kFract:
4964 return glsl::ExtInst::ExtInstFract;
4965 case Builtins::kSign:
4966 return glsl::ExtInst::ExtInstFSign;
4967 case Builtins::kLength:
4968 case Builtins::kFastLength:
4969 return glsl::ExtInst::ExtInstLength;
4970 case Builtins::kDistance:
4971 case Builtins::kFastDistance:
4972 return glsl::ExtInst::ExtInstDistance;
4973 case Builtins::kStep:
4974 return glsl::ExtInst::ExtInstStep;
4975 case Builtins::kSmoothstep:
4976 return glsl::ExtInst::ExtInstSmoothStep;
4977 case Builtins::kCross:
4978 return glsl::ExtInst::ExtInstCross;
4979 case Builtins::kNormalize:
4980 case Builtins::kFastNormalize:
4981 return glsl::ExtInst::ExtInstNormalize;
SJW61531372020-06-09 07:31:08 -05004982 case Builtins::kSpirvPack:
4983 return glsl::ExtInst::ExtInstPackHalf2x16;
4984 case Builtins::kSpirvUnpack:
4985 return glsl::ExtInst::ExtInstUnpackHalf2x16;
SJW2c317da2020-03-23 07:39:13 -05004986 default:
4987 break;
4988 }
4989
SJW61531372020-06-09 07:31:08 -05004990 if (func_info.getName().find("llvm.fmuladd.") == 0) {
4991 return glsl::ExtInst::ExtInstFma;
4992 }
4993 return kGlslExtInstBad;
David Neto3fbb4072017-10-16 11:28:14 -04004994}
4995
SJW61531372020-06-09 07:31:08 -05004996glsl::ExtInst SPIRVProducerPass::getIndirectExtInstEnum(
4997 const Builtins::FunctionInfo &func_info) {
4998 switch (func_info.getType()) {
SJW2c317da2020-03-23 07:39:13 -05004999 case Builtins::kClz:
5000 return glsl::ExtInst::ExtInstFindUMsb;
5001 case Builtins::kAcospi:
5002 return glsl::ExtInst::ExtInstAcos;
5003 case Builtins::kAsinpi:
5004 return glsl::ExtInst::ExtInstAsin;
5005 case Builtins::kAtanpi:
5006 return glsl::ExtInst::ExtInstAtan;
5007 case Builtins::kAtan2pi:
5008 return glsl::ExtInst::ExtInstAtan2;
5009 default:
5010 break;
5011 }
5012 return kGlslExtInstBad;
David Neto3fbb4072017-10-16 11:28:14 -04005013}
5014
SJW61531372020-06-09 07:31:08 -05005015glsl::ExtInst SPIRVProducerPass::getDirectOrIndirectExtInstEnum(
5016 const Builtins::FunctionInfo &func_info) {
5017 auto direct = getExtInstEnum(func_info);
David Neto3fbb4072017-10-16 11:28:14 -04005018 if (direct != kGlslExtInstBad)
5019 return direct;
SJW61531372020-06-09 07:31:08 -05005020 return getIndirectExtInstEnum(func_info);
David Neto22f144c2017-06-12 14:26:21 -04005021}
5022
David Neto22f144c2017-06-12 14:26:21 -04005023void SPIRVProducerPass::WriteOneWord(uint32_t Word) {
David Neto0676e6f2017-07-11 18:47:44 -04005024 binaryOut->write(reinterpret_cast<const char *>(&Word), sizeof(uint32_t));
David Neto22f144c2017-06-12 14:26:21 -04005025}
5026
SJW88ed5fe2020-05-11 12:40:57 -05005027void SPIRVProducerPass::WriteResultID(const SPIRVInstruction &Inst) {
SJW01901d92020-05-21 08:58:31 -05005028 WriteOneWord(Inst.getResultID().get());
David Neto22f144c2017-06-12 14:26:21 -04005029}
5030
SJW88ed5fe2020-05-11 12:40:57 -05005031void SPIRVProducerPass::WriteWordCountAndOpcode(const SPIRVInstruction &Inst) {
David Neto22f144c2017-06-12 14:26:21 -04005032 // High 16 bit : Word Count
5033 // Low 16 bit : Opcode
SJW88ed5fe2020-05-11 12:40:57 -05005034 uint32_t Word = Inst.getOpcode();
5035 const uint32_t count = Inst.getWordCount();
David Netoee2660d2018-06-28 16:31:29 -04005036 if (count > 65535) {
5037 errs() << "Word count limit of 65535 exceeded: " << count << "\n";
5038 llvm_unreachable("Word count too high");
5039 }
SJW88ed5fe2020-05-11 12:40:57 -05005040 Word |= Inst.getWordCount() << 16;
David Neto22f144c2017-06-12 14:26:21 -04005041 WriteOneWord(Word);
5042}
5043
SJW88ed5fe2020-05-11 12:40:57 -05005044void SPIRVProducerPass::WriteOperand(const SPIRVOperand &Op) {
5045 SPIRVOperandType OpTy = Op.getType();
David Neto22f144c2017-06-12 14:26:21 -04005046 switch (OpTy) {
5047 default: {
5048 llvm_unreachable("Unsupported SPIRV Operand Type???");
5049 break;
5050 }
5051 case SPIRVOperandType::NUMBERID: {
SJW88ed5fe2020-05-11 12:40:57 -05005052 WriteOneWord(Op.getNumID());
David Neto22f144c2017-06-12 14:26:21 -04005053 break;
5054 }
5055 case SPIRVOperandType::LITERAL_STRING: {
SJW88ed5fe2020-05-11 12:40:57 -05005056 std::string Str = Op.getLiteralStr();
David Neto22f144c2017-06-12 14:26:21 -04005057 const char *Data = Str.c_str();
5058 size_t WordSize = Str.size() / 4;
5059 for (unsigned Idx = 0; Idx < WordSize; Idx++) {
5060 WriteOneWord(*reinterpret_cast<const uint32_t *>(&Data[4 * Idx]));
5061 }
5062
5063 uint32_t Remainder = Str.size() % 4;
5064 uint32_t LastWord = 0;
5065 if (Remainder) {
5066 for (unsigned Idx = 0; Idx < Remainder; Idx++) {
5067 LastWord |= Data[4 * WordSize + Idx] << 8 * Idx;
5068 }
5069 }
5070
5071 WriteOneWord(LastWord);
5072 break;
5073 }
SJW88ed5fe2020-05-11 12:40:57 -05005074 case SPIRVOperandType::LITERAL_WORD: {
5075 WriteOneWord(Op.getLiteralNum()[0]);
5076 break;
5077 }
5078 case SPIRVOperandType::LITERAL_DWORD: {
5079 WriteOneWord(Op.getLiteralNum()[0]);
5080 WriteOneWord(Op.getLiteralNum()[1]);
David Neto22f144c2017-06-12 14:26:21 -04005081 break;
5082 }
5083 }
5084}
5085
5086void SPIRVProducerPass::WriteSPIRVBinary() {
SJW69939d52020-04-16 07:29:07 -05005087 for (int i = 0; i < kSectionCount; ++i) {
5088 WriteSPIRVBinary(SPIRVSections[i]);
5089 }
5090}
5091
5092void SPIRVProducerPass::WriteSPIRVBinary(SPIRVInstructionList &SPIRVInstList) {
David Neto22f144c2017-06-12 14:26:21 -04005093
SJW88ed5fe2020-05-11 12:40:57 -05005094 for (const auto &Inst : SPIRVInstList) {
5095 const auto &Ops = Inst.getOperands();
5096 spv::Op Opcode = static_cast<spv::Op>(Inst.getOpcode());
David Neto22f144c2017-06-12 14:26:21 -04005097
5098 switch (Opcode) {
5099 default: {
David Neto5c22a252018-03-15 16:07:41 -04005100 errs() << "Unsupported SPIR-V instruction opcode " << int(Opcode) << "\n";
David Neto22f144c2017-06-12 14:26:21 -04005101 llvm_unreachable("Unsupported SPIRV instruction");
5102 break;
5103 }
5104 case spv::OpCapability:
5105 case spv::OpExtension:
5106 case spv::OpMemoryModel:
5107 case spv::OpEntryPoint:
5108 case spv::OpExecutionMode:
5109 case spv::OpSource:
5110 case spv::OpDecorate:
5111 case spv::OpMemberDecorate:
5112 case spv::OpBranch:
5113 case spv::OpBranchConditional:
5114 case spv::OpSelectionMerge:
5115 case spv::OpLoopMerge:
5116 case spv::OpStore:
5117 case spv::OpImageWrite:
5118 case spv::OpReturnValue:
5119 case spv::OpControlBarrier:
5120 case spv::OpMemoryBarrier:
5121 case spv::OpReturn:
5122 case spv::OpFunctionEnd:
5123 case spv::OpCopyMemory: {
5124 WriteWordCountAndOpcode(Inst);
5125 for (uint32_t i = 0; i < Ops.size(); i++) {
5126 WriteOperand(Ops[i]);
5127 }
5128 break;
5129 }
5130 case spv::OpTypeBool:
5131 case spv::OpTypeVoid:
5132 case spv::OpTypeSampler:
5133 case spv::OpLabel:
5134 case spv::OpExtInstImport:
5135 case spv::OpTypePointer:
5136 case spv::OpTypeRuntimeArray:
5137 case spv::OpTypeStruct:
5138 case spv::OpTypeImage:
5139 case spv::OpTypeSampledImage:
5140 case spv::OpTypeInt:
5141 case spv::OpTypeFloat:
5142 case spv::OpTypeArray:
5143 case spv::OpTypeVector:
5144 case spv::OpTypeFunction: {
5145 WriteWordCountAndOpcode(Inst);
5146 WriteResultID(Inst);
5147 for (uint32_t i = 0; i < Ops.size(); i++) {
5148 WriteOperand(Ops[i]);
5149 }
5150 break;
5151 }
5152 case spv::OpFunction:
5153 case spv::OpFunctionParameter:
5154 case spv::OpAccessChain:
5155 case spv::OpPtrAccessChain:
5156 case spv::OpInBoundsAccessChain:
5157 case spv::OpUConvert:
5158 case spv::OpSConvert:
5159 case spv::OpConvertFToU:
5160 case spv::OpConvertFToS:
5161 case spv::OpConvertUToF:
5162 case spv::OpConvertSToF:
5163 case spv::OpFConvert:
5164 case spv::OpConvertPtrToU:
5165 case spv::OpConvertUToPtr:
5166 case spv::OpBitcast:
alan-bakerc9c55ae2019-12-02 16:01:27 -05005167 case spv::OpFNegate:
David Neto22f144c2017-06-12 14:26:21 -04005168 case spv::OpIAdd:
5169 case spv::OpFAdd:
5170 case spv::OpISub:
5171 case spv::OpFSub:
5172 case spv::OpIMul:
5173 case spv::OpFMul:
5174 case spv::OpUDiv:
5175 case spv::OpSDiv:
5176 case spv::OpFDiv:
5177 case spv::OpUMod:
5178 case spv::OpSRem:
5179 case spv::OpFRem:
Kévin Petit8a560882019-03-21 15:24:34 +00005180 case spv::OpUMulExtended:
5181 case spv::OpSMulExtended:
David Neto22f144c2017-06-12 14:26:21 -04005182 case spv::OpBitwiseOr:
5183 case spv::OpBitwiseXor:
5184 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04005185 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04005186 case spv::OpShiftLeftLogical:
5187 case spv::OpShiftRightLogical:
5188 case spv::OpShiftRightArithmetic:
5189 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04005190 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04005191 case spv::OpCompositeExtract:
5192 case spv::OpVectorExtractDynamic:
5193 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04005194 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04005195 case spv::OpVectorInsertDynamic:
5196 case spv::OpVectorShuffle:
5197 case spv::OpIEqual:
5198 case spv::OpINotEqual:
5199 case spv::OpUGreaterThan:
5200 case spv::OpUGreaterThanEqual:
5201 case spv::OpULessThan:
5202 case spv::OpULessThanEqual:
5203 case spv::OpSGreaterThan:
5204 case spv::OpSGreaterThanEqual:
5205 case spv::OpSLessThan:
5206 case spv::OpSLessThanEqual:
5207 case spv::OpFOrdEqual:
5208 case spv::OpFOrdGreaterThan:
5209 case spv::OpFOrdGreaterThanEqual:
5210 case spv::OpFOrdLessThan:
5211 case spv::OpFOrdLessThanEqual:
5212 case spv::OpFOrdNotEqual:
5213 case spv::OpFUnordEqual:
5214 case spv::OpFUnordGreaterThan:
5215 case spv::OpFUnordGreaterThanEqual:
5216 case spv::OpFUnordLessThan:
5217 case spv::OpFUnordLessThanEqual:
5218 case spv::OpFUnordNotEqual:
5219 case spv::OpExtInst:
5220 case spv::OpIsInf:
5221 case spv::OpIsNan:
5222 case spv::OpAny:
5223 case spv::OpAll:
5224 case spv::OpUndef:
5225 case spv::OpConstantNull:
5226 case spv::OpLogicalOr:
5227 case spv::OpLogicalAnd:
5228 case spv::OpLogicalNot:
5229 case spv::OpLogicalNotEqual:
5230 case spv::OpConstantComposite:
5231 case spv::OpSpecConstantComposite:
5232 case spv::OpConstantTrue:
5233 case spv::OpConstantFalse:
5234 case spv::OpConstant:
5235 case spv::OpSpecConstant:
5236 case spv::OpVariable:
5237 case spv::OpFunctionCall:
5238 case spv::OpSampledImage:
alan-baker75090e42020-02-20 11:21:04 -05005239 case spv::OpImageFetch:
David Neto22f144c2017-06-12 14:26:21 -04005240 case spv::OpImageSampleExplicitLod:
David Neto5c22a252018-03-15 16:07:41 -04005241 case spv::OpImageQuerySize:
alan-bakerce179f12019-12-06 19:02:22 -05005242 case spv::OpImageQuerySizeLod:
David Neto22f144c2017-06-12 14:26:21 -04005243 case spv::OpSelect:
5244 case spv::OpPhi:
5245 case spv::OpLoad:
5246 case spv::OpAtomicIAdd:
5247 case spv::OpAtomicISub:
5248 case spv::OpAtomicExchange:
5249 case spv::OpAtomicIIncrement:
5250 case spv::OpAtomicIDecrement:
5251 case spv::OpAtomicCompareExchange:
5252 case spv::OpAtomicUMin:
5253 case spv::OpAtomicSMin:
5254 case spv::OpAtomicUMax:
5255 case spv::OpAtomicSMax:
5256 case spv::OpAtomicAnd:
5257 case spv::OpAtomicOr:
5258 case spv::OpAtomicXor:
SJW806a5d82020-07-15 12:51:38 -05005259 case spv::OpDot:
5260 case spv::OpGroupNonUniformAll:
5261 case spv::OpGroupNonUniformAny:
5262 case spv::OpGroupNonUniformBroadcast:
5263 case spv::OpGroupNonUniformIAdd:
5264 case spv::OpGroupNonUniformFAdd:
5265 case spv::OpGroupNonUniformSMin:
5266 case spv::OpGroupNonUniformUMin:
5267 case spv::OpGroupNonUniformFMin:
5268 case spv::OpGroupNonUniformSMax:
5269 case spv::OpGroupNonUniformUMax:
5270 case spv::OpGroupNonUniformFMax: {
David Neto22f144c2017-06-12 14:26:21 -04005271 WriteWordCountAndOpcode(Inst);
5272 WriteOperand(Ops[0]);
5273 WriteResultID(Inst);
5274 for (uint32_t i = 1; i < Ops.size(); i++) {
5275 WriteOperand(Ops[i]);
5276 }
5277 break;
5278 }
5279 }
5280 }
5281}
Alan Baker9bf93fb2018-08-28 16:59:26 -04005282
alan-bakerb6b09dc2018-11-08 16:59:28 -05005283bool SPIRVProducerPass::IsTypeNullable(const Type *type) const {
Alan Baker9bf93fb2018-08-28 16:59:26 -04005284 switch (type->getTypeID()) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05005285 case Type::HalfTyID:
5286 case Type::FloatTyID:
5287 case Type::DoubleTyID:
5288 case Type::IntegerTyID:
James Price59a1c752020-04-23 23:06:16 -04005289 case Type::FixedVectorTyID:
alan-bakerb6b09dc2018-11-08 16:59:28 -05005290 return true;
5291 case Type::PointerTyID: {
5292 const PointerType *pointer_type = cast<PointerType>(type);
5293 if (pointer_type->getPointerAddressSpace() !=
5294 AddressSpace::UniformConstant) {
5295 auto pointee_type = pointer_type->getPointerElementType();
5296 if (pointee_type->isStructTy() &&
5297 cast<StructType>(pointee_type)->isOpaque()) {
5298 // Images and samplers are not nullable.
5299 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04005300 }
Alan Baker9bf93fb2018-08-28 16:59:26 -04005301 }
alan-bakerb6b09dc2018-11-08 16:59:28 -05005302 return true;
5303 }
5304 case Type::ArrayTyID:
alan-baker8eb435a2020-04-08 00:42:06 -04005305 return IsTypeNullable(type->getArrayElementType());
alan-bakerb6b09dc2018-11-08 16:59:28 -05005306 case Type::StructTyID: {
5307 const StructType *struct_type = cast<StructType>(type);
5308 // Images and samplers are not nullable.
5309 if (struct_type->isOpaque())
Alan Baker9bf93fb2018-08-28 16:59:26 -04005310 return false;
alan-bakerb6b09dc2018-11-08 16:59:28 -05005311 for (const auto element : struct_type->elements()) {
5312 if (!IsTypeNullable(element))
5313 return false;
5314 }
5315 return true;
5316 }
5317 default:
5318 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04005319 }
5320}
Alan Bakerfcda9482018-10-02 17:09:59 -04005321
SJW77b87ad2020-04-21 14:37:52 -05005322void SPIRVProducerPass::PopulateUBOTypeMaps() {
Alan Bakerfcda9482018-10-02 17:09:59 -04005323 if (auto *offsets_md =
SJW77b87ad2020-04-21 14:37:52 -05005324 module->getNamedMetadata(clspv::RemappedTypeOffsetMetadataName())) {
Alan Bakerfcda9482018-10-02 17:09:59 -04005325 // Metdata is stored as key-value pair operands. The first element of each
5326 // operand is the type and the second is a vector of offsets.
5327 for (const auto *operand : offsets_md->operands()) {
5328 const auto *pair = cast<MDTuple>(operand);
5329 auto *type =
5330 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
5331 const auto *offset_vector = cast<MDTuple>(pair->getOperand(1));
5332 std::vector<uint32_t> offsets;
5333 for (const Metadata *offset_md : offset_vector->operands()) {
5334 const auto *constant_md = cast<ConstantAsMetadata>(offset_md);
alan-bakerb6b09dc2018-11-08 16:59:28 -05005335 offsets.push_back(static_cast<uint32_t>(
5336 cast<ConstantInt>(constant_md->getValue())->getZExtValue()));
Alan Bakerfcda9482018-10-02 17:09:59 -04005337 }
5338 RemappedUBOTypeOffsets.insert(std::make_pair(type, offsets));
5339 }
5340 }
5341
5342 if (auto *sizes_md =
SJW77b87ad2020-04-21 14:37:52 -05005343 module->getNamedMetadata(clspv::RemappedTypeSizesMetadataName())) {
Alan Bakerfcda9482018-10-02 17:09:59 -04005344 // Metadata is stored as key-value pair operands. The first element of each
5345 // operand is the type and the second is a triple of sizes: type size in
5346 // bits, store size and alloc size.
5347 for (const auto *operand : sizes_md->operands()) {
5348 const auto *pair = cast<MDTuple>(operand);
5349 auto *type =
5350 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
5351 const auto *size_triple = cast<MDTuple>(pair->getOperand(1));
5352 uint64_t type_size_in_bits =
5353 cast<ConstantInt>(
5354 cast<ConstantAsMetadata>(size_triple->getOperand(0))->getValue())
5355 ->getZExtValue();
5356 uint64_t type_store_size =
5357 cast<ConstantInt>(
5358 cast<ConstantAsMetadata>(size_triple->getOperand(1))->getValue())
5359 ->getZExtValue();
5360 uint64_t type_alloc_size =
5361 cast<ConstantInt>(
5362 cast<ConstantAsMetadata>(size_triple->getOperand(2))->getValue())
5363 ->getZExtValue();
5364 RemappedUBOTypeSizes.insert(std::make_pair(
5365 type, std::make_tuple(type_size_in_bits, type_store_size,
5366 type_alloc_size)));
5367 }
5368 }
5369}
5370
5371uint64_t SPIRVProducerPass::GetTypeSizeInBits(Type *type,
5372 const DataLayout &DL) {
5373 auto iter = RemappedUBOTypeSizes.find(type);
5374 if (iter != RemappedUBOTypeSizes.end()) {
5375 return std::get<0>(iter->second);
5376 }
5377
5378 return DL.getTypeSizeInBits(type);
5379}
5380
5381uint64_t SPIRVProducerPass::GetTypeStoreSize(Type *type, const DataLayout &DL) {
5382 auto iter = RemappedUBOTypeSizes.find(type);
5383 if (iter != RemappedUBOTypeSizes.end()) {
5384 return std::get<1>(iter->second);
5385 }
5386
5387 return DL.getTypeStoreSize(type);
5388}
5389
5390uint64_t SPIRVProducerPass::GetTypeAllocSize(Type *type, const DataLayout &DL) {
5391 auto iter = RemappedUBOTypeSizes.find(type);
5392 if (iter != RemappedUBOTypeSizes.end()) {
5393 return std::get<2>(iter->second);
5394 }
5395
5396 return DL.getTypeAllocSize(type);
5397}
alan-baker5b86ed72019-02-15 08:26:50 -05005398
Kévin Petitbbbda972020-03-03 19:16:31 +00005399uint32_t SPIRVProducerPass::GetExplicitLayoutStructMemberOffset(
5400 StructType *type, unsigned member, const DataLayout &DL) {
5401 const auto StructLayout = DL.getStructLayout(type);
5402 // Search for the correct offsets if this type was remapped.
5403 std::vector<uint32_t> *offsets = nullptr;
5404 auto iter = RemappedUBOTypeOffsets.find(type);
5405 if (iter != RemappedUBOTypeOffsets.end()) {
5406 offsets = &iter->second;
5407 }
5408 auto ByteOffset =
5409 static_cast<uint32_t>(StructLayout->getElementOffset(member));
5410 if (offsets) {
5411 ByteOffset = (*offsets)[member];
5412 }
5413
5414 return ByteOffset;
5415}
5416
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04005417void SPIRVProducerPass::setVariablePointersCapabilities(
5418 unsigned address_space) {
alan-baker5b86ed72019-02-15 08:26:50 -05005419 if (GetStorageClass(address_space) == spv::StorageClassStorageBuffer) {
SJW01901d92020-05-21 08:58:31 -05005420 setVariablePointersStorageBuffer();
alan-baker5b86ed72019-02-15 08:26:50 -05005421 } else {
SJW01901d92020-05-21 08:58:31 -05005422 setVariablePointers();
alan-baker5b86ed72019-02-15 08:26:50 -05005423 }
5424}
5425
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04005426Value *SPIRVProducerPass::GetBasePointer(Value *v) {
alan-baker5b86ed72019-02-15 08:26:50 -05005427 if (auto *gep = dyn_cast<GetElementPtrInst>(v)) {
5428 return GetBasePointer(gep->getPointerOperand());
5429 }
5430
5431 // Conservatively return |v|.
5432 return v;
5433}
5434
5435bool SPIRVProducerPass::sameResource(Value *lhs, Value *rhs) const {
5436 if (auto *lhs_call = dyn_cast<CallInst>(lhs)) {
5437 if (auto *rhs_call = dyn_cast<CallInst>(rhs)) {
SJW61531372020-06-09 07:31:08 -05005438 auto lhs_func_info = Builtins::Lookup(lhs_call->getCalledFunction());
5439 auto rhs_func_info = Builtins::Lookup(rhs_call->getCalledFunction());
5440 if (lhs_func_info.getType() == Builtins::kClspvResource &&
5441 rhs_func_info.getType() == Builtins::kClspvResource) {
alan-baker5b86ed72019-02-15 08:26:50 -05005442 // For resource accessors, match descriptor set and binding.
5443 if (lhs_call->getOperand(0) == rhs_call->getOperand(0) &&
5444 lhs_call->getOperand(1) == rhs_call->getOperand(1))
5445 return true;
SJW61531372020-06-09 07:31:08 -05005446 } else if (lhs_func_info.getType() == Builtins::kClspvLocal &&
5447 rhs_func_info.getType() == Builtins::kClspvLocal) {
alan-baker5b86ed72019-02-15 08:26:50 -05005448 // For workgroup resources, match spec id.
5449 if (lhs_call->getOperand(0) == rhs_call->getOperand(0))
5450 return true;
5451 }
5452 }
5453 }
5454
5455 return false;
5456}
5457
5458bool SPIRVProducerPass::selectFromSameObject(Instruction *inst) {
5459 assert(inst->getType()->isPointerTy());
5460 assert(GetStorageClass(inst->getType()->getPointerAddressSpace()) ==
5461 spv::StorageClassStorageBuffer);
5462 const bool hack_undef = clspv::Option::HackUndef();
5463 if (auto *select = dyn_cast<SelectInst>(inst)) {
5464 auto *true_base = GetBasePointer(select->getTrueValue());
5465 auto *false_base = GetBasePointer(select->getFalseValue());
5466
5467 if (true_base == false_base)
5468 return true;
5469
5470 // If either the true or false operand is a null, then we satisfy the same
5471 // object constraint.
5472 if (auto *true_cst = dyn_cast<Constant>(true_base)) {
5473 if (true_cst->isNullValue() || (hack_undef && isa<UndefValue>(true_base)))
5474 return true;
5475 }
5476
5477 if (auto *false_cst = dyn_cast<Constant>(false_base)) {
5478 if (false_cst->isNullValue() ||
5479 (hack_undef && isa<UndefValue>(false_base)))
5480 return true;
5481 }
5482
5483 if (sameResource(true_base, false_base))
5484 return true;
5485 } else if (auto *phi = dyn_cast<PHINode>(inst)) {
5486 Value *value = nullptr;
5487 bool ok = true;
5488 for (unsigned i = 0; ok && i != phi->getNumIncomingValues(); ++i) {
5489 auto *base = GetBasePointer(phi->getIncomingValue(i));
5490 // Null values satisfy the constraint of selecting of selecting from the
5491 // same object.
5492 if (!value) {
5493 if (auto *cst = dyn_cast<Constant>(base)) {
5494 if (!cst->isNullValue() && !(hack_undef && isa<UndefValue>(base)))
5495 value = base;
5496 } else {
5497 value = base;
5498 }
5499 } else if (base != value) {
5500 if (auto *base_cst = dyn_cast<Constant>(base)) {
5501 if (base_cst->isNullValue() || (hack_undef && isa<UndefValue>(base)))
5502 continue;
5503 }
5504
5505 if (sameResource(value, base))
5506 continue;
5507
5508 // Values don't represent the same base.
5509 ok = false;
5510 }
5511 }
5512
5513 return ok;
5514 }
5515
5516 // Conservatively return false.
5517 return false;
5518}
alan-bakere9308012019-03-15 10:25:13 -04005519
5520bool SPIRVProducerPass::CalledWithCoherentResource(Argument &Arg) {
5521 if (!Arg.getType()->isPointerTy() ||
5522 Arg.getType()->getPointerAddressSpace() != clspv::AddressSpace::Global) {
5523 // Only SSBOs need to be annotated as coherent.
5524 return false;
5525 }
5526
5527 DenseSet<Value *> visited;
5528 std::vector<Value *> stack;
5529 for (auto *U : Arg.getParent()->users()) {
5530 if (auto *call = dyn_cast<CallInst>(U)) {
5531 stack.push_back(call->getOperand(Arg.getArgNo()));
5532 }
5533 }
5534
5535 while (!stack.empty()) {
5536 Value *v = stack.back();
5537 stack.pop_back();
5538
5539 if (!visited.insert(v).second)
5540 continue;
5541
5542 auto *resource_call = dyn_cast<CallInst>(v);
5543 if (resource_call &&
SJW61531372020-06-09 07:31:08 -05005544 Builtins::Lookup(resource_call->getCalledFunction()).getType() ==
5545 Builtins::kClspvResource) {
alan-bakere9308012019-03-15 10:25:13 -04005546 // If this is a resource accessor function, check if the coherent operand
5547 // is set.
5548 const auto coherent =
5549 unsigned(dyn_cast<ConstantInt>(resource_call->getArgOperand(5))
5550 ->getZExtValue());
5551 if (coherent == 1)
5552 return true;
5553 } else if (auto *arg = dyn_cast<Argument>(v)) {
5554 // If this is a function argument, trace through its callers.
alan-bakere98f3f92019-04-08 15:06:36 -04005555 for (auto U : arg->getParent()->users()) {
alan-bakere9308012019-03-15 10:25:13 -04005556 if (auto *call = dyn_cast<CallInst>(U)) {
5557 stack.push_back(call->getOperand(arg->getArgNo()));
5558 }
5559 }
5560 } else if (auto *user = dyn_cast<User>(v)) {
5561 // If this is a user, traverse all operands that could lead to resource
5562 // variables.
5563 for (unsigned i = 0; i != user->getNumOperands(); ++i) {
5564 Value *operand = user->getOperand(i);
5565 if (operand->getType()->isPointerTy() &&
5566 operand->getType()->getPointerAddressSpace() ==
5567 clspv::AddressSpace::Global) {
5568 stack.push_back(operand);
5569 }
5570 }
5571 }
5572 }
5573
5574 // No coherent resource variables encountered.
5575 return false;
5576}
alan-baker06cad652019-12-03 17:56:47 -05005577
SJW77b87ad2020-04-21 14:37:52 -05005578void SPIRVProducerPass::PopulateStructuredCFGMaps() {
alan-baker06cad652019-12-03 17:56:47 -05005579 // First, track loop merges and continues.
5580 DenseSet<BasicBlock *> LoopMergesAndContinues;
SJW77b87ad2020-04-21 14:37:52 -05005581 for (auto &F : *module) {
alan-baker06cad652019-12-03 17:56:47 -05005582 if (F.isDeclaration())
5583 continue;
5584
5585 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
5586 const LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>(F).getLoopInfo();
5587 std::deque<BasicBlock *> order;
5588 DenseSet<BasicBlock *> visited;
5589 clspv::ComputeStructuredOrder(&*F.begin(), &DT, LI, &order, &visited);
5590
5591 for (auto BB : order) {
5592 auto terminator = BB->getTerminator();
5593 auto branch = dyn_cast<BranchInst>(terminator);
5594 if (LI.isLoopHeader(BB)) {
5595 auto L = LI.getLoopFor(BB);
5596 BasicBlock *ContinueBB = nullptr;
5597 BasicBlock *MergeBB = nullptr;
5598
5599 MergeBB = L->getExitBlock();
5600 if (!MergeBB) {
5601 // StructurizeCFG pass converts CFG into triangle shape and the cfg
5602 // has regions with single entry/exit. As a result, loop should not
5603 // have multiple exits.
5604 llvm_unreachable("Loop has multiple exits???");
5605 }
5606
5607 if (L->isLoopLatch(BB)) {
5608 ContinueBB = BB;
5609 } else {
5610 // From SPIR-V spec 2.11, Continue Target must dominate that back-edge
5611 // block.
5612 BasicBlock *Header = L->getHeader();
5613 BasicBlock *Latch = L->getLoopLatch();
5614 for (auto *loop_block : L->blocks()) {
5615 if (loop_block == Header) {
5616 continue;
5617 }
5618
5619 // Check whether block dominates block with back-edge.
5620 // The loop latch is the single block with a back-edge. If it was
5621 // possible, StructurizeCFG made the loop conform to this
5622 // requirement, otherwise |Latch| is a nullptr.
5623 if (DT.dominates(loop_block, Latch)) {
5624 ContinueBB = loop_block;
5625 }
5626 }
5627
5628 if (!ContinueBB) {
5629 llvm_unreachable("Wrong continue block from loop");
5630 }
5631 }
5632
5633 // Record the continue and merge blocks.
5634 MergeBlocks[BB] = MergeBB;
5635 ContinueBlocks[BB] = ContinueBB;
5636 LoopMergesAndContinues.insert(MergeBB);
5637 LoopMergesAndContinues.insert(ContinueBB);
5638 } else if (branch && branch->isConditional()) {
5639 auto L = LI.getLoopFor(BB);
5640 bool HasBackedge = false;
5641 while (L && !HasBackedge) {
5642 if (L->isLoopLatch(BB)) {
5643 HasBackedge = true;
5644 }
5645 L = L->getParentLoop();
5646 }
5647
5648 if (!HasBackedge) {
5649 // Only need a merge if the branch doesn't include a loop break or
5650 // continue.
5651 auto true_bb = branch->getSuccessor(0);
5652 auto false_bb = branch->getSuccessor(1);
5653 if (!LoopMergesAndContinues.count(true_bb) &&
5654 !LoopMergesAndContinues.count(false_bb)) {
5655 // StructurizeCFG pass already manipulated CFG. Just use false block
5656 // of branch instruction as merge block.
5657 MergeBlocks[BB] = false_bb;
5658 }
5659 }
5660 }
5661 }
5662 }
5663}