0% found this document useful (0 votes)
83 views88 pages

Introduction To Verilog

This document provides an introduction and overview of Verilog HDL: - It outlines topics including lexical elements, data types, structures, operators, assignments, control statements, tasks and functions. - It defines HDL as hardware description language used to describe circuits through syntax and sentences at a high level, rather than schematics. Verilog and SystemVerilog are common HDLs. - The document discusses behavioral and structural modeling in Verilog, and how Verilog can be used for both simulation to verify circuits operate correctly and synthesis to transform descriptions into logic gates.

Uploaded by

master vijay
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
83 views88 pages

Introduction To Verilog

This document provides an introduction and overview of Verilog HDL: - It outlines topics including lexical elements, data types, structures, operators, assignments, control statements, tasks and functions. - It defines HDL as hardware description language used to describe circuits through syntax and sentences at a high level, rather than schematics. Verilog and SystemVerilog are common HDLs. - The document discusses behavioral and structural modeling in Verilog, and how Verilog can be used for both simulation to verify circuits operate correctly and synthesis to transform descriptions into logic gates.

Uploaded by

master vijay
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 88

Introduction to Verilog HDL

Outline
• HDL Verilog Lexical elements
Data type representation
• Synthesis Verilog tutorial Structures and Hierarchy
Operators
• Synthesis coding Assignments
Control statements
guidelines Task and functions
Generate blocks
• Verilog - Test bench
• Fine State Machines
• References
HDL
VERILOG
What is HDL?
• Hard & Difficult Language?
– No, means Hardware Description Language
• High Level Language
– To describe the circuits by syntax and sentences
– As oppose to circuit described by schematics
• Widely used HDLs
– Verilog – Similar to C
– SystemVerilog – Similar to C++
– VHDL – Similar to PASCAL
Verilog
• Verilog was developed by Gateway Design
Automation as a proprietary language for logic
simulation in 1984.
• Gateway was acquired by Cadence in 1989
• Verilog was made an open standard in 1990 under the
control of Open Verilog International.
• The language became an IEEE standard in 1995
(IEEE STD 1364) and was updated in 2001 and
2005.
SystemVerilog
• SystemVerilog is the industry's first unified hardware
description and verification language
• Started with Superlog language to Accellera in 2002
• Verification functionality (base on OpenVera
language) came from Synopsys
• In 2005 SystemVerilog was adopted as IEEE
Standard (1800-2005). The current version is
1800-2009
IEEE-1364 / IEEE-1800
Verilog 2005 (IEEE
Standard 1364-2005)
consists of minor
corrections, spec
clarifications, and a few
new language features

SystemVerilog is a superset
of Verilog-2005, with many
new features and
capabilities to aid design-
verification and design-
modeling
Types of modeling
• Behavioral
– Models describe what a rst Counter
cnt
module does. clk
If (rst) cnt
= 0; else
cnt = cnt+1; [0:3]
– Use of assignment
statements, loops, if, else
kind of statements
• Structural
– Describes the structure of
the hardware components
– Interconnections of primitive
gates (AND, OR, NAND, NOR,
etc.) and other modules
Behavioral - Structural
Behavioral Structural
module c t e r ( module c t e r ( r s t , c l o c k , count ) ;
input r s t , clock, outp ut [ 1 : 0 ] count;
outp ut reg [ 1 : 0 ] count input r s t , clock;
); w ire N5, n1, n4, n5, n6;
always@(posedge c l o c k ) FFD U0 (.D(N5), .CP(cl oc k) ,
begin . Q ( c o u n t [ 0 ] ) , .QN(n6));
i f ( r s t ) count = 0 ; FFD U1 ( . D ( n 1 ) , .CP(cl o ck ) ,
else count = count +1; . Q ( c o u n t [ 1 ] ) , .QN(n5));
end MUX21U2 ( . A ( N 5 ) , . B ( n 4 ) ,
.S(n5), .Z(n1) ) ;
endmodule
NRU3 ( . A ( n 6 ) , . B ( r s t ) , . Z ( n 4 ) ) ;
NRU4 ( . A ( c o u n t [ 0 ] ) , . B ( r s t ) ,
.Z(N5));
endmodule
Simulation and Synthesis
• The two major purposes of HDLs are
logic simulation and synthesis
– During simulation, inputs are applied to a module,
and the outputs are checked to verify that the
module operates correctly
– During synthesis, the textual description of a
module is transformed into logic gates
• Circuit descriptions in HDL resemble code in
a programming language. But the code is
intended to represent hardware
Simulation and Synthesis
• Not all of the Verilog commands can
be synthesized into hardware
• Our primary interest is to build hardware, we will
emphasize a synthesizable subset of the
language
• Will divide HDL code into synthesizable
modules and a test bench (simulation).
– The synthesizable modules describe the hardware.
– The test bench checks whether the output results are
correct (only for simulation and cannot be
synthesized)
SYNTHESIS VERILOG
TUTORIAL
Outline
• Lexical elements
• Data type representation
• Structures and Hierarchy
• Operators
• Assignments
• Control statements
• Task and functions
Lexical elements
• Case sensitive - keywords are lower case
• Semicolons(;) are line terminators
• Comments:
– One line comments start with / / ...
– Multi-line comments start with /*and
end w i t h * /
• System tasks and functions start with a
dollar sign, ex $display, $signed
Lexical elements
• Variable names have to start with an
alphabetic character or underscore (_)
followed by alphanumeric or underscore
characters
• Escaped identifiers ( \ )
– Permit non alphanumeric characters in Verilog name
– The escaped name includes all the characters
following the backslash until the first white
space character
wire \fo+o=a ; / / Declare the va r a i b l e fo+o=a=a
wire \ f o +o =a ; / / Assign a t o wire fo+o
Compiler directives
• The directives start with
a grave accent ( ` ) `include “ f i l e 1 . v ”
/ / Used as `WORD_SIZE i n code
followed by some
` d e f i n e WORD_SIZE 32
keyword
`define module t e s t ( ) ;
Text-macro substitution ` i f d e f TEST
`ifdef, `ifndef, ` e ls e , / / A implementation
`endif `else
/ / B implementation
Conditional compilation
`endif
` i n c lu d e assi g n out = ` WORD_SIZ E{1 ’b 1 };
File inclusion endmodule
Reserved keywords
and always assign attribute begin buf bufif0 bufif1
case cmos deassign def ault defparam d i sa b l e else endattribute
end endcase endf unction e n d p r i mi ti ve endmodule endtable endtask event
for force f o r e ve r fork function highz0 highz1 if
initial inout input integer join large medium module
nand negedge nor not notif0 notif1 nmos or
output parameter pmos posedge primitive pulldown pullup pull0
pull1 rcmos reg release repeat rnmos rpmos rtran
rtranif0 rtranif1 scalared small sp e c i f y specparam strong0 strong1
supply0 supply1 table t a sk tran tranif0 tranif1 time
tri triand trior trireg tri0 tri1 vectored wait
wand weak0 weak1 w h i le wire wor
Outline
• Lexical elements
• Data type representation
• Structures and Hierarchy
• Operators
• Assignments
• Control statements
• Task and functions
Logical values
• A bit can have any of these values
– 0 representing logic low (false)
– 1 representing logic high (true)
– X representing either 0, 1, or Z
– Z representing high impedance for tri-
state (unconnected inputs are set to Z)
Logical values
• Logic with multilevel (0,1,X,Z) logic values
– Nand anything with 0 is 1
– Nand two get an X
• True tables define the how outputs are compute

| 0 1 X Z
& 0 1 X Z
0 0 1 X X
0 0 0 0 0
1 0 1 X X 1 1 1 1 1

X 0 X X X X X 1 X X
Z 0 X X X Z X 1 X X
Number representation
<size>'<base format><number>

• <size>:
– number of bits (optional)
• <base format>:
– It is a single character ' followed by one of the
following characters b, d, o and h, which stand for
binary, decimal, octal and hex, respectively.
• <number>
– Contains digits which are legal for the <base format>
– ‘_’ underscore can be use for readability
Number representation
• Negative numbers are store as 2’s
complement
• Extended number
– If MSB is 0, Xor Z number is extended to fill
MSBs with 0, X, Z respectively
3’b01=3’b001 3’bx1=3’bxx1 3’bz=3’bzz

– If MSB is 1 number is extend to fill MSBs with


0/1, depending on the sign
3’b1=3’b001 -3’b1=-3’b01=3’b111
Number representation
Unsized numbers (at least 32 bit)
549 / / decimal number
'h8F_F / / hex number
'o765 / / o c t a l number
Size numbers

4'b11 // 4 - b i t bi nary number 0011


3'b10x // 3 - b i t b i n a ry number wi th LSM b i t unknown
8' hz // 8 - b i t bi nary high-impedance number
4'hz1 // 4’bzzz1
5'd3 // 5-bit decimal number
Signed numbers
-8'd6 / / 8 - b i t two' s complement o f 6 ( - 6 )
4'shF / / 4- b i t number ‘ 1111’ t o be i n t e r p r e t e d as
/ / 2 ’ s complement number
Data types (reg)
• A reg ( reg ) stores its value from one
assignment to the next (model data
storage elements)
– Don’t confuse reg with register
– Default value is X
– Default range is one bit
– By default are unsigned, but can be
declare signed, using keyword signed
Data types (Nets)
• Nets ( wire ) correspond to physical wires
that connect instances
– Nets do not store values
– Have to be continuously driven
– The default range is one bit
– By default are unsigned
• The wire declaration is used most
frequently, other net types are wand, wor,
t r i , t r i a n d , t r i o r , etc.
Other data types
• Integer ( integer )
– Convenient to counting purposes
– At least 32-bit wide
– Useful for loop
• Real ( real ) simulation only
– Can be specified in decimal and scientific
notation
Verilog vectors
Know as BUS in hardware
• Declare by a range following the type
<data type> [ l e f t range : r i g h t range] <Variable name>
• Single element that is n-bits wide
reg [0 :7 ] A, B; / /T wo 8- b it re g w i th MSB as th e 0th b it
wir e [ 3 : 0 ] Data; / / 4 - b i t wide wir e MSB as the 4 th b i t

• Vector part select (access)


A[5] / / b i t # 5 of v ec tor A
Data [2 : 0 ] / / Th ree LSB o f vecto r Data
Verilog arrays
• Array: range follows the name
<dat a t ype> <a r r ay name> [ <ar r a y i ndi ces>]
reg B [1 5: 0 ] ; / / ar r a y of 16 r eg e lement s
• Array of vectors
<d a ta typ e> [ <vect o r ind i c es>] <arra y
name>[<array i ndi c es > ]
reg [ 1 5 : 0 ] C [ 1 0 2 3 : 0 ] ; / / array o f vectors
• Memory access
<var name>[ <a r r ay ind i c e s>] [ <vecto r in d i c es>]
Data storage and Verilog arrays
Simple RAM Model
module RAM ( o u t p u t [7:0] Obus,
input [7:0] Inbus,
input [3:0] Adr,
input C l k , Read
);
reg [ 7 : 0 ] St o r a g e [ 1 5 : 0 ] ;
reg [ 7 : 0 ] ObusReg;

assign Obus = ObusReg;

always @(posedge Cl k)
i f (Read==1’b0) Storage[Adr] = I n b u s ;
else ObusReg = Sto r a g e [Adr ];

endmodule
Data storage and Verilog arrays
Counter
module c t e r ( i n p u t r s t , c l o c k , jmp,
i nput [ 7 : 0 ] jump,
output reg [ 7 : 0 ] count
);
always@(posedge c l o c k )
begin
if (rst) count = 8 ’h 0 0 ;
else i f ( jmp ) count = jump + c o u n t ;
else count = count + 8 ’ h 1 ;
end
endmodul e
Outline
• Lexical elements
• Data type representation
• Structures and Hierarchy
• Operators
• Assignments
• Control statements
• Task and functions
Structures and Hierarchy
• Hierarchical HDL structures are achieved
by defining modules and instantiating
modules
top.v TOP
co mp.v COMP

MUX
mux.v
Module declaration

module <module name> #(<param l i s t > ) ( < p o r t l i s t > ) ;


<Declarations>
< In s t a n t i at i on s >
<Data fl ow statements>
<Behavioral blocks>
<task and functions>
endmodule
Module header
• Start with module keyword, contains the I/O ports
• Port declarations begins with output , i n p u t or
i n o u t follow by bus indices
• Each directions are followed by one or more
I/O names
• Each declaration is separated by comma (,)

module ALU ( o u t p u t [ 3 1 : 0 ] z ,
in put [ 1 5 : 0 ] A, B,
in put c lo c k , ena) ;
Port declaration
• i n p u t and i n o u t are declared as wires
• outputs port can be declared as reg
(holds a value)
• 2 flavors for port declaration:
module S1 ( a , b , c , d , e ) ; module S2 ( i n p u t [ 1 : 0 ] a , b ,
input [1 :0 ] a, b; input c,
input c ; output reg [ 1 : 0 ] d ,
output reg [ 1 : 0 ] d ; output e ) ;
output e ;
/ / Ve r i l o g 1995 St yl e //ANSI CSt yl e
endmodule endmodule
Parameters
• Parameters are means of giving
names to constant values
• The values can be overridden when the
design is compiled
• Parameters cannot be used as variables
• Syntax:
parameter <name> = <constant expression>;
Parameter declaration
• Default value need to be set at declaration
time
• 32 bit wide by default, but may be declared
of any width parameter [ 2 : 0 ] IDLE = 3 ’ d 0 ;
• 2 declaration flavors:
Inside a module In module header
module t e s t ( . . . I / O ’ s . . . ) module t e s t
parameter ASIZE = 32, BSIZE =16; #(parameter ASIZE = 32, BSIZE =16)
//… ( . . . I/O’s . . . ) ;
reg [ASIZE - 1 : 0 ] Abus, Zbus; //…
w ire [BSIZE-1:0] Bw ire; reg [ASIZE - 1 : 0 ] Abus, Zbus;
//… w ire [BSIZE-1:0] Bw ire;
endmodule //…
endmodule
Example
module Adder ( A , B, Cin, S,
A[N-1:0]
Cout, C l k ) ; Adder S[N-1:0]
parameter N=8; B[N-1:0]
N-
i n p u t [ N - 1 : 0 ] A , B;
i n p u t Cin; Cin bits Cout
i n p u t C l k ; outp ut (8 by
[ N - 1 : 0 ] S; outp ut default)
Cout; reg-ouputs
reg [ N - 1 : 0 ] S; Clk
reg Cout;
//module i n t e r n a l s module Adder #(parameter N=8)
endmodule ( i n p u t [ N - 1 : 0 ] A , B,
i n p u t Cin,
input Clk,
outp ut reg [ N - 1 : 0 ] S,
outp ut reg Cout
ANSI C style );
//module i n t e r n a l s
endmodule
Structures and Hierarchy
• Instance of a module
– Instantiation is the process of “calling” a module
– Create objects from a module template
<module name> #(<param l i s t > )
<instance name> ( < p o r t l i s t > ) ;
Where:
<module name> Module to be instantiated
<param l i s t > Parameters values passed to the instance
<instance name> Identifies the instance of the module
<port l i s t > Port list connection
Port list connections
• Ports
– Provide the interface by which a module
can communicate with the environment
– Port declarations ( input , output , inout )

reg o net net reg o net net

input outp ut
net inout

net
Port connections/Parameter
overwrite
• Named connection
– Explicitly linking the 2 names for each side
of the connection
my_mod #(.W (1), . N ( 4 ) ) U1 ( . i n 1 ( a ) , . i n 2 ( b ) ,
.out(c));
• Order connection
– Expression shall be listed in the same order
as the port declaration
my_mod # ( 1 , 4 ) U2 ( a , b , c ) ;
Hierarchy example

TOP module TOP (…port_ list … );


U1 ALU U1 (…port connection…);
ALU S1 MEM U2 (…port connection…);
FIFO endmodule
module ALU ( …por t _lis t …) ;
U2 FIFO S1 ( …po r t connec t ion …) ;
endmodule
MEM
module FIFO ( …por t _lis t …) ;
//...
endmodul e
Outline
• Lexical elements
• Data type representation
• Structures and Hierarchy
• Operators
• Assignments
• Control statements
• Task and functions
Relational operators

• Mainly use in expression (e.g. if sentences)


• Returns a logical value (1/true 0/false)
• If there are any X or Z bit returns X (false on a
expression)

< a < b // is a le s s than b?


> a > b // is a greater than b?
>= a >= b // is a greater than o r equal t o b
<= a <= b // is a le s s than o r equal t o b
Arithmetic operators
• Binary operators
– Takes 2 operators
• Unary operators (+/-)
– Specify the sign of the operand
– Negative numbers are represented as 2’s
complement
* c = a * b ; // m u lt i p ly a wi t h b
/ c = a / b ; // i n t d i v i d e a by b
+ sum = a + b ; // add a and b
- diff = a - b ; // s u b t r a c t b from a

% amodb = a % b / / a mod(b)
;
Logical operators
• Logical operators evaluate to a 1-bit value
&& a && b ; // is a and b true? returns 1-bit true/false
|| a || b ; // is a or b true? returns 1-bit true/false
! if (!a) c = b; // if a is not true assign b to c

• If an operant is not zero is treat as logical 1


A=3; B=0;
A&&B //Ev aluates t o 0 Equivalent t o ( l o g i c a l - 1 && l o g i c a l - 0 )
!B //Ev aluates t o 1 Equivalent t o ( ! l o g i c a l - 0 )
• If an operant is Z o X is treat as X (false)
A=2’b0x; B=2’b10;
A&&B //Ev aluates t o x Equivalent t o ( x && l o g i c a l - 0 )
Equality and Identity operators

== c == a ; /* is c equal to a returns 1-bit true/false


applies for 1 or 0, logic equality, using
X or Z operands returns always false
('hx == 'h5 returns 0) */
!= c ! = a ; // is c not equal to a, returns 1-bit true
=== a === b ; // is a identical to b (includes 0, 1, x, z)
/* is a not identical to b returns 1-
! == a ! == b ;
bit true/false*/
Bitwise and Reduction operations

/* AND all bits of a


& b = &a ;
(reduction) * /
| b = |a ; /*OR a l l b i t s ( r e d u c t i o n ) * /
/ * E x c lu s i v e o r a l l b i t s o f
^ b = ^a ;
a (reduction)*/
/ * NAND, NOR, EX-NOR a l l
~&, ~ |, ~ ^ c = ~& b ;
b i t s together * /
/*bit-wise NOT, AND,
~,&, | , ^ b = ~a ; e = b | a
OR, EX-OR*/
/*bit-wise NAND, NOR, EX-
~&, ~ | , ~^ e = a ~^ b ;
NOR*/
Shift and other operator
<< a << 1 ; / / s h i f t l e f t a by 1 - b i t
>> a >> 1 ; / / s h i f t r i g h t a by 1
<<< b <<< 1 ; / / a r i t h me t i c s h i f t by 1
>>> b >>> 1 ; / / a r i t h me t i c s h i f t by 1
/ * i f s e l i s t r u e c = a , else c
?: c = sel ? a : b ;
= b , ? : t e r n a r y operator * /

/ * add a , b , c i assign the


overflow t o co and the r e s u l t t o
{} { c o , sum} = a + b + c i ;
sum: operator i s c a l l e d
concatenation * /

/ * r e p l i c a t e a 3 t i me s,
{{}} b = {3{a}}
e q u i vale nt t o { a , a , a } * /
Operators precedence
Operator precedence

