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
68 const Id NoResult = 0;
71 const unsigned int BadValue = 0xFFFFFFFF;
72 const Decoration NoPrecision = (Decoration)BadValue;
73 const MemorySemanticsMask MemorySemanticsAllMemory = (MemorySemanticsMask)0x3FF;
76 // SPIR-V IR instruction.
81 Instruction(Id resultId, Id typeId, Op opCode) : resultId(resultId), typeId(typeId), opCode(opCode), block(nullptr) { }
82 explicit Instruction(Op opCode) : resultId(NoResult), typeId(NoType), opCode(opCode), block(nullptr) { }
83 virtual ~Instruction() {}
84 void addIdOperand(Id id) { operands.push_back(id); }
85 void addImmediateOperand(unsigned int immediate) { operands.push_back(immediate); }
86 void addStringOperand(const char* str)
90 char* wordString = (char*)&word;
91 char* wordPtr = wordString;
99 addImmediateOperand(word);
100 wordPtr = wordString;
105 // deal with partial last word
108 for (; charCount < 4; ++charCount)
110 addImmediateOperand(word);
113 void setBlock(Block* b) { block = b; }
114 Block* getBlock() const { return block; }
115 Op getOpCode() const { return opCode; }
116 int getNumOperands() const { return (int)operands.size(); }
117 Id getResultId() const { return resultId; }
118 Id getTypeId() const { return typeId; }
119 Id getIdOperand(int op) const { return operands[op]; }
120 unsigned int getImmediateOperand(int op) const { return operands[op]; }
121 const char* getStringOperand() const { return originalString.c_str(); }
123 // Write out the binary form.
124 void dump(std::vector<unsigned int>& out) const
126 // Compute the wordCount
127 unsigned int wordCount = 1;
132 wordCount += (unsigned int)operands.size();
134 // Write out the beginning of the instruction
135 out.push_back(((wordCount) << WordCountShift) | opCode);
137 out.push_back(typeId);
139 out.push_back(resultId);
141 // Write out the operands
142 for (int op = 0; op < (int)operands.size(); ++op)
143 out.push_back(operands[op]);
147 Instruction(const Instruction&);
151 std::vector<Id> operands;
152 std::string originalString; // could be optimized away; convenience for getting string operand
162 Block(Id id, Function& parent);
167 Id getId() { return instructions.front()->getResultId(); }
169 Function& getParent() const { return parent; }
170 void addInstruction(std::unique_ptr<Instruction> inst);
171 void addPredecessor(Block* pred) { predecessors.push_back(pred); pred->successors.push_back(this);}
172 void addLocalVariable(std::unique_ptr<Instruction> inst) { localVariables.push_back(std::move(inst)); }
173 const std::vector<Block*>& getPredecessors() const { return predecessors; }
174 const std::vector<Block*>& getSuccessors() const { return successors; }
175 void setUnreachable() { unreachable = true; }
176 bool isUnreachable() const { return unreachable; }
177 // Returns the block's merge instruction, if one exists (otherwise null).
178 const Instruction* getMergeInstruction() const {
179 if (instructions.size() < 2) return nullptr;
180 const Instruction* nextToLast = (instructions.cend() - 2)->get();
181 switch (nextToLast->getOpCode()) {
182 case OpSelectionMerge:
191 bool isTerminated() const
193 switch (instructions.back()->getOpCode()) {
195 case OpBranchConditional:
206 void dump(std::vector<unsigned int>& out) const
208 // skip the degenerate unreachable blocks
209 // TODO: code gen: skip all unreachable blocks (transitive closure)
210 // (but, until that's done safer to keep non-degenerate unreachable blocks, in case others depend on something)
211 if (unreachable && instructions.size() <= 2)
214 instructions[0]->dump(out);
215 for (int i = 0; i < (int)localVariables.size(); ++i)
216 localVariables[i]->dump(out);
217 for (int i = 1; i < (int)instructions.size(); ++i)
218 instructions[i]->dump(out);
223 Block& operator=(Block&);
225 // To enforce keeping parent and ownership in sync:
228 std::vector<std::unique_ptr<Instruction> > instructions;
229 std::vector<Block*> predecessors, successors;
230 std::vector<std::unique_ptr<Instruction> > localVariables;
233 // track whether this block is known to be uncreachable (not necessarily
234 // true for all unreachable blocks, but should be set at least
235 // for the extraneous ones introduced by the builder).
239 // Traverses the control-flow graph rooted at root in an order suited for
240 // readable code generation. Invokes callback at every node in the traversal
242 void inReadableOrder(Block* root, std::function<void(Block*)> callback);
245 // SPIR-V IR Function.
250 Function(Id id, Id resultType, Id functionType, Id firstParam, Module& parent);
253 for (int i = 0; i < (int)parameterInstructions.size(); ++i)
254 delete parameterInstructions[i];
256 for (int i = 0; i < (int)blocks.size(); ++i)
259 Id getId() const { return functionInstruction.getResultId(); }
260 Id getParamId(int p) { return parameterInstructions[p]->getResultId(); }
262 void addBlock(Block* block) { blocks.push_back(block); }
263 void removeBlock(Block* block)
265 auto found = find(blocks.begin(), blocks.end(), block);
266 assert(found != blocks.end());
271 Module& getParent() const { return parent; }
272 Block* getEntryBlock() const { return blocks.front(); }
273 Block* getLastBlock() const { return blocks.back(); }
274 void addLocalVariable(std::unique_ptr<Instruction> inst);
275 Id getReturnType() const { return functionInstruction.getTypeId(); }
276 void dump(std::vector<unsigned int>& out) const
279 functionInstruction.dump(out);
281 // OpFunctionParameter
282 for (int p = 0; p < (int)parameterInstructions.size(); ++p)
283 parameterInstructions[p]->dump(out);
286 inReadableOrder(blocks[0], [&out](const Block* b) { b->dump(out); });
287 Instruction end(0, 0, OpFunctionEnd);
292 Function(const Function&);
293 Function& operator=(Function&);
296 Instruction functionInstruction;
297 std::vector<Instruction*> parameterInstructions;
298 std::vector<Block*> blocks;
310 // TODO delete things
313 void addFunction(Function *fun) { functions.push_back(fun); }
315 void mapInstruction(Instruction *instruction)
317 spv::Id resultId = instruction->getResultId();
318 // map the instruction's result id
319 if (resultId >= idToInstruction.size())
320 idToInstruction.resize(resultId + 16);
321 idToInstruction[resultId] = instruction;
324 Instruction* getInstruction(Id id) const { return idToInstruction[id]; }
325 spv::Id getTypeId(Id resultId) const { return idToInstruction[resultId]->getTypeId(); }
326 StorageClass getStorageClass(Id typeId) const
328 assert(idToInstruction[typeId]->getOpCode() == spv::OpTypePointer);
329 return (StorageClass)idToInstruction[typeId]->getImmediateOperand(0);
332 void dump(std::vector<unsigned int>& out) const
334 for (int f = 0; f < (int)functions.size(); ++f)
335 functions[f]->dump(out);
339 Module(const Module&);
340 std::vector<Function*> functions;
342 // map from result id to instruction having that result id
343 std::vector<Instruction*> idToInstruction;
345 // map from a result id to its type id
349 // Implementation (it's here due to circular type definitions).
353 // - the OpFunction instruction
354 // - all the OpFunctionParameter instructions
355 __inline Function::Function(Id id, Id resultType, Id functionType, Id firstParamId, Module& parent)
356 : parent(parent), functionInstruction(id, resultType, OpFunction)
359 functionInstruction.addImmediateOperand(FunctionControlMaskNone);
360 functionInstruction.addIdOperand(functionType);
361 parent.mapInstruction(&functionInstruction);
362 parent.addFunction(this);
364 // OpFunctionParameter
365 Instruction* typeInst = parent.getInstruction(functionType);
366 int numParams = typeInst->getNumOperands() - 1;
367 for (int p = 0; p < numParams; ++p) {
368 Instruction* param = new Instruction(firstParamId + p, typeInst->getIdOperand(p + 1), OpFunctionParameter);
369 parent.mapInstruction(param);
370 parameterInstructions.push_back(param);
374 __inline void Function::addLocalVariable(std::unique_ptr<Instruction> inst)
376 Instruction* raw_instruction = inst.get();
377 blocks[0]->addLocalVariable(std::move(inst));
378 parent.mapInstruction(raw_instruction);
381 __inline Block::Block(Id id, Function& parent) : parent(parent), unreachable(false)
383 instructions.push_back(std::unique_ptr<Instruction>(new Instruction(id, NoType, OpLabel)));
384 instructions.back()->setBlock(this);
385 parent.getParent().mapInstruction(instructions.back().get());
388 __inline void Block::addInstruction(std::unique_ptr<Instruction> inst)
390 Instruction* raw_instruction = inst.get();
391 instructions.push_back(std::move(inst));
392 raw_instruction->setBlock(this);
393 if (raw_instruction->getResultId())
394 parent.getParent().mapInstruction(raw_instruction);
397 }; // end spv namespace