// 流水线控制器 - 处理冒险和气泡
module pipeline_controller #(
    parameter STAGES = 4
)(
    input  wire        clk,
    input  wire        rst_n,
    input  wire        stall_request [0:STAGES-2],
    output wire [STAGES-1:0] stage_valid,
    output wire        pipeline_flush
);
    reg [STAGES-1:0] valid;
    reg flush;
    integer i;
    
    always @(posedge clk or negedge rst_n) begin
        if (!rst_n) begin
            valid <= {STAGES{1'b0}};
            flush <= 1'b0;
        end else begin
            flush <= 1'b0;
            // 检查停顿请求
            for (i = STAGES-1; i > 0; i = i - 1) begin
                if (stall_request[i-1])
                    valid[i] <= valid[i];  // 保持
                else
                    valid[i] <= valid[i-1];  // 传递
            end
            valid[0] <= 1'b1;  // 第一阶段始终有效
        end
    end
    
    assign stage_valid = valid;
    assign pipeline_flush = flush;
endmodule