Unary, Multiply, Divide, +,-,!,~ Highest


Modulus *, / %
+, -
Add, subtract, shift
<<. >>
< , < = , > , >=
Relational
Equality = , ==. ! =
===, ! ==
&, ~&
^ , ^~
Reduction
Logical | , ~|
&&
||
Conditional ?: Lowest
Outline
• Lexical elements
• Data type representation
• Structures and Hierarchy
• Operators
• Assignments
• Control statements
• Task and functions
Concurrent blocks
• Blocks of code with no well-defined
order relative to one another
– Module instance is the most important
concurrent block
– Continuous assignments, and procedural
blocks are concurrent within a module
module AND ( i n p u t A, B, output C) ;
wire w;
NAND U1 ( A , B, w) ;
NAND U2 ( w, w, C) ;
endmodule
Continuous assignments
• Continuous assignments imply that whenever
any change on the RHS of the assignment
occurs, it is evaluated and assigned to the
LHS
• Continuous assignments always implement
combinational logic
• Continuous assignments drive wire variables

wire A;
assign A = (B|C)&D;
Continuous assignments
• Implicit continuous assignment
– Continuous assignment can be placed when
the net is declared
wire A = i 1 & i 2 ;

• Implicit net declaration (not recommended)


– If a signal name is used to the left of a continuous
assignment, a implicit net declaration will be
inferred
wire i 1 , i 2 ;
assign A = i 1 & i 2 ;
Example
A module NAND( A , B, C) ;
C i n p u t A, B;
output C;
B / / Continuous assignments
assign C= ~(A&B);
endmodule

