Coverage Report

Created: 2026-06-04 06:49

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/shaderc/third_party/spirv-tools/source/disassemble.cpp
Line
Count
Source
1
// Copyright (c) 2015-2020 The Khronos Group Inc.
2
// Modifications Copyright (C) 2020 Advanced Micro Devices, Inc. All rights
3
// reserved.
4
//
5
// Licensed under the Apache License, Version 2.0 (the "License");
6
// you may not use this file except in compliance with the License.
7
// You may obtain a copy of the License at
8
//
9
//     http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing, software
12
// distributed under the License is distributed on an "AS IS" BASIS,
13
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
// See the License for the specific language governing permissions and
15
// limitations under the License.
16
17
// This file contains a disassembler:  It converts a SPIR-V binary
18
// to text.
19
20
#include "source/disassemble.h"
21
22
#include <algorithm>
23
#include <cassert>
24
#include <cstring>
25
#include <iomanip>
26
#include <ios>
27
#include <memory>
28
#include <set>
29
#include <sstream>
30
#include <stack>
31
#include <unordered_map>
32
#include <utility>
33
34
#include "source/binary.h"
35
#include "source/diagnostic.h"
36
#include "source/ext_inst.h"
37
#include "source/opcode.h"
38
#include "source/parsed_operand.h"
39
#include "source/print.h"
40
#include "source/spirv_constant.h"
41
#include "source/spirv_endian.h"
42
#include "source/table2.h"
43
#include "source/util/hex_float.h"
44
#include "source/util/make_unique.h"
45
#include "spirv-tools/libspirv.h"
46
47
namespace spvtools {
48
namespace {
49
50
// Indices to ControlFlowGraph's list of blocks from one block to its successors
51
struct BlockSuccessors {
52
  // Merge block in OpLoopMerge and OpSelectionMerge
53
  uint32_t merge_block_id = 0;
54
  // The continue block in OpLoopMerge
55
  uint32_t continue_block_id = 0;
56
  // The true and false blocks in OpBranchConditional
57
  uint32_t true_block_id = 0;
58
  uint32_t false_block_id = 0;
59
  // The body block of a loop, as specified by OpBranch after a merge
60
  // instruction
61
  uint32_t body_block_id = 0;
62
  // The same-nesting-level block that follows this one, indicated by an
63
  // OpBranch with no merge instruction.
64
  uint32_t next_block_id = 0;
65
  // The cases (including default) of an OpSwitch
66
  std::vector<uint32_t> case_block_ids;
67
};
68
69
class ParsedInstruction {
70
 public:
71
0
  ParsedInstruction(const spv_parsed_instruction_t* instruction) {
72
    // Make a copy of the parsed instruction, including stable memory for its
73
    // operands.
74
0
    instruction_ = *instruction;
75
0
    operands_ =
76
0
        std::make_unique<spv_parsed_operand_t[]>(instruction->num_operands);
77
0
    memcpy(operands_.get(), instruction->operands,
78
0
           instruction->num_operands * sizeof(*instruction->operands));
79
0
    instruction_.operands = operands_.get();
80
0
  }
81
82
0
  const spv_parsed_instruction_t* get() const { return &instruction_; }
83
84
 private:
85
  spv_parsed_instruction_t instruction_;
86
  std::unique_ptr<spv_parsed_operand_t[]> operands_;
87
};
88
89
// One block in the CFG
90
struct SingleBlock {
91
  // The byte offset in the SPIR-V where the block starts.  Used for printing in
92
  // a comment.
93
  size_t byte_offset;
94
95
  // Block instructions
96
  std::vector<ParsedInstruction> instructions;
97
98
  // Successors of this block
99
  BlockSuccessors successors;
100
101
  // The nesting level for this block.
102
  uint32_t nest_level = 0;
103
  bool nest_level_assigned = false;
104
105
  // Whether the block was reachable
106
  bool reachable = false;
107
};
108
109
// CFG for one function
110
struct ControlFlowGraph {
111
  std::vector<SingleBlock> blocks;
112
};
113
114
// A Disassembler instance converts a SPIR-V binary to its assembly
115
// representation.
116
class Disassembler {
117
 public:
118
  Disassembler(uint32_t options, NameMapper name_mapper)
119
140
      : print_(spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_PRINT, options)),
120
        nested_indent_(
121
140
            spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_NESTED_INDENT, options)),
122
        reorder_blocks_(
123
140
            spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_REORDER_BLOCKS, options)),
124
140
        text_(),
125
140
        out_(print_ ? out_stream() : out_stream(text_)),
126
140
        instruction_disassembler_(out_.get(), options, name_mapper),
127
140
        header_(!spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_NO_HEADER, options)),
128
140
        byte_offset_(0) {}
129
130
  // Emits the assembly header for the module, and sets up internal state
131
  // so subsequent callbacks can handle the cases where the entire module
132
  // is either big-endian or little-endian.
133
  spv_result_t HandleHeader(spv_endianness_t endian, uint32_t version,
134
                            uint32_t generator, uint32_t id_bound,
135
                            uint32_t schema);
136
  // Emits the assembly text for the given instruction.
137
  spv_result_t HandleInstruction(const spv_parsed_instruction_t& inst);
138
139
  // If not printing, populates text_result with the accumulated text.
140
  // Returns SPV_SUCCESS on success.
141
  spv_result_t SaveTextResult(spv_text* text_result) const;
142
143
 private:
144
  void EmitCFG();
145
146
  const bool print_;  // Should we also print to the standard output stream?
147
  const bool nested_indent_;  // Should the blocks be indented according to the
148
                              // control flow structure?
149
  const bool
150
      reorder_blocks_;       // Should the blocks be reordered for readability?
151
  spv_endianness_t endian_;  // The detected endianness of the binary.
152
  std::stringstream text_;   // Captures the text, if not printing.
153
  out_stream out_;  // The Output stream.  Either to text_ or standard output.
154
  disassemble::InstructionDisassembler instruction_disassembler_;
155
  const bool header_;   // Should we output header as the leading comment?
156
  size_t byte_offset_;  // The number of bytes processed so far.
157
  bool inserted_decoration_space_ = false;
158
  bool inserted_debug_space_ = false;
159
  bool inserted_type_space_ = false;
160
161
  // The CFG for the current function
162
  ControlFlowGraph current_function_cfg_;
