Dead Code Elimination

Paolo Invernizzi paolo.invernizzi at gmail.com
Wed Oct 21 14:59:20 UTC 2026


On Wednesday, 21 October 2026 at 09:32:25 UTC, user1234 wrote:
> On Sunday, 18 October 2026 at 15:33:17 UTC, libxmoc wrote:
>> I noticed that dmd doesn't do DCE, my executable is quite 
>> large for what it does. Any plan to add that? I tried to do it 
>> myself, a simple bool in DSymbol + a visitor (yoinked it from 
>> the unused import PR) to scan things, and it shrank build time 
>> by ~15% and executable went down to 3.5mb from 5.5mb.
>>
>> Surely someone smarter than me could do even better.
>
> It's hard to say when something is used, simple example:
>
> ```d
> void unused(){}
>
> void main()
> {
>     import core.stdc.stdio;
>     printf("%p\n",&unused);
> }
> ```
>
> same problem with virtual functions.
>
> Otherwise what you call DCE is rather WPO (whole program 
> optimization).

Not an answer on the compiler side, but related, since today 
djs-vscode (0.2.0) shows unused code in the editor.

It walks the semantic AST of the whole program from `main` (the 
same thing `-i` compiles) and greys out every declaration it 
cannot reach: functions, methods, templates, aggregates, enums, 
mutable globals. Hovering tells you why ("unreferenced", "only 
referenced from unreachable code", ...).

Because the walk runs after semantic analysis, string mixins are 
already expanded and `__traits` resolved, so a function named 
only inside a mixin counts as used.

And user1234's example works as it should: `&unused` is a use, so 
`unused` is not greyed.

Screenshot: 
https://raw.githubusercontent.com/DeepGlance/djs-vscode/main/extension/media/unused.png
Hover: 
https://raw.githubusercontent.com/DeepGlance/djs-vscode/main/extension/media/unused-hover.png

Caveats: it is "unused in this build", so code used only under a 
`version` that is not compiled, or only in a `unittest` when you 
compile without `-unittest`, is kept rather than greyed; 
`extern(C)` and exported symbols count as roots; separately 
compiled libraries are out of sight. It does not touch the 
binary, it only shows you what the linker would not need.

Paolo



More information about the Digitalmars-d mailing list