Coverage Report

Created: 2026-12-01 07:22

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
321
      : print_(spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_PRINT, options)),
120
        nested_indent_(
121
321
            spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_NESTED_INDENT, options)),
122
        reorder_blocks_(
123
321
            spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_REORDER_BLOCKS, options)),
124
321
        text_(),
125
321
        out_(print_ ? out_stream() : out_stream(text_)),
126
321
        instruction_disassembler_(out_.get(), options, name_mapper),
127
321
        header_(!spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_NO_HEADER, options)),
128
321
        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
321
                                        uint32_t id_bound, uint32_t schema) {
168
321
  endian_ = endian;
169
170
321
  if (header_) {
171
271
    instruction_disassembler_.EmitHeaderSpirv();
172
271
    instruction_disassembler_.EmitHeaderVersion(version);
173
271
    instruction_disassembler_.EmitHeaderGenerator(generator);
174
271
    instruction_disassembler_.EmitHeaderIdBound(id_bound);
175
271
    instruction_disassembler_.EmitHeaderSchema(schema);
176
271
  }
177
178
321
  byte_offset_ = SPV_INDEX_INSTRUCTION * sizeof(uint32_t);
179
180
321
  return SPV_SUCCESS;
181
321
}
182
183
spv_result_t Disassembler::HandleInstruction(
184
72.6k
    const spv_parsed_instruction_t& inst) {
185
72.6k
  instruction_disassembler_.EmitSectionComment(inst, inserted_decoration_space_,
186
72.6k
                                               inserted_debug_space_,
187
72.6k
                                               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
72.6k
  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
72.6k
  } else {
223
72.6k
    instruction_disassembler_.EmitInstruction(inst, byte_offset_);
224
72.6k
  }
225
226
72.6k
  byte_offset_ += inst.num_words * sizeof(uint32_t);
227
228
72.6k
  return SPV_SUCCESS;
229
72.6k
}
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
  // The id may not refer to a block in this function if the CFG is malformed.
317
0
  const auto iter = id_to_index.find(id);
318
0
  if (iter == id_to_index.end()) {
319
0
    return;
320
0
  }
321
322
0
  SingleBlock& block = cfg.blocks[iter->second];
323
324
0
  if (!block.nest_level_assigned) {
325
0
    block.nest_level = level;
326
0
    block.nest_level_assigned = true;
327
0
  }
328
0
}
329
330
// For a given block, assign nesting level to its successors.
331
void NestSuccessors(ControlFlowGraph& cfg, const SingleBlock& block,
332
0
                    const std::unordered_map<uint32_t, uint32_t>& id_to_index) {
333
0
  assert(block.nest_level_assigned);
334
335
  // Nest loops as such:
336
  //
337
  //     %loop = OpLabel
338
  //               OpLoopMerge %merge %cont ...
339
  //               OpBranch %body
340
  //     %body =     OpLabel
341
  //                   Op...
342
  //     %cont =   OpLabel
343
  //                 Op...
344
  //    %merge = OpLabel
345
  //               Op...
346
  //
347
  // Nest conditional branches as such:
348
  //
349
  //   %header = OpLabel
350
  //               OpSelectionMerge %merge ...
351
  //               OpBranchConditional ... %true %false
352
  //     %true =     OpLabel
353
  //                   Op...
354
  //    %false =     OpLabel
355
  //                   Op...
356
  //    %merge = OpLabel
357
  //               Op...
358
  //
359
  // Nest switch/case as such:
360
  //
361
  //   %header = OpLabel
362
  //               OpSelectionMerge %merge ...
363
  //               OpSwitch ... %default ... %case0 ... %case1 ...
364
  //  %default =     OpLabel
365
  //                   Op...
366
  //    %case0 =     OpLabel
367
  //                   Op...
368
  //    %case1 =     OpLabel
369
  //                   Op...
370
  //             ...
371
  //    %merge = OpLabel
372
  //               Op...
373
  //
374
  // The following can be observed:
375
  //
376
  // - In all cases, the merge block has the same nesting as this block
377
  // - The continue block of loops is nested 1 level deeper
378
  // - The body/branches/cases are nested 2 levels deeper
379
  //
380
  // Back branches to the header block, branches to the merge block, etc
381
  // are correctly handled by processing the header block first (that is
382
  // _this_ block, already processed), then following the above rules
383
  // (in the same order) for any block that is not already processed.
384
0
  Nest(cfg, id_to_index, block.successors.merge_block_id, block.nest_level);
385
0
  Nest(cfg, id_to_index, block.successors.continue_block_id,
386
0
       block.nest_level + 1);
387
0
  Nest(cfg, id_to_index, block.successors.true_block_id, block.nest_level + 2);
388
0
  Nest(cfg, id_to_index, block.successors.false_block_id, block.nest_level + 2);
389
0
  Nest(cfg, id_to_index, block.successors.body_block_id, block.nest_level + 2);
390
0
  Nest(cfg, id_to_index, block.successors.next_block_id, block.nest_level);
391
0
  for (uint32_t case_block_id : block.successors.case_block_ids) {
392
0
    Nest(cfg, id_to_index, case_block_id, block.nest_level + 2);
393
0
  }
394
0
}
395
396
struct StackEntry {
397
  // The index of the block (in ControlFlowGraph::blocks) to process.
398
  uint32_t block_index;
399
  // Whether this is the pre or post visit of the block.  Because a post-visit
400
  // traversal is needed, the same block is pushed back on the stack on
401
  // pre-visit so it can be visited again on post-visit.
402
  bool post_visit = false;
403
};
404
405
// Helper to deal with DFS traversal and non-existing ids
406
void VisitSuccesor(std::stack<StackEntry>* dfs_stack,
407
                   const std::unordered_map<uint32_t, uint32_t>& id_to_index,
408
0
                   uint32_t id) {
409
0
  if (id == 0) {
410
0
    return;
411
0
  }
412
413
  // The id may not refer to a block in this function if the CFG is malformed.
414
0
  const auto iter = id_to_index.find(id);
415
0
  if (iter == id_to_index.end()) {
416
0
    return;
417
0
  }
418
419
0
  dfs_stack->push({iter->second, false});
420
0
}
421
422
// Given the control flow graph, calculates and returns the reverse post-order
423
// ordering of the blocks.  The blocks are then disassembled in that order for
424
// readability.
425
std::vector<uint32_t> OrderBlocks(
426
    ControlFlowGraph& cfg,
427
0
    const std::unordered_map<uint32_t, uint32_t>& id_to_index) {
428
0
  std::vector<uint32_t> post_order;
429
430
  // Nest level of a function's first block is 0.
431
0
  cfg.blocks[0].nest_level = 0;
432
0
  cfg.blocks[0].nest_level_assigned = true;
433
434
  // Stack of block indices as they are visited.
435
0
  std::stack<StackEntry> dfs_stack;
436
0
  dfs_stack.push({0, false});
437
438
0
  std::set<uint32_t> visited;
439
440
0
  while (!dfs_stack.empty()) {
441
0
    const uint32_t block_index = dfs_stack.top().block_index;
442
0
    const bool post_visit = dfs_stack.top().post_visit;
443
0
    dfs_stack.pop();
444
445
    // If this is the second time the block is visited, that's the post-order
446
    // visit.
447
0
    if (post_visit) {
448
0
      post_order.push_back(block_index);
449
0
      continue;
450
0
    }
451
452
    // If already visited, another path got to it first (like a case
453
    // fallthrough), avoid reprocessing it.
454
0
    if (visited.count(block_index) > 0) {
455
0
      continue;
456
0
    }
457
0
    visited.insert(block_index);
458
459
    // Push it back in the stack for post-order visit
460
0
    dfs_stack.push({block_index, true});
461
462
0
    SingleBlock& block = cfg.blocks[block_index];
463
464
    // Assign nest levels of successors right away.  The successors are either
465
    // nested under this block, or are back or forward edges to blocks outside
466
    // this nesting level (no farther than the merge block), whose nesting
467
    // levels are already assigned before this block is visited.
468
0
    NestSuccessors(cfg, block, id_to_index);
469
0
    block.reachable = true;
470
471
    // The post-order visit yields the order in which the blocks are naturally
472
    // ordered _backwards_. So blocks to be ordered last should be visited
473
    // first.  In other words, they should be pushed to the DFS stack last.
474
0
    VisitSuccesor(&dfs_stack, id_to_index, block.successors.true_block_id);
475
0
    VisitSuccesor(&dfs_stack, id_to_index, block.successors.false_block_id);
476
0
    VisitSuccesor(&dfs_stack, id_to_index, block.successors.body_block_id);
477
0
    VisitSuccesor(&dfs_stack, id_to_index, block.successors.next_block_id);
478
0
    for (uint32_t case_block_id : block.successors.case_block_ids) {
479
0
      VisitSuccesor(&dfs_stack, id_to_index, case_block_id);
480
0
    }
481
0
    VisitSuccesor(&dfs_stack, id_to_index, block.successors.continue_block_id);
482
0
    VisitSuccesor(&dfs_stack, id_to_index, block.successors.merge_block_id);
483
0
  }
484
485
0
  std::vector<uint32_t> order(post_order.rbegin(), post_order.rend());
486
487
  // Finally, dump all unreachable blocks at the end
488
0
  for (size_t index = 0; index < cfg.blocks.size(); ++index) {
489
0
    SingleBlock& block = cfg.blocks[index];
490
491
0
    if (!block.reachable) {
492
0
      order.push_back(static_cast<uint32_t>(index));
493
0
      block.nest_level = 0;
494
0
      block.nest_level_assigned = true;
495
0
    }
496
0
  }
497
498
0
  return order;
499
0
}
500
501
0
void Disassembler::EmitCFG() {
502
  // Build the CFG edges.  At the same time, build an ID->block index map to
503
  // simplify building the CFG edges.
504
0
  const std::unordered_map<uint32_t, uint32_t> id_to_index =
505
0
      BuildControlFlowGraph(current_function_cfg_);
506
507
  // Walk the CFG in reverse post-order to find the best ordering of blocks for
508
  // presentation
509
0
  std::vector<uint32_t> block_order =
510
0
      OrderBlocks(current_function_cfg_, id_to_index);
511
0
  assert(block_order.size() == current_function_cfg_.blocks.size());
512
513
  // Walk the CFG either in block order or input order based on whether the
514
  // reorder_blocks_ option is given.
515
0
  for (uint32_t index = 0; index < current_function_cfg_.blocks.size();
516
0
       ++index) {
517
0
    const uint32_t block_index = reorder_blocks_ ? block_order[index] : index;
518
0
    const SingleBlock& block = current_function_cfg_.blocks[block_index];
519
520
    // Emit instructions for this block
521
0
    size_t byte_offset = block.byte_offset;
522
0
    assert(block.nest_level_assigned);
523
524
0
    for (const ParsedInstruction& inst : block.instructions) {
525
0
      instruction_disassembler_.EmitInstructionInBlock(*inst.get(), byte_offset,
526
0
                                                       block.nest_level);
527
0
      byte_offset += inst.get()->num_words * sizeof(uint32_t);
528
0
    }
529
0
  }
530
531
0
  current_function_cfg_.blocks.clear();
532
0
}
533
534
320
spv_result_t Disassembler::SaveTextResult(spv_text* text_result) const {
535
320
  if (!print_) {
536
320
    size_t length = text_.str().size();
537
320
    char* str = new char[length + 1];
538
320
    if (!str) return SPV_ERROR_OUT_OF_MEMORY;
539
320
    strncpy(str, text_.str().c_str(), length + 1);
540
320
    spv_text text = new spv_text_t();
541
320
    if (!text) {
542
0
      delete[] str;
543
0
      return SPV_ERROR_OUT_OF_MEMORY;
544
0
    }
545
320
    text->str = str;
546
320
    text->length = length;
547
320
    *text_result = text;
548
320
  }
549
320
  return SPV_SUCCESS;
550
320
}
551
552
spv_result_t DisassembleHeader(void* user_data, spv_endianness_t endian,
553
                               uint32_t /* magic */, uint32_t version,
554
                               uint32_t generator, uint32_t id_bound,
555
271
                               uint32_t schema) {
556
271
  assert(user_data);
557
271
  auto disassembler = static_cast<Disassembler*>(user_data);
558
271
  return disassembler->HandleHeader(endian, version, generator, id_bound,
559
271
                                    schema);
560
271
}
561
562
spv_result_t DisassembleInstruction(
563
72.6k
    void* user_data, const spv_parsed_instruction_t* parsed_instruction) {
564
72.6k
  assert(user_data);
565
72.6k
  auto disassembler = static_cast<Disassembler*>(user_data);
566
72.6k
  return disassembler->HandleInstruction(*parsed_instruction);
567
72.6k
}
568
569
// Simple wrapper class to provide extra data necessary for targeted
570
// instruction disassembly.
571
class WrappedDisassembler {
572
 public:
573
  WrappedDisassembler(Disassembler* dis, const uint32_t* binary, size_t wc)
574
50
      : disassembler_(dis), inst_binary_(binary), word_count_(wc) {}
575
576
100
  Disassembler* disassembler() { return disassembler_; }
577
440
  const uint32_t* inst_binary() const { return inst_binary_; }
578
1.17k
  size_t word_count() const { return word_count_; }
579
580
 private:
581
  Disassembler* disassembler_;
582
  const uint32_t* inst_binary_;
583
  const size_t word_count_;
584
};
585
586
spv_result_t DisassembleTargetHeader(void* user_data, spv_endianness_t endian,
587
                                     uint32_t /* magic */, uint32_t version,
588
                                     uint32_t generator, uint32_t id_bound,
589
50
                                     uint32_t schema) {
590
50
  assert(user_data);
591
50
  auto wrapped = static_cast<WrappedDisassembler*>(user_data);
592
50
  return wrapped->disassembler()->HandleHeader(endian, version, generator,
593
50
                                               id_bound, schema);
594
50
}
595
596
spv_result_t DisassembleTargetInstruction(
597
954
    void* user_data, const spv_parsed_instruction_t* parsed_instruction) {
598
954
  assert(user_data);
599
954
  auto wrapped = static_cast<WrappedDisassembler*>(user_data);
600
  // Check if this is the instruction we want to disassemble.
601
954
  if (wrapped->word_count() == parsed_instruction->num_words &&
602
220
      std::equal(wrapped->inst_binary(),
603
220
                 wrapped->inst_binary() + wrapped->word_count(),
604
220
                 parsed_instruction->words)) {
605
    // Found the target instruction. Disassemble it and signal that we should
606
    // stop searching so we don't output the same instruction again.
607
50
    if (auto error =
608
50
            wrapped->disassembler()->HandleInstruction(*parsed_instruction))
609
0
      return error;
610
50
    return SPV_REQUESTED_TERMINATION;
611
50
  }
612
904
  return SPV_SUCCESS;
613
954
}
614
615
0
uint32_t GetLineLengthWithoutColor(const std::string& line) {
616
  // Currently, every added color is in the form \x1b...m, so instead of doing a
617
  // lot of string comparisons with spvtools::clr::* strings, we just ignore
618
  // those ranges.
619
0
  uint32_t length = 0;
620
0
  for (size_t i = 0; i < line.size(); ++i) {
621
0
    if (line[i] == '\x1b') {
622
0
      do {
623
0
        ++i;
624
0
      } while (i < line.size() && line[i] != 'm');
625
0
      continue;
626
0
    }
627
628
0
    ++length;
629
0
  }
630
631
0
  return length;
632
0
}
633
634
constexpr int kStandardIndent = 15;
635
constexpr int kBlockNestIndent = 2;
636
constexpr int kBlockBodyIndentOffset = 2;
637
constexpr uint32_t kCommentColumn = 50;
638
}  // namespace
639
640
namespace disassemble {
641
InstructionDisassembler::InstructionDisassembler(std::ostream& stream,
642
                                                 uint32_t options,
643
                                                 NameMapper name_mapper)
644
321
    : stream_(stream),
645
321
      print_(spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_PRINT, options)),