module AND( A , B, C) ;
i n p u t A, B;
output C;
A
C wire w;
/ / 2 NAND i n s t a n t i a t i o n s
B
NAND U1 ( A , B, w) ;
NAND U2 ( w, w, C) ;
endmodule
Procedural blocks
• Each procedural block represent a
separate activity flow in Verilog
• Procedural blocks
– always blocks
• To model a block of activity that is repeated continuously
– i n i t i a l blocks simulation only
• To model a block of activity that is executed at the
beginning
• Multiple behavioral statements can be
grouped using keywords begin and end
Procedural assignments
• Procedural assignment changes the state of a
reg
• Used for both combinational and
sequential logic inference
• All procedural statements must be within always
(or i n i t a l ) block

reg A;
always @ (B o r C)
begin
A = ~(B & C);
end
Always block – Event control (@)
• Always blocks model an activity that is
repeated continuously
• @can control the execution
– posdege or negedge make sensitive to edge
– @*/ @(*), are sensitive to any signal that may be
read in the statement group
– Use “ , ” / o r for multiple signals
Always block – Event control (@)
module M1( i n p u t B, C, c l k , r s t , output reg X, Y, Z ) ;
/ / c o n t r o l l e d by any value change i n B o r C
always @ (B o r C) X = B & C;

/ / Co n t r o lle d by p o s i t i v e edge o f c l k
always @(posedge c l k ) Y= B &
C;

/ / Co n t r o lled by negative edge o f c l k o r r s t


always @(negedge c l k , negedge r s t )
i f ( ! r s t ) Z = B & C; else
Z = B & C;
endmodule
Example
D Q D Q

R G

module FFD ( i n p u t C l k , R, D, module LD (G, D, Q);


output reg Q); i n p u t G, D;
always @ (posedge Cl k) output Q;
begin reg Q;
i f (R) always @ (G o r D)
Q= 1 ' b 0 ; i f (G)
else Q = D;
Q= D; endmodule
end
endmodule
Blocking / Non-Blocking
assignment
Blocking assignment always @(posedge Clk)
begin
• (= operator) acts much like / / b l o c k i n g procedural assignment
in traditional programming C= C + 1 ;
languages A = C + 1;
end
• The whole statement is
done before control passes always @(posedge Clk)
on to the next statement. begin
//non -b l o cki n g procedural assignment
Non-blocking assignment D<= D + 1 ;
• (<= operator) Evaluates all the B <= D + 1 ;
end
right-hand sides for the
current time unit and assigns Example: During every clock
the left- hand sides at the end cycle
of the time unit. A is ahead of C
by 1 B is same
as D
Procedural blocks (summary)
• Blocks of code within a concurrent block
which are read (simulated, executed) in order
• Procedural blocks may contain:
– Blocking assignments
– Nonblocking assignments
– Procedural control statements ( i f , f o r , case)
– f unction , or task calls
– Event control ( ‘ @ ’ )
– Nested procedural blocks enclosed in begin …end
Outline
• Lexical elements
• Data type representation
• Structures and Hierarchy
• Operators
• Assignments
• Control statements
• Task and functions
Conditional statements (i f …else)
• The statement occurs if the expressions
controlling the if statement evaluates to true
– True: 1 or non-zero value
always @ (WRITE or STATUS)
– False: 0 or ambiguous (X) begin

• Explicit priority i f (!WRITE)


begin
out = oldv alue ;
i f (<expression>) end
/ / statement1 else i f (!STATUS)
else i f (<expression>) begin
/ / statement2 q = newstatus;
else end
/ / statement3 end
Conditional statements (case)
• case, casex, casez: case statements are used
for switching between multiple selections
– If there are multiple matches only the first is
evaluated
– Breaks automatically
• casez treats Z as don’t care
• casex treats Z and X as don’t care

case (<expression>)
<alternative 1> : <statement 1>;
<alternative 2> : <statement 2>;
default : <default statement>;
endcase
Conditional statements (case)
always @(s, a, b, c, d)
case (s)
2'b00: out = a; always @*
2'b01: out = b; casex (state)
2'b10: out = c; /*
2'b11: out = d; during comparison : 3'b01z,
endcase 3'b01x, 3b'011 ... match case
3'b01x
*/
always @* 3'b01x: fsm = 0 ;
casez (state) 3'b0xx: fsm = 1 ;
// 3'b11z, 3'b1zz,... Match 3'b1?? default: fsm = 1 ;
3'b1??: fsm = 0; endcase
3'b01?: fsm = 1;
endcase
Example
module mux(a, b , c , d , s , o u t ) ;
input [ 7 : 0 ] a , b , c , d ;
a input [ 1 : 0 ] s ;
b output [ 7 : 0 ] o u t ;
8-bit out reg [ 7 : 0 ] out;
c 4-to- / / used i n procedural statement
1 always @ ( s o r a o r b o r c o r d )
d multiplexe case ( s )
r 2 ' b 00 : out = a ;
2 ' b0 1 : out = b ;
2 ' b1 0 : out = c ;
s[0 s[1 2 ' b 11 : out = d ;
] ] endcase
endmodul e
Latches / Muxes (Comb logic)
• Assuming only level sensitivity on a always block:
– A variable or signal when is fully specified (it is
assigned under all possible conditions) a mux
or combinational logic.
– If a variable or signal is not fully specified a latch
will be inferred

always @ ( a , b , s e l ) always @ (DATA, GATE) always @ (DATA, GATE)


i f (sel==1’b 1) i f (GATE) begin
z=a; Q= DATA; Q= 0 ;
else i f (GATE) Q= DATA;
z=b; end

LATCH COMB LOGIC


MUX
Loop statements (for)
• Works the same ways as C
• Unary increment/decrement is not allowed

f o r (<loop var i n i t > ; <loop var r e e n t r y expr>; <loop var update>)


<statement>;

/ / Gener a l purpose lo op
interger i ;
always @*
f or ( i = 0 ; i < 7 ; i=i+1)
memory[i] = 0 ;
Loop statements (while)
• Loop execute until the expression is not true

always @*
wh i l e ( d e l a y)
/ / mu l t i p l e statement groups wi th begin-end
begin
ldlang = ol dl dl ang;
delay = delay – 1 ;
end
Loop statements (repeat)
• Repeat statement a specified number of times
• The number is evaluated only at the beginning

