• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

SamboyCoding / Cpp2IL / 30747683456

02 Aug 2026 12:22PM UTC coverage: 36.169% (+0.01%) from 36.157%
30747683456

push

github

SamboyCoding
Decompiler: Fix operand setting not invalidating sources, leading to invalid cast exceptions

2874 of 9077 branches covered (31.66%)

Branch coverage included in aggregate %.

16 of 45 new or added lines in 13 files covered. (35.56%)

5290 of 13495 relevant lines covered (39.2%)

163818.52 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

65.16
/Cpp2IL.Core/Graphs/ISILControlFlowGraph.cs
1
using System;
2
using System.Collections.Generic;
3
using System.Linq;
4
using Cpp2IL.Core.ISIL;
5

6
namespace Cpp2IL.Core.Graphs;
7

8
public class ISILControlFlowGraph
9
{
10
    public Block EntryBlock;
11
    public Block ExitBlock;
12
    public int Count => Blocks.Count;
×
13
    public List<Block> Blocks;
14

15
    public List<Instruction> Instructions
16
    {
17
        get
18
        {
19
            // BFS search
20
            var visited = new HashSet<Block>();
3✔
21
            var queue = new Queue<Block>();
3✔
22
            var result = new List<Instruction>();
3✔
23

24
            queue.Enqueue(EntryBlock);
3✔
25

26
            while (queue.Count > 0)
21✔
27
            {
28
                var current = queue.Dequeue();
18✔
29

30
                if (!visited.Add(current))
18✔
31
                    continue;
32

33
                result.AddRange(current.Instructions);
17✔
34

35
                foreach (var successor in current.Successors)
66✔
36
                {
37
                    if (!visited.Contains(successor))
16✔
38
                        queue.Enqueue(successor);
15✔
39
                }
40
            }
41

42
            return result; // Should this be cached?
3✔
43
        }
44
    }
45

46
    private int idCounter;
47

48
    public ISILControlFlowGraph(List<Instruction> instructions)
23✔
49
    {
50
        EntryBlock = new Block
23✔
51
        {
23✔
52
            ID = idCounter++,
23✔
53
            BlockType = BlockType.Entry
23✔
54
        };
23✔
55

56
        ExitBlock = new Block
23✔
57
        {
23✔
58
            ID = idCounter++,
23✔
59
            BlockType = BlockType.Exit
23✔
60
        };
23✔
61

62
        Blocks =
23✔
63
        [
23✔
64
            EntryBlock,
23✔
65
            ExitBlock
23✔
66
        ];
23✔
67

68
        Build(instructions);
23✔
69
    }
23✔
70

71
    private bool TryGetTargetJumpInstructionIndex(Instruction instruction, out int jumpInstructionIndex)
72
    {
73
        jumpInstructionIndex = 0;
5✔
74
        try
75
        {
76
            jumpInstructionIndex = ((Instruction)instruction.Operands[0]).Index;
5✔
77
            return true;
5✔
78
        }
79
        catch
×
80
        {
81
            // ignore
82
        }
×
83

84
        return false;
×
85
    }
5✔
86

87
    public void RemoveUnreachableBlocks()
88
    {
89
        if (Blocks.Count == 0)
×
90
            return;
×
91

92
        // Get blocks reachable from entry
93
        var reachable = new List<Block>();
×
94
        var visited = new List<Block> { EntryBlock };
×
95
        reachable.Add(EntryBlock);
×
96

97
        var total = 0;
×
98
        while (total < reachable.Count)
×
99
        {
100
            var block = reachable[total];
×
101
            total++;
×
102

103
            foreach (var successor in block.Successors)
×
104
            {
105
                if (visited.Contains(successor))
×
106
                    continue;
107
                visited.Add(successor);
×
108
                reachable.Add(successor);
×
109
            }
110
        }
111

112
        // Get unreachable blocks
113
        var unreachable = Blocks.Where(block => !visited.Remove(block)).ToList();
×
114

115
        // Remove those
116
        foreach (var block in unreachable)
×
117
        {
118
            // Don't remove entry or exit
119
            if (block == EntryBlock || block == ExitBlock)
×
120
                continue;
121

122
            // Fully detach the block so no remaining block keeps a dangling reference to it.
123
            // (A reachable block can have an unreachable predecessor; leaving that reference
124
            // behind makes later passes such as dominator computation throw.)
125
            foreach (var successor in block.Successors)
×
126
                successor.Predecessors.Remove(block);
×
127
            foreach (var predecessor in block.Predecessors)
×
128
                predecessor.Successors.Remove(block);
×
129

130
            block.Successors.Clear();
×
131
            block.Predecessors.Clear();
×
132
            Blocks.Remove(block);
×
133
        }
134
    }
×
135

136
    public void RemoveNops()
137
    {
138
        var usedAsTarget = new HashSet<Instruction>();
3✔
139

140
        // Get all instructions used as branch targets
141
        foreach (var block in Blocks)
38✔
142
        {
143
            foreach (var instr in block.Instructions)
70✔
144
            {
145
                foreach (var operand in instr.Operands)
84✔
146
                {
147
                    if (operand is Instruction target)
23!
148
                        usedAsTarget.Add(target);
×
149
                }
150
            }
151
        }
152

153
        // Build replacement map for NOPs that are safe to replace
154
        var instructionReplacement = new Dictionary<Instruction, Instruction>();
3✔
155
        foreach (var block in Blocks)
38✔
156
        {
157
            Instruction? replacement = null;
16✔
158
            for (var i = block.Instructions.Count - 1; i >= 0; i--)
70✔
159
            {
160
                var instr = block.Instructions[i];
19✔
161
                if (instr.OpCode == OpCode.Nop)
19✔
162
                {
163
                    if (replacement != null && !usedAsTarget.Contains(instr))
6✔
164
                        instructionReplacement[instr] = replacement;
6✔
165
                }
166
                else
167
                {
168
                    replacement = instr;
13✔
169
                }
170
            }
171
        }
172

173
        // Update operands
174
        foreach (var block in Blocks)
38✔
175
        {
176
            foreach (var instr in block.Instructions)
70✔
177
            {
178
                for (var i = 0; i < instr.Operands.Count; i++)
84✔
179
                {
180
                    if (instr.Operands[i] is Instruction target && instructionReplacement.TryGetValue(target, out var newTarget))
23!
NEW
181
                        instr.SetOperand(i, newTarget);
×
182
                }
183
            }
184
        }
185

186
        // Remove NOPs
187
        foreach (var block in Blocks)
38✔
188
        {
189
            block.Instructions.RemoveAll(i => i.OpCode == OpCode.Nop && !usedAsTarget.Contains(i));
35✔
190
        }
191
    }
3✔
192

193
    public void RemoveEmptyBlocks()
194
    {
195
        var toRemove = new List<Block>();
3✔
196

197
        foreach (var block in Blocks)
38✔
198
        {
199
            if (block == EntryBlock || block == ExitBlock)
16✔
200
                continue;
201

202
            if (block.Instructions.Count == 0)
10!
203
            {
204
                // Redirect predecessors to successors
205
                foreach (var pred in block.Predecessors)
×
206
                {
207
                    pred.Successors.Remove(block);
×
208
                    foreach (var succ in block.Successors)
×
209
                    {
210
                        if (!pred.Successors.Contains(succ))
×
211
                            pred.Successors.Add(succ);
×
212
                    }
213
                }
214

215
                // Redirect successors to predecessors
216
                foreach (var succ in block.Successors)
×
217
                {
218
                    succ.Predecessors.Remove(block);
×
219
                    foreach (var pred in block.Predecessors)
×
220
                    {
221
                        if (!succ.Predecessors.Contains(pred))
×
222
                            succ.Predecessors.Add(pred);
×
223
                    }
224
                }
225

226
                toRemove.Add(block);
×
227
            }
228
        }
229

230
        foreach (var block in toRemove)
6!
231
            Blocks.Remove(block);
×
232
    }
3✔
233

234
    public void BuildUseDefLists()
235
    {
236
        foreach (var block in Blocks)
30✔
237
        {
238
            var use = new List<object>();
13✔
239
            var def = new List<object>();
13✔
240

241
            foreach (var instruction in block.Instructions)
56✔
242
            {
243
                foreach (var operand in instruction.Sources.Where(operand => !use.Contains(operand)))
49✔
244
                    use.Add(operand);
6✔
245

246
                if (instruction.Destination != null && !def.Contains(instruction.Destination))
15✔
247
                    def.Add(instruction.Destination);
7✔
248
            }
249

250
            block.Use = use;
13✔
251
            block.Def = def;
13✔
252
        }
253
    }
2✔
254

255
    public void MergeCallBlocks()
256
    {
257
        var toRemove = new List<Block>();
×
258

259
        for (var i = 0; i < Blocks.Count; i++)
×
260
        {
261
            var block = Blocks[i];
×
262
            if (block.BlockType != BlockType.Call) continue;
×
263

264
            if (block.Successors.Count != 1)
×
265
                continue;
266

267
            var nextBlock = block.Successors[0];
×
268

269
            // make sure that the next block only has one predecessor (this)
270
            if (nextBlock.Predecessors.Count != 1 || nextBlock.Predecessors[0] != block)
×
271
                continue;
272

273
            // merge instructions
274
            block.Instructions.AddRange(nextBlock.Instructions);
×
275
            block.Successors = nextBlock.Successors;
×
276

277
            // fix up successors predecessors
278
            foreach (var successor in nextBlock.Successors)
×
279
            {
280
                for (var j = 0; j < successor.Predecessors.Count; j++)
×
281
                {
282
                    if (successor.Predecessors[j] == nextBlock)
×
283
                        successor.Predecessors[j] = block;
×
284
                }
285
            }
286

287
            toRemove.Add(nextBlock);
×
288
        }
289

290
        // Remove all merged blocks
291
        foreach (var removed in toRemove)
×
292
            Blocks.Remove(removed);
×
293

294
        foreach (var block in Blocks)
×
295
            block.CalculateBlockType();
×
296
    }
×
297

298
    private void Build(List<Instruction> instructions)
299
    {
300
        if (instructions == null)
23!
301
            throw new ArgumentNullException(nameof(instructions));
×
302

303
        var currentBlock = new Block() { ID = idCounter++ };
23✔
304
        AddBlock(currentBlock);
23✔
305
        AddDirectedEdge(EntryBlock, currentBlock);
23✔
306

307
        for (var i = 0; i < instructions.Count; i++)
546✔
308
        {
309
            var isLast = i == instructions.Count - 1;
250✔
310
            Block newBlock;
311

312
            switch (instructions[i].OpCode)
250✔
313
            {
314
                case OpCode.Jump:
315
                case OpCode.ConditionalJump:
316
                    currentBlock.AddInstruction(instructions[i]);
30✔
317

318
                    if (!isLast)
30!
319
                    {
320
                        newBlock = new Block() { ID = idCounter++ };
30✔
321
                        AddBlock(newBlock);
30✔
322

323
                        if (instructions[i].OpCode == OpCode.Jump)
30✔
324
                        {
325
                            if (TryGetTargetJumpInstructionIndex(instructions[i], out int jumpTargetIndex))
5!
326
                                currentBlock.Dirty = true;
5✔
327
                            else
328
                                AddDirectedEdge(currentBlock, ExitBlock);
×
329
                        }
330
                        else
331
                        {
332
                            AddDirectedEdge(currentBlock, newBlock);
25✔
333
                            currentBlock.Dirty = true;
25✔
334
                        }
335

336
                        currentBlock.CalculateBlockType();
30✔
337
                        currentBlock = newBlock;
30✔
338
                    }
339
                    else
340
                    {
341
                        AddDirectedEdge(currentBlock, ExitBlock);
×
342

343
                        if (instructions[i].OpCode == OpCode.Jump)
×
344
                            currentBlock.Dirty = true;
×
345
                    }
346

347
                    break;
×
348

349
                case OpCode.Call:
350
                case OpCode.CallVoid:
351
                case OpCode.Return:
352
                    var isReturn = instructions[i].OpCode == OpCode.Return;
59✔
353

354
                    currentBlock.AddInstruction(instructions[i]);
59✔
355

356
                    if (!isLast)
59✔
357
                    {
358
                        newBlock = new Block() { ID = idCounter++ };
36✔
359
                        AddBlock(newBlock);
36✔
360
                        AddDirectedEdge(currentBlock, isReturn ? ExitBlock : newBlock);
36✔
361
                        currentBlock.CalculateBlockType();
36✔
362
                        currentBlock = newBlock;
36✔
363
                    }
364
                    else
365
                    {
366
                        AddDirectedEdge(currentBlock, ExitBlock);
23✔
367
                        currentBlock.CalculateBlockType();
23✔
368
                    }
369

370
                    break;
23✔
371

372
                default:
373
                    currentBlock.AddInstruction(instructions[i]);
161✔
374
                    if (isLast)
161!
375
                    {
376
                        AddDirectedEdge(currentBlock, ExitBlock);
×
377
                        currentBlock.CalculateBlockType();
×
378
                    }
379
                    break;
380
            }
381
        }
382

383
        for (var index = 0; index < Blocks.Count; index++)
338✔
384
        {
385
            var node = Blocks[index];
146✔
386
            if (node.Dirty)
146✔
387
                FixBlock(node);
30✔
388
        }
389

390
        // Connect blocks without successors to exit
391
        foreach (var block in Blocks)
338✔
392
        {
393
            if (block.Successors.Count == 0 && block != EntryBlock && block != ExitBlock)
146!
394
                AddDirectedEdge(block, ExitBlock);
×
395
        }
396

397
        // Change branch targets to blocks
398
        foreach (var instruction in Blocks.SelectMany(block => block.Instructions))
692✔
399
        {
400
            if (instruction.Operands.Count > 0 && instruction.Operands[0] is Instruction target)
250✔
401
                instruction.SetOperand(0, FindBlockByInstruction(target)!);
30✔
402
        }
403
    }
23✔
404

405
    private void FixBlock(Block block, bool removeJmp = false)
406
    {
407
        if (block.BlockType is BlockType.Fall)
30!
408
            return;
×
409

410
        var jump = block.Instructions.Last();
30✔
411

412
        var targetInstruction = jump.Operands[0] as Instruction;
30✔
413

414
        var destination = FindBlockByInstruction(targetInstruction);
30✔
415

416
        if (destination == null)
30!
417
        {
418
            //We assume that we're tail calling another method somewhere. Need to verify if this breaks anywhere but it shouldn't in general
419
            block.BlockType = BlockType.TailCall;
×
420
            return;
×
421
        }
422

423

424
        int index = destination.Instructions.FindIndex(instruction => instruction == targetInstruction);
75✔
425

426
        var targetNode = SplitAndCreate(destination, index);
30✔
427

428
        AddDirectedEdge(block, targetNode);
30✔
429
        block.Dirty = false;
30✔
430

431
        if (removeJmp)
30!
432
            block.Instructions.Remove(jump);
×
433
    }
30✔
434

435
    public Block? FindBlockByInstruction(Instruction? instruction)
436
    {
437
        if (instruction == null)
60!
438
            return null;
×
439

440
        for (var i = 0; i < Blocks.Count; i++)
1,052!
441
        {
442
            var block = Blocks[i];
526✔
443
            for (var j = 0; j < block.Instructions.Count; j++)
3,254✔
444
            {
445
                var instr = block.Instructions[j];
1,161✔
446
                if (instr == instruction)
1,161✔
447
                {
448
                    return block;
60✔
449
                }
450
            }
451
        }
452

453
        return null;
×
454
    }
455

456
    private Block SplitAndCreate(Block target, int index)
457
    {
458
        if (index < 0 || index >= target.Instructions.Count)
30!
459
            throw new ArgumentOutOfRangeException(nameof(index));
×
460

461
        // Don't need to split...
462
        if (index == 0)
30✔
463
            return target;
19✔
464

465
        var newBlock = new Block() { ID = idCounter++ };
11✔
466

467
        // target split in two
468
        // targetFirstPart -> targetSecondPart aka newNode
469

470
        // Take the instructions for the secondPart
471
        var instructions = target.Instructions.GetRange(index, target.Instructions.Count - index);
11✔
472
        target.Instructions.RemoveRange(index, target.Instructions.Count - index);
11✔
473

474
        // Add those to the newNode
475
        newBlock.Instructions.AddRange(instructions);
11✔
476
        // Transfer control flow
477
        newBlock.BlockType = target.BlockType;
11✔
478
        target.BlockType = BlockType.Fall;
11✔
479

480
        // Transfer successors
481
        newBlock.Successors = target.Successors;
11✔
482
        if (target.Dirty)
11✔
483
            newBlock.Dirty = true;
4✔
484
        target.Dirty = false;
11✔
485
        target.Successors = [];
11✔
486

487
        // Correct the predecessors for all the successors
488
        foreach (var successor in newBlock.Successors)
46✔
489
        {
490
            for (int i = 0; i < successor.Predecessors.Count; i++)
48✔
491
            {
492
                if (successor.Predecessors[i].ID == target.ID)
12✔
493
                    successor.Predecessors[i] = newBlock;
12✔
494
            }
495
        }
496

497
        // Add newNode and connect it
498
        AddBlock(newBlock);
11✔
499
        AddDirectedEdge(target, newBlock);
11✔
500

501
        return newBlock;
11✔
502
    }
503

504
    private void AddDirectedEdge(Block from, Block to)
505
    {
506
        from.Successors.Add(to);
148✔
507
        to.Predecessors.Add(from);
148✔
508
    }
148✔
509

510
    protected void AddBlock(Block block) => Blocks.Add(block);
100✔
511
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc