ece 551 digital design and synthesis lecture 04 features of behavioral verilog

Post on 24-Dec-2015

230 Views

Category:

Documents

2 Downloads

Preview:

Click to see full reader

TRANSCRIPT

ECE 551Digital 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

DFF with enable input

3

module dff(output reg Q, input D, clk);

endmodule

module dffe(output reg Q, input D, clk, en);

endmodule

Flip-Flop Exercise 2 Implement the following flip-flops:

Synchronous reset: triggered by clock signal

Asynchronous clear: not dependent on clock edge

4

module dff_sync(output reg Q, input D, clk, rst);

endmodule

module dff_async(output reg Q, input D, clk, clr);

endmodule

What Happens Here? clk is edge triggered, but clr is not edge

triggered…

5

module dff_BAD(output reg Q, input D, clk, clr); always @(posedge clk, clr) begin if (clr) Q <= 1’b0; else Q <= D; endendmodule

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 integer – 32 or more bits 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

Not necessarily a “register”!!!

Examples Of Variables

reg signed [7:0] A_reg; // 8-bit signed vector register

reg Reg_Array[7:0]; // array of eight 1-bit registers

integer Int_Array[1:100]; // array of 100 integers

real B, Real_Array[0:5]; // scalar & array of 6 reals

time Time_Array[1:100]; // array of 100 timesrealtime D, Real_Time[1:5]; // scalar & array of 5 realtimesinitial begin

A_reg = 8’ha6; // Assigns all eight bits Reg_Array[7] = 1; // Assigns one bitInt_Array[3] = -1; // Assign integer -1B = 1.23e-4; // Assign realTime_Array[20] = $time; // Assigned by system call

D = 1.25; // Assign real time end

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; // now declared as wire reg d; // now declared as reg dff FF(q, d, clk); // why is d reg and q wire? clockgen myclk(clk); initial begin d = 0;

#5 d = 1; endendmodule

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 info11

Strings Strings are stored using properly sized

registersreg [12*8: 1] stringvar; // 12 character string, 8 bits/charstringvar = “Hello World”; // 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]; // 128 16-bit wordsreg array_2D [15:0] [0:127]; // 2D array of 1-bit regs

Can only access full word of memorymem_name[122] = 35; // assigns wordmem_name[13][5] = 1; // illegal – works in

simulationarray_2D[122] = 35; // illegal – causes compiler

errorarray_2D[13][5] = 1; // assigns bit

Can use continuous assign to read bitsassign mem_val = mem[13]; // get word in slot 13assign out = mem_val[5]; // get value in bit 5 of wordassign dataout = mem[addr];assign 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: Memorymodule 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];

endmodule16

Example: Memorymodule 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];

endmodule17

synchronous reset!

synchronous write

synchronous read

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

20

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;

endendmodule

+ +

+

out

in1 in2 in3 in4

part1 part2

Nonblocking Assignments “Updated” simultaneously if no delays given Used for sequential logic

21

module swap(output reg out0, out1, input rst, clk);

always @(posedge clk) beginif (rst) begin

out0 <= 1’b0;out1 <= 1’b1;

endelse begin

out0 <= out1;out1 <= out0;

endendendmodule

D Q

rst to 1

D Q

rst to 0clkrst

out1

out0

Swapping – Ugly version In blocking, sometime use a “temporary”

variable

22

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;

endendendmodule

Which values get included on the sensitivity list from *?

We can write this module in a better way

swap

in1

in0out0

out1

Swapping - Better

23

module swap(output reg out0, out1, input in0, in1, swap);

always @(*) beginif (swap) begin

out0 = in1;out1 = in0;

endelse begin

out0 = in1;out1 = in0;

endendendmodule

Easier to do the sensitivity list in this case!

swap

in1

in0out0

out1

Blocking & Nonblocking Example

Assume initially that A=1, B=2, C=3, and D=4

Note: Shouldn’t use blocking when describing sequential logic! Why?

24

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

Blocking & Nonblocking Example

Say we wanted to get the same output as the blocking statement version, but wanted to use non-blocking statements

How can we do it?

25

Using Non-blocking Statements

26

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;

endalways @(*) 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 thesynthesizer, this one

maycreate a lot of hardware!

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: Blockingmodule 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

29

E

rst

clk

C B A

R

QD

R

QD

R

QD

R

QDD

E

rst

clk

R

QDA

the order matters!

A = B; B = C; C = D; D = E; // option 1D = E; C = D; B = C; A = B; // option 2

2

1

Shift Register: Nonblockingmodule 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

31

E

rst

clk

C B A

R

QD

R

QD

R

QD

R

QDD

E

rst

clk

C B A

R

QD

R

QD

R

QD

R

QDD

the order doesn’t matter!

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]

33

module mac(output reg [15:0] out,input [7:0] a, b, input clk, rst);

always @(posedge clk) beginif (rst) out <= 16’d0;else out <= out + (a*b);

end

endmodule

Multiply-Accumulate [2]

34

module mac(output reg [15:0] out,input [7:0] a, b, input clk, rst);

reg [15:0] product;

always @(*) beginproduct = a * b;

end

always @(posedge clk) beginif (rst) out <= 16’d0;else out <= out + product;

end

endmodule

Multiply-Accumulate [3]

35

module mac(output reg [15:0] out,input [7:0] a, b, input clk, rst);

reg [15:0] sum;reg [15:0] product;

always @(*) beginproduct = a * b;sum = product + out;

end

always @(posedge clk) beginif (rst) out <= 16’d0;else out <= sum;

end

endmodule

Multiply-Accumulate [4]

36

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) beginif (rst) out <= 16’d0;else out <= sum;

end

endmodule

Multiply-Accumulate [5]

37

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) beginif (rst) out <= 16’d0;else out <= sum;

end

endmodule

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

43

module race(output reg f, input b, c);

always @(*) begin f = b & c;end

always @(*) begin f = b | c;end

endmodule

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

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]

45

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

simulation “race condition” with $display can

cause confusion

Simulation ModelLet T be current simulation timewhile (there are events scheduled at T) {

if (no active events) {if (inactive events) activate inactive eventselse if (n.b. update events) activate n.b. update eventselse if (monitor events) activate monitor eventselse { 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 objectadd evaluation events for sensitive processes to the event

queue} else { // evaluation event: in y = a | b, the evaluation of a | b

evaluate the processadd 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 Conditionsassign 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)

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

always @ (A, C)begin

…D = A & C;…

end

always @ (posedge clk)

begin…A <= B;…

end

Interacting Behaviors [2]always @ (posedge clk or posedge rst) // behavior1

if (rst) y1 = 0; //resetelse y1 = y2;

always @ (posedge clk or posedge rst) // behavior2

if (rst) y2 = 1; // presetelse y2 = y1;

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

example taken from Cummings paper!

Interacting Behaviors [3]always @ (posedge clk or posedge rst)

if (rst) y1 <= 0; //resetelse y1 <= y2;

always @ (posedge clk or posedge rst)if (rst) y2 <= 1; // presetelse y2 <= y1;

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

example taken from Cummings paper!

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:

Evaluation of the right hand side (RHS) Assignment of the value to left hand side (LHS)

Delays can affect: 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) beginb = a + a;# 5 c = b + a;# 2 d = c + a;

endinitial 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) beginb = a + a;c = # 5 b + a;d = # 2 c + a;

endinitial 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) beginb <= a + a;# 5 c <= b + a;# 2 d <= c + a;

endinitial 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) beginb <= a + a;c <= # 5 b + a;d <= # 2 c + a;

endinitial 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 Examplesmodule 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 16end

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 4endendmodule

62

Mixed Blocking/Nonblocking (BAD)

always @(posedge clk) beginb = a + a;c <= b + a;d <= #2 c + a;c = d + a;

endinitial 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) beginout = 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) beginif (a) begin

if (b) beginif (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 assignmentalways @ (posedge clk) begin // Flip-flop with synchronous

set/resetif (reset) q <= 1’b0; // Active-high set and resetelse if (set) q <= 1’b1;else q <= data;

endendmodule

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: $display(“Signal is

floating.”);1’bx: $display(“Signal is

unknown.”);default: $display(“Signal is %b.”,

sig);endcase

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) begincasex (code) // case

expression2’b0?: control = 8’b00100110; // case

item12’b10: control = 8’b11000010; // case

item 2 2’b11: control = 8’b00111101; // case item 3

endcaseend

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

always @ (code) begincasez (code)

2’b0?: control = 8’b00100110; // item 12’bz1: control = 8’b11000010; // item 2

default: control = 8b’xxxxxxxx; // item 3 endcaseend

What is the output for code = 2b’01? What is the output for code = 2b’zz?

72

says we don’t care what control is in other cases… more on this next…

Adding a default case statement is a great way to avoid inferring latches and make debugging easier!

“Don’t Care” Assignment With case Sometimes we know not all cases will occur Can “don’t care” what is assigned

always@(state, b) begincase (state) // state is

“expression”2’d0: next_state = 2’d1; // 2’d0 is

case item2’d1: next_state = 2’d2; // ordering

implied2’d2: if (b) next_state = 2’d0; else next_state = 2’d1;default: next_state = 2’dx; // for all other

states,endcase // don’t care what is

end // assigned73

“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) beginif (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

75

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

Unintended Latches [1] (BAD) Always use else or provide “default value” when

using if to describe combinational logic!

always @(en, a, b) beginif (en) c = a + b; // latch! – What about en =

1’b0?end

always @(en, a, b) beginc = 8’b0; // Fixed! Assign default value to Cif (en) c = a + b; // Will be overwritten if en=1’b1

end

always @(en, a, b) beginif (en) c = a + b; // Fixed! Add an Else statementelse c = 8’b0; // Could have used a

different valueend 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 : beginout1 = 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);

endinitial 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;

endalways @(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; endalways @(f, y, z) begin if (y) f = f + z; else f = f – z;

endmodule

What is the difference between case and casex? 81

top related