Skip to content

optimize state machine inside loop into computed goto #2162

@andrewrk

Description

@andrewrk

Related issues:

One remaining use case for computed goto is performance. This pattern:

const State = enum {
    one,
    two,
};
while (true) {
    switch (state) {
        .one => {
            state = .two;
        },
        .two => {
            // ...
        },
    }
}

Here the code relies on setting the state variable and a loop iteration. In C the code could directly goto another switch label. In Zig this is not available, and the code generated is worse than in C due to the optimizer's inability to detect this pattern.

Upstream bug, reported by @shawnl: https://bugs.llvm.org/show_bug.cgi?id=39043

Potential solutions include:

  • (ideal) send upstream patch to LLVM making it able to detect this pattern and optimize it. It seems reasonable that this should work, given that both gcc and icc are able to do it.
  • make zig detect this pattern and emit different LLVM IR

I don't consider this to be blocking a 1.0.0 release.

Metadata

Metadata

Assignees

No one assigned

    Labels

    contributor friendlyThis issue is limited in scope and/or knowledge of Zig internals.optimizationupstreamAn issue with a third party project that Zig uses.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions