Codiode

The Variable Loop Bound

MediumVerilog / SystemVerilogBuildFree1 solved

In software a loop runs over time. In hardware, synthesis unrolls it into parallel logic, so the number of iterations must be fixed when the design is built. A loop bound that depends on an input can't be unrolled.

The solution module receives an 8-bit input data and must locate the most significant set bit (the highest index where the bit is 1). The output index indicates this position, and the valid signal is asserted. If the input is exactly zero, valid is deasserted and index is set to 0. All outputs are registered.

A software developer might try to write while (temp > 0) { temp >>= 1; count++; }, which is unsynthesizable because the number of iterations depends on the runtime value of data. The correct hardware approach uses a static parallel structure, such as a priority encoder, mapped to sequential outputs.

Timing and Reset Rules

  • Clock edge: posedge clk
  • Reset type: Asynchronous
  • Reset polarity: Active-low (rst_n)
  • Output values on reset: valid goes to 0, index goes to 0
  • Output timing: All outputs are registered and update one clock cycle after the input is presented

Worked Trace

Cycle 1: rst_n=0 → valid=0, index=0
Cycle 2: rst_n=1, data=8'b0000_1000 → valid=0, index=0 (evaluating)
Cycle 3: data=8'b1000_0000 → valid=1, index=3 (result of Cycle 2)
Cycle 4: data=8'b0000_0000 → valid=1, index=7 (result of Cycle 3)
Cycle 5: data=8'b0110_1101 → valid=0, index=0 (result of Cycle 4)
Cycle 6: data=8'b0000_0001 → valid=1, index=6 (result of Cycle 5)

Waveform

Port Table

Signal Direction Width Description
clk input 1 Positive-edge triggered clock
rst_n input 1 Asynchronous active-low reset; outputs go to 0 when asserted
data input 8 Input data vector to be scanned
valid output 1 Asserted if at least one bit in data is set
index output 3 Index of the most significant set bit (0 to 7); 0 if valid is 0

Constraints

  • You must use a synthesizable parallel logic structure (static loops or direct boolean logic).
  • Do not use while loops or for loops bounded by the data input.
  • The rst_n signal is asynchronous and active-low.
  • All outputs must be registered on the positive edge of clk.

Topics

Priority EncoderSynthesisRegistered Logic

Solve this problem

Write the module in Verilog, SystemVerilog or VHDL. Your submission is compiled and simulated against the problem's testbench. You get the waveform back, not a stored answer.

Free to solve. A Codiode account keeps your progress.

The circuit builder and code editor need a desktop screen. On a phone, read the problem here and open it on a laptop to solve.

Part of Synthesis Intuition

Problem 4 of 25 in the Synthesis Intuition track.

Related problems

Browse all problems · Verilog practice problems · Learning tracks

Solve this on a laptopSend yourself the link and continue there.