Merge pull request #1465 from otakuto/remove-execute-permissions
[platform/upstream/glslang.git] / SPIRV / spvIR.h
1 //
2 // Copyright (C) 2014 LunarG, Inc.
3 //
4 // All rights reserved.
5 //
6 // Redistribution and use in source and binary forms, with or without
7 // modification, are permitted provided that the following conditions
8 // are met:
9 //
10 //    Redistributions of source code must retain the above copyright
11 //    notice, this list of conditions and the following disclaimer.
12 //
13 //    Redistributions in binary form must reproduce the above
14 //    copyright notice, this list of conditions and the following
15 //    disclaimer in the documentation and/or other materials provided
16 //    with the distribution.
17 //
18 //    Neither the name of 3Dlabs Inc. Ltd. nor the names of its
19 //    contributors may be used to endorse or promote products derived
20 //    from this software without specific prior written permission.
21 //
22 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
25 // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
26 // COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
27 // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
28 // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29 // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
30 // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
32 // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33 // POSSIBILITY OF SUCH DAMAGE.
34
35 // SPIRV-IR
36 //
37 // Simple in-memory representation (IR) of SPIRV.  Just for holding
38 // Each function's CFG of blocks.  Has this hierarchy:
39 //  - Module, which is a list of
40 //    - Function, which is a list of
41 //      - Block, which is a list of
42 //        - Instruction
43 //
44
45 #pragma once
46 #ifndef spvIR_H
47 #define spvIR_H
48
49 #include "spirv.hpp"
50
51 #include <algorithm>
52 #include <cassert>
53 #include <functional>
54 #include <iostream>
55 #include <memory>
56 #include <vector>
57
58 namespace spv {
59
60 class Block;
61 class Function;
62 class Module;
63
64 const Id NoResult = 0;
65 const Id NoType = 0;
66
67 const Decoration NoPrecision = DecorationMax;
68
69 #ifdef __GNUC__
70 #   define POTENTIALLY_UNUSED __attribute__((unused))
71 #else
72 #   define POTENTIALLY_UNUSED
73 #endif
74
75 POTENTIALLY_UNUSED
76 const MemorySemanticsMask MemorySemanticsAllMemory =
77                 (MemorySemanticsMask)(MemorySemanticsUniformMemoryMask |
78                                       MemorySemanticsWorkgroupMemoryMask |
79                                       MemorySemanticsAtomicCounterMemoryMask |
80                                       MemorySemanticsImageMemoryMask);
81
82 struct IdImmediate {
83     bool isId;      // true if word is an Id, false if word is an immediate
84     unsigned word;
85 };
86
87 //
88 // SPIR-V IR instruction.
89 //
90
91 class Instruction {
92 public:
93     Instruction(Id resultId, Id typeId, Op opCode) : resultId(resultId), typeId(typeId), opCode(opCode), block(nullptr) { }
94     explicit Instruction(Op opCode) : resultId(NoResult), typeId(NoType), opCode(opCode), block(nullptr) { }
95     virtual ~Instruction() {}
96     void addIdOperand(Id id) {
97         operands.push_back(id);
98         idOperand.push_back(true);
99     }
100     void addImmediateOperand(unsigned int immediate) {
101         operands.push_back(immediate);
102         idOperand.push_back(false);
103     }
104     void addStringOperand(const char* str)
105     {
106         unsigned int word;
107         char* wordString = (char*)&word;
108         char* wordPtr = wordString;
109         int charCount = 0;
110         char c;
111         do {
112             c = *(str++);
113             *(wordPtr++) = c;
114             ++charCount;
115             if (charCount == 4) {
116                 addImmediateOperand(word);
117                 wordPtr = wordString;
118                 charCount = 0;
119             }
120         } while (c != 0);
121
122         // deal with partial last word
123         if (charCount > 0) {
124             // pad with 0s
125             for (; charCount < 4; ++charCount)
126                 *(wordPtr++) = 0;
127             addImmediateOperand(word);
128         }
129     }
130     bool isIdOperand(int op) const { return idOperand[op]; }
131     void setBlock(Block* b) { block = b; }
132     Block* getBlock() const { return block; }
133     Op getOpCode() const { return opCode; }
134     int getNumOperands() const
135     {
136         assert(operands.size() == idOperand.size());
137         return (int)operands.size();
138     }
139     Id getResultId() const { return resultId; }
140     Id getTypeId() const { return typeId; }
141     Id getIdOperand(int op) const {
142         assert(idOperand[op]);
143         return operands[op];
144     }
145     unsigned int getImmediateOperand(int op) const {
146         assert(!idOperand[op]);
147         return operands[op];
148     }
149
150     // Write out the binary form.
151     void dump(std::vector<unsigned int>& out) const
152     {
153         // Compute the wordCount
154         unsigned int wordCount = 1;
155         if (typeId)
156             ++wordCount;
157         if (resultId)
158             ++wordCount;
159         wordCount += (unsigned int)operands.size();
160
161         // Write out the beginning of the instruction
162         out.push_back(((wordCount) << WordCountShift) | opCode);
163         if (typeId)
164             out.push_back(typeId);
165         if (resultId)
166             out.push_back(resultId);
167
168         // Write out the operands
169         for (int op = 0; op < (int)operands.size(); ++op)
170             out.push_back(operands[op]);
171     }
172
173 protected:
174     Instruction(const Instruction&);
175     Id resultId;
176     Id typeId;
177     Op opCode;
178     std::vector<Id> operands;     // operands, both <id> and immediates (both are unsigned int)
179     std::vector<bool> idOperand;  // true for operands that are <id>, false for immediates
180     Block* block;
181 };
182
183 //
184 // SPIR-V IR block.
185 //
186
187 class Block {
188 public:
189     Block(Id id, Function& parent);
190     virtual ~Block()
191     {
192     }
193
194     Id getId() { return instructions.front()->getResultId(); }
195
196     Function& getParent() const { return parent; }
197     void addInstruction(std::unique_ptr<Instruction> inst);
198     void addPredecessor(Block* pred) { predecessors.push_back(pred); pred->successors.push_back(this);}
199     void addLocalVariable(std::unique_ptr<Instruction> inst) { localVariables.push_back(std::move(inst)); }
200     const std::vector<Block*>& getPredecessors() const { return predecessors; }
201     const std::vector<Block*>& getSuccessors() const { return successors; }
202     const std::vector<std::unique_ptr<Instruction> >& getInstructions() const {
203         return instructions;
204     }
205     void setUnreachable() { unreachable = true; }
206     bool isUnreachable() const { return unreachable; }
207     // Returns the block's merge instruction, if one exists (otherwise null).
208     const Instruction* getMergeInstruction() const {
209         if (instructions.size() < 2) return nullptr;
210         const Instruction* nextToLast = (instructions.cend() - 2)->get();
211         switch (nextToLast->getOpCode()) {
212             case OpSelectionMerge:
213             case OpLoopMerge:
214                 return nextToLast;
215             default:
216                 return nullptr;
217         }
218         return nullptr;
219     }
220
221     bool isTerminated() const
222     {
223         switch (instructions.back()->getOpCode()) {
224         case OpBranch:
225         case OpBranchConditional:
226         case OpSwitch:
227         case OpKill:
228         case OpReturn:
229         case OpReturnValue:
230             return true;
231         default:
232             return false;
233         }
234     }
235
236     void dump(std::vector<unsigned int>& out) const
237     {
238         instructions[0]->dump(out);
239         for (int i = 0; i < (int)localVariables.size(); ++i)
240             localVariables[i]->dump(out);
241         for (int i = 1; i < (int)instructions.size(); ++i)
242             instructions[i]->dump(out);
243     }
244
245 protected:
246     Block(const Block&);
247     Block& operator=(Block&);
248
249     // To enforce keeping parent and ownership in sync:
250     friend Function;
251
252     std::vector<std::unique_ptr<Instruction> > instructions;
253     std::vector<Block*> predecessors, successors;
254     std::vector<std::unique_ptr<Instruction> > localVariables;
255     Function& parent;
256
257     // track whether this block is known to be uncreachable (not necessarily
258     // true for all unreachable blocks, but should be set at least
259     // for the extraneous ones introduced by the builder).
260     bool unreachable;
261 };
262
263 // Traverses the control-flow graph rooted at root in an order suited for
264 // readable code generation.  Invokes callback at every node in the traversal
265 // order.
266 void inReadableOrder(Block* root, std::function<void(Block*)> callback);
267
268 //
269 // SPIR-V IR Function.
270 //
271
272 class Function {
273 public:
274     Function(Id id, Id resultType, Id functionType, Id firstParam, Module& parent);
275     virtual ~Function()
276     {
277         for (int i = 0; i < (int)parameterInstructions.size(); ++i)
278             delete parameterInstructions[i];
279
280         for (int i = 0; i < (int)blocks.size(); ++i)
281             delete blocks[i];
282     }
283     Id getId() const { return functionInstruction.getResultId(); }
284     Id getParamId(int p) const { return parameterInstructions[p]->getResultId(); }
285     Id getParamType(int p) const { return parameterInstructions[p]->getTypeId(); }
286
287     void addBlock(Block* block) { blocks.push_back(block); }
288     void removeBlock(Block* block)
289     {
290         auto found = find(blocks.begin(), blocks.end(), block);
291         assert(found != blocks.end());
292         blocks.erase(found);
293         delete block;
294     }
295
296     Module& getParent() const { return parent; }
297     Block* getEntryBlock() const { return blocks.front(); }
298     Block* getLastBlock() const { return blocks.back(); }
299     const std::vector<Block*>& getBlocks() const { return blocks; }
300     void addLocalVariable(std::unique_ptr<Instruction> inst);
301     Id getReturnType() const { return functionInstruction.getTypeId(); }
302
303     void setImplicitThis() { implicitThis = true; }
304     bool hasImplicitThis() const { return implicitThis; }
305
306     void dump(std::vector<unsigned int>& out) const
307     {
308         // OpFunction
309         functionInstruction.dump(out);
310
311         // OpFunctionParameter
312         for (int p = 0; p < (int)parameterInstructions.size(); ++p)
313             parameterInstructions[p]->dump(out);
314
315         // Blocks
316         inReadableOrder(blocks[0], [&out](const Block* b) { b->dump(out); });
317         Instruction end(0, 0, OpFunctionEnd);
318         end.dump(out);
319     }
320
321 protected:
322     Function(const Function&);
323     Function& operator=(Function&);
324
325     Module& parent;
326     Instruction functionInstruction;
327     std::vector<Instruction*> parameterInstructions;
328     std::vector<Block*> blocks;
329     bool implicitThis;  // true if this is a member function expecting to be passed a 'this' as the first argument
330 };
331
332 //
333 // SPIR-V IR Module.
334 //
335
336 class Module {
337 public:
338     Module() {}
339     virtual ~Module()
340     {
341         // TODO delete things
342     }
343
344     void addFunction(Function *fun) { functions.push_back(fun); }
345
346     void mapInstruction(Instruction *instruction)
347     {
348         spv::Id resultId = instruction->getResultId();
349         // map the instruction's result id
350         if (resultId >= idToInstruction.size())
351             idToInstruction.resize(resultId + 16);
352         idToInstruction[resultId] = instruction;
353     }
354
355     Instruction* getInstruction(Id id) const { return idToInstruction[id]; }
356     const std::vector<Function*>& getFunctions() const { return functions; }
357     spv::Id getTypeId(Id resultId) const {
358         return idToInstruction[resultId] == nullptr ? NoType : idToInstruction[resultId]->getTypeId();
359     }
360     StorageClass getStorageClass(Id typeId) const
361     {
362         assert(idToInstruction[typeId]->getOpCode() == spv::OpTypePointer);
363         return (StorageClass)idToInstruction[typeId]->getImmediateOperand(0);
364     }
365
366     void dump(std::vector<unsigned int>& out) const
367     {
368         for (int f = 0; f < (int)functions.size(); ++f)
369             functions[f]->dump(out);
370     }
371
372 protected:
373     Module(const Module&);
374     std::vector<Function*> functions;
375
376     // map from result id to instruction having that result id
377     std::vector<Instruction*> idToInstruction;
378
379     // map from a result id to its type id
380 };
381
382 //
383 // Implementation (it's here due to circular type definitions).
384 //
385
386 // Add both
387 // - the OpFunction instruction
388 // - all the OpFunctionParameter instructions
389 __inline Function::Function(Id id, Id resultType, Id functionType, Id firstParamId, Module& parent)
390     : parent(parent), functionInstruction(id, resultType, OpFunction), implicitThis(false)
391 {
392     // OpFunction
393     functionInstruction.addImmediateOperand(FunctionControlMaskNone);
394     functionInstruction.addIdOperand(functionType);
395     parent.mapInstruction(&functionInstruction);
396     parent.addFunction(this);
397
398     // OpFunctionParameter
399     Instruction* typeInst = parent.getInstruction(functionType);
400     int numParams = typeInst->getNumOperands() - 1;
401     for (int p = 0; p < numParams; ++p) {
402         Instruction* param = new Instruction(firstParamId + p, typeInst->getIdOperand(p + 1), OpFunctionParameter);
403         parent.mapInstruction(param);
404         parameterInstructions.push_back(param);
405     }
406 }
407
408 __inline void Function::addLocalVariable(std::unique_ptr<Instruction> inst)
409 {
410     Instruction* raw_instruction = inst.get();
411     blocks[0]->addLocalVariable(std::move(inst));
412     parent.mapInstruction(raw_instruction);
413 }
414
415 __inline Block::Block(Id id, Function& parent) : parent(parent), unreachable(false)
416 {
417     instructions.push_back(std::unique_ptr<Instruction>(new Instruction(id, NoType, OpLabel)));
418     instructions.back()->setBlock(this);
419     parent.getParent().mapInstruction(instructions.back().get());
420 }
421
422 __inline void Block::addInstruction(std::unique_ptr<Instruction> inst)
423 {
424     Instruction* raw_instruction = inst.get();
425     instructions.push_back(std::move(inst));
426     raw_instruction->setBlock(this);
427     if (raw_instruction->getResultId())
428         parent.getParent().mapInstruction(raw_instruction);
429 }
430
431 };  // end spv namespace
432
433 #endif // spvIR_H