dotnet / dotnet/runtime

[API Proposal]: System.Reflection.Metadata.Ecma335.ControlFlowBuilder.MarkLabel

Open
#132,719 6 comments 0 reactions 0 assignees View on GitHub
api-suggestion area-System.Reflection.Metadata untriaged
Dominant language
C#
Stars
18.3k
Forks
5.6k
PR merge metrics
PR metrics pending

Description

### Background and motivation

`InstructionEncoder.MarkLabel(LabelHandle)` can only associate a label with the encoder's current IL offset. Consumers that parse or rewrite existing IL may instead need to associate labels with offsets supplied by the input.

The managed IL assembler in #131507 needs this for numeric branch targets and exception-region boundaries. `ControlFlowBuilder` already implements the required operation internally, but ILAssembler currently has to access it through `UnsafeAccessor`. Exposing the existing member removes that dependency on a non-public implementation detail.

No related API proposal was found.

### API Proposal

```csharp
namespace System.Reflection.Metadata.Ecma335;

public sealed partial class ControlFlowBuilder
{
public void MarkLabel(int ilOffset, LabelHandle label);
}
```

### API Usage

Pulled from ILAssembler in this repo:

```csharp
if (argument is CILParser.Int32Context int32)
{
int offset = VisitInt32(int32).Value;
LabelHandle label = _currentMethod!.Definition.MethodBody.DefineLabel();
_currentMethod.Definition.MethodBody.Branch(opcode, label);
_currentMethod.Definition.MethodBody.ControlFlowBuilder!.MarkLabel(
_currentMethod.Definition.MethodBody.Offset + offset,
label);
}
```

### Alternative Designs

- Add an explicit-offset overload to `InstructionEncoder.MarkLabel` instead.

### Risks

The API permits callers to associate labels with arbitrary offsets, including offsets beyond the currently emitted stream, which is required for forward numeric targets. The implementation should validate that `ilOffset` is non-negative; it cannot validate an upper bound because `ControlFlowBuilder` does not own the IL stream.

This is an additive API and does not change existing behavior or performance.

> [!NOTE]
> This proposal was created with GitHub Copilot.

Contributor guide

Open the contributing guide

Research direction

Locate ControlFlowBuilder's existing internal operation and the ILAssembler usage described in the issue. Expose the operation with the proposed signature, validate that ilOffset is non-negative, and confirm ILAssembler no longer needs UnsafeAccessor while preserving existing behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
csharp
Domain
api, compilers
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Active
Clarity
Clearly specified
Newbie friendliness
58/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.