A data hazard of the read-after-write kind appears when an instruction reads a register that the instruction just before it writes.
What to build
A program that tells, for every instruction after the first, whether it depends on the one just before it.
Requirements
add,sub,and,or,addiandlwwrite their first register and read the others.swwrites no register and reads all registers it names.nopuses none.- For instruction number i (from 2), print
i: dependentif it reads the register written by instruction i − 1, otherwisei: independent.
Input
A line with n, then n instructions, one per line.
Output
n − 1 lines.
Constraints
2 ≤ n ≤ 50; registers are written r0 to r31.
Example
Input:
2
add r1, r2, r3
sub r4, r1, r5
Output:
2: dependent
Why it works
Only the instruction immediately before can still be in the pipeline with its result not yet ready, so comparing each instruction's sources with the previous destination finds the hazards that need forwarding or a stall.
Examples
2 add r1, r2, r3 sub r4, r1, r5
2: dependent
3 add r1, r2, r3 sub r4, r5, r6 and r7, r1, r4
2: independent 3: dependent
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Pull the register names out of a line with re.findall(r"r\d+", line.lower()).
Hint 2
For sw the first register is a source, not a destination; nop has no registers at all. For other instructions the first register is the destination and the rest are sources.
Solution
Show one correct solution (try it yourself first)
import re
n = int(input())
dest, srcs = [], []
for _ in range(n):
line = input().strip().lower()
regs = re.findall(r"r\d+", line)
op = line.split()[0]
if op == "nop":
dest.append(None)
srcs.append([])
elif op == "sw":
dest.append(None)
srcs.append(regs)
else:
dest.append(regs[0])
srcs.append(regs[1:])
for i in range(1, n):
dep = dest[i - 1] is not None and dest[i - 1] in srcs[i]
print(f"{i + 1}: {'dependent' if dep else 'independent'}")
▶ Open this solution in the compiler, then press Visualize to watch it run step by step