163
};
164
165
spv_result_t Disassembler::HandleHeader(spv_endianness_t endian,
166
                                        uint32_t version, uint32_t generator,
167
140
                                        uint32_t id_bound, uint32_t schema) {
168
140
  endian_ = endian;
169
170
140
  if (header_) {
171
88
    instruction_disassembler_.EmitHeaderSpirv();
172
88
    instruction_disassembler_.EmitHeaderVersion(version);
173
88
    instruction_disassembler_.EmitHeaderGenerator(generator);
174
88
    instruction_disassembler_.EmitHeaderIdBound(id_bound);
175
88
    instruction_disassembler_.EmitHeaderSchema(schema);
176
88
  }
177
178
140
  byte_offset_ = SPV_INDEX_INSTRUCTION * sizeof(uint32_t);
179
180
140
  return SPV_SUCCESS;
181
140
}
182
183
spv_result_t Disassembler::HandleInstruction(
184
14.8k
    const spv_parsed_instruction_t& inst) {
185
14.8k
  instruction_disassembler_.EmitSectionComment(inst, inserted_decoration_space_,
186
14.8k
                                               inserted_debug_space_,
187
14.8k
                                               inserted_type_space_);
188
189
  // When nesting needs to be calculated or when the blocks are reordered, we
190
  // have to have the full picture of the CFG first.  Defer processing of the
191
  // instructions until the entire function is visited.  This is not done
192
  // without those options (even if simpler) to improve debuggability; for
193
  // example to be able to see whatever is parsed so far even if there is a
194
  // parse error.
195
14.8k
  if (nested_indent_ || reorder_blocks_) {
196
0
    switch (static_cast<spv::Op>(inst.opcode)) {
197
0
      case spv::Op::OpLabel: {
198
        // Add a new block to the CFG
199
0
        SingleBlock new_block;
200
0
        new_block.byte_offset = byte_offset_;
201
0
        new_block.instructions.emplace_back(&inst);
202
0
        current_function_cfg_.blocks.push_back(std::move(new_block));
203
0
        break;
204
0
      }
205
0
      case spv::Op::OpFunctionEnd:
206
        // Process the CFG and output the instructions
207
0
        if (!current_function_cfg_.blocks.empty()) {
208
0
          EmitCFG();
209
0
        }
210
        // Output OpFunctionEnd itself too
211
0
        [[fallthrough]];
212
0
      default:
213
0
        if (!current_function_cfg_.blocks.empty()) {
214
          // If in a function, stash the instruction for later.
215
0
          current_function_cfg_.blocks.back().instructions.emplace_back(&inst);
216
0
        } else {
217
          // Otherwise emit the instruction right away.
218
0
          instruction_disassembler_.EmitInstruction(inst, byte_offset_);
219
0
        }
220
0
        break;
221
0
    }
222
14.8k
  } else {
223
14.8k
    instruction_disassembler_.EmitInstruction(inst, byte_offset_);
224
14.8k
  }
225
226
14.8k
  byte_offset_ += inst.num_words * sizeof(uint32_t);
227
228
14.8k
  return SPV_SUCCESS;
229
14.8k
}
230
231
// Helper to get the operand of an instruction as an id.
232
uint32_t GetOperand(const spv_parsed_instruction_t* instruction,
233
0
                    uint32_t operand) {
234
0
  return instruction->words[instruction->operands[operand].offset];
235
0
}
236
237
std::unordered_map<uint32_t, uint32_t> BuildControlFlowGraph(
238
0
    ControlFlowGraph& cfg) {
239
0
  std::unordered_map<uint32_t, uint32_t> id_to_index;
240
241
0
  for (size_t index = 0; index < cfg.blocks.size(); ++index) {
242
0
    SingleBlock& block = cfg.blocks[index];
243
244
    // For future use, build the ID->index map
245
0
    assert(static_cast<spv::Op>(block.instructions[0].get()->opcode) ==
246
0
           spv::Op::OpLabel);
247
0
    const uint32_t id = block.instructions[0].get()->result_id;
248
249
0
    id_to_index[id] = static_cast<uint32_t>(index);
250
251
    // Look for a merge instruction first.  The function of OpBranch depends on
252
    // that.
253
0
    if (block.instructions.size() >= 3) {
254
0
      const spv_parsed_instruction_t* maybe_merge =
255
0
          block.instructions[block.instructions.size() - 2].get();
256
257
0
      switch (static_cast<spv::Op>(maybe_merge->opcode)) {
258
0
        case spv::Op::OpLoopMerge:
259
0
          block.successors.merge_block_id = GetOperand(maybe_merge, 0);
260
0
          block.successors.continue_block_id = GetOperand(maybe_merge, 1);
261
0
          break;
262
263
0
        case spv::Op::OpSelectionMerge:
264
0
          block.successors.merge_block_id = GetOperand(maybe_merge, 0);
265
0
          break;
266
267
0
        default:
268
0
          break;
269
0
      }
270
0
    }
271
272
    // Then look at the last instruction; it must be a branch
273
0
    assert(block.instructions.size() >= 2);
274
275
0
    const spv_parsed_instruction_t* branch = block.instructions.back().get();
276
0
    switch (static_cast<spv::Op>(branch->opcode)) {
277
0
      case spv::Op::OpBranch:
278
0
        if (block.successors.merge_block_id != 0) {
279
0
          block.successors.body_block_id = GetOperand(branch, 0);
280
0
        } else {
281
0
          block.successors.next_block_id = GetOperand(branch, 0);
282
0
        }
283
0
        break;
284
285
0
      case spv::Op::OpBranchConditional:
286
0
        block.successors.true_block_id = GetOperand(branch, 1);
287
0
        block.successors.false_block_id = GetOperand(branch, 2);
288
0
        break;
289
290
0
      case spv::Op::OpSwitch:
291
0
        for (uint32_t case_index = 1; case_index < branch->num_operands;
292
0
             case_index += 2) {
293
0
          block.successors.case_block_ids.push_back(
294
0
              GetOperand(branch, case_index));
295
0
        }
296
0
        break;
297
298
0
      default:
299
0
        break;
300
0
    }
301
0
  }
302
303
0
  return id_to_index;
304
0
}
305
306
// Helper to deal with nesting and non-existing ids / previously-assigned
307
// levels.  It assigns a given nesting level `level` to the block identified by
308
// `id` (unless that block already has a nesting level assigned).
309
void Nest(ControlFlowGraph& cfg,
310
          const std::unordered_map<uint32_t, uint32_t>& id_to_index,
311
0
          uint32_t id, uint32_t level) {
312
0
  if (id == 0) {
313
0
    return;
314
0
  }
315
316
0
  const uint32_t block_index = id_to_index.at(id);
317
0
  SingleBlock& block = cfg.blocks[block_index];
318
319
0
  if (!block.nest_level_assigned) {
320
0
    block.nest_level = level;
321
0
    block.nest_level_assigned = true;
322
0
  }
323
0
}
324
325
// For a given block, assign nesting level to its successors.
326
void NestSuccessors(ControlFlowGraph& cfg, const SingleBlock& block,
327
0
                    const std::unordered_map<uint32_t, uint32_t>& id_to_index) {
328
0
  assert(block.nest_level_assigned);
329
330
  // Nest loops as such:
331
  //
332
  //     %loop = OpLabel
333
  //               OpLoopMerge %merge %cont ...
334
  //               OpBranch %body
335
  //     %body =     OpLabel
336
  //                   Op...
337
  //     %cont =   OpLabel
338
  //                 Op...
339
  //    %merge = OpLabel
340
  //               Op...
341
  //
342
  // Nest conditional branches as such:
343
  //
344
  //   %header = OpLabel
345
  //               OpSelectionMerge %merge ...
346
  //               OpBranchConditional ... %true %false
347
  //     %true =     OpLabel
348
  //                   Op...
349
  //    %false =     OpLabel
350
  //                   Op...
351
  //    %merge = OpLabel
352
  //               Op...
353
  //
354
  // Nest switch/case as such:
355
  //
356
  //   %header = OpLabel
357
  //               OpSelectionMerge %merge ...
358
  //               OpSwitch ... %default ... %case0 ... %case1 ...
359
  //  %default =     OpLabel
360
  //                   Op...
361
  //    %case0 =     OpLabel
362
  //                   Op...
363
  //    %case1 =     OpLabel
364
  //                   Op...
365
  //             ...
366
  //    %merge = OpLabel
367
  //               Op...
368
  //
369
  // The following can be observed:
370
  //
371
  // - In all cases, the merge block has the same nesting as this block
372
  // - The continue block of loops is nested 1 level deeper
373
  // - The body/branches/cases are nested 2 levels deeper
374
  //
375
  // Back branches to the header block, branches to the merge block, etc
376
  // are correctly handled by processing the header block first (that is
377
  // _this_ block, already processed), then following the above rules
378
  // (in the same order) for any block that is not already processed.
379
0
  Nest(cfg, id_to_index, block.successors.merge_block_id, block.nest_level);
380
0
  Nest(cfg, id_to_index, block.successors.continue_block_id,
381
0
       block.nest_level + 1);
382
0
  Nest(cfg, id_to_index, block.successors.true_block_id, block.nest_level + 2);
383
0
  Nest(cfg, id_to_index, block.successors.false_block_id, block.nest_level + 2);
384
0
  Nest(cfg, id_to_index, block.successors.body_block_id, block.nest_level + 2);
385
0
  Nest(cfg, id_to_index, block.successors.next_block_id, block.nest_level);
386
0
  for (uint32_t case_block_id : block.successors.case_block_ids) {
387
0
    Nest(cfg, id_to_index, case_block_id, block.nest_level + 2);
388
0
  }
389
0
}
390
391
struct StackEntry {
392
  // The index of the block (in ControlFlowGraph::blocks) to process.
393
  uint32_t block_index;
394
  // Whether this is the pre or post visit of the block.  Because a post-visit
395
  // traversal is needed, the same block is pushed back on the stack on
396
  // pre-visit so it can be visited again on post-visit.
397
  bool post_visit = false;
398
};
399
400
// Helper to deal with DFS traversal and non-existing ids
401
void VisitSuccesor(std::stack<StackEntry>* dfs_stack,
402
                   const std::unordered_map<uint32_t, uint32_t>& id_to_index,
403
0
                   uint32_t id) {
404
0
  if (id != 0) {
405
0
    dfs_stack->push({id_to_index.at(id), false});
406
0
  }
407
0
}
408
409
// Given the control flow graph, calculates and returns the reverse post-order
410
// ordering of the blocks.  The blocks are then disassembled in that order for
411
// readability.
412
std::vector<uint32_t> OrderBlocks(
413
    ControlFlowGraph& cfg,
414
0
    const std::unordered_map<uint32_t, uint32_t>& id_to_index) {
415
0
  std::vector<uint32_t> post_order;
416
417
  // Nest level of a function's first block is 0.
418
0
  cfg.blocks[0].nest_level = 0;
419
0
  cfg.blocks[0].nest_level_assigned = true;
420
421
  // Stack of block indices as they are visited.
422
0
  std::stack<StackEntry> dfs_stack;
423
0
  dfs_stack.push({0, false});
424
425
0
  std::set<uint32_t> visited;
426
427
0
  while (!dfs_stack.empty()) {
428
0
    const uint32_t block_index = dfs_stack.top().block_index;
429
0
    const bool post_visit = dfs_stack.top().post_visit;
430
0
    dfs_stack.pop();
431
432
    // If this is the second time the block is visited, that's the post-order
433
    // visit.
434
0
    if (post_visit) {
435
0
      post_order.push_back(block_index);
436
0
      continue;
437
0
    }
438
439
    // If already visited, another path got to it first (like a case
440
    // fallthrough), avoid reprocessing it.
441
0
    if (visited.count(block_index) > 0) {
442
0
      continue;
443
0
    }
444
0
    visited.insert(block_index);
445
446
    // Push it back in the stack for post-order visit
447
0
    dfs_stack.push({block_index, true});
448
449
0
    SingleBlock& block = cfg.blocks[block_index];
450
451
    // Assign nest levels of successors right away.  The successors are either
452
    // nested under this block, or are back or forward edges to blocks outside
453
    // this nesting level (no farther than the merge block), whose nesting
454
    // levels are already assigned before this block is visited.
455
0
    NestSuccessors(cfg, block, id_to_index);
456
0
    block.reachable = true;
457
458
    // The post-order visit yields the order in which the blocks are naturally
459
    // ordered _backwards_. So blocks to be ordered last should be visited
460
    // first.  In other words, they should be pushed to the DFS stack last.
461
0
    VisitSuccesor(&dfs_stack, id_to_index, block.successors.true_block_id);
462
0
    VisitSuccesor(&dfs_stack, id_to_index, block.successors.false_block_id);
463
0
    VisitSuccesor(&dfs_stack, id_to_index, block.successors.body_block_id);
464
0
    VisitSuccesor(&dfs_stack, id_to_index, block.successors.next_block_id);
465
0
    for (uint32_t case_block_id : block.successors.case_block_ids) {
466
0
      VisitSuccesor(&dfs_stack, id_to_index, case_block_id);
467
0
    }
468
0
    VisitSuccesor(&dfs_stack, id_to_index, block.successors.continue_block_id);
469
0
    VisitSuccesor(&dfs_stack, id_to_index, block.successors.merge_block_id);
470
0
  }
471
472
0
  std::vector<uint32_t> order(post_order.rbegin(), post_order.rend());
473
474
  // Finally, dump all unreachable blocks at the end
475
0
  for (size_t index = 0; index < cfg.blocks.size(); ++index) {
476
0
    SingleBlock& block = cfg.blocks[index];
477
478
0
    if (!block.reachable) {
479
0
      order.push_back(static_cast<uint32_t>(index));
480
0
      block.nest_level = 0;
481
0
      block.nest_level_assigned = true;
482
0
    }
483
0
  }
484
485
0
  return order;
486
0
}
487
488
0
void Disassembler::EmitCFG() {
489
  // Build the CFG edges.  At the same time, build an ID->block index map to
490
  // simplify building the CFG edges.
491
0
  const std::unordered_map<uint32_t, uint32_t> id_to_index =
492
0
      BuildControlFlowGraph(current_function_cfg_);
493
494
  // Walk the CFG in reverse post-order to find the best ordering of blocks for
495
  // presentation
496
0
  std::vector<uint32_t> block_order =
497
0
      OrderBlocks(current_function_cfg_, id_to_index);
498
0
  assert(block_order.size() == current_function_cfg_.blocks.size());
499
500
  // Walk the CFG either in block order or input order based on whether the
501
  // reorder_blocks_ option is given.
502
0
  for (uint32_t index = 0; index < current_function_cfg_.blocks.size();
503
0
       ++index) {
504
0
    const uint32_t block_index = reorder_blocks_ ? block_order[index] : index;
505
0
    const SingleBlock& block = current_function_cfg_.blocks[block_index];
506
507
    // Emit instructions for this block
508
0
    size_t byte_offset = block.byte_offset;
509
0
    assert(block.nest_level_assigned);
510
511
0
    for (const ParsedInstruction& inst : block.instructions) {
512
0
      instruction_disassembler_.EmitInstructionInBlock(*inst.get(), byte_offset,
513
0
                                                       block.nest_level);
514
0
      byte_offset += inst.get()->num_words * sizeof(uint32_t);
515
0
    }
516
0
  }
517
518
0
  current_function_cfg_.blocks.clear();
519
0
}
520
521
139
spv_result_t Disassembler::SaveTextResult(spv_text* text_result) const {
522
139
  if (!print_) {
523
139
    size_t length = text_.str().size();
524
139
    char* str = new char[length + 1];
525
139
    if (!str) return SPV_ERROR_OUT_OF_MEMORY;
526
139
    strncpy(str, text_.str().c_str(), length + 1);
527
139
    spv_text text = new spv_text_t();
528
139
    if (!text) {
529
0
      delete[] str;
530
0
      return SPV_ERROR_OUT_OF_MEMORY;
531
0
    }
532
139
    text->str = str;
533
139
    text->length = length;
534
139
    *text_result = text;
535
139
  }
536
139
  return SPV_SUCCESS;
537
139
}
538
539
spv_result_t DisassembleHeader(void* user_data, spv_endianness_t endian,
540
                               uint32_t /* magic */, uint32_t version,
541
                               uint32_t generator, uint32_t id_bound,
542
88
                               uint32_t schema) {
543
88
  assert(user_data);
544
88
  auto disassembler = static_cast<Disassembler*>(user_data);
545
88
  return disassembler->HandleHeader(endian, version, generator, id_bound,
546
88
                                    schema);
547
88
}
548
549
spv_result_t DisassembleInstruction(
550
14.8k
    void* user_data, const spv_parsed_instruction_t* parsed_instruction) {
551
14.8k
  assert(user_data);
552
14.8k
  auto disassembler = static_cast<Disassembler*>(user_data);
553
14.8k
  return disassembler->HandleInstruction(*parsed_instruction);
554
14.8k
}
555
556
// Simple wrapper class to provide extra data necessary for targeted
557
// instruction disassembly.
558
class WrappedDisassembler {
559
 public:
560
  WrappedDisassembler(Disassembler* dis, const uint32_t* binary, size_t wc)
561
52
      : disassembler_(dis), inst_binary_(binary), word_count_(wc) {}
562
563
104
  Disassembler* disassembler() { return disassembler_; }
564
584
  const uint32_t* inst_binary() const { return inst_binary_; }
565
1.09k
  size_t word_count() const { return word_count_; }
566
567
 private:
568
  Disassembler* disassembler_;
569
  const uint32_t* inst_binary_;
570
  const size_t word_count_;
571
};
572
573
spv_result_t DisassembleTargetHeader(void* user_data, spv_endianness_t endian,
574
                                     uint32_t /* magic */, uint32_t version,
575
                                     uint32_t generator, uint32_t id_bound,
576
52
                                     uint32_t schema) {
577
52
  assert(user_data);
578
52
  auto wrapped = static_cast<WrappedDisassembler*>(user_data);
579
52
  return wrapped->disassembler()->HandleHeader(endian, version, generator,
580
52
                                               id_bound, schema);
581
52
}
582
583
spv_result_t DisassembleTargetInstruction(
584
804
    void* user_data, const spv_parsed_instruction_t* parsed_instruction) {
585
804
  assert(user_data);
586
804
  auto wrapped = static_cast<WrappedDisassembler*>(user_data);
587
  // Check if this is the instruction we want to disassemble.
588
804
  if (wrapped->word_count() == parsed_instruction->num_words &&
589
292
      std::equal(wrapped->inst_binary(),
590
292
                 wrapped->inst_binary() + wrapped->word_count(),
591
292
                 parsed_instruction->words)) {
592
    // Found the target instruction. Disassemble it and signal that we should
593
    // stop searching so we don't output the same instruction again.
594
52
    if (auto error =
595
52
            wrapped->disassembler()->HandleInstruction(*parsed_instruction))
596
0
      return error;
597
52
    return SPV_REQUESTED_TERMINATION;
598
52
  }
599
752
  return SPV_SUCCESS;
600
804
}
601
602
0
uint32_t GetLineLengthWithoutColor(const std::string line) {
603
  // Currently, every added color is in the form \x1b...m, so instead of doing a
604
  // lot of string comparisons with spvtools::clr::* strings, we just ignore
605
  // those ranges.
606
0
  uint32_t length = 0;
607
0
  for (size_t i = 0; i < line.size(); ++i) {
608
0
    if (line[i] == '\x1b') {
609
0
      do {
610
0
        ++i;
611
0
      } while (i < line.size() && line[i] != 'm');
612
0
      continue;
613
0
    }
614
615
0
    ++length;
616
0
  }
617
618
0
  return length;
619
0
}
620
621
constexpr int kStandardIndent = 15;
622
constexpr int kBlockNestIndent = 2;
623
constexpr int kBlockBodyIndentOffset = 2;
624
constexpr uint32_t kCommentColumn = 50;
625
}  // namespace
626
627
namespace disassemble {
628
InstructionDisassembler::InstructionDisassembler(std::ostream& stream,
629
                                                 uint32_t options,
630
                                                 NameMapper name_mapper)
631
140
    : stream_(stream),
632
140
      print_(spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_PRINT, options)),