always @*
repeat(`BIT-WIDTH)
begin
i f ( a [ 0 ] ) out = b + o u t ;
a = a << 1 ;
end
Outline
• Lexical elements
• Data type representation
• Structures and Hierarchy
• Operators
• Assignments
• Control statements
• Task and functions
Tasks and Functions
Task and function serve the same purpose on
Verilog as subroutines do in C
Task: Functions:
• Declare with task and • Declare with f u n c t i o n
endtask and
• May have zero endfunction
arguments or more • Must have at lease one
arguments of type
input
input, output, i n o u t
• Do not return with a • Always return a single
value, can pass values value (cannot have
through output and output or i n o u t
i n o u t arguments arguments)
Tasks and Functions - example
module top (input a1, a2, output reg [1:0] b1, b2);
always @ (a1, a2)
begin
b1 = out (a1, a2); // function calling
out_task (a1, a2, b2); // task calling
end
function [1:0] out (input in1, in2); // Function Declaration
begin
if (in1) out = {in2,in1}; else out = {in1,in2};
end
endfunction
task out_task (input in1, in2, output [1:0] out); // Task Declaration
begin
if (in1) out = {in2,in1}; else out = {in1,in2};
end
endtask
endmodule
Task and Functions
• Functions are simpler
Function Task

Can call another function Can call another function or task

Can modify only one value Can modify multiple values

• Data Sharing
– Functions and task could be declare as automatic
– A static function retains the value of all it's
internal variables between calls. An
automatic function re-initializes them each call
Tasks and Functions in Verilog
Why Tasks and Functions?

• A designer is frequently required to implement the


same functionality at many places in a behavioral
design.
• This means that the commonly used parts should be
abstracted into routines and the routines must be
invoked instead of repeating the code.
• Most programming languages provide procedures or
subroutines to accomplish this.
• Verilog provides tasks and functions to break up large
behavioral designs into smaller pieces.
• Tasks and functions allow the designer to abstract
Verilog code that is used at many places in the design.
Differences Between Tasks and Functions
Functions Tasks
A function can enable another A task can enable other tasks and
function but not another task. functions.
Functions always execute in 0 Tasks may execute in non-zero
simulation Time. simulation Time.
Functions must not contain any delay, Tasks may contain delay, event, or
event, or timing control statements. timing control statements.
Functions must have at least one input Tasks may have zero or more
argument. They can have more than arguments of type input, output or
one Input. inout.
Functions always return a single value. Tasks do not return with a value but
They cannot have output or inout can pass multiple values through
arguments. output and inout arguments.
Where do use functions ad tasks?

Both tasks and functions must be defined in a module


and are local to the module.
Tasks are used for common Functions are used when
Verilog code that common Verilog code is
purely combinational,
contains delays, executes in zero simulation
timing, event constructs, or time and
 multiple output arguments.. provides exactly one output.
Functions are typically used
for conversions and commonly
used calculations.
What do Tasks and Functions can have?

• Tasks can have input, output, and inout ports;


• Functions can have input ports.
• In addition, they can have local variables, registers, time
variables, integers, real, or events.
• Tasks or functions cannot have wires.
• Tasks and functions contain behavioral statements only.
• Tasks and functions do not contain always or i n i t i a l
statements but are called from always blocks, i n i t i a l
blocks, or other tasks and functions
Tasks
• Tasks are declared with the keywords
task
:
endtask.
Tasks must be used if any one of the following conditions is
true for the procedure.
• There are delay, timing, or event control constructs in
the procedure.
• The procedure has zero or more than one output
arguments.
• The procedure has no input arguments.
Task Example 1
//Define a module called operation that contains the task bitwise-oper:
module operation;
parameter delay = 10;
reg [15:0] A, B;
reg [ 15 : 0 ] AB-AND, AB-OR, AB-XOR; //invoke the task bitwise-oper. provide 2 input arguments A, B
always @(A or B) //whenever A or B changes in value //Expect 3 output arguments AB-AND, AB-OR, AB-XOR
//The arguments must be specified in the same order as they
begin //appear in the task declaration.
bitwise-oper(AB-AND, AB-OR, AB-XOR, A, B);
end
...
//define task bitwise-oper
task bitwise-oper;
output [15:01 ab-and, ab-or, ab-xor; //outputs from the task
input [15:0] a, b; //inputs to the task
begin
#delay ab-and = a & b;
ab-or = a I b;
ab-xor = a ^ b;
end
endtask
endmodule
Task Example 2
//Define a module that contains the task asymmetric-sequence
module sequence;
reg clock;
Initial
init-sequence; //Invoke the task init-sequence
always
begin
asymmetric-sequence; //Invoke the task asymmetric-sequence
end
...
//Initialization sequence
task init-sequence;
begin
clock = 1'b0;
end
endtask
//define task to generate asymmetric sequence
//operate directly on the clock defined in the module.
task asymmetric-sequence;
begin
#l2 clock = 1'b0;
#5 clock = 1'b1;
#3 clock = 1'b0;
#l0 clock =1'b1;
end
endtask
endmodule
Functions
• Functions are declared with the keywords
function
:
endfunction.
• Functions are used if all of the following conditions
are true for the procedure.
There are no delay, timing, or event control
constructs in the procedure.
The procedure returns a single value.
There is at least one input argument.
Function Example 1
//Define a module that contains the function calcparity (Calculate Parity)
module parity;
reg [31:0] addr;
reg parity;
//Compute new parity whenever address value changes
always @ (addr )
begin
parity = calcparity(addr); //First invocation of calcparity
$display("Parity calculated = %b", calcparity(addr) ) ;
end
//define the parity calculation function
function calcparity;
input [31: 0] address;
begin
//set the output value appropriately. Use the implicit internal register calcparity.
calcparity = ^address; //Return the xor of all address bits.
end
endfunction
endmodule
Function Example 2
// define a factorial with recursive function
module top;
//define the function
function automatic integer factorial;
input [31:0] oper;
integer i;
begin
if (operand>=2)
factorial =factorial(oper-1)* oper; // recursive call
else
factorial=1;
end
endfunction

//call the function


integer result
initial
begin
result= factorial (4); // call the factorial of 4
$display (“factorial of 4 is %d”, result); //displays 24
end
endmodule
References
• Verilog HDL – Samir Palnitkar
• The Fundamentals of Efficient Synthesizable
Finite State Machine Design using NC-
Verilog and Build Gates – Clifford E.
Cummings
• Verilog: Frequently Asked Questions, Springer
Science

You might also like