ECE 551 Digital Design And Synthesis Lecture 04 Features of Behavioral Verilog Topics Flip-flops and direct set/reset (preset/clear) Variable data types Memories Procedural assignments Blocking vs. nonblocking Simulation and the Verilog stratified event queue Interacting behaviors Procedural assignments with delay Behavioral Control Statements if/else case/casex/casez 2 Flip-Flop Exercise 1 Implement the following flip-flops: Basic DFF module dff(output reg Q, input D, clk); endmodule DFF with enable input module dffe(output reg Q, input D, clk, en); endmodule 3 Flip-Flop Exercise 2 Implement the following flip-flops: Synchronous reset: triggered by clock signal module dff_sync(output reg Q, input D, clk, rst); endmodule Asynchronous clear: not dependent on clock edge module dff_async(output reg Q, input D, clk, clr); endmodule 4 What Happens Here? clk is edge triggered, but clr is not edge triggered… module dff_BAD(output reg Q, input D, clk, clr); always @(posedge clk, clr) begin if (clr) Q <= 1’b0; else Q <= D; end endmodule 5 Topics Flip-flops and direct set/reset (preset/clear) Variable data types Memories Procedural assignments Blocking vs. nonblocking Simulation and the Verilog stratified event queue Interacting behaviors Procedural assignments with delay Behavioral Control Statements if/else case/casex/casez 6 Datatype Categories Net Represents a physical wire Describes structural connectivity Assigned to in continuous assignment statements Outputs of primitives and instantiated sub-modules Variables Used in behavioral procedural blocks Depending on how used, can represent either synchronous registers or wires in combinational logic 7 Variable Datatypes reg – scalar or vector binary values Not necessarily integer – 32 or more bits a “register”!!! time – time values represented in 64 bits (unsigned) real – double precision values in 64 or more bits realtime - stores time as real (64-bit +) Assigned value only within a behavioral block CANNOT USE AS: Output of primitive gate or instantiated submodule LHS of continuous assignment Input or inout port within a module 8 Examples Of Variables reg signed [7:0] A_reg; reg Reg_Array[7:0]; integer Int_Array[1:100]; real B, Real_Array[0:5]; time Time_Array[1:100]; realtime D, Real_Time[1:5]; initial begin A_reg = 8’ha6; Reg_Array[7] = 1; Int_Array[3] = -1; B = 1.23e-4; Time_Array[20] = $time; D = 1.25; end // // // // // // 8-bit signed vector register array of eight 1-bit registers array of 100 integers scalar & array of 6 reals array of 100 times scalar & array of 5 realtimes // // // // // // Assigns all eight bits Assigns one bit Assign integer -1 Assign real Assigned by system call Assign real time 9 wire vs. reg Same “value” used both as ‘wire’ and as ‘reg’ module dff (q, d, clk); output reg q; // reg declaration, input wire d, clk; // wire declarations, since module inputs always @(posedge clk) q <= d; // why is q reg and d wire? endmodule module t_dff; wire q, clk; reg d; dff FF(q, d, clk); clockgen myclk(clk); initial begin d = 0; #5 d = 1; end endmodule // now declared as wire // now declared as reg // why is d reg and q wire? 10 Signed vs. Unsigned Net types and reg variables unsigned by default Have to declare them as signed if desired! reg signed [7:0] signedreg; wire signed [3:0] signedwire; All bit-selects and part-selects are unsigned A[6], B[5:2], etc. integer, real, realtime are signed System calls can force values to be signed or unsigned reg [5:0] A = $unsigned(-4); reg signed [5:0] B = $signed(4’b1101); See the Supplemental Reading for more info 11 Strings Strings are stored using properly sized registers reg [12*8: 1] stringvar; stringvar = “Hello World”; // 12 character string, 8 bits/char // string assignment Uses ASCII values Unused characters are filled with zeros Strings can be copied, compared, concatenated Most common use of strings is in testbenches 13 Memories & Multi-Dimensional Arrays A memory is an array of n-bit registers reg [15:0] mem_name [0:127]; reg array_2D [15:0] [0:127]; // 128 16-bit words // 2D array of 1-bit regs Can only access full word of memory mem_name[122] = 35; mem_name[13][5] = 1; array_2D[122] = 35; array_2D[13][5] = 1; // // // // assigns word illegal – works in simulation illegal – causes compiler error assigns bit Can use continuous assign to read bits assign assign assign assign mem_val = mem[13]; // get word in slot 13 out = mem_val[5]; // get value in bit 5 of word dataout = mem[addr]; databit = dataout[bitpos]; 14 Array Interfaces – SystemVerilog Verilog doesn’t support the use of arrays as module ports SystemVerilog allows multi-dimensional arrays to be used as vectors module(input [7:0] pixel[640:1][480:1], output b); 15 Example: Memory module memory(output reg [7:0] out, input [7:0] in, input [7:0] addr, input wr, clk, rst); reg [7:0] mem [0:255]; reg [8:0] initaddr; always @ (posedge clk) begin if (rst) begin for (initaddr = 0; initaddr < 256; initaddr = initaddr + 1) begin mem[initaddr] <= 8’d0; end end else if (wr) mem[addr] <= in; end always @(posedge clk) out <= mem[addr]; endmodule 16 Example: Memory module memory(output reg [7:0] out, input [7:0] in, input [7:0] addr, input wr, clk, rst); reg [7:0] mem [0:255]; reg [8:0] initaddr; always @ (posedge clk) begin synchronous reset! if (rst) begin for (initaddr = 0; initaddr < 256; initaddr = initaddr + 1) begin mem[initaddr] <= 8’d0; synchronous write end end else if (wr) mem[addr] <= in; end synchronous read always @(posedge clk) out <= mem[addr]; endmodule 17 Topics Flip-flops and direct set/reset (preset/clear) Variable data types Memories Procedural assignments Blocking vs. nonblocking Simulation and the Verilog stratified event queue Interacting behaviors Procedural assignments with delay Behavioral Control Statements if/else case/casex/casez 18 Procedural Assignments Used within a behavioral block (initial, always) Types = <= // blocking assignment // nonblocking assignment Assignments to variables: reg integer real realtime time 19 Blocking Assignments “Evaluated” sequentially Works a lot like software (danger!) Used for combinational logic module addtree(output reg [9:0] out, input [7:0] in1, in2, in3, in4); reg [8:0] part1, part2; always @(in1, in2, in3, in4) begin part1 = in1 + in2; part2 = in3 + in4; out = part1 + part2; end endmodule in1 in2 in3 in4 + + part1 part2 + out 20 Nonblocking Assignments “Updated” simultaneously if no delays given Used for sequential logic module swap(output reg out0, out1, input rst, clk); always @(posedge clk) begin if (rst) begin out0 <= 1’b0; out1 <= 1’b1; end else begin out0 <= out1; out1 <= out0; end end endmodule D rst clk Q out0 rst to 0 D Q out1 rst to 1 21 Swapping – Ugly version In blocking, sometime use a “temporary” variable module swap(output reg out0, out1, input in0, in1, swap); reg temp; always @(*) begin out0 = in0; out1 = in1; if (swap) begin temp = out0; out0 = out1; out1 = temp; end end endmodule in0 in1 out0 swap out1 Which values get included on the sensitivity list from *? We can write this module in a better way 22 Swapping - Better module swap(output reg out0, out1, input in0, in1, swap); always @(*) begin if (swap) begin out0 = in1; out1 = in0; end else begin out0 = in1; out1 = in0; end end endmodule in0 in1 out0 swap out1 Easier to do the sensitivity list in this case! 23 Blocking & Nonblocking Example reg [7:0] A, B, C, D; always @(posedge clk) begin A = B + C; B = A + D; C = A + B; D = B + D; end reg [7:0] A, B, C, D; always @(posedge clk) begin A <= B + C; B <= A + D; C <= A + B; D <= B + D; end Assume initially that A=1, B=2, C=3, and D=4 Note: Shouldn’t use blocking when describing sequential logic! Why? 24 Blocking & Nonblocking Example Say we wanted to get the same output as the blocking statement version, but wanted to use nonblocking statements How can we do it? 25 Using Non-blocking Statements reg [7:0] A, B, C, D; reg [7:0] newA, newB, newC, newD; always @(posedge clk) begin A <= newA; B <= newB; C <= newC; D <= newD; end always @(*) begin newA = B + C; newB = newA + D; newC = newA + newB; newD = newB + D; end reg [7:0] A, B, C, D; always @(posedge clk) begin A <= B + C; B <= B + C + D; C <= B + C + B + C + D; D <= B + C + D + D; end Depending on the synthesizer, this one may create a lot of hardware! 26 Why Not ‘=‘ In Sequential Logic? Yes, it can “work”, but… Flip-Flops are meant to update simultaneously, not in fixed order Order of statements is important with = = make ordering can complicated when using multiple blocks Easy to describe behavior that is un-synthesizable Use these style guidelines for better success <= for sequential blocks = for combinational blocks Never mix assignment types in the same block! Read Cummings SNUG paper for more details See examples later in lecture 27 Shift Register: Blocking module shiftreg(E, A, clk, rst); output A; input E; input clk, rst; reg A, B, C, D; always @ (posedge clk or posedge rst) begin if (rst) begin A = 0; B = 0; C = 0; D = 0; end else begin A = B; B = C; C = D; D = E; end // option 1 // else begin D = E; C = D; B = C; A = B; end // option 2 end endmodule What are we describing with each option? 28 Shift Register: Blocking 2 E A D Q A = B; B = C; C = D; D = E; // option 1 D = E; C = D; B = C; A = B; // option 2 R clk rst the order matters! E D D Q R clk rst C D Q R B D Q R D A Q R 1 29 Shift Register: Nonblocking module shiftreg(E, A, clk, rst); output A; input E; input clk, rst; reg A, B, C, D; always @ (posedge clk or posedge rst) begin if (rst) begin A <= 0; B <= 0; C <= 0; D <= 0; end else begin A <= B; B <= C; C <= D; D <= E; end // opt. 1 // else begin D <= E; C <= D; B <= C; A <= B; end // opt. 2 end endmodule What do we get with each option? 30 Shift Register: Nonblocking E D D Q C D R Q B D R Q D R Q A R clk the order doesn’t matter! rst E D D Q R C D Q R B D Q R D Q A R clk rst 31 Combinational/Sequential Verilog Can describe many circuits several ways Even within “good practice”! Sometimes all equally good Circuit complexity can affect this choice Simple circuit More likely to be able to use 0-2 always blocks Complex circuit (big FSM, etc) Can be good to separate comb/seq logic 32 Multiply-Accumulate [1] module mac(output reg [15:0] out, input [7:0] a, b, input clk, rst); always @(posedge clk) begin if (rst) out <= 16’d0; else out <= out + (a*b); end endmodule 33 Multiply-Accumulate [2] module mac(output reg [15:0] out, input [7:0] a, b, input clk, rst); reg [15:0] product; always @(*) begin product = a * b; end always @(posedge clk) begin if (rst) out <= 16’d0; else out <= out + product; end endmodule 34 Multiply-Accumulate [3] module mac(output reg [15:0] out, input [7:0] a, b, input clk, rst); reg [15:0] sum; reg [15:0] product; always @(*) begin product = a * b; sum = product + out; end always @(posedge clk) begin if (rst) out <= 16’d0; else out <= sum; end endmodule 35 Multiply-Accumulate [4] module mac(output reg [15:0] out, input [7:0] a, b, input clk, rst); reg [15:0] sum; reg [15:0] product; always @(*) product = a * b; always @(*) sum = product + out; always @(posedge clk) begin if (rst) out <= 16’d0; else out <= sum; end endmodule 36 Multiply-Accumulate [5] module mac(output reg [15:0] out, input [7:0] a, b, input clk, rst); wire [15:0] sum; wire [15:0] product; assign product = a * b; assign sum = product + out; always @(posedge clk) begin if (rst) out <= 16’d0; else out <= sum; end endmodule 37 Topics Flip-flops and direct set/reset (preset/clear) Variable data types Memories Procedural assignments Blocking vs. nonblocking Simulation & Verilog stratified event queue Interacting behaviors Procedural assignments with delay Behavioral Control Statements if/else case/casex/casez 38 Understanding Statement Ordering In Behavioral Verilog, we describe the behavior of a circuit and the synthesizer creates hardware to try to match that behavior. The “behavior” is the input/output and timing relationships we see when simulating our HDL. Therefore, to understand the behavior we are describing, we must understand the our statements will be executed in Simulation Because the language is designed to express parallelism, the most challenging concept is figuring out the order that Verilog statements will occur in and how this will impact the behavior. 39 Verilog Stratified Event Queue Need to be able to model both parallel and sequential logic Need to make sure simulation matches hardware Verilog defines how ordering of statements is interpreted by both simulator and synthesis tools Simulation matches hardware if code well-written Can have some differences with “bad” code Simulator is sequential Hardware is parallel Race conditions can occur Important to remember that “making it work” in SIMULATION doesn’t mean it works in SYNTHESIS 40 Simulation Terminology [1] These only apply to SIMULATION Processes Objects that can be evaluated Includes primitives, modules, initial and always blocks, continuous assignments, and tasks Update event Change in the value of a net or register Evaluation event Computing the RHS of a statement and saving the result value for a later Update Event Scheduling an event Putting an event on the event queue 41 Simulation Terminology [2] Simulation time Time value used by simulator to model actual time. Simulation cycle Complete processing of all currently active events Can be multiple simulation cycles per simulation time Explicit zero delay (#0) Described in detail in SNUG paper Simulation trick to change order of statements #0 doesn’t synthesize! Don’t use it. 42 Determinism vs. Non-Determinism Standard guarantees some scheduling order Statements in same begin-end block “executed” in the order in which they appear Statements in different begin-end blocks in same simulation time have no order guarantee module race(output reg f, input b, c); always @(*) begin f = b & c; end always @(*) begin f = b | c; end Race condition – which assignment to f will occur first vs. last in simulation is not known Note that in hardware this actually models a SHORT CIRCUIT endmodule 43 Verilog Stratified Event Queue [1] Region 1: Active Events Most events except those explicitly in other regions Includes $display system tasks Region 2: Inactive Events Processed after all active events #0 delay events (evil !) Region 3: Non-blocking Assignment Update Events Evaluation previously performed Update is after all active and inactive events complete Region 4: Monitor Events Caused by $monitor and $strobe system tasks Region 5: Future Events Occurs at some future simulation time Includes future events of other regions Other regions only contain events for CURRENT simulation time 44 Verilog Stratified Event Queue [2] simulation “race condition” with $display can cause confusion within a Behavioral block, events of the same class are in order Between different blocks events of the same class can occur in any order 45 Simulation Model Let T be current simulation time while (there are events scheduled at T) { if (no active events) { if (inactive events) activate inactive events else if (n.b. update events) activate n.b. update events else if (monitor events) activate monitor events else { advance T to the next event time activate all inactive events for time T } } } // can cause non-determinism! E = next active event in any block, primitive, or continuous assignment; if (E is an update event) { // in y = a | b, the assigning of value to y update the modified object add evaluation events for sensitive processes to the event queue } else { // evaluation event: in y = a | b, the evaluation of a | b evaluate the process add update event(s) for LHS to the event queue } 46 How Much Do We Need To Know? Don’t need to memorize Exact Simulation model The process of activating events from a region Do need to understand Order statements are evaluated Whether there is a guaranteed order of evaluation i.e. cases of non-determinism Active, Non-Blocking, and Monitor regions $display vs. $strobe vs. $monitor Separation of evaluation and update of nonblocking How this relates to hardware synthesis 47 Race Conditions assign p = q; initial begin q = 1; #1 q = 0; $display(p); end What is displayed? What if $strobe(p) were used instead? 48 Understanding Statement Ordering In Behavioral Verilog, we describe the behavior of a circuit and the synthesizer creates hardware to try to match that behavior. The “behavior” is the input/output and timing relationships we see when simulating our HDL. Therefore, to understand the behavior we are describing, we must understand the our statements will be executed in Simulation Because the language is designed to express parallelism, the most challenging concept is figuring out the order that Verilog statements will occur in and how this will impact the behavior. 49 Topics Flip-flops and direct set/reset (preset/clear) Variable data types Memories Procedural assignments Blocking vs. nonblocking Simulation & Verilog stratified event queue Interacting behaviors Procedural assignments with delay Behavioral Control Statements if/else case/casex/casez 50 Interacting Behaviors [1] Assignments can trigger other assignments Nonblocking assignments (Region 3) CAN trigger blocking assignments (Region 1) always @ (posedge clk) begin … A <= B; … end always @ (A, C) begin … D = A & C; … end In hardware, reflects that the output of the A flip flop or register can be the input to combinational logic When the FF changes value, that change must propagate through the combinational logic it feeds into 51 Interacting Behaviors [2] always @ (posedge clk or posedge rst) // behavior1 if (rst) y1 = 0; //reset else y1 = y2; always @ (posedge clk or posedge rst) // behavior2 if (rst) y2 = 1; // preset example taken from else y2 = y1; Cummings paper! If behavior1 always first after reset, y1 = y2 = 1 If behavior2 always first after reset, y2 = y1 = 0. Results are order dependent, ambiguous – race condition! This is why we don’t use blocking assigns for flip-flops… 52 Interacting Behaviors [3] always @ (posedge clk or posedge rst) if (rst) y1 <= 0; //reset else y1 <= y2; always @ (posedge clk or posedge rst) if (rst) y2 <= 1; // preset example taken from else y2 <= y1; Cummings paper! Assignments for y1 and y2 occur in parallel y1 = 1 and y2 = 0 after reset Values swap each clock cycle after the reset No race condition! 53 Topics Flip-flops and direct set/reset (preset/clear) Variable data types Memories Procedural assignments Blocking vs. nonblocking Simulation & Verilog stratified event queue Interacting behaviors Procedural assignments with delay Behavioral Control Statements if/else case/casex/casez 54 Procedural Assignments with Delay Assignment consists of two separate events: Delays can affect: Evaluation of the right hand side (RHS) Assignment of the value to left hand side (LHS) Time of execution of the current and subsequent assignments Time of evaluation of the RHS Time of assignment to the LHS Type of assignment matters! Covered in Clause 9 of Verilog Standard 55 Blocking Assignments Assignment must be completed before the next statement in the same block is activated Inter-assignment delays block both evaluation and update #4 c = d + e; //Same as: #4; c = d + e; Intra-assignment delays block update but not evaluation c = #4 d + e; //Immediately computes (d+e) then waits to assign What about a mix? #4 c = #8 d + e; For blocking assignments, both types of delays block subsequent statements 56 Blocking: Inter-Assignment Delay Delays both the evaluation and the update always @(posedge clk) begin b = a + a; # 5 c = b + a; # 2 d = c + a; end initial begin a = 3; b = 2; c = 1; end Note: # delays don’t synthesize! Mostly used for input sequencing in testbenches 57 Blocking: Intra-Assignment Delay Delays the update, but not the evaluation always @(posedge clk) begin b = a + a; c = # 5 b + a; d = # 2 c + a; end initial begin a = 3; b = 2; c = 1; end Remember: # delays don’t synthesize! Sometimes used to model delays in combinational logic. 58 Nonblocking Assignments Statements in same timestep considered simultaneously Evaluate all RHS first, then assign in order Inter-assignment delays block evaluation and update Blocks subsequent statements (in different time step) #4 c <= d; #8 e <= f; Intra-assignment delays block update but not evaluation Does not block subsequent statements c <= #4 d; e <= #8 f; For non-blocking assigns, only inter-assignment delays block subsequent statements 59 Nonblocking: Inter-Assignment Delay Delays both the evaluation and the update always @(posedge clk) begin b <= a + a; # 5 c <= b + a; # 2 d <= c + a; end initial begin a = 3; b = 2; c = 1; end Note: # delays don’t synthesize! This type of delay is rarely used in practice 60 Nonblocking: Intra-Assignment Delay Delays the update, but not the evaluation always @(posedge clk) begin b <= a + a; c <= # 5 b + a; d <= # 2 c + a; end initial begin a = 3; b = 2; c = 1; end Note: # delays don’t synthesize! This might be used to model Clock-to-Q delay for a flip flop 61 Intra-Assignment Examples module bnb; reg a, b, c, d, e, f; initial begin // blocking assignments a = #10 1; // a will be assigned 1 at time 10 b = #2 0; // b will be assigned 0 at time 12 c = #4 1; // c will be assigned 1 at time 16 end initial begin // nonblocking assignments d <= #10 1; // d will be assigned 1 at time 10 e <= #2 0; // e will be assigned 0 at time 2 f <= #4 1; // f will be assigned 1 at time 4 end endmodule 62 Mixed Blocking/Nonblocking (BAD) always @(posedge clk) begin b = a + a; c <= b + a; d <= #2 c + a; c = d + a; end initial begin a = 3; b = 2; c = 1; d = 0; end Non-blocking evaluated after blocking in same timestep Confusing to you… confusing to the synthesis tool! Promise not to do this and I won’t ask you to solve a problem like this on the exam. 63 Topics Flip-flops and direct set/reset (preset/clear) Variable data types Memories Procedural assignments Blocking vs. nonblocking Simulation & Verilog stratified event queue Interacting behaviors Procedural assignments with delay Behavioral Control Statements if/else case/casex/casez 64 Control Statements Behavioral Verilog looks a lot like software (risk! – danger and opportunity) Provides similar control structures Not all of these actually synthesize, but some non- synthesizable statements are useful in testbenches What kinds synthesize? if case for loops with constant bounds 65 if… else if… else Operator ? : for simple conditional assignments Sometimes need more complex behavior Can use if statement! Does not conditionally “execute” block of “code” Does not conditionally create hardware! It makes a multiplexer or similar logic Generally: Hardware for all paths is created All paths produce their results in parallel One path’s result is selected depending on the condition 66 Potential Issues With if Can sometimes create long multiplexer chains always @(select, a, b, c, d) begin out = d; if (select == 2’b00) out = a; if (select == 2’b01) out = b; if (select == 2’b10) out = c; end always @(a, b, c, d) begin if (a) begin if (b) begin if (c) out = d; else out = ~d; else out = 1; else out = 0; end 67 if Statement: Flip-Flop Set/Reset module df_sr_behav (q, q_n, data, set, reset, clk); input data, set, clk, reset; output q, q_n; reg q; assign q_n = ~q; // continuous assignment always @ (posedge clk) begin // Flip-flop with synchronous set/reset if (reset) q <= 1’b0; // Active-high set and reset else if (set) q <= 1’b1; else q <= data; end endmodule Does set or reset have priority? 68 case Statements Verilog has three types of case statements: case, casex, and casez Performs bitwise match of expression and case item Both must have same bitwidth to match! case Can detect x and z! (only in simulation) casez Can detect x (In simulation) Uses z and ? as wildcard bits in case items and expression casex Uses x, z, and ? as wildcard bits in case items and expression 69 Using case To Detect x And z Only use this functionality in a testbench; it won’t synthesize! Example taken from Verilog-2001 standard: case (sig) 1’bz: 1’bx: default: endcase $display(“Signal is floating.”); $display(“Signal is unknown.”); $display(“Signal is %b.”, sig); 70 casex Statement Uses x, z, and ? as single-bit wildcards in case item and expression Uses only the first match encountered – Inherent priority! always @ (code) begin casex (code) // case expression 2’b0?: control = 8’b00100110; // case item1 2’b10: control = 8’b11000010; // case item 2 2’b11: control = 8’b00111101; // case item 3 endcase end What is the output for code = 2’b01? What is the output for code = 2’b1x? casex construct is often used to describe logic with priority 71 casez Statement Uses z, and ? as single-bit wildcards in case item and expression Uses first match encountered says we don’t care what control is in other cases… more on this next… always @ (code) begin casez (code) 2’b0?: control = 8’b00100110; // item 1 2’bz1: control = 8’b11000010; // item 2 default: control = 8b’xxxxxxxx; // item 3 endcase end Adding a default case statement is a great way What is the output for code = 2b’01? to avoid inferring latches What is the output for code = 2b’zz? and make debugging easier! 72 “Don’t Care” Assignment With case Sometimes we know not all cases will occur Can “don’t care” what is assigned always@(state, b) begin case (state) 2’d0: next_state = 2’d1; 2’d1: next_state = 2’d2; 2’d2: if (b) next_state = 2’d0; else next_state = 2’d1; default: next_state = 2’dx; endcase end // state is “expression” // 2’d0 is case item // ordering implied // for all other states, // don’t care what is // assigned 73 “Don’t Care” Assignment With if Some combinations don’t happen Can “don’t care” what is assigned For the real hardware, the actual value assigned is either 1 or 0 (or a vector of 1s and/or 0s), but the synthesizer gets to choose always@(a, b, c) begin if (a && b) d = c; else if (a) d = ~c; else d = 1’bx; end For what inputs does the “don’t care” value of d happen? 74 Inferring Latches Earlier we saw how to explicitly create latches We can also implicitly “infer” latches Often this is unintentional and the result of poor coding, accidentally creating a latch instead of comb. logic Unintentional latches are a leading cause of simulation and synthesis results not matching! Two common ways of inferring latches Failing to fully specify all possible cases when using if/else, case, or conditional assignment when describing combinational logic Failing to assign values to each variable in all cases 75 Unintended Latches [1] (BAD) Always use else or provide “default value” when using if to describe combinational logic! always @(en, a, b) begin if (en) c = a + b; // latch! – What about en = 1’b0? end always @(en, a, b) begin c = 8’b0; if (en) c = a + b; end // Fixed! Assign default value to C // Will be overwritten if en=1’b1 always @(en, a, b) begin if (en) c = a + b; else c = 8’b0; end // Fixed! Add an Else statement // Could have used a different value 76 Unintended Latches [2] (BAD) Make sure that no matter what the value of your case selector is, if a variable is assigned in one case, it must be assigned in EVERY case. always @(sel, a, b) case (sel) 2’b00 : begin out1 = a + b; out2 = a – b; end 2’b01 : out1 = a + b; //Latch! What about out2’s value? 2’b10 : out2 = a – b; //Latch! What about out1’s value? //Latch! What about out1 and out2’s values for sel=2’b11? endcase How could we modify this code to remove the latches? 77 Review Questions Does the following correspond to synchronous or asynchronous reset? always @(posedge clk, posedge reset) What value is returned for each of the following? reg signed [7:0] A = $signed(4’b1101); reg [7:0] B = $unsigned(4’b1101); Show how to declare a memory called my_memory with 128 12-bit words. Do you use blocking or non-blocking assignments for sequential circuits? 78 Review Questions What happens in the following? reg [3:0] a, b, c, d; always @(*) begin b <= #1 a + a; c = #2 b + a; #3 d <= c + a; d = a ?( b + 1): (c + 2); end initial begin a = 3; b = 2; c = 1; d = 0; end 79 Review Questions What happens in the following? reg [3:0] w = 1, x = 2, y = 3, z; reg clk = 0; initial #1 clk = 1; always @(posedge clk) begin w <= #2 x + y; x <= #3 x + 1; end always @(w, x) begin #2 y = w + x; #3 z = w & x; end 80 Review Questions What is wrong with the following code? module circuit(output [3:0] f, input x, input [3:0] y, z); always @(y,z) begin f = 0; if (x) f = x + y; end always @(f, y, z) begin if (y) f = f + z; else f = f – z; endmodule What is the difference between case and casex? 81