646
321
      color_(spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_COLOR, options)),
647
321
      indent_(spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_INDENT, options)
648
321
                  ? kStandardIndent
649
321
                  : 0),
650
      nested_indent_(
651
321
          spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_NESTED_INDENT, options)),
652
321
      comment_(spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_COMMENT, options)),
653
      show_byte_offset_(
654
321
          spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_SHOW_BYTE_OFFSET, options)),
655
321
      handle_unknown_opcodes_(spvIsInBitfield(
656
          SPV_BINARY_TO_TEXT_OPTION_HANDLE_UNKNOWN_OPCODES, options)),
657
321
      name_mapper_(std::move(name_mapper)),
658
321
      last_instruction_comment_alignment_(0) {}
659
660
271
void InstructionDisassembler::EmitHeaderSpirv() { stream_ << "; SPIR-V\n"; }
661
662
271
void InstructionDisassembler::EmitHeaderVersion(uint32_t version) {
663
271
  stream_ << "; Version: " << SPV_SPIRV_VERSION_MAJOR_PART(version) << "."
664
271
          << SPV_SPIRV_VERSION_MINOR_PART(version) << "\n";
665
271
}
666
667
271
void InstructionDisassembler::EmitHeaderGenerator(uint32_t generator) {
668
271
  const char* generator_tool =
669
271
      spvGeneratorStr(SPV_GENERATOR_TOOL_PART(generator));
670
271
  stream_ << "; Generator: " << generator_tool;
671
  // For unknown tools, print the numeric tool value.
672
271
  if (0 == strcmp("Unknown", generator_tool)) {
673
0
    stream_ << "(" << SPV_GENERATOR_TOOL_PART(generator) << ")";
674
0
  }
675
  // Print the miscellaneous part of the generator word on the same
676
  // line as the tool name.
677
271
  stream_ << "; " << SPV_GENERATOR_MISC_PART(generator) << "\n";
678
271
}
679
680
271
void InstructionDisassembler::EmitHeaderIdBound(uint32_t id_bound) {
681
271
  stream_ << "; Bound: " << id_bound << "\n";
682
271
}
683
684
271
void InstructionDisassembler::EmitHeaderSchema(uint32_t schema) {
685
271
  stream_ << "; Schema: " << schema << "\n";
686
271
}
687
688
void InstructionDisassembler::EmitInstruction(
689
72.6k
    const spv_parsed_instruction_t& inst, size_t inst_byte_offset) {
690
72.6k
  EmitInstructionImpl(inst, inst_byte_offset, 0, false);
691
72.6k
}
692
693
void InstructionDisassembler::EmitInstructionInBlock(
694
    const spv_parsed_instruction_t& inst, size_t inst_byte_offset,
695
0
    uint32_t block_indent) {
696
0
  EmitInstructionImpl(inst, inst_byte_offset, block_indent, true);
697
0
}
698
699
void InstructionDisassembler::EmitInstructionImpl(
700
    const spv_parsed_instruction_t& inst, size_t inst_byte_offset,
701
72.6k
    uint32_t block_indent, bool is_in_block) {
702
72.6k
  auto opcode = static_cast<spv::Op>(inst.opcode);
703
704
  // To better align the comments (if any), write the instruction to a line
705
  // first so its length can be readily available.
706
72.6k
  std::ostringstream line;
707
708
72.6k
  if (handle_unknown_opcodes_) {
709
0
    const InstructionDesc* opcode_desc = nullptr;
710
0
    bool needs_raw_emit = LookupOpcode(opcode, &opcode_desc) != SPV_SUCCESS;
711
712
    // Also check for an unknown extended instruction number in a semantic
713
    // extended instruction set. The ext_inst_type is set by the parser even
714
    // when the instruction number itself is unknown.
715
0
    if (!needs_raw_emit && opcode == spv::Op::OpExtInst &&
716
0
        inst.ext_inst_type != SPV_EXT_INST_TYPE_NONE &&
717
0
        !spvExtInstIsNonSemantic(inst.ext_inst_type) && inst.num_words >= 5) {
718
0
      const ExtInstDesc* ext_desc = nullptr;
719
0
      needs_raw_emit = LookupExtInst(inst.ext_inst_type, inst.words[4],
720
0
                                     &ext_desc) != SPV_SUCCESS;
721
0
    }
722
723
    // Also check for a known opcode whose operands were not decoded because
724
    // one of its enum operands had an unknown value. The parser signals this
725
    // by setting num_operands = 0 while leaving num_words intact.
726
    // Legitimately zero-operand instructions (OpNop, OpReturn, etc.) have an
727
    // empty grammar operand list, so this check does not trigger for them.
728
0
    if (!needs_raw_emit && opcode_desc != nullptr &&
729
0
        !opcode_desc->operands().empty() && inst.num_operands == 0) {
730
0
      needs_raw_emit = true;
731
0
    }
732
733
0
    if (needs_raw_emit) {
734
0
      line << std::string(indent_, ' ');
735
0
      line << "OpUnknown(" << inst.opcode << ", " << inst.num_words << ")";
736
0
      for (uint16_t i = 1; i < inst.num_words; i++) {
737
0
        line << " " << inst.words[i];
738
0
      }
739
      // Warn that the ID bound in the reassembled module may be incorrect
740
      // if this instruction defines a result ID, because the assembler does
741
      // not track integers inside OpUnknown as ID assignments.
742
0
      line << "  ; note: ID bound may be incorrect after reassembly";
743
0
      stream_ << line.str() << "\n";
744
0
      last_instruction_comment_alignment_ = 0;
745
0
      return;
746
0
    }
747
0
  }
748
749
72.6k
  if (nested_indent_ && opcode == spv::Op::OpLabel) {
750
    // Separate the blocks by an empty line to make them easier to separate
751
0
    stream_ << std::endl;
752
0
  }
753
754
72.6k
  if (inst.result_id) {
755
52.0k
    SetBlue(line);
756
52.0k
    const std::string id_name = name_mapper_(inst.result_id);
757
52.0k
    if (indent_)
758
52.0k
      line << std::setw(std::max(0, indent_ - 3 - int(id_name.size())));
759
52.0k
    line << "%" << id_name;
760
52.0k
    ResetColor(line);
761
52.0k
    line << " = ";
762
52.0k
  } else {
763
20.6k
    line << std::string(indent_, ' ');
764
20.6k
  }
765
766
72.6k
  if (nested_indent_ && is_in_block) {
767
    // Output OpLabel at the specified nest level, and instructions inside
768
    // blocks nested a little more.
769
0
    uint32_t indent = block_indent;
770
0
    bool body_indent = opcode != spv::Op::OpLabel;
771
772
0
    line << std::string(
773
0
        indent * kBlockNestIndent + (body_indent ? kBlockBodyIndentOffset : 0),
774
0
        ' ');
775
0
  }
776
777
72.6k
  line << "Op" << spvOpcodeString(opcode);
778
779
312k
  for (uint16_t i = 0; i < inst.num_operands; i++) {
780
240k
    const spv_operand_type_t type = inst.operands[i].type;
781
240k
    assert(type != SPV_OPERAND_TYPE_NONE);
782
240k
    if (type == SPV_OPERAND_TYPE_RESULT_ID) continue;
783
187k
    line << " ";
784
187k
    EmitOperand(line, inst, i);
785
187k
  }
786
787
  // For the sake of comment generation, store information from some
788
  // instructions for the future.
789
72.6k
  if (comment_) {
790
0
    GenerateCommentForDecoratedId(inst);
791
0
  }
792
793
72.6k
  std::ostringstream comments;
794
72.6k
  const char* comment_separator = "";
795
796
72.6k
  if (show_byte_offset_) {
797
0
    SetGrey(comments);
798
0
    auto saved_flags = comments.flags();
799
0
    auto saved_fill = comments.fill();
800
0
    comments << comment_separator << "0x" << std::setw(8) << std::hex
801
0
             << std::setfill('0') << inst_byte_offset;
802
0
    comments.flags(saved_flags);
803
0
    comments.fill(saved_fill);
804
0
    ResetColor(comments);
805
0
    comment_separator = ", ";
806
0
  }
807
808
72.6k
  if (comment_ && opcode == spv::Op::OpName) {
809
0
    const spv_parsed_operand_t& operand = inst.operands[0];
810
0
    const uint32_t word = inst.words[operand.offset];
811
0
    comments << comment_separator << "id %" << word;
812
0
    comment_separator = ", ";
813
0
  }
814
815
72.6k
  if (comment_ && inst.result_id && id_comments_.count(inst.result_id) > 0) {
816
0
    comments << comment_separator << id_comments_[inst.result_id].str();
817
0
    comment_separator = ", ";
818
0
  }
819
820
72.6k
  const std::string line_str = line.str();
821
72.6k
  stream_ << line_str;
822
823
72.6k
  if (!comments.str().empty()) {
824
    // Align the comments
825
0
    const uint32_t line_length = GetLineLengthWithoutColor(line_str);
826
0
    uint32_t align = std::max(
827
0
        {line_length + 2, last_instruction_comment_alignment_, kCommentColumn});
828
    // Round up the alignment to a multiple of 4 for more niceness.
829
0
    align = (align + 3) & ~0x3u;
830
0
    last_instruction_comment_alignment_ = std::min({align, 256u});
831
832
0
    stream_ << std::string(align - line_length, ' ') << "; " << comments.str();
833
72.6k
  } else {
834
72.6k
    last_instruction_comment_alignment_ = 0;
835
72.6k
  }
836
837
72.6k
  stream_ << "\n";
838
72.6k
}
839
840
void InstructionDisassembler::GenerateCommentForDecoratedId(
841
0
    const spv_parsed_instruction_t& inst) {
842
0
  assert(comment_);
843
0
  auto opcode = static_cast<spv::Op>(inst.opcode);
844
845
0
  std::ostringstream partial;
846
0
  uint32_t id = 0;
847
0
  const char* separator = "";
848
849
0
  switch (opcode) {
850
0
    case spv::Op::OpDecorate:
851
      // Take everything after `OpDecorate %id` and associate it with id.
852
0
      id = inst.words[inst.operands[0].offset];
853
0
      for (uint16_t i = 1; i < inst.num_operands; i++) {
854
0
        partial << separator;
855
0
        separator = " ";
856
0
        EmitOperand(partial, inst, i);
857
0
      }
858
0
      break;
859
0
    default:
860
0
      break;
861
0
  }
862
863
0
  if (id == 0) {
864
0
    return;
865
0
  }
866
867
  // Add the new comment to the comments of this id
868
0
  std::ostringstream& id_comment = id_comments_[id];
869
0
  if (!id_comment.str().empty()) {
870
0
    id_comment << ", ";
871
0
  }
872
0
  id_comment << partial.str();
873
0
}
874
875
void InstructionDisassembler::EmitSectionComment(
876
    const spv_parsed_instruction_t& inst, bool& inserted_decoration_space,
877
72.6k
    bool& inserted_debug_space, bool& inserted_type_space) {
878
72.6k
  auto opcode = static_cast<spv::Op>(inst.opcode);
879
72.6k
  if (comment_ && opcode == spv::Op::OpFunction) {
880
0
    stream_ << std::endl;
881
0
    if (nested_indent_) {
882
      // Double the empty lines between Function sections since nested_indent_
883
      // also separates blocks by a blank.
884
0
      stream_ << std::endl;
885
0
    }
886
0
    stream_ << std::string(indent_, ' ');
887
0
    stream_ << "; Function " << name_mapper_(inst.result_id) << std::endl;
888
0
  }
889
72.6k
  if (comment_ && !inserted_decoration_space && spvOpcodeIsDecoration(opcode)) {
890
0
    inserted_decoration_space = true;
891
0
    stream_ << std::endl;
892
0
    stream_ << std::string(indent_, ' ');
893
0
    stream_ << "; Annotations" << std::endl;
894
0
  }
895
72.6k
  if (comment_ && !inserted_debug_space && spvOpcodeIsDebug(opcode)) {
896
0
    inserted_debug_space = true;
897
0
    stream_ << std::endl;
898
0
    stream_ << std::string(indent_, ' ');
899
0
    stream_ << "; Debug Information" << std::endl;
900
0
  }
901
72.6k
  if (comment_ && !inserted_type_space && spvOpcodeGeneratesType(opcode)) {
902
0
    inserted_type_space = true;
903
0
    stream_ << std::endl;
904
0
    stream_ << std::string(indent_, ' ');
905
0
    stream_ << "; Types, variables and constants" << std::endl;
906
0
  }
907
72.6k
}
908
909
void InstructionDisassembler::EmitOperand(std::ostream& stream,
910
                                          const spv_parsed_instruction_t& inst,
911
187k
                                          const uint16_t operand_index) const {
912
187k
  assert(operand_index < inst.num_operands);
913
187k
  const spv_parsed_operand_t& operand = inst.operands[operand_index];
914
187k
  const uint32_t word = inst.words[operand.offset];
915
187k
  switch (operand.type) {
916
0
    case SPV_OPERAND_TYPE_RESULT_ID:
917
0
      assert(false && "<result-id> is not supposed to be handled here");
918
0
      SetBlue(stream);
919
0
      stream << "%" << name_mapper_(word);
920
0
      break;
921
103k
    case SPV_OPERAND_TYPE_ID:
922
143k
    case SPV_OPERAND_TYPE_TYPE_ID:
923
144k
    case SPV_OPERAND_TYPE_SCOPE_ID:
924
146k
    case SPV_OPERAND_TYPE_MEMORY_SEMANTICS_ID:
925
146k
      SetYellow(stream);
926
146k
      stream << "%" << name_mapper_(word);
927
146k
      break;
928
986
    case SPV_OPERAND_TYPE_EXTENSION_INSTRUCTION_NUMBER: {
929
986
      SetRed(stream);
930
986
      const ExtInstDesc* desc = nullptr;
931
986
      if (LookupExtInst(inst.ext_inst_type, word, &desc) == SPV_SUCCESS) {
932
986
        stream << desc->name().data();
933
986
      } else {
934
0
        if (!spvExtInstIsNonSemantic(inst.ext_inst_type)) {
935
0
          assert(false && "should have caught this earlier");
936
0
        } else {
937
          // for non-semantic instruction sets we can just print the number
938
0
          stream << word;
939
0
        }
940
0
      }
941
986
    } break;
942
60
    case SPV_OPERAND_TYPE_SPEC_CONSTANT_OP_NUMBER: {
943
60
      const spvtools::InstructionDesc* opcodeEntry = nullptr;
944
60
      if (LookupOpcode(spv::Op(word), &opcodeEntry))
945
60
        assert(false && "should have caught this earlier");
946
60
      SetRed(stream);
947
60
      stream << opcodeEntry->name().data();
948
60
    } break;
949
20.5k
    case SPV_OPERAND_TYPE_LITERAL_INTEGER:
950
24.3k
    case SPV_OPERAND_TYPE_TYPED_LITERAL_NUMBER:
951
24.3k
    case SPV_OPERAND_TYPE_LITERAL_FLOAT: {
952
24.3k
      SetRed(stream);
953
24.3k
      EmitNumericLiteral(&stream, inst, operand);
954
24.3k
      ResetColor(stream);
955
24.3k
    } break;
956
2.20k
    case SPV_OPERAND_TYPE_LITERAL_STRING: {
957
2.20k
      stream << "\"";
958
2.20k
      SetGreen(stream);
959
960
2.20k
      std::string str = spvDecodeLiteralStringOperand(inst, operand_index);
961
23.3k
      for (char const& c : str) {
962
23.3k
        if (c == '"' || c == '\\') stream << '\\';
963
23.3k
        stream << c;
964
23.3k
      }
965
2.20k
      ResetColor(stream);
966
2.20k
      stream << '"';
967
2.20k
    } break;
968
940
    case SPV_OPERAND_TYPE_CAPABILITY:
969
940
    case SPV_OPERAND_TYPE_OPTIONAL_CAPABILITY:
970
991
    case SPV_OPERAND_TYPE_SOURCE_LANGUAGE:
971
1.26k
    case SPV_OPERAND_TYPE_EXECUTION_MODEL:
972
1.53k
    case SPV_OPERAND_TYPE_ADDRESSING_MODEL:
973
1.80k
    case SPV_OPERAND_TYPE_MEMORY_MODEL:
974
1.80k
    case SPV_OPERAND_TYPE_EXECUTION_MODE:
975
5.55k
    case SPV_OPERAND_TYPE_STORAGE_CLASS:
976
6.12k
    case SPV_OPERAND_TYPE_DIMENSIONALITY:
977
6.12k
    case SPV_OPERAND_TYPE_SAMPLER_ADDRESSING_MODE:
978
6.12k
    case SPV_OPERAND_TYPE_SAMPLER_FILTER_MODE:
979
6.69k
    case SPV_OPERAND_TYPE_SAMPLER_IMAGE_FORMAT:
980
6.69k
    case SPV_OPERAND_TYPE_FP_ROUNDING_MODE:
981
6.69k
    case SPV_OPERAND_TYPE_LINKAGE_TYPE:
982
6.69k
    case SPV_OPERAND_TYPE_ACCESS_QUALIFIER:
983
6.69k
    case SPV_OPERAND_TYPE_FUNCTION_PARAMETER_ATTRIBUTE:
984
11.4k
    case SPV_OPERAND_TYPE_DECORATION:
985
11.4k
    case SPV_OPERAND_TYPE_BUILT_IN:
986
11.4k
    case SPV_OPERAND_TYPE_GROUP_OPERATION:
987
11.4k
    case SPV_OPERAND_TYPE_KERNEL_ENQ_FLAGS:
988
11.4k
    case SPV_OPERAND_TYPE_KERNEL_PROFILING_INFO:
989
11.4k
    case SPV_OPERAND_TYPE_RAY_FLAGS:
990
11.4k
    case SPV_OPERAND_TYPE_RAY_QUERY_INTERSECTION:
991
11.4k
    case SPV_OPERAND_TYPE_RAY_QUERY_COMMITTED_INTERSECTION_TYPE:
992
11.4k
    case SPV_OPERAND_TYPE_RAY_QUERY_CANDIDATE_INTERSECTION_TYPE:
993
11.4k
    case SPV_OPERAND_TYPE_DEBUG_BASE_TYPE_ATTRIBUTE_ENCODING:
994
11.4k
    case SPV_OPERAND_TYPE_DEBUG_COMPOSITE_TYPE:
995
11.4k
    case SPV_OPERAND_TYPE_DEBUG_TYPE_QUALIFIER:
996
11.4k
    case SPV_OPERAND_TYPE_DEBUG_OPERATION:
997
11.4k
    case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_BASE_TYPE_ATTRIBUTE_ENCODING:
998
11.4k
    case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_COMPOSITE_TYPE:
999
11.4k
    case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_TYPE_QUALIFIER:
1000
11.4k
    case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_OPERATION:
1001
11.4k
    case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_IMPORTED_ENTITY:
1002
11.4k
    case SPV_OPERAND_TYPE_FPDENORM_MODE:
1003
11.4k
    case SPV_OPERAND_TYPE_FPOPERATION_MODE:
1004
11.4k
    case SPV_OPERAND_TYPE_QUANTIZATION_MODES:
1005
11.4k
    case SPV_OPERAND_TYPE_FPENCODING:
1006
11.4k
    case SPV_OPERAND_TYPE_OVERFLOW_MODES: {
1007
11.4k
      const spvtools::OperandDesc* entry = nullptr;
1008
11.4k
      if (spvtools::LookupOperand(operand.type, word, &entry))
1009
11.4k
        assert(false && "should have caught this earlier");
1010
11.4k
      stream << entry->name().data();
1011
11.4k
    } break;
1012
0
    case SPV_OPERAND_TYPE_FP_FAST_MATH_MODE:
1013
294
    case SPV_OPERAND_TYPE_FUNCTION_CONTROL:
1014
772
    case SPV_OPERAND_TYPE_LOOP_CONTROL:
1015
1.26k
    case SPV_OPERAND_TYPE_IMAGE:
1016
1.29k
    case SPV_OPERAND_TYPE_MEMORY_ACCESS:
1017
2.70k
    case SPV_OPERAND_TYPE_SELECTION_CONTROL:
1018
2.70k
    case SPV_OPERAND_TYPE_DEBUG_INFO_FLAGS:
1019
2.70k
    case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_INFO_FLAGS:
1020
2.70k
    case SPV_OPERAND_TYPE_RAW_ACCESS_CHAIN_OPERANDS:
1021
2.70k
      EmitMaskOperand(stream, operand.type, word);
1022
2.70k
      break;
1023
157
    default:
1024
157
      if (spvOperandIsConcreteMask(operand.type)) {
1025
0
        EmitMaskOperand(stream, operand.type, word);
1026
157
      } else if (spvOperandIsConcrete(operand.type)) {
1027
157
        const spvtools::OperandDesc* entry = nullptr;
1028
157
        if (spvtools::LookupOperand(operand.type, word, &entry))
1029
157
          assert(false && "should have caught this earlier");
1030
157
        stream << entry->name().data();
1031
157
      } else {
1032
0
        assert(false && "unhandled or invalid case");
1033
0
      }
1034
157
      break;
1035
187k
  }
1036
187k
  ResetColor(stream);
1037
187k
}
1038
1039
void InstructionDisassembler::EmitMaskOperand(std::ostream& stream,
1040
                                              const spv_operand_type_t type,
1041
2.70k
                                              const uint32_t word) const {
1042
  // Scan the mask from least significant bit to most significant bit.  For each
1043
  // set bit, emit the name of that bit. Separate multiple names with '|'.
1044
2.70k
  uint32_t remaining_word = word;
1045
2.70k
  uint32_t mask;
1046
2.70k
  int num_emitted = 0;
1047
4.07k
  for (mask = 1; remaining_word; mask <<= 1) {
1048
1.37k
    if (remaining_word & mask) {
1049
558
      remaining_word ^= mask;
1050
558
      const spvtools::OperandDesc* entry = nullptr;
1051
558
      if (spvtools::LookupOperand(type, mask, &entry))
1052
558
        assert(false && "should have caught this earlier");
1053
558
      if (num_emitted) stream << "|";
1054
558
      stream << entry->name().data();
1055
558
      num_emitted++;
1056
558
    }
1057
1.37k
  }
1058
2.70k
  if (!num_emitted) {
1059
    // An operand value of 0 was provided, so represent it by the name
1060
    // of the 0 value. In many cases, that's "None".
1061
2.15k
    const spvtools::OperandDesc* entry = nullptr;
1062
2.15k
    if (SPV_SUCCESS == spvtools::LookupOperand(type, 0, &entry))
1063
2.15k
      stream << entry->name().data();
1064
2.15k
  }
1065
2.70k
}
1066
1067
266k
void InstructionDisassembler::ResetColor(std::ostream& stream) const {
1068
266k
  if (color_) stream << spvtools::clr::reset{print_};
1069
266k
}
1070
0
void InstructionDisassembler::SetGrey(std::ostream& stream) const {
1071
0
  if (color_) stream << spvtools::clr::grey{print_};
1072
0
}
1073
52.0k
void InstructionDisassembler::SetBlue(std::ostream& stream) const {
1074
52.0k
  if (color_) stream << spvtools::clr::blue{print_};
1075
52.0k
}
1076
146k
void InstructionDisassembler::SetYellow(std::ostream& stream) const {
1077
146k
  if (color_) stream << spvtools::clr::yellow{print_};
1078
146k
}
1079
25.3k
void InstructionDisassembler::SetRed(std::ostream& stream) const {
1080
25.3k
  if (color_) stream << spvtools::clr::red{print_};
1081
25.3k
}
1082
2.20k
void InstructionDisassembler::SetGreen(std::ostream& stream) const {
1083
2.20k
  if (color_) stream << spvtools::clr::green{print_};
1084
2.20k
}
1085
1086
0
void InstructionDisassembler::ResetColor() { ResetColor(stream_); }
1087
0
void InstructionDisassembler::SetGrey() { SetGrey(stream_); }
1088
0
void InstructionDisassembler::SetBlue() { SetBlue(stream_); }
1089
0
void InstructionDisassembler::SetYellow() { SetYellow(stream_); }
1090
0
void InstructionDisassembler::SetRed() { SetRed(stream_); }
1091
0
void InstructionDisassembler::SetGreen() { SetGreen(stream_); }
1092
}  // namespace disassemble
1093
1094
std::string spvInstructionBinaryToText(const spv_target_env env,
1095
                                       const uint32_t* instCode,
1096
                                       const size_t instWordCount,
1097
                                       const uint32_t* code,
1098
                                       const size_t wordCount,
1099
50
                                       const uint32_t options) {
1100
50
  spv_context context = spvContextCreate(env);
1101
1102
  // Generate friendly names for Ids if requested.
1103
50
  std::unique_ptr<FriendlyNameMapper> friendly_mapper;
1104
50
  NameMapper name_mapper = GetTrivialNameMapper();
1105
50
  if (options & SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES) {
1106
50
    friendly_mapper =
1107
50
        MakeUnique<FriendlyNameMapper>(context, code, wordCount, options);
1108
50
    name_mapper = friendly_mapper->GetNameMapper();
1109
50
  }
1110
1111
  // Now disassemble!
1112
50
  Disassembler disassembler(options, name_mapper);
1113
50
  WrappedDisassembler wrapped(&disassembler, instCode, instWordCount);
1114
50
  spvBinaryParseWithOptions(context, &wrapped, code, wordCount,
1115
50
                            DisassembleTargetHeader,
1116
50
                            DisassembleTargetInstruction, nullptr, options);
1117
1118
50
  spv_text text = nullptr;
1119
50
  std::string output;
1120
50
  if (disassembler.SaveTextResult(&text) == SPV_SUCCESS) {
1121
50
    output.assign(text->str, text->str + text->length);
1122
    // Drop trailing newline characters.
1123
100
    while (!output.empty() && output.back() == '\n') output.pop_back();
1124
50
  }
1125
50
  spvTextDestroy(text);
1126
50
  spvContextDestroy(context);
1127
1128
50
  return output;
1129
50
}
1130
}  // namespace spvtools
1131
1132
spv_result_t spvBinaryToText(const spv_const_context context,
1133
                             const uint32_t* code, const size_t wordCount,
1134
                             const uint32_t options, spv_text* pText,
1135
271
                             spv_diagnostic* pDiagnostic) {
1136
271
  spv_context_t hijack_context = *context;
1137
271
  if (pDiagnostic) {
1138
0
    *pDiagnostic = nullptr;
1139
0
    spvtools::UseDiagnosticAsMessageConsumer(&hijack_context, pDiagnostic);
1140
0
  }
1141
1142
  // Generate friendly names for Ids if requested.
1143
271
  std::unique_ptr<spvtools::FriendlyNameMapper> friendly_mapper;
1144
271
  spvtools::NameMapper name_mapper = spvtools::GetTrivialNameMapper();
1145
271
  if (options & SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES) {
1146
271
    friendly_mapper = spvtools::MakeUnique<spvtools::FriendlyNameMapper>(
1147
271
        &hijack_context, code, wordCount, options);
1148
271
    name_mapper = friendly_mapper->GetNameMapper();
1149
271
  }
1150
1151
  // Now disassemble!
1152
271
  spvtools::Disassembler disassembler(options, name_mapper);
1153
271
  if (auto error = spvBinaryParseWithOptions(
1154
271
          &hijack_context, &disassembler, code, wordCount,
1155
271
          spvtools::DisassembleHeader, spvtools::DisassembleInstruction,
1156
271
          pDiagnostic, options)) {
1157
1
    return error;
1158
1
  }
1159
1160
270
  return disassembler.SaveTextResult(pText);
1161
271
}