Skip to content

introduce @branchHint builtin #21148

Closed
Closed
@andrewrk

Description

@andrewrk

This proposal supplants:

Basic example syntax:

if (x > 100) {
    @branchHint(.likely);
    // ...
} else {
    // ...
}
pub const BranchHint = enum {
    /// Equivalent to no hint given.
    none,
    /// This branch of control flow is more likely to be reached than its peers.
    /// The optimizer should optimize for reaching it.
    likely,
    /// This branch of control flow is less likely to be reached than its peers.
    /// The optimizer should optimize for not reaching it.
    unlikely,
    /// This branch of control flow is unlikely to *ever* be reached.
    /// The optimizer may place it in a different page of memory to optimize other branches.
    cold,
    /// It is difficult to predict whether this branch of control flow will be reached.
    /// The optimizer should avoid branching behavior with expensive mispredictions.
    unpredictable,
};

Some rules:

  • The @branchHint operand is a comptime expression.
  • For comparison purposes, "likely" compares greater than than "none" (default unannotated branch weight), which compares greater than "unlikely". Equal weight branches are allowed.
  • All branches that lead to a @panic (including from safety check) implicitly are "cold".
  • Multiple @branchHint calls in the same block is a compile error.
  • Compile error if @branchHint is not the first statement in a block.

Furthermore:

  • No "expect" builtin or similar.
  • No @cold or @setCold builtin. (replaced by @branchHint(.cold); at the beginning of the function.
  • Error branches (weight error branches against errors #84) get a default hint of unlikely and can be overridden.

Issue close criteria:

  • Implement the syntax
  • Implement the hint in the LLVM backend, including unpredictable, cold, default error branch weight
  • Remove @setCold builtin

Metadata

Metadata

Assignees

No one assigned

    Labels

    acceptedThis proposal is planned.breakingImplementing this issue could cause existing code to no longer compile or have different behavior.proposalThis issue suggests modifications. If it also has the "accepted" label then it is planned.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions