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)
114 unsigned int word = 0;
115 unsigned int shiftAmount = 0;
120 word |= ((unsigned int)c) << shiftAmount;
122 if (shiftAmount == 32) {
123 addImmediateOperand(word);
129 // deal with partial last word
130 if (shiftAmount > 0) {
131 addImmediateOperand(word);
134 bool isIdOperand(int op) const { return idOperand[op]; }
135 void setBlock(Block* b) { block = b; }
136 Block* getBlock() const { return block; }
137 Op getOpCode() const { return opCode; }
138 int getNumOperands() const
140 assert(operands.size() == idOperand.size());
141 return (int)operands.size();
143 Id getResultId() const { return resultId; }
144 Id getTypeId() const { return typeId; }
145 Id getIdOperand(int op) const {
146 assert(idOperand[op]);
149 unsigned int getImmediateOperand(int op) const {
150 assert(!idOperand[op]);
154 // Write out the binary form.
155 void dump(std::vector<unsigned int>& out) const
157 // Compute the wordCount
158 unsigned int wordCount = 1;
163 wordCount += (unsigned int)operands.size();
165 // Write out the beginning of the instruction
166 out.push_back(((wordCount) << WordCountShift) | opCode);
168 out.push_back(typeId);
170 out.push_back(resultId);
172 // Write out the operands
173 for (int op = 0; op < (int)operands.size(); ++op)
174 out.push_back(operands[op]);
178 Instruction(const Instruction&);
182 std::vector<Id> operands; // operands, both <id> and immediates (both are unsigned int)
183 std::vector<bool> idOperand; // true for operands that are <id>, false for immediates
193 Block(Id id, Function& parent);
198 Id getId() { return instructions.front()->getResultId(); }
200 Function& getParent() const { return parent; }
201 void addInstruction(std::unique_ptr<Instruction> inst);
202 void addPredecessor(Block* pred) { predecessors.push_back(pred); pred->successors.push_back(this);}
203 void addLocalVariable(std::unique_ptr<Instruction> inst) { localVariables.push_back(std::move(inst)); }
204 const std::vector<Block*>& getPredecessors() const { return predecessors; }
205 const std::vector<Block*>& getSuccessors() const { return successors; }
206 const std::vector<std::unique_ptr<Instruction> >& getInstructions() const {
209 const std::vector<std::unique_ptr<Instruction> >& getLocalVariables() const { return localVariables; }
210 void setUnreachable() { unreachable = true; }
211 bool isUnreachable() const { return unreachable; }
212 // Returns the block's merge instruction, if one exists (otherwise null).
213 const Instruction* getMergeInstruction() const {
214 if (instructions.size() < 2) return nullptr;
215 const Instruction* nextToLast = (instructions.cend() - 2)->get();
216 switch (nextToLast->getOpCode()) {
217 case OpSelectionMerge:
226 // Change this block into a canonical dead merge block. Delete instructions
227 // as necessary. A canonical dead merge block has only an OpLabel and an
229 void rewriteAsCanonicalUnreachableMerge() {
230 assert(localVariables.empty());
231 // Delete all instructions except for the label.
232 assert(instructions.size() > 0);
233 instructions.resize(1);
235 addInstruction(std::unique_ptr<Instruction>(new Instruction(OpUnreachable)));
237 // Change this block into a canonical dead continue target branching to the
238 // given header ID. Delete instructions as necessary. A canonical dead continue
239 // target has only an OpLabel and an unconditional branch back to the corresponding
241 void rewriteAsCanonicalUnreachableContinue(Block* header) {
242 assert(localVariables.empty());
243 // Delete all instructions except for the label.
244 assert(instructions.size() > 0);
245 instructions.resize(1);
247 // Add OpBranch back to the header.
248 assert(header != nullptr);
249 Instruction* branch = new Instruction(OpBranch);
250 branch->addIdOperand(header->getId());
251 addInstruction(std::unique_ptr<Instruction>(branch));
252 successors.push_back(header);
255 bool isTerminated() const
257 switch (instructions.back()->getOpCode()) {
259 case OpBranchConditional:
262 case OpTerminateInvocation:
272 void dump(std::vector<unsigned int>& out) const
274 instructions[0]->dump(out);
275 for (int i = 0; i < (int)localVariables.size(); ++i)
276 localVariables[i]->dump(out);
277 for (int i = 1; i < (int)instructions.size(); ++i)
278 instructions[i]->dump(out);
283 Block& operator=(Block&);
285 // To enforce keeping parent and ownership in sync:
288 std::vector<std::unique_ptr<Instruction> > instructions;
289 std::vector<Block*> predecessors, successors;
290 std::vector<std::unique_ptr<Instruction> > localVariables;
293 // track whether this block is known to be uncreachable (not necessarily
294 // true for all unreachable blocks, but should be set at least
295 // for the extraneous ones introduced by the builder).
299 // The different reasons for reaching a block in the inReadableOrder traversal.
301 // Reachable from the entry block via transfers of control, i.e. branches.
302 ReachViaControlFlow = 0,
303 // A continue target that is not reachable via control flow.
305 // A merge block that is not reachable via control flow.
309 // Traverses the control-flow graph rooted at root in an order suited for
310 // readable code generation. Invokes callback at every node in the traversal
311 // order. The callback arguments are:
313 // - the reason we reached the block,
314 // - if the reason was that block is an unreachable continue or unreachable merge block
315 // then the last parameter is the corresponding header block.
316 void inReadableOrder(Block* root, std::function<void(Block*, ReachReason, Block* header)> callback);
319 // SPIR-V IR Function.
324 Function(Id id, Id resultType, Id functionType, Id firstParam, Module& parent);
327 for (int i = 0; i < (int)parameterInstructions.size(); ++i)
328 delete parameterInstructions[i];
330 for (int i = 0; i < (int)blocks.size(); ++i)
333 Id getId() const { return functionInstruction.getResultId(); }
334 Id getParamId(int p) const { return parameterInstructions[p]->getResultId(); }
335 Id getParamType(int p) const { return parameterInstructions[p]->getTypeId(); }
337 void addBlock(Block* block) { blocks.push_back(block); }
338 void removeBlock(Block* block)
340 auto found = find(blocks.begin(), blocks.end(), block);
341 assert(found != blocks.end());
346 Module& getParent() const { return parent; }
347 Block* getEntryBlock() const { return blocks.front(); }
348 Block* getLastBlock() const { return blocks.back(); }
349 const std::vector<Block*>& getBlocks() const { return blocks; }
350 void addLocalVariable(std::unique_ptr<Instruction> inst);
351 Id getReturnType() const { return functionInstruction.getTypeId(); }
352 void setReturnPrecision(Decoration precision)
354 if (precision == DecorationRelaxedPrecision)
355 reducedPrecisionReturn = true;
357 Decoration getReturnPrecision() const
358 { return reducedPrecisionReturn ? DecorationRelaxedPrecision : NoPrecision; }
360 void setImplicitThis() { implicitThis = true; }
361 bool hasImplicitThis() const { return implicitThis; }
363 void addParamPrecision(unsigned param, Decoration precision)
365 if (precision == DecorationRelaxedPrecision)
366 reducedPrecisionParams.insert(param);
368 Decoration getParamPrecision(unsigned param) const
370 return reducedPrecisionParams.find(param) != reducedPrecisionParams.end() ?
371 DecorationRelaxedPrecision : NoPrecision;
374 void dump(std::vector<unsigned int>& out) const
377 functionInstruction.dump(out);
379 // OpFunctionParameter
380 for (int p = 0; p < (int)parameterInstructions.size(); ++p)
381 parameterInstructions[p]->dump(out);
384 inReadableOrder(blocks[0], [&out](const Block* b, ReachReason, Block*) { b->dump(out); });
385 Instruction end(0, 0, OpFunctionEnd);
390 Function(const Function&);
391 Function& operator=(Function&);
394 Instruction functionInstruction;
395 std::vector<Instruction*> parameterInstructions;
396 std::vector<Block*> blocks;
397 bool implicitThis; // true if this is a member function expecting to be passed a 'this' as the first argument
398 bool reducedPrecisionReturn;
399 std::set<int> reducedPrecisionParams; // list of parameter indexes that need a relaxed precision arg
411 // TODO delete things
414 void addFunction(Function *fun) { functions.push_back(fun); }
416 void mapInstruction(Instruction *instruction)
418 spv::Id resultId = instruction->getResultId();
419 // map the instruction's result id
420 if (resultId >= idToInstruction.size())
421 idToInstruction.resize(resultId + 16);
422 idToInstruction[resultId] = instruction;
425 Instruction* getInstruction(Id id) const { return idToInstruction[id]; }
426 const std::vector<Function*>& getFunctions() const { return functions; }
427 spv::Id getTypeId(Id resultId) const {
428 return idToInstruction[resultId] == nullptr ? NoType : idToInstruction[resultId]->getTypeId();
430 StorageClass getStorageClass(Id typeId) const
432 assert(idToInstruction[typeId]->getOpCode() == spv::OpTypePointer);
433 return (StorageClass)idToInstruction[typeId]->getImmediateOperand(0);
436 void dump(std::vector<unsigned int>& out) const
438 for (int f = 0; f < (int)functions.size(); ++f)
439 functions[f]->dump(out);
443 Module(const Module&);
444 std::vector<Function*> functions;
446 // map from result id to instruction having that result id
447 std::vector<Instruction*> idToInstruction;
449 // map from a result id to its type id
453 // Implementation (it's here due to circular type definitions).
457 // - the OpFunction instruction
458 // - all the OpFunctionParameter instructions
459 __inline Function::Function(Id id, Id resultType, Id functionType, Id firstParamId, Module& parent)
460 : parent(parent), functionInstruction(id, resultType, OpFunction), implicitThis(false),
461 reducedPrecisionReturn(false)
464 functionInstruction.addImmediateOperand(FunctionControlMaskNone);
465 functionInstruction.addIdOperand(functionType);
466 parent.mapInstruction(&functionInstruction);
467 parent.addFunction(this);
469 // OpFunctionParameter
470 Instruction* typeInst = parent.getInstruction(functionType);
471 int numParams = typeInst->getNumOperands() - 1;
472 for (int p = 0; p < numParams; ++p) {
473 Instruction* param = new Instruction(firstParamId + p, typeInst->getIdOperand(p + 1), OpFunctionParameter);
474 parent.mapInstruction(param);
475 parameterInstructions.push_back(param);
479 __inline void Function::addLocalVariable(std::unique_ptr<Instruction> inst)
481 Instruction* raw_instruction = inst.get();
482 blocks[0]->addLocalVariable(std::move(inst));
483 parent.mapInstruction(raw_instruction);
486 __inline Block::Block(Id id, Function& parent) : parent(parent), unreachable(false)
488 instructions.push_back(std::unique_ptr<Instruction>(new Instruction(id, NoType, OpLabel)));
489 instructions.back()->setBlock(this);
490 parent.getParent().mapInstruction(instructions.back().get());
493 __inline void Block::addInstruction(std::unique_ptr<Instruction> inst)
495 Instruction* raw_instruction = inst.get();
496 instructions.push_back(std::move(inst));
497 raw_instruction->setBlock(this);
498 if (raw_instruction->getResultId())
499 parent.getParent().mapInstruction(raw_instruction);
502 } // end spv namespace