2 //Copyright (C) 2014 LunarG, Inc.
6 //Redistribution and use in source and binary forms, with or without
7 //modification, are permitted provided that the following conditions
10 // Redistributions of source code must retain the above copyright
11 // notice, this list of conditions and the following disclaimer.
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.
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.
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.
36 // Author: John Kessenich, LunarG
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
66 const Id NoResult = 0;
69 const unsigned int BadValue = 0xFFFFFFFF;
70 const Decoration NoPrecision = (Decoration)BadValue;
71 const MemorySemanticsMask MemorySemanticsAllMemory = (MemorySemanticsMask)0x3FF;
74 // SPIR-V IR instruction.
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)
88 char* wordString = (char*)&word;
89 char* wordPtr = wordString;
97 addImmediateOperand(word);
103 // deal with partial last word
106 for (; charCount < 4; ++charCount)
108 addImmediateOperand(word);
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(); }
119 // Write out the binary form.
120 void dump(std::vector<unsigned int>& out) const
122 // Compute the wordCount
123 unsigned int wordCount = 1;
128 wordCount += (unsigned int)operands.size();
130 // Write out the beginning of the instruction
131 out.push_back(((wordCount) << WordCountShift) | opCode);
133 out.push_back(typeId);
135 out.push_back(resultId);
137 // Write out the operands
138 for (int op = 0; op < (int)operands.size(); ++op)
139 out.push_back(operands[op]);
143 Instruction(const Instruction&);
147 std::vector<Id> operands;
148 std::string originalString; // could be optimized away; convenience for getting string operand
157 Block(Id id, Function& parent);
162 Id getId() { return instructions.front()->getResultId(); }
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:
186 bool isTerminated() const
188 switch (instructions.back()->getOpCode()) {
190 case OpBranchConditional:
201 void dump(std::vector<unsigned int>& out) const
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)
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);
218 Block& operator=(Block&);
220 // To enforce keeping parent and ownership in sync:
223 std::vector<std::unique_ptr<Instruction> > instructions;
224 std::vector<Block*> predecessors, successors;
225 std::vector<std::unique_ptr<Instruction> > localVariables;
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).
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
237 void inReadableOrder(Block* root, std::function<void(Block*)> callback);
240 // SPIR-V IR Function.
245 Function(Id id, Id resultType, Id functionType, Id firstParam, Module& parent);
248 for (int i = 0; i < (int)parameterInstructions.size(); ++i)
249 delete parameterInstructions[i];
251 for (int i = 0; i < (int)blocks.size(); ++i)
254 Id getId() const { return functionInstruction.getResultId(); }
255 Id getParamId(int p) { return parameterInstructions[p]->getResultId(); }
257 void addBlock(Block* block) { blocks.push_back(block); }
258 void popBlock(Block*) { blocks.pop_back(); }
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
268 functionInstruction.dump(out);
270 // OpFunctionParameter
271 for (int p = 0; p < (int)parameterInstructions.size(); ++p)
272 parameterInstructions[p]->dump(out);
275 inReadableOrder(blocks[0], [&out](const Block* b) { b->dump(out); });
276 Instruction end(0, 0, OpFunctionEnd);
281 Function(const Function&);
282 Function& operator=(Function&);
285 Instruction functionInstruction;
286 std::vector<Instruction*> parameterInstructions;
287 std::vector<Block*> blocks;
299 // TODO delete things
302 void addFunction(Function *fun) { functions.push_back(fun); }
304 void mapInstruction(Instruction *instruction)
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;
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
317 assert(idToInstruction[typeId]->getOpCode() == spv::OpTypePointer);
318 return (StorageClass)idToInstruction[typeId]->getImmediateOperand(0);
321 void dump(std::vector<unsigned int>& out) const
323 for (int f = 0; f < (int)functions.size(); ++f)
324 functions[f]->dump(out);
328 Module(const Module&);
329 std::vector<Function*> functions;
331 // map from result id to instruction having that result id
332 std::vector<Instruction*> idToInstruction;
334 // map from a result id to its type id
338 // Implementation (it's here due to circular type definitions).
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)
348 functionInstruction.addImmediateOperand(FunctionControlMaskNone);
349 functionInstruction.addIdOperand(functionType);
350 parent.mapInstruction(&functionInstruction);
351 parent.addFunction(this);
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);
363 __inline void Function::addLocalVariable(std::unique_ptr<Instruction> inst)
365 Instruction* raw_instruction = inst.get();
366 blocks[0]->addLocalVariable(std::move(inst));
367 parent.mapInstruction(raw_instruction);
370 __inline Block::Block(Id id, Function& parent) : parent(parent), unreachable(false)
372 instructions.push_back(std::unique_ptr<Instruction>(new Instruction(id, NoType, OpLabel)));
375 __inline void Block::addInstruction(std::unique_ptr<Instruction> inst)
377 Instruction* raw_instruction = inst.get();
378 instructions.push_back(std::move(inst));
379 if (raw_instruction->getResultId())
380 parent.getParent().mapInstruction(raw_instruction);
383 }; // end spv namespace