633
140
      color_(spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_COLOR, options)),
634
140
      indent_(spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_INDENT, options)
635
140
                  ? kStandardIndent
636
140
                  : 0),
637
      nested_indent_(
638
140
          spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_NESTED_INDENT, options)),
639
140
      comment_(spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_COMMENT, options)),
640
      show_byte_offset_(
641
140
          spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_SHOW_BYTE_OFFSET, options)),
642
140
      handle_unknown_opcodes_(spvIsInBitfield(
643
          SPV_BINARY_TO_TEXT_OPTION_HANDLE_UNKNOWN_OPCODES, options)),
644
140
      name_mapper_(std::move(name_mapper)),
645
140
      last_instruction_comment_alignment_(0) {}
646
647
88
void InstructionDisassembler::EmitHeaderSpirv() { stream_ << "; SPIR-V\n"; }
648
649
88
void InstructionDisassembler::EmitHeaderVersion(uint32_t version) {
650
88
  stream_ << "; Version: " << SPV_SPIRV_VERSION_MAJOR_PART(version) << "."
651
88
          << SPV_SPIRV_VERSION_MINOR_PART(version) << "\n";
652
88
}
653
654
88
void InstructionDisassembler::EmitHeaderGenerator(uint32_t generator) {
655
88
  const char* generator_tool =
656
88
      spvGeneratorStr(SPV_GENERATOR_TOOL_PART(generator));
657
88
  stream_ << "; Generator: " << generator_tool;
658
  // For unknown tools, print the numeric tool value.
659
88
  if (0 == strcmp("Unknown", generator_tool)) {
660
0
    stream_ << "(" << SPV_GENERATOR_TOOL_PART(generator) << ")";
661
0
  }
662
  // Print the miscellaneous part of the generator word on the same
663
  // line as the tool name.
664
88
  stream_ << "; " << SPV_GENERATOR_MISC_PART(generator) << "\n";
665
88
}
666
667
88
void InstructionDisassembler::EmitHeaderIdBound(uint32_t id_bound) {
668
88
  stream_ << "; Bound: " << id_bound << "\n";
669
88
}
670
671
88
void InstructionDisassembler::EmitHeaderSchema(uint32_t schema) {
672
88
  stream_ << "; Schema: " << schema << "\n";
673
88
}
674
675
void InstructionDisassembler::EmitInstruction(
676
14.8k
    const spv_parsed_instruction_t& inst, size_t inst_byte_offset) {
677
14.8k
  EmitInstructionImpl(inst, inst_byte_offset, 0, false);
678
14.8k
}
679
680
void InstructionDisassembler::EmitInstructionInBlock(
681
    const spv_parsed_instruction_t& inst, size_t inst_byte_offset,
682
0
    uint32_t block_indent) {
683
0
  EmitInstructionImpl(inst, inst_byte_offset, block_indent, true);
684
0
}
685
686
void InstructionDisassembler::EmitInstructionImpl(
687
    const spv_parsed_instruction_t& inst, size_t inst_byte_offset,
688
14.8k
    uint32_t block_indent, bool is_in_block) {
689
14.8k
  auto opcode = static_cast<spv::Op>(inst.opcode);
690
691
  // To better align the comments (if any), write the instruction to a line
692
  // first so its length can be readily available.
693
14.8k
  std::ostringstream line;
694
695
14.8k
  if (handle_unknown_opcodes_) {
696
0
    const InstructionDesc* opcode_desc = nullptr;
697
0
    bool needs_raw_emit = LookupOpcode(opcode, &opcode_desc) != SPV_SUCCESS;
698
699
    // Also check for an unknown extended instruction number in a semantic
700
    // extended instruction set. The ext_inst_type is set by the parser even
701
    // when the instruction number itself is unknown.
702
0
    if (!needs_raw_emit && opcode == spv::Op::OpExtInst &&
703
0
        inst.ext_inst_type != SPV_EXT_INST_TYPE_NONE &&
704
0
        !spvExtInstIsNonSemantic(inst.ext_inst_type) && inst.num_words >= 5) {
705
0
      const ExtInstDesc* ext_desc = nullptr;
706
0
      needs_raw_emit = LookupExtInst(inst.ext_inst_type, inst.words[4],
707
0
                                     &ext_desc) != SPV_SUCCESS;
708
0
    }
709
710
    // Also check for a known opcode whose operands were not decoded because
711
    // one of its enum operands had an unknown value. The parser signals this
712
    // by setting num_operands = 0 while leaving num_words intact.
713
    // Legitimately zero-operand instructions (OpNop, OpReturn, etc.) have an
714
    // empty grammar operand list, so this check does not trigger for them.
715
0
    if (!needs_raw_emit && opcode_desc != nullptr &&
716
0
        !opcode_desc->operands().empty() && inst.num_operands == 0) {
717
0
      needs_raw_emit = true;
718
0
    }
719
720
0
    if (needs_raw_emit) {
721
0
      line << std::string(indent_, ' ');
722
0
      line << "OpUnknown(" << inst.opcode << ", " << inst.num_words << ")";
723
0
      for (uint16_t i = 1; i < inst.num_words; i++) {
724
0
        line << " " << inst.words[i];
725
0
      }
726
      // Warn that the ID bound in the reassembled module may be incorrect
727
      // if this instruction defines a result ID, because the assembler does
728
      // not track integers inside OpUnknown as ID assignments.
729
0
      line << "  ; note: ID bound may be incorrect after reassembly";
730
0
      stream_ << line.str() << "\n";
731
0
      last_instruction_comment_alignment_ = 0;
732
0
      return;
733
0
    }
734
0
  }
735
736
14.8k
  if (nested_indent_ && opcode == spv::Op::OpLabel) {
737
    // Separate the blocks by an empty line to make them easier to separate
738
0
    stream_ << std::endl;
739
0
  }
740
741
14.8k
  if (inst.result_id) {
742
9.44k
    SetBlue(line);
743
9.44k
    const std::string id_name = name_mapper_(inst.result_id);
744
9.44k
    if (indent_)
745
9.44k
      line << std::setw(std::max(0, indent_ - 3 - int(id_name.size())));
746
9.44k
    line << "%" << id_name;
747
9.44k
    ResetColor(line);
748
9.44k
    line << " = ";
749
9.44k
  } else {
750
5.41k
    line << std::string(indent_, ' ');
751
5.41k
  }
752
753
14.8k
  if (nested_indent_ && is_in_block) {
754
    // Output OpLabel at the specified nest level, and instructions inside
755
    // blocks nested a little more.
756
0
    uint32_t indent = block_indent;
757
0
    bool body_indent = opcode != spv::Op::OpLabel;
758
759
0
    line << std::string(
760
0
        indent * kBlockNestIndent + (body_indent ? kBlockBodyIndentOffset : 0),
761
0
        ' ');
762
0
  }
763
764
14.8k
  line << "Op" << spvOpcodeString(opcode);
765
766
60.6k
  for (uint16_t i = 0; i < inst.num_operands; i++) {
767
45.8k
    const spv_operand_type_t type = inst.operands[i].type;
768
45.8k
    assert(type != SPV_OPERAND_TYPE_NONE);
769
45.8k
    if (type == SPV_OPERAND_TYPE_RESULT_ID) continue;
770
36.4k
    line << " ";
771
36.4k
    EmitOperand(line, inst, i);
772
36.4k
  }
773
774
  // For the sake of comment generation, store information from some
775
  // instructions for the future.
776
14.8k
  if (comment_) {
777
0
    GenerateCommentForDecoratedId(inst);
778
0
  }
779
780
14.8k
  std::ostringstream comments;
781
14.8k
  const char* comment_separator = "";
782
783
14.8k
  if (show_byte_offset_) {
784
0
    SetGrey(comments);
785
0
    auto saved_flags = comments.flags();
786
0
    auto saved_fill = comments.fill();
787
0
    comments << comment_separator << "0x" << std::setw(8) << std::hex
788
0
             << std::setfill('0') << inst_byte_offset;
789
0
    comments.flags(saved_flags);
790
0
    comments.fill(saved_fill);
791
0
    ResetColor(comments);
792
0
    comment_separator = ", ";
793
0
  }
794
795
14.8k
  if (comment_ && opcode == spv::Op::OpName) {
796
0
    const spv_parsed_operand_t& operand = inst.operands[0];
797
0
    const uint32_t word = inst.words[operand.offset];
798
0
    comments << comment_separator << "id %" << word;
799
0
    comment_separator = ", ";
800
0
  }
801
802
14.8k
  if (comment_ && inst.result_id && id_comments_.count(inst.result_id) > 0) {
803
0
    comments << comment_separator << id_comments_[inst.result_id].str();
804
0
    comment_separator = ", ";
805
0
  }
806
807
14.8k
  stream_ << line.str();
808
809
14.8k
  if (!comments.str().empty()) {
810
    // Align the comments
811
0
    const uint32_t line_length = GetLineLengthWithoutColor(line.str());
812
0
    uint32_t align = std::max(
813
0
        {line_length + 2, last_instruction_comment_alignment_, kCommentColumn});
814
    // Round up the alignment to a multiple of 4 for more niceness.
815
0
    align = (align + 3) & ~0x3u;
816
0
    last_instruction_comment_alignment_ = std::min({align, 256u});
817
818
0
    stream_ << std::string(align - line_length, ' ') << "; " << comments.str();
819
14.8k
  } else {
820
14.8k
    last_instruction_comment_alignment_ = 0;
821
14.8k
  }
822
823
14.8k
  stream_ << "\n";
824
14.8k
}
825
826
void InstructionDisassembler::GenerateCommentForDecoratedId(
827
0
    const spv_parsed_instruction_t& inst) {
828
0
  assert(comment_);
829
0
  auto opcode = static_cast<spv::Op>(inst.opcode);
830
831
0
  std::ostringstream partial;
832
0
  uint32_t id = 0;
833
0
  const char* separator = "";
834
835
0
  switch (opcode) {
836
0
    case spv::Op::OpDecorate:
837
      // Take everything after `OpDecorate %id` and associate it with id.
838
0
      id = inst.words[inst.operands[0].offset];
839
0
      for (uint16_t i = 1; i < inst.num_operands; i++) {
840
0
        partial << separator;
841
0
        separator = " ";
842
0
        EmitOperand(partial, inst, i);
843
0
      }
844
0
      break;
845
0
    default:
846
0
      break;
847
0
  }
848
849
0
  if (id == 0) {
850
0
    return;
851
0
  }
852
853
  // Add the new comment to the comments of this id
854
0
  std::ostringstream& id_comment = id_comments_[id];
855
0
  if (!id_comment.str().empty()) {
856
0
    id_comment << ", ";
857
0
  }
858
0
  id_comment << partial.str();
859
0
}
860
861
void InstructionDisassembler::EmitSectionComment(
862
    const spv_parsed_instruction_t& inst, bool& inserted_decoration_space,
863
14.8k
    bool& inserted_debug_space, bool& inserted_type_space) {
864
14.8k
  auto opcode = static_cast<spv::Op>(inst.opcode);
865
14.8k
  if (comment_ && opcode == spv::Op::OpFunction) {
866
0
    stream_ << std::endl;
867
0
    if (nested_indent_) {
868
      // Double the empty lines between Function sections since nested_indent_
869
      // also separates blocks by a blank.
870
0
      stream_ << std::endl;
871
0
    }
872
0
    stream_ << std::string(indent_, ' ');
873
0
    stream_ << "; Function " << name_mapper_(inst.result_id) << std::endl;
874
0
  }
875
14.8k
  if (comment_ && !inserted_decoration_space && spvOpcodeIsDecoration(opcode)) {
876
0
    inserted_decoration_space = true;
877
0
    stream_ << std::endl;
878
0
    stream_ << std::string(indent_, ' ');
879
0
    stream_ << "; Annotations" << std::endl;
880
0
  }
881
14.8k
  if (comment_ && !inserted_debug_space && spvOpcodeIsDebug(opcode)) {
882
0
    inserted_debug_space = true;
883
0
    stream_ << std::endl;
884
0
    stream_ << std::string(indent_, ' ');
885
0
    stream_ << "; Debug Information" << std::endl;
886
0
  }
887
14.8k
  if (comment_ && !inserted_type_space && spvOpcodeGeneratesType(opcode)) {
888
0
    inserted_type_space = true;
889
0
    stream_ << std::endl;
890
0
    stream_ << std::string(indent_, ' ');
891
0
    stream_ << "; Types, variables and constants" << std::endl;
892
0
  }
893
14.8k
}
894
895
void InstructionDisassembler::EmitOperand(std::ostream& stream,
896
                                          const spv_parsed_instruction_t& inst,
897
36.4k
                                          const uint16_t operand_index) const {
898
36.4k
  assert(operand_index < inst.num_operands);
899
36.4k
  const spv_parsed_operand_t& operand = inst.operands[operand_index];
900
36.4k
  const uint32_t word = inst.words[operand.offset];
901
36.4k
  switch (operand.type) {
902
0
    case SPV_OPERAND_TYPE_RESULT_ID:
903
0
      assert(false && "<result-id> is not supposed to be handled here");
904
0
      SetBlue(stream);
905
0
      stream << "%" << name_mapper_(word);
906
0
      break;
907
18.4k
    case SPV_OPERAND_TYPE_ID:
908
25.4k
    case SPV_OPERAND_TYPE_TYPE_ID:
909
25.8k
    case SPV_OPERAND_TYPE_SCOPE_ID:
910
26.2k
    case SPV_OPERAND_TYPE_MEMORY_SEMANTICS_ID:
911
26.2k
      SetYellow(stream);
912
26.2k
      stream << "%" << name_mapper_(word);
913
26.2k
      break;
914
51
    case SPV_OPERAND_TYPE_EXTENSION_INSTRUCTION_NUMBER: {
915
51
      SetRed(stream);
916
51
      const ExtInstDesc* desc = nullptr;
917
51
      if (LookupExtInst(inst.ext_inst_type, word, &desc) == SPV_SUCCESS) {
918
51
        stream << desc->name().data();
919
51
      } else {
920
0
        if (!spvExtInstIsNonSemantic(inst.ext_inst_type)) {
921
0
          assert(false && "should have caught this earlier");
922
0
        } else {
923
          // for non-semantic instruction sets we can just print the number
924
0
          stream << word;
925
0
        }
926
0
      }
927
51
    } break;
928
19
    case SPV_OPERAND_TYPE_SPEC_CONSTANT_OP_NUMBER: {
929
19
      const spvtools::InstructionDesc* opcodeEntry = nullptr;
930
19
      if (LookupOpcode(spv::Op(word), &opcodeEntry))
931
19
        assert(false && "should have caught this earlier");
932
19
      SetRed(stream);
933
19
      stream << opcodeEntry->name().data();
934
19
    } break;
935
3.82k
    case SPV_OPERAND_TYPE_LITERAL_INTEGER:
936
4.39k
    case SPV_OPERAND_TYPE_TYPED_LITERAL_NUMBER:
937
4.39k
    case SPV_OPERAND_TYPE_LITERAL_FLOAT: {
938
4.39k
      SetRed(stream);
939
4.39k
      EmitNumericLiteral(&stream, inst, operand);
940
4.39k
      ResetColor(stream);
941
4.39k
    } break;
942
1.55k
    case SPV_OPERAND_TYPE_LITERAL_STRING: {
943
1.55k
      stream << "\"";
944
1.55k
      SetGreen(stream);
945
946
1.55k
      std::string str = spvDecodeLiteralStringOperand(inst, operand_index);
947
16.1k
      for (char const& c : str) {
948
16.1k
        if (c == '"' || c == '\\') stream << '\\';
949
16.1k
        stream << c;
950
16.1k
      }
951
1.55k
      ResetColor(stream);
952
1.55k
      stream << '"';
953
1.55k
    } break;
954
287
    case SPV_OPERAND_TYPE_CAPABILITY:
955
287
    case SPV_OPERAND_TYPE_OPTIONAL_CAPABILITY:
956
331
    case SPV_OPERAND_TYPE_SOURCE_LANGUAGE:
957
419
    case SPV_OPERAND_TYPE_EXECUTION_MODEL:
958
507
    case SPV_OPERAND_TYPE_ADDRESSING_MODEL:
959
595
    case SPV_OPERAND_TYPE_MEMORY_MODEL:
960
595
    case SPV_OPERAND_TYPE_EXECUTION_MODE:
961
1.83k
    case SPV_OPERAND_TYPE_STORAGE_CLASS:
962
1.99k
    case SPV_OPERAND_TYPE_DIMENSIONALITY:
963
1.99k
    case SPV_OPERAND_TYPE_SAMPLER_ADDRESSING_MODE:
964
1.99k
    case SPV_OPERAND_TYPE_SAMPLER_FILTER_MODE:
965
2.15k
    case SPV_OPERAND_TYPE_SAMPLER_IMAGE_FORMAT:
966
2.15k
    case SPV_OPERAND_TYPE_FP_ROUNDING_MODE:
967
2.15k
    case SPV_OPERAND_TYPE_LINKAGE_TYPE:
968
2.15k
    case SPV_OPERAND_TYPE_ACCESS_QUALIFIER:
969
2.15k
    case SPV_OPERAND_TYPE_FUNCTION_PARAMETER_ATTRIBUTE:
970
3.64k
    case SPV_OPERAND_TYPE_DECORATION:
971
3.67k
    case SPV_OPERAND_TYPE_BUILT_IN:
972
3.67k
    case SPV_OPERAND_TYPE_GROUP_OPERATION:
973
3.67k
    case SPV_OPERAND_TYPE_KERNEL_ENQ_FLAGS:
974
3.67k
    case SPV_OPERAND_TYPE_KERNEL_PROFILING_INFO:
975
3.67k
    case SPV_OPERAND_TYPE_RAY_FLAGS:
976
3.67k
    case SPV_OPERAND_TYPE_RAY_QUERY_INTERSECTION:
977
3.67k
    case SPV_OPERAND_TYPE_RAY_QUERY_COMMITTED_INTERSECTION_TYPE:
978
3.67k
    case SPV_OPERAND_TYPE_RAY_QUERY_CANDIDATE_INTERSECTION_TYPE:
979
3.67k
    case SPV_OPERAND_TYPE_DEBUG_BASE_TYPE_ATTRIBUTE_ENCODING:
980
3.67k
    case SPV_OPERAND_TYPE_DEBUG_COMPOSITE_TYPE:
981
3.67k
    case SPV_OPERAND_TYPE_DEBUG_TYPE_QUALIFIER:
982
3.67k
    case SPV_OPERAND_TYPE_DEBUG_OPERATION:
983
3.67k
    case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_BASE_TYPE_ATTRIBUTE_ENCODING:
984
3.67k
    case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_COMPOSITE_TYPE:
985
3.67k
    case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_TYPE_QUALIFIER:
986
3.67k
    case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_OPERATION:
987
3.67k
    case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_IMPORTED_ENTITY:
988
3.67k
    case SPV_OPERAND_TYPE_FPDENORM_MODE:
989
3.67k
    case SPV_OPERAND_TYPE_FPOPERATION_MODE:
990
3.67k
    case SPV_OPERAND_TYPE_QUANTIZATION_MODES:
991
3.67k
    case SPV_OPERAND_TYPE_FPENCODING:
992
3.67k
    case SPV_OPERAND_TYPE_OVERFLOW_MODES: {
993
3.67k
      const spvtools::OperandDesc* entry = nullptr;
994
3.67k
      if (spvtools::LookupOperand(operand.type, word, &entry))
995
3.67k
        assert(false && "should have caught this earlier");
996
3.67k
      stream << entry->name().data();
997
3.67k
    } break;
998
0
    case SPV_OPERAND_TYPE_FP_FAST_MATH_MODE:
999
110
    case SPV_OPERAND_TYPE_FUNCTION_CONTROL:
1000
160
    case SPV_OPERAND_TYPE_LOOP_CONTROL:
1001
236
    case SPV_OPERAND_TYPE_IMAGE:
1002
260
    case SPV_OPERAND_TYPE_MEMORY_ACCESS:
1003
404
    case SPV_OPERAND_TYPE_SELECTION_CONTROL:
1004
404
    case SPV_OPERAND_TYPE_DEBUG_INFO_FLAGS:
1005
404
    case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_INFO_FLAGS:
1006
404
    case SPV_OPERAND_TYPE_RAW_ACCESS_CHAIN_OPERANDS:
1007
404
      EmitMaskOperand(stream, operand.type, word);
1008
404
      break;
1009
24
    default:
1010
24
      if (spvOperandIsConcreteMask(operand.type)) {
1011
0
        EmitMaskOperand(stream, operand.type, word);
1012
24
      } else if (spvOperandIsConcrete(operand.type)) {
1013
24
        const spvtools::OperandDesc* entry = nullptr;
1014
24
        if (spvtools::LookupOperand(operand.type, word, &entry))
1015
24
          assert(false && "should have caught this earlier");
1016
24
        stream << entry->name().data();
1017
24
      } else {
1018
0
        assert(false && "unhandled or invalid case");
1019
0
      }
1020
24
      break;
1021
36.4k
  }
1022
36.4k
  ResetColor(stream);
1023
36.4k
}
1024
1025
void InstructionDisassembler::EmitMaskOperand(std::ostream& stream,
1026
                                              const spv_operand_type_t type,
1027
404
                                              const uint32_t word) const {
1028
  // Scan the mask from least significant bit to most significant bit.  For each
1029
  // set bit, emit the name of that bit. Separate multiple names with '|'.
1030
404
  uint32_t remaining_word = word;
1031
404
  uint32_t mask;
1032
404
  int num_emitted = 0;
1033
688
  for (mask = 1; remaining_word; mask <<= 1) {
1034
284
    if (remaining_word & mask) {
1035
134
      remaining_word ^= mask;
1036
134
      const spvtools::OperandDesc* entry = nullptr;
1037
134
      if (spvtools::LookupOperand(type, mask, &entry))
1038
134
        assert(false && "should have caught this earlier");
1039
134
      if (num_emitted) stream << "|";
1040
134
      stream << entry->name().data();
1041
134
      num_emitted++;
1042
134
    }
1043
284
  }
1044
404
  if (!num_emitted) {
1045
    // An operand value of 0 was provided, so represent it by the name
1046
    // of the 0 value. In many cases, that's "None".
1047
274
    const spvtools::OperandDesc* entry = nullptr;
1048
274
    if (SPV_SUCCESS == spvtools::LookupOperand(type, 0, &entry))
1049
274
      stream << entry->name().data();
1050
274
  }
1051
404
}
1052
1053
51.7k
void InstructionDisassembler::ResetColor(std::ostream& stream) const {
1054
51.7k
  if (color_) stream << spvtools::clr::reset{print_};
1055
51.7k
}
1056
0
void InstructionDisassembler::SetGrey(std::ostream& stream) const {
1057
0
  if (color_) stream << spvtools::clr::grey{print_};
1058
0
}
1059
9.44k
void InstructionDisassembler::SetBlue(std::ostream& stream) const {
1060
9.44k
  if (color_) stream << spvtools::clr::blue{print_};
1061
9.44k
}
1062
26.2k
void InstructionDisassembler::SetYellow(std::ostream& stream) const {
1063
26.2k
  if (color_) stream << spvtools::clr::yellow{print_};
1064
26.2k
}
1065
4.46k
void InstructionDisassembler::SetRed(std::ostream& stream) const {
1066
4.46k
  if (color_) stream << spvtools::clr::red{print_};
1067
4.46k
}
1068
1.55k
void InstructionDisassembler::SetGreen(std::ostream& stream) const {
1069
1.55k
  if (color_) stream << spvtools::clr::green{print_};
1070
1.55k
}
1071
1072
0
void InstructionDisassembler::ResetColor() { ResetColor(stream_); }
1073
0
void InstructionDisassembler::SetGrey() { SetGrey(stream_); }
1074
0
void InstructionDisassembler::SetBlue() { SetBlue(stream_); }
1075
0
void InstructionDisassembler::SetYellow() { SetYellow(stream_); }
1076
0
void InstructionDisassembler::SetRed() { SetRed(stream_); }
1077
0
void InstructionDisassembler::SetGreen() { SetGreen(stream_); }
1078
}  // namespace disassemble
1079
1080
std::string spvInstructionBinaryToText(const spv_target_env env,
1081
                                       const uint32_t* instCode,
1082
                                       const size_t instWordCount,
1083
                                       const uint32_t* code,
1084
                                       const size_t wordCount,
1085
52
                                       const uint32_t options) {
1086
52
  spv_context context = spvContextCreate(env);
1087
1088
  // Generate friendly names for Ids if requested.
1089
52
  std::unique_ptr<FriendlyNameMapper> friendly_mapper;
1090
52
  NameMapper name_mapper = GetTrivialNameMapper();
1091
52
  if (options & SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES) {
1092
52
    friendly_mapper =
1093
52
        MakeUnique<FriendlyNameMapper>(context, code, wordCount, options);
1094
52
    name_mapper = friendly_mapper->GetNameMapper();
1095
52
  }
1096
1097
  // Now disassemble!
1098
52
  Disassembler disassembler(options, name_mapper);
1099
52
  WrappedDisassembler wrapped(&disassembler, instCode, instWordCount);
1100
52
  spvBinaryParseWithOptions(context, &wrapped, code, wordCount,
1101
52
                            DisassembleTargetHeader,
1102
52
                            DisassembleTargetInstruction, nullptr, options);
1103
1104
52
  spv_text text = nullptr;
1105
52
  std::string output;
1106
52
  if (disassembler.SaveTextResult(&text) == SPV_SUCCESS) {
1107
52
    output.assign(text->str, text->str + text->length);
1108
    // Drop trailing newline characters.
1109
104
    while (!output.empty() && output.back() == '\n') output.pop_back();
1110
52
  }
1111
52
  spvTextDestroy(text);
1112
52
  spvContextDestroy(context);
1113
1114
52
  return output;
1115
52
}
1116
}  // namespace spvtools
1117
1118
spv_result_t spvBinaryToText(const spv_const_context context,
1119
                             const uint32_t* code, const size_t wordCount,
1120
                             const uint32_t options, spv_text* pText,
1121
88
                             spv_diagnostic* pDiagnostic) {
1122
88
  spv_context_t hijack_context = *context;
1123
88
  if (pDiagnostic) {
1124
0
    *pDiagnostic = nullptr;
1125
0
    spvtools::UseDiagnosticAsMessageConsumer(&hijack_context, pDiagnostic);
1126
0
  }
1127
1128
  // Generate friendly names for Ids if requested.
1129
88
  std::unique_ptr<spvtools::FriendlyNameMapper> friendly_mapper;
1130
88
  spvtools::NameMapper name_mapper = spvtools::GetTrivialNameMapper();
1131
88
  if (options & SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES) {
1132
88
    friendly_mapper = spvtools::MakeUnique<spvtools::FriendlyNameMapper>(
1133
88
        &hijack_context, code, wordCount, options);
1134
88
    name_mapper = friendly_mapper->GetNameMapper();
1135
88
  }
1136
1137
  // Now disassemble!
1138
88
  spvtools::Disassembler disassembler(options, name_mapper);
1139
88
  if (auto error = spvBinaryParseWithOptions(
1140
88
          &hijack_context, &disassembler, code, wordCount,
1141
88
          spvtools::DisassembleHeader, spvtools::DisassembleInstruction,
1142
88
          pDiagnostic, options)) {
1143
1
    return error;
1144
1
  }
1145
1146
87
  return disassembler.SaveTextResult(pText);
1147
88
}