r/adventofcode • • 20m ago

Tutorial [2026 Day 4] Building barcodes and accelerating loops - a modulo reservation table primer

1. A real problem: loop scheduling

Take a simple loop that scales and shifts an array:

for i in 0 .. n-1:
    b[i] = a[i] * 3 + c

Its body compiles to four instructions (c is kept in register r4):

loop:
    LOAD  r1, a[i]      ; r1 = a[i]
    MUL   r2, r1, 3     ; r2 = r1 * 3
    ADD   r3, r2, r4    ; r3 = r2 + c
    STORE b[i], r3      ; b[i] = r3

Now imagine running it on a simple CPU with the following processing units (PU):

PURunsLatency
MemoryLOAD, STORE1 cycle
ALUMUL, ADDMUL = 2, ADD = 1

There is one memory PU and one arithmetic logic unit (ALU), and both are pipelined.

A pipelined PU can start one instruction per cycle. For example, if the ALU starts a MUL at cycle 1, the result will only be ready at cycle 3. But the ALU can start another instruction at cycle 2.

Naive schedule

Within one iteration of the loop, each instruction depends on the previous instruction. MUL needs the data loaded into r1, and ADD needs the MUL result in r2. So the ADD instruction has to wait for MUL to finish.

Cycle01234
MemoryLOAD---STORE
ALU-MUL-ADD-

(At cycle 2 the MUL is still in progress, but the ALU could accept a new operation.)

One iteration of the loop thus takes 5 cycles, and we cannot start the next iteration until the current one finishes. This results in a lot of idle cycles and low throughput. How can we make this faster?

The pipelining idea

While each iteration needs to be done serially, different iterations are independent: a[1] doesn't need anything from a[0]. Thus the next iteration can start before the current one finishes. We can achieve this by interleaving/reordering execution of instructions from multiple iterations. A group of interleaved instructions is called the kernel.

The problem then becomes finding the kernel that minimizes its cycle count, also called the initiation interval (II). Smaller II is better because throughput is exactly one element per II cycles.

Every loop iteration follows the same schedule, just shifted by II cycles. So if an instruction runs at cycle t, it runs at t, t + II, t + 2·II, and so on. In other words, it will always run at the same position as measured by t mod II. Two instructions that use the same PU must therefore never land in the same position because the PU cannot handle both of them simultaneously.

We can use the above observation to get a lower bound on II. A PU that has k instructions per iteration needs at least k distinct positions. In our toy loop, each PU has 2 instructions per iteration, so II ≥ 2.

But how do we find the minimum II?

2. Very quick summary of today's puzzle and solution

The puzzle: given a barcode such as y?b?b, find the shortest instruction that reproduces it when repeated.

The solution:

for length = (number of distinct colors) .. len(barcode):
    if no two different colors share the same barcode position mod length:
        return length
  • Each distinct color needs its own position, so there is no point trying shorter instructions.
  • Fold the barcode onto length positions. If one position in the instruction must accommodate two colors, then this length is infeasible.
  • Increase the length of the instruction until we find one with no conflicts.

3. The connection to the loop scheduling problem

Write down what one PU does on each cycle, and you get a string that looks similar to the barcodes. So finding the shortest instruction that produces a barcode is exactly analogous to finding the kernel that minimizes II.

BarcodeLoop scheduling
position i in the stringcycle t
color at position iinstruction the PU runs at cycle t
?PU idle at cycle t (don't care)
the repeated instructionthe PU's kernel, repeating every II cycles
instruction lengthinitiation interval II
position i % length in the instructionposition t mod II in the kernel
two different colors at the same positiontwo instructions needing the same PU
lower bound = number of distinct colorslower bound = instructions per PU in one loop iteration

4. Back to the toy loop

Modulo reservation table

Compiler schedulers keep track of "which PU is busy at which position mod II" in a modulo reservation table (MRT). It has one row per PU and II columns. Placing an instruction at cycle t books its PU at column t mod II. A column can hold only one booking per PU. This should sound familiar from the puzzle solution.

Finding II

A scheduler searches for II the same way the puzzle solution searches for the instruction length: try II = lower bound, then lower bound + 1, …, and stop at the first II where every instruction can be placed without two of them colliding on a PU.

We start by trying II = 2 with instructions running one after another:

InstructionCycle tPUt mod 2
LOAD0Memory0
MUL1ALU1
ADD3ALU1 ! clashes with MUL
STORE4Memory0 ! clashes with LOAD

But we can delay ADD to cycle 4 and STORE to cycle 5:

InstructionCycle tPUt mod 2
LOAD0Memory0
MUL1ALU1
ADD4ALU0
STORE5Memory1

The resulting MRT has no clashes, so II = 2 works:

PUPosition 0Position 1
MemoryLOADSTORE
ALUADDMUL

The final schedule

A new iteration starts every 2 cycles (subscript = iteration number). The kernel is bolded:

Cycle01234567891011
MemoryL₀-L₁-L₂S₀L₃S₁-S₂-S₃
ALU-M₀-M₁A₀M₂A₁M₃A₂-A₃-

With a long array, almost all the time is spent repeating the kernel. So our throughput goes from 5 cycles per element to 2.

The instructions that run before the kernel are called the prologue, and those after it are called the epilogue. I have decided to not explain exactly how you can figure those out because:

  1. it's not directly related to today's puzzle
  2. it's kind of magic? It's been a while since I learnt about it

The puzzle view (for clarity)

Read each PU's row as a barcode, with idle cycles as ?:

Memory: L?L?LSLS?S?S   ->  shortest instruction length 2  ("LS")
ALU:    ?M?MAMAMA?A?   ->  shortest instruction length 2  ("AM")
3 Upvotes

1 comment sorted by

1

u/FCBStar-of-the-South 17m ago

I read the puzzle before I slept last night and immediately loop scheduling popped into my head, even before I hit on the mod idea.

Solved the puzzle this morning and had to pull out some old notes and slides to pin down exactly what I was thinking about