I have to create a 32 bit ALU in structural verilog with opcodes for AND(000), OR(001), ADD(010), SUB(110), SLT(111), and BEQ(100). I understand how each of these work individually at the gate level I'm just confused on how to use opcodes to get my desired output. For example if it was a high level language I would write something like if opcode == 100 {output = branch}. I apologize if this is a dumb question I'm just new to verilog and many of the answers online either use behavioral verilog or are very confusing.
You can use the same technique you described in Verilog... to use if
statements, they have to be in an always
block, like so:
always @ (*) begin
if (operation == 3'b000) begin
alu_result = and_result;
end else if (operation == 3'b001) begin
alu_result = or_result;
end else if (operation == 3'b010) begin
alu_result = add_result;
// ...repeat this pattern for the other operations except BEQ...
end else begin
alu_result = beq_result;
end
end
In this example, the *_result
wires are the resulting values from the individual operations. The code will synthesise to a multiplexer that selects between the individual result values (dependent on the operation
) and drives the alu_result
which is the final ALU output.
Instead of using if
statements, for this application it is probably better to use case
like in the following:
always @ (*) begin
case (operation)
3'b000: alu_result = and_result;
3'b001: alu_result = or_result;
3'b010: alu_result = add_result;
// ...repeat this pattern for the other operations except BEQ...
default: alu_result = beq_result;
endcase
end
As you can see, this is a bit more compact and easy to read. If written correctly, both variants should lead to exactly the same multiplexer logic. Note that in both variants, the alu_result
needs to be of type reg [31:0]
because we're assigning within a always
blocks, but there is a way to use wire
if you prefer:
alu_result = operation == 3'b000 ? and_result
: operation == 3'b001 ? or_result
: operation == 3'b010 ? add_result
// ...repeat this pattern for the other operations except BEQ...
: beq_result;
EDIT
The OP indicated that he needs a bit-level, structural multiplexer code.
A very simple multiplexer can be created out of AND, OR and NOT gates. For example, a 2-way multiplexer could be created as follows:
not(select_inv,select);
and(selected_signal_a,signal_a,select_inv);
and(selected_signal_b,signal_b,select);
or(selected_result,selected_signal_a,selected_signal_b);
In this example, select
determines which one of the signal_a
and signal_b
gets through to the final output selected_result
.
You can use the same pattern for more than one select bit (hint: you need three) by eg stacking multiple multiplexers in series.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.