2 // Copyright (C) 2014 LunarG, Inc.
3 // Copyright (C) 2015-2018 Google, Inc.
5 // All rights reserved.
7 // Redistribution and use in source and binary forms, with or without
8 // modification, are permitted provided that the following conditions
11 // Redistributions of source code must retain the above copyright
12 // notice, this list of conditions and the following disclaimer.
14 // Redistributions in binary form must reproduce the above
15 // copyright notice, this list of conditions and the following
16 // disclaimer in the documentation and/or other materials provided
17 // with the distribution.
19 // Neither the name of 3Dlabs Inc. Ltd. nor the names of its
20 // contributors may be used to endorse or promote products derived
21 // from this software without specific prior written permission.
23 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26 // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27 // COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28 // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29 // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30 // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31 // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33 // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34 // POSSIBILITY OF SUCH DAMAGE.
38 // Simple in-memory representation (IR) of SPIRV. Just for holding
39 // Each function's CFG of blocks. Has this hierarchy:
40 // - Module, which is a list of
41 // - Function, which is a list of
42 // - Block, which is a list of
66 const Id NoResult = 0;
69 const Decoration NoPrecision = DecorationMax;
72 # define POTENTIALLY_UNUSED __attribute__((unused))
74 # define POTENTIALLY_UNUSED
78 const MemorySemanticsMask MemorySemanticsAllMemory =
79 (MemorySemanticsMask)(MemorySemanticsUniformMemoryMask |
80 MemorySemanticsWorkgroupMemoryMask |
81 MemorySemanticsAtomicCounterMemoryMask |
82 MemorySemanticsImageMemoryMask);
85 bool isId; // true if word is an Id, false if word is an immediate
87 IdImmediate(bool i, unsigned w) : isId(i), word(w) {}
91 // SPIR-V IR instruction.
96 Instruction(Id resultId, Id typeId, Op opCode) : resultId(resultId), typeId(typeId), opCode(opCode), block(nullptr) { }
97 explicit Instruction(Op opCode) : resultId(NoResult), typeId(NoType), opCode(opCode), block(nullptr) { }
98 virtual ~Instruction() {}
99 void addIdOperand(Id id) {
100 operands.push_back(id);
101 idOperand.push_back(true);
103 void addImmediateOperand(unsigned int immediate) {
104 operands.push_back(immediate);
105 idOperand.push_back(false);
107 void setImmediateOperand(unsigned idx, unsigned int immediate) {
108 assert(!idOperand[idx]);
109 operands[idx] = immediate;
112 void addStringOperand(const char* str)
115 char* wordString = (char*)&word;
116 char* wordPtr = wordString;
123 if (charCount == 4) {
124 addImmediateOperand(word);
125 wordPtr = wordString;
130 // deal with partial last word
133 for (; charCount < 4; ++charCount)
135 addImmediateOperand(word);
138 bool isIdOperand(int op) const { return idOperand[op]; }
139 void setBlock(Block* b) { block = b; }
140 Block* getBlock() const { return block; }
141 Op getOpCode() const { return opCode; }
142 int getNumOperands() const
144 assert(operands.size() == idOperand.size());
145 return (int)operands.size();
147 Id getResultId() const { return resultId; }
148 Id getTypeId() const { return typeId; }
149 Id getIdOperand(int op) const {
150 assert(idOperand[op]);
153 unsigned int getImmediateOperand(int op) const {
154 assert(!idOperand[op]);
158 // Write out the binary form.
159 void dump(std::vector<unsigned int>& out) const
161 // Compute the wordCount
162 unsigned int wordCount = 1;
167 wordCount += (unsigned int)operands.size();
169 // Write out the beginning of the instruction
170 out.push_back(((wordCount) << WordCountShift) | opCode);
172 out.push_back(typeId);
174 out.push_back(resultId);
176 // Write out the operands
177 for (int op = 0; op < (int)operands.size(); ++op)
178 out.push_back(operands[op]);
182 Instruction(const Instruction&);
186 std::vector<Id> operands; // operands, both <id> and immediates (both are unsigned int)
187 std::vector<bool> idOperand; // true for operands that are <id>, false for immediates
197 Block(Id id, Function& parent);
202 Id getId() { return instructions.front()->getResultId(); }
204 Function& getParent() const { return parent; }
205 void addInstruction(std::unique_ptr<Instruction> inst);
206 void addPredecessor(Block* pred) { predecessors.push_back(pred); pred->successors.push_back(this);}
207 void addLocalVariable(std::unique_ptr<Instruction> inst) { localVariables.push_back(std::move(inst)); }
208 const std::vector<Block*>& getPredecessors() const { return predecessors; }
209 const std::vector<Block*>& getSuccessors() const { return successors; }
210 const std::vector<std::unique_ptr<Instruction> >& getInstructions() const {
213 const std::vector<std::unique_ptr<Instruction> >& getLocalVariables() const { return localVariables; }
214 void setUnreachable() { unreachable = true; }
215 bool isUnreachable() const { return unreachable; }
216 // Returns the block's merge instruction, if one exists (otherwise null).
217 const Instruction* getMergeInstruction() const {
218 if (instructions.size() < 2) return nullptr;
219 const Instruction* nextToLast = (instructions.cend() - 2)->get();
220 switch (nextToLast->getOpCode()) {
221 case OpSelectionMerge:
230 // Change this block into a canonical dead merge block. Delete instructions
231 // as necessary. A canonical dead merge block has only an OpLabel and an
233 void rewriteAsCanonicalUnreachableMerge() {
234 assert(localVariables.empty());
235 // Delete all instructions except for the label.
236 assert(instructions.size() > 0);
237 instructions.resize(1);
239 addInstruction(std::unique_ptr<Instruction>(new Instruction(OpUnreachable)));
241 // Change this block into a canonical dead continue target branching to the
242 // given header ID. Delete instructions as necessary. A canonical dead continue
243 // target has only an OpLabel and an unconditional branch back to the corresponding
245 void rewriteAsCanonicalUnreachableContinue(Block* header) {
246 assert(localVariables.empty());
247 // Delete all instructions except for the label.
248 assert(instructions.size() > 0);
249 instructions.resize(1);
251 // Add OpBranch back to the header.
252 assert(header != nullptr);
253 Instruction* branch = new Instruction(OpBranch);
254 branch->addIdOperand(header->getId());
255 addInstruction(std::unique_ptr<Instruction>(branch));
256 successors.push_back(header);
259 bool isTerminated() const
261 switch (instructions.back()->getOpCode()) {
263 case OpBranchConditional:
266 case OpTerminateInvocation:
276 void dump(std::vector<unsigned int>& out) const
278 instructions[0]->dump(out);
279 for (int i = 0; i < (int)localVariables.size(); ++i)
280 localVariables[i]->dump(out);
281 for (int i = 1; i < (int)instructions.size(); ++i)
282 instructions[i]->dump(out);
287 Block& operator=(Block&);
289 // To enforce keeping parent and ownership in sync:
292 std::vector<std::unique_ptr<Instruction> > instructions;
293 std::vector<Block*> predecessors, successors;
294 std::vector<std::unique_ptr<Instruction> > localVariables;
297 // track whether this block is known to be uncreachable (not necessarily
298 // true for all unreachable blocks, but should be set at least
299 // for the extraneous ones introduced by the builder).
303 // The different reasons for reaching a block in the inReadableOrder traversal.
305 // Reachable from the entry block via transfers of control, i.e. branches.
306 ReachViaControlFlow = 0,
307 // A continue target that is not reachable via control flow.
309 // A merge block that is not reachable via control flow.
313 // Traverses the control-flow graph rooted at root in an order suited for
314 // readable code generation. Invokes callback at every node in the traversal
315 // order. The callback arguments are:
317 // - the reason we reached the block,
318 // - if the reason was that block is an unreachable continue or unreachable merge block
319 // then the last parameter is the corresponding header block.
320 void inReadableOrder(Block* root, std::function<void(Block*, ReachReason, Block* header)> callback);
323 // SPIR-V IR Function.
328 Function(Id id, Id resultType, Id functionType, Id firstParam, Module& parent);
331 for (int i = 0; i < (int)parameterInstructions.size(); ++i)
332 delete parameterInstructions[i];
334 for (int i = 0; i < (int)blocks.size(); ++i)
337 Id getId() const { return functionInstruction.getResultId(); }
338 Id getParamId(int p) const { return parameterInstructions[p]->getResultId(); }
339 Id getParamType(int p) const { return parameterInstructions[p]->getTypeId(); }
341 void addBlock(Block* block) { blocks.push_back(block); }
342 void removeBlock(Block* block)
344 auto found = find(blocks.begin(), blocks.end(), block);
345 assert(found != blocks.end());
350 Module& getParent() const { return parent; }
351 Block* getEntryBlock() const { return blocks.front(); }
352 Block* getLastBlock() const { return blocks.back(); }
353 const std::vector<Block*>& getBlocks() const { return blocks; }
354 void addLocalVariable(std::unique_ptr<Instruction> inst);
355 Id getReturnType() const { return functionInstruction.getTypeId(); }
356 void setReturnPrecision(Decoration precision)
358 if (precision == DecorationRelaxedPrecision)
359 reducedPrecisionReturn = true;
361 Decoration getReturnPrecision() const
362 { return reducedPrecisionReturn ? DecorationRelaxedPrecision : NoPrecision; }
364 void setImplicitThis() { implicitThis = true; }
365 bool hasImplicitThis() const { return implicitThis; }
367 void addParamPrecision(unsigned param, Decoration precision)
369 if (precision == DecorationRelaxedPrecision)
370 reducedPrecisionParams.insert(param);
372 Decoration getParamPrecision(unsigned param) const
374 return reducedPrecisionParams.find(param) != reducedPrecisionParams.end() ?
375 DecorationRelaxedPrecision : NoPrecision;
378 void dump(std::vector<unsigned int>& out) const
381 functionInstruction.dump(out);
383 // OpFunctionParameter
384 for (int p = 0; p < (int)parameterInstructions.size(); ++p)
385 parameterInstructions[p]->dump(out);
388 inReadableOrder(blocks[0], [&out](const Block* b, ReachReason, Block*) { b->dump(out); });
389 Instruction end(0, 0, OpFunctionEnd);
394 Function(const Function&);
395 Function& operator=(Function&);
398 Instruction functionInstruction;
399 std::vector<Instruction*> parameterInstructions;
400 std::vector<Block*> blocks;
401 bool implicitThis; // true if this is a member function expecting to be passed a 'this' as the first argument
402 bool reducedPrecisionReturn;
403 std::set<int> reducedPrecisionParams; // list of parameter indexes that need a relaxed precision arg
415 // TODO delete things
418 void addFunction(Function *fun) { functions.push_back(fun); }
420 void mapInstruction(Instruction *instruction)
422 spv::Id resultId = instruction->getResultId();
423 // map the instruction's result id
424 if (resultId >= idToInstruction.size())
425 idToInstruction.resize(resultId + 16);
426 idToInstruction[resultId] = instruction;
429 Instruction* getInstruction(Id id) const { return idToInstruction[id]; }
430 const std::vector<Function*>& getFunctions() const { return functions; }
431 spv::Id getTypeId(Id resultId) const {
432 return idToInstruction[resultId] == nullptr ? NoType : idToInstruction[resultId]->getTypeId();
434 StorageClass getStorageClass(Id typeId) const
436 assert(idToInstruction[typeId]->getOpCode() == spv::OpTypePointer);
437 return (StorageClass)idToInstruction[typeId]->getImmediateOperand(0);
440 void dump(std::vector<unsigned int>& out) const
442 for (int f = 0; f < (int)functions.size(); ++f)
443 functions[f]->dump(out);
447 Module(const Module&);
448 std::vector<Function*> functions;
450 // map from result id to instruction having that result id
451 std::vector<Instruction*> idToInstruction;
453 // map from a result id to its type id
457 // Implementation (it's here due to circular type definitions).
461 // - the OpFunction instruction
462 // - all the OpFunctionParameter instructions
463 __inline Function::Function(Id id, Id resultType, Id functionType, Id firstParamId, Module& parent)
464 : parent(parent), functionInstruction(id, resultType, OpFunction), implicitThis(false),
465 reducedPrecisionReturn(false)
468 functionInstruction.addImmediateOperand(FunctionControlMaskNone);
469 functionInstruction.addIdOperand(functionType);
470 parent.mapInstruction(&functionInstruction);
471 parent.addFunction(this);
473 // OpFunctionParameter
474 Instruction* typeInst = parent.getInstruction(functionType);
475 int numParams = typeInst->getNumOperands() - 1;
476 for (int p = 0; p < numParams; ++p) {
477 Instruction* param = new Instruction(firstParamId + p, typeInst->getIdOperand(p + 1), OpFunctionParameter);
478 parent.mapInstruction(param);
479 parameterInstructions.push_back(param);
483 __inline void Function::addLocalVariable(std::unique_ptr<Instruction> inst)
485 Instruction* raw_instruction = inst.get();
486 blocks[0]->addLocalVariable(std::move(inst));
487 parent.mapInstruction(raw_instruction);
490 __inline Block::Block(Id id, Function& parent) : parent(parent), unreachable(false)
492 instructions.push_back(std::unique_ptr<Instruction>(new Instruction(id, NoType, OpLabel)));
493 instructions.back()->setBlock(this);
494 parent.getParent().mapInstruction(instructions.back().get());
497 __inline void Block::addInstruction(std::unique_ptr<Instruction> inst)
499 Instruction* raw_instruction = inst.get();
500 instructions.push_back(std::move(inst));
501 raw_instruction->setBlock(this);
502 if (raw_instruction->getResultId())
503 parent.getParent().mapInstruction(raw_instruction);
506 } // end spv namespace