Implement inReadableOrder().
[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 //
36 // Author: John Kessenich, LunarG
37 //
38
39 // SPIRV-IR
40 //
41 // Simple in-memory representation (IR) of SPIRV.  Just for holding
42 // Each function's CFG of blocks.  Has this hierarchy:
43 //  - Module, which is a list of 
44 //    - Function, which is a list of 
45 //      - Block, which is a list of 
46 //        - Instruction
47 //
48
49 #pragma once
50 #ifndef spvIR_H
51 #define spvIR_H
52
53 #include "spirv.hpp"
54
55 #include <cassert>
56 #include <functional>
57 #include <iostream>
58 #include <memory>
59 #include <vector>
60
61 namespace spv {
62
63 class Function;
64 class Module;
65
66 const Id NoResult = 0;
67 const Id NoType = 0;
68
69 const unsigned int BadValue = 0xFFFFFFFF;
70 const Decoration NoPrecision = (Decoration)BadValue;
71 const MemorySemanticsMask MemorySemanticsAllMemory = (MemorySemanticsMask)0x3FF;
72
73 //
74 // SPIR-V IR instruction.
75 //
76
77 class Instruction {
78 public:
79     Instruction(Id resultId, Id typeId, Op opCode) : resultId(resultId), typeId(typeId), opCode(opCode) { }
80     explicit Instruction(Op opCode) : resultId(NoResult), typeId(NoType), opCode(opCode) { }
81     virtual ~Instruction() {}
82     void addIdOperand(Id id) { operands.push_back(id); }
83     void addImmediateOperand(unsigned int immediate) { operands.push_back(immediate); }
84     void addStringOperand(const char* str)
85     {
86         originalString = str;
87         unsigned int word;
88         char* wordString = (char*)&word;
89         char* wordPtr = wordString;
90         int charCount = 0;
91         char c;
92         do {
93             c = *(str++);
94             *(wordPtr++) = c;
95             ++charCount;
96             if (charCount == 4) {
97                 addImmediateOperand(word);
98                 wordPtr = wordString;
99                 charCount = 0;
100             }
101         } while (c != 0);
102
103         // deal with partial last word
104         if (charCount > 0) {
105             // pad with 0s
106             for (; charCount < 4; ++charCount)
107                 *(wordPtr++) = 0;
108             addImmediateOperand(word);
109         }
110     }
111     Op getOpCode() const { return opCode; }
112     int getNumOperands() const { return (int)operands.size(); }
113     Id getResultId() const { return resultId; }
114     Id getTypeId() const { return typeId; }
115     Id getIdOperand(int op) const { return operands[op]; }
116     unsigned int getImmediateOperand(int op) const { return operands[op]; }
117     const char* getStringOperand() const { return originalString.c_str(); }
118
119     // Write out the binary form.
120     void dump(std::vector<unsigned int>& out) const
121     {
122         // Compute the wordCount
123         unsigned int wordCount = 1;
124         if (typeId)
125             ++wordCount;
126         if (resultId)
127             ++wordCount;
128         wordCount += (unsigned int)operands.size();
129
130         // Write out the beginning of the instruction
131         out.push_back(((wordCount) << WordCountShift) | opCode);
132         if (typeId)
133             out.push_back(typeId);
134         if (resultId)
135             out.push_back(resultId);
136
137         // Write out the operands
138         for (int op = 0; op < (int)operands.size(); ++op)
139             out.push_back(operands[op]);
140     }
141
142 protected:
143     Instruction(const Instruction&);
144     Id resultId;
145     Id typeId;
146     Op opCode;
147     std::vector<Id> operands;
148     std::string originalString;        // could be optimized away; convenience for getting string operand
149 };
150
151 //
152 // SPIR-V IR block.
153 //
154
155 class Block {
156 public:
157     Block(Id id, Function& parent);
158     virtual ~Block()
159     {
160     }
161
162     Id getId() { return instructions.front()->getResultId(); }
163
164     Function& getParent() const { return parent; }
165     void addInstruction(std::unique_ptr<Instruction> inst);
166     void addPredecessor(Block* pred) { predecessors.push_back(pred); pred->successors.push_back(this);}
167     void addLocalVariable(std::unique_ptr<Instruction> inst) { localVariables.push_back(std::move(inst)); }
168     const std::vector<Block*> getPredecessors() const { return predecessors; }
169     const std::vector<Block*> getSuccessors() const { return successors; }
170     void setUnreachable() { unreachable = true; }
171     bool isUnreachable() const { return unreachable; }
172     // Returns the block's merge instruction, if one exists (otherwise null).
173     const Instruction* getMergeInstruction() const {
174         if (instructions.size() < 2) return nullptr;
175         const Instruction* nextToLast = *(instructions.cend() - 2);
176         switch (nextToLast->getOpCode()) {
177             case OpSelectionMerge:
178             case OpLoopMerge:
179                 return nextToLast;
180             default:
181                 return nullptr;
182         }
183         return nullptr;
184     }
185
186     bool isTerminated() const
187     {
188         switch (instructions.back()->getOpCode()) {
189         case OpBranch:
190         case OpBranchConditional:
191         case OpSwitch:
192         case OpKill:
193         case OpReturn:
194         case OpReturnValue:
195             return true;
196         default:
197             return false;
198         }
199     }
200
201     void dump(std::vector<unsigned int>& out) const
202     {
203         // skip the degenerate unreachable blocks
204         // TODO: code gen: skip all unreachable blocks (transitive closure)
205         //                 (but, until that's done safer to keep non-degenerate unreachable blocks, in case others depend on something)
206         if (unreachable && instructions.size() <= 2)
207             return;
208
209         instructions[0]->dump(out);
210         for (int i = 0; i < (int)localVariables.size(); ++i)
211             localVariables[i]->dump(out);
212         for (int i = 1; i < (int)instructions.size(); ++i)
213             instructions[i]->dump(out);
214     }
215
216 protected:
217     Block(const Block&);
218     Block& operator=(Block&);
219
220     // To enforce keeping parent and ownership in sync:
221     friend Function;
222
223     std::vector<std::unique_ptr<Instruction> > instructions;
224     std::vector<Block*> predecessors, successors;
225     std::vector<std::unique_ptr<Instruction> > localVariables;
226     Function& parent;
227
228     // track whether this block is known to be uncreachable (not necessarily 
229     // true for all unreachable blocks, but should be set at least
230     // for the extraneous ones introduced by the builder).
231     bool unreachable;
232 };
233
234 // Traverses the control-flow graph rooted at root in an order suited for
235 // readable code generation.  Invokes callback at every node in the traversal
236 // order.
237 void inReadableOrder(Block* root, std::function<void(Block*)> callback);
238
239 //
240 // SPIR-V IR Function.
241 //
242
243 class Function {
244 public:
245     Function(Id id, Id resultType, Id functionType, Id firstParam, Module& parent);
246     virtual ~Function()
247     {
248         for (int i = 0; i < (int)parameterInstructions.size(); ++i)
249             delete parameterInstructions[i];
250
251         for (int i = 0; i < (int)blocks.size(); ++i)
252             delete blocks[i];
253     }
254     Id getId() const { return functionInstruction.getResultId(); }
255     Id getParamId(int p) { return parameterInstructions[p]->getResultId(); }
256
257     void addBlock(Block* block) { blocks.push_back(block); }
258     void popBlock(Block*) { blocks.pop_back(); }
259
260     Module& getParent() const { return parent; }
261     Block* getEntryBlock() const { return blocks.front(); }
262     Block* getLastBlock() const { return blocks.back(); }
263     void addLocalVariable(std::unique_ptr<Instruction> inst);
264     Id getReturnType() const { return functionInstruction.getTypeId(); }
265     void dump(std::vector<unsigned int>& out) const
266     {
267         // OpFunction
268         functionInstruction.dump(out);
269
270         // OpFunctionParameter
271         for (int p = 0; p < (int)parameterInstructions.size(); ++p)
272             parameterInstructions[p]->dump(out);
273
274         // Blocks
275         inReadableOrder(blocks[0], [&out](const Block* b) { b->dump(out); });
276         Instruction end(0, 0, OpFunctionEnd);
277         end.dump(out);
278     }
279
280 protected:
281     Function(const Function&);
282     Function& operator=(Function&);
283
284     Module& parent;
285     Instruction functionInstruction;
286     std::vector<Instruction*> parameterInstructions;
287     std::vector<Block*> blocks;
288 };
289
290 //
291 // SPIR-V IR Module.
292 //
293
294 class Module {
295 public:
296     Module() {}
297     virtual ~Module()
298     {
299         // TODO delete things
300     }
301
302     void addFunction(Function *fun) { functions.push_back(fun); }
303
304     void mapInstruction(Instruction *instruction)
305     {
306         spv::Id resultId = instruction->getResultId();
307         // map the instruction's result id
308         if (resultId >= idToInstruction.size())
309             idToInstruction.resize(resultId + 16);
310         idToInstruction[resultId] = instruction;
311     }
312
313     Instruction* getInstruction(Id id) const { return idToInstruction[id]; }
314     spv::Id getTypeId(Id resultId) const { return idToInstruction[resultId]->getTypeId(); }
315     StorageClass getStorageClass(Id typeId) const
316     {
317         assert(idToInstruction[typeId]->getOpCode() == spv::OpTypePointer);
318         return (StorageClass)idToInstruction[typeId]->getImmediateOperand(0);
319     }
320
321     void dump(std::vector<unsigned int>& out) const
322     {
323         for (int f = 0; f < (int)functions.size(); ++f)
324             functions[f]->dump(out);
325     }
326
327 protected:
328     Module(const Module&);
329     std::vector<Function*> functions;
330
331     // map from result id to instruction having that result id
332     std::vector<Instruction*> idToInstruction;
333
334     // map from a result id to its type id
335 };
336
337 //
338 // Implementation (it's here due to circular type definitions).
339 //
340
341 // Add both
342 // - the OpFunction instruction
343 // - all the OpFunctionParameter instructions
344 __inline Function::Function(Id id, Id resultType, Id functionType, Id firstParamId, Module& parent)
345     : parent(parent), functionInstruction(id, resultType, OpFunction)
346 {
347     // OpFunction
348     functionInstruction.addImmediateOperand(FunctionControlMaskNone);
349     functionInstruction.addIdOperand(functionType);
350     parent.mapInstruction(&functionInstruction);
351     parent.addFunction(this);
352
353     // OpFunctionParameter
354     Instruction* typeInst = parent.getInstruction(functionType);
355     int numParams = typeInst->getNumOperands() - 1;
356     for (int p = 0; p < numParams; ++p) {
357         Instruction* param = new Instruction(firstParamId + p, typeInst->getIdOperand(p + 1), OpFunctionParameter);
358         parent.mapInstruction(param);
359         parameterInstructions.push_back(param);
360     }
361 }
362
363 __inline void Function::addLocalVariable(std::unique_ptr<Instruction> inst)
364 {
365     Instruction* raw_instruction = inst.get();
366     blocks[0]->addLocalVariable(std::move(inst));
367     parent.mapInstruction(raw_instruction);
368 }
369
370 __inline Block::Block(Id id, Function& parent) : parent(parent), unreachable(false)
371 {
372     instructions.push_back(std::unique_ptr<Instruction>(new Instruction(id, NoType, OpLabel)));
373 }
374
375 __inline void Block::addInstruction(std::unique_ptr<Instruction> inst)
376 {
377   Instruction* raw_instruction = inst.get();
378     instructions.push_back(std::move(inst));
379     if (raw_instruction->getResultId())
380         parent.getParent().mapInstruction(raw_instruction);
381 }
382
383 };  // end spv namespace
384
385 #endif // spvIR_H