0% found this document useful (0 votes)
8 views143 pages

Introduction to Basic Verilog Concepts

Uploaded by

Arie Gutkin
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views143 pages

Introduction to Basic Verilog Concepts

Uploaded by

Arie Gutkin
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Basic Verilog

Elazar Sarel

Based on the Basic Level Verilog course written by


Heela Shemen, Itai Yarom and Dan Jacobi

Last update Sep 2003


Intel Confidential

Basic Icons
The non-synthesizable person –
announces that a feature is not
synthesizable.

Basic Verilog
Intel Confidential

Agenda
 Introduction
 Lexical Rules
 Module Structure
 Data Types
 Structural Modeling
 Behavioral Modeling, Statements
 Hardware Elements
 Compiler Directives & System tasks
 State Machines
 Simulation
Basic Verilog
Intel Confidential

Goals
 Get familiar with the Verilog language.
 Gain basic knowledge of different
coding styles (structural and behavioral)
and abstraction levels
 Be able to write a simple RTL model in
Verilog
 Verilog coding for simulation (delays,IO,
File managing etc…)
 Invoking Verilog Simulator

Basic Verilog
Intel Confidential

In this course we will not learn


 Verilog advanced features
– Parallel block
– Primitives
– Tasks/Functions

Basic Verilog
Intel Confidential

References and Literature


 Verilog IEEE standards
– IEEE 1364-1995 – Verilog 95
– IEEE 1364-2001 – Verilog 2001
– IEEE 1364.1 – Verilog synthesizable subset
• All IEEE standards can be found under the LVT/RTL Design web
page :
[Link]
 Manual
– [Link]
 “Verilog HDL A guide to Digital Design and Synthesis”, by Samir
Palnitkar
 “Verilog HDL Quick Reference Guide” – based on the
Verilog 2001 standard, by Stuart Sutherland, Sutherland HDL.
Basic Verilog
Intel Confidential

What is HDL
Hardware Description Language
A language used to describe digital
hardware elements
Various levels of abstraction:

– Behavioral: flow control, arithmetic operators,
High Small
complex delays
– Register Transfer Level (RTL): description of the
Abst. Level

registers and the signal changes between

Code Size
registers
– Gate level: combinatorial logic gates.
– Switch level: layout description of the wires,
Low resistors and transistors (CMOS,PMOS etc…). Large
not described in this course.
If it is easier to write RTL in the Behavioral abstraction
level, why should we
Basic use lower abstraction levels ?
Verilog
Intel Confidential

What is Verilog ?
 It is a Hierarchical Hardware Description
Language
 It supports all levels of abstraction
 Verilog also supports constructs
understood by simulation tools (Non-
synthesizable high level behavioral
code).

Basic Verilog
Intel Confidential

Verilog Vs. VHDL


 Verilog
–  Easier to understand and use
–  Lacks constructs for system level spec
 VHDL
–  more flexible
–  better suited for complex designs
–  more complex, difficult to learn and use

Basic Verilog
Intel Confidential

A Short Example
// Interface
8
module comparator
a (a, b, a_bigger_b);
a_bigger_b
8 Comparator input [7:0] a, b;
b output a_bigger_b;

// Internal Signals
reg a_bigger_b;

// logic
always @(a or b)
begin
if (a > b)
a_bigger_b = 1;
else
a_bigger_b = 0;
end // always @(a or b)
Basic Verilog
endmodule // comparator
Intel Confidential

Verilog History
 1984 – Gateway company started to develop the
Verilog language.
 1985 – First simulators for Verilog were available.
 1990 – Cadence bought Gateway, and started to
push the Verilog language.
Verilog
 1990 – the OVI (Open Verilog International) 95
committee has been formed.
 1995 –Verilog (+ PLI) has been accepted as an Verilog
IEEE’s standard (IEEE.1364-1995). 2001
 2001 – A new Verilog (+ PLI) IEEE standard with SystemVerilog
extended constructs (IEEE.1364-2001). AKA Verilog 2000
 Future – System-Verilog a new language based on
Verilog with high level modeling features (structs,
interfaces …)

Basic Verilog
Intel Confidential

RTL Languages in Intel


 CPU world
– EPD (Servers) – using iHDL
– DPG (Desktops)- New Projects using
Verilog and System Verilog
– MPG (Mobile) - using iHDL (Currently not
using Verilog)
 Chip-Sets : Verilog 95 / VHDL
 ICG: Verilog 95 / VHDL

Basic Verilog
Intel Confidential

Design Flow
Verilog model

Functional Stage
RTL Simulation

Synthesis
Libraries
Layout Implementation Stage

Gate Level Simulation

Basic Verilog
Intel Confidential

Lexical Rules - Content


 Lexical conventions
 Comments
 Spaces
 Numbers specification
 Strings
 Identifiers and keywords
 Escaped identifiers
 Summary

Basic Verilog
Intel Confidential

Lexical Conventions
 White space consist of the following:
– Blank spaces (\b). - Spaces (‘ ‘)
– Tabs (\t). - New lines (\n)
 Verilog ignores white spaces, except
when they separate words
 Every Verilog statement ends with
semicolon (;)
 Verilog is case sensitive

Basic Verilog
Intel Confidential

Comments
 In Verilog there are line comments and
multiple line comments (like in C++)
a = b && c; //this is a line comment
Line comment
/* This is a multiple line
comment */
Multiple lines
/* This is /* an illegal */ comment */ comments

// This is /* an illegal
comment */
Basic Verilog
Intel Confidential

Numbers Specification
 Sized numbers are written in the following
specification:
<size>’<base format (b,o,d,h)><number>
Be aware : use right ‘
 Unsized numbers are written without the
<size> parameter, using the default size of 32
bits.
– Unsized numbers without the <base format> are decimal ones
 Zero padding if the size is greater than the number of
bits specified
– Example : 8’b0 is similar to 8’b00000000

Basic Verilog
Intel Confidential

Numbers Example
5’b10101
5 bit binary number 10101
Sized numbers

16 bit hexadecimal number


16’ha3ce
16 bit decimal number
16’d255
6 bit octal number
6’o34 32 bits
…0 0 0 0 0 1 0 1 0 1
’b10101 32 bit binary number
Unsized

32 bit hexadecimal number


’ha3ce
32 bit decimal number
255
Basic Verilog
Intel Confidential

Operators
 Operators are of three types unary,
binary and ternary

~ is an unary operator. b is the operand

a = ~b; && is a binary operator. b and c are the


operands
a = b && c;
?: is a ternary operator. b,c and d are
a = b ? c : d; the operands

Basic Verilog
Intel Confidential
Arithmetic + Add B/U

1
-
*
Subtract
Multiply
B/U
B
Operators
1
1
/
%
Divide
Modulus
Power
B
B Table
2 ** B
Reduction & Reduction and U
Logical ! Logical negation U
~& Reduction nand U
&& Logical and B
| Reduction or U
|| Logical or B
Relational > Greater than B ~| Reduction nor U

< Less than B ^ Reduction xor U


>= Greater or equal B ^~ ,~^ Reduction xnor U
<= Less or Equal B
Shift >> Shift right B
Equality == Equal B
<< Shift left B
!= Not equal B
3 >>> Arithmetic shift R B
=== Case equality B
3 !=== Case inequality B <<< Arithmetic shift L B
Bit-wise ~ Bit-wise not U Concatenation {,} Concatenation B
& Bit-wise and B
{{}} Replication B
| Bit-wise or B
Conditional ?: Conditional T
^ Bit-wise xor B
Sensitivity list or Event or B
^~ ,~^ Bit-wise xnor B

1. Synthesizable only if op2 is power of 2


2. Synthesizable only if op1 is 2 Basic Verilog
3. Non synthesizable
Intel Confidential

Bitwise and Reduction


Operators
reg [4:0] a,b;
reg c,d;
… Bit-wise operator:
b = 5’b10110;
‘a’ will have the value 5’b01001
a = ~b;
Reduction operators:

c = &b; ‘c’ will have the value 1’b0


‘d’ will have the value 1’b1
d = |b;

Basic Verilog
Intel Confidential

Logical Operators
If result = 0  false (logical 0)
If result  0  true (logical 1)
reg [3:0] i,j,k;
reg a,b,c;

i = 4’b0101;
j = 4’hf;
k = 4’h0;

a = i && j; // “true and true“  true  1

b = i || k; // “true or false“  true  1

Verilog
c = !i; // “not true”Basic false  0
Intel Confidential

Concatenation
 The concatenation operator provides
mechanism to append multiple
operands
 The operands must be sized
 The operands can be:
– scalar nets or variables, vector nets or
registers, bit-select, part-select or sized
constants

Basic Verilog
Intel Confidential

Concatenation (continue)
 Syntax:
– { operand [, operand]* }

a=1’b1; b=2’b00; c=2’b10;


d=3’b110;
Y is 4’b0010
y = { b , c };
Y is 11’b10010110001
y = { a,b,c,d, 3’b001 };
Y is 3’b101
y = { a, c[0], d[1]};

Basic Verilog
Intel Confidential

Replication Concatenation
 Replication operator enables us to replicate
an expression
 The operands must be sized
 Syntax:
– { number { operand } }

A=1’b1; B=2’b00; C=2’b10;


Y = { 4 { A } }; Y is 4’b1111

Y = { 4{A} , 2{B} }; Y is 8’b11110000

Y = { 4{A} , 2{B} , C }; Y is 10’b1111000010


Basic Verilog
Intel Confidential

Strings
 A string is a sequence of characters that
are enclosed by double quotes.
 Strings must be on one line.
Examples of strings
Strings are
“This is a string”
“a = x && y;”
not truly
synthesizable

Basic Verilog
Intel Confidential

Identifiers and Keywords


 Keywords are special identifiers
reserved to define language constructs
 Keywords are all in lowercase
 Identifiers are names given to objects
so that they can be referenced in a
design
 Identifiers syntax is: [a-zA-Z_$0-9]*
» The identifier name shall start with an under
score ‘_’ or an alpha
reg signal; reg and input are keywords, and
input clock; signal and clock are identifiers.
Basic Verilog
Intel Confidential
Keywords Table
always end ifnone not release tranif0
and endcase incdir notif0 repeat tranif1
assign endconfig include notif1 rnmos tri
automatic endfunction initial or rpmos tri0
begin endgenerate inout output rtran tri1
buf endmodule input parameter rtranif0 triand
bufif0 endprimitive instance pmos rtranif1 trior
bufif1 endspecify integer posedge scalared trireg
case endtable join primitive showcancelled unsigned
casex endtask large pull0 signed use
casez event liblist pull1 small vectored
cell for library pulldown specify wait
cmos force localparam pullup specparam wand
config forever macromodule pulsestyle_on strong0 weak0
deassign fork medium event strong1 weak1
default function module pulsestyle_on supply0 while
defparam generate nand detect supply1 wire
design genvar negedge rcmos table wor
disable highz0 nmos real task xnor
edge highz1 nor realtime time xor
else if noshowcancelled reg tran

Basic Verilog
Intel Confidential

Escaped Identifiers
 Escaped identifiers begin with the
backslash (\) character and end with
white space.
 All characters between the backslash
and the white space are acceptable.

\a+b-c
\**my_name**
\address[10]

Basic Verilog
Intel Confidential

String Format Specification

 %d – display the variable in decimal


 %b – display the variable in binary
 %s – display a string
 %h – display the variable in hex
 %c – display ASCII character
 %m – display hierarchical name
 %o – display the variable in octal
 %t – display in time format

Basic Verilog
Intel Confidential

Summary
 Lexical convention of operations,
comments, white space, numbers,
strings and identifiers were discussed.
 In the next slides we’ll discuss how to
use those elements in Verilog

Basic Verilog
Intel Confidential

A Short Quiz #1
 Write the following numbers :
– 7 in a hexadecimal format (3 bits)
– 9 in a binary format (4 bits)

 What are the Decimal values of the following


expressions :
– 8’b11110000 ^ 8’h0f
– 4’d8 && 4’b1010
– 7
– 1’h8

Basic Verilog
Intel Confidential

Modules
 Modules are Verilog design blocks
 Modules allow you to create unique
objects:
– Hardware cells
– Hardware blocks with instantiations of
multiple cells
– Test benches for simulation

Basic Verilog
Intel Confidential

Module structure
 Definition
– Module name
– Interface
– Ports declaration
– Parameters declaration
 Body
– Internal signals declaration
– Assign statements
– Always blocks
– Initial blocks
– Instantiations
Basic Verilog
Intel Confidential

Module structure - example


The
// Interface interface
module myflop (d,clk,q);
Ports
input d, clk;
declaration
output q;
wire d, clk; Parameter
reg q; declaration
Module
parameter ZERO = 0;
definition
// Body
wire ff_out, buf_out; Internal signal
dff inst1 (d, clk, ff_out); declaration
assign buf_out = d; Instantiation
always @ (ff_out or buf_out)
Assign statement
q = ff_out | buf_out;
endmodule Always block
Basic Verilog
Intel Confidential

Module Definition
 Module name module mymodule(…)



endmodule
 End of module

Basic Verilog
Intel Confidential

Interface - Ports
 Ports are the interface by which a module
communicates with the outside world
 Ports are used to connect other modules
 3 kinds of port directions:
– input – driven by external module
– output – driven by the current module
– inout – can be used in both modes
 Input and inout ports must be nets
 Output ports that hold their values must be
“reg”s
 Explanation of net and reg will follow
Basic Verilog
Intel Confidential

Port Declaration Components


module mymodule (a,b)
 Port List
input a;
 Port Direction
output b;
 Port Type
wire a; // may be omitted

reg b;


endmodule

Basic Verilog
Intel Confidential

Port declaration - example


Verilog 95 style Verilog 2001 styles
module myflop (d,clk,q,bus); module myflop (
input d, clk; input wire d, clk,
output [1:0] q; output reg [1:0] q,
inout bus; inout bus);
wire d, clk, bus; endmodule
reg [1:0] q;
endmodule OR
module myflop
(d,clk,q,bus);
input wire d, clk;
output reg [1:0] q;
inout bus;
endmodule
Basic Verilog
Intel Confidential

Signal values
 Each bit of a signal can contain the
following values:
–0
–1
– Z : disconnected net (high impedance)
– X : unknown / contention / propagation or
an unknown/disconnected value

Basic Verilog
Intel Confidential

Signal values – example

5’b1x10z 5-bit binary number

16’ha3xe 16-bit hexadecimal number

6’o3x 6-bit octal number

32’bx 32-bit bits of unknown number

Basic Verilog
Intel Confidential

Advanced Signals Values


 Negative numbers can be specified by putting
the minus sign before the <size>.
 The ‘_’ is ignored in a number, and it can be
used in order to increase readability.
 The ‘?’ is alternative for ‘z’ in case selectors.
-8’d5 8-bits of the –5 number in
8’d-5 2’s complement format
Illegal
8’b1101_0011 Use ‘_’ for readability
8’b_1101_0011

5’b101?? Equal to 5’b101zz


Basic Verilog
Intel Confidential

Signal types
 2 Signal types:
– Net, usually Wire
» do not store value
» Value is valid for as long as it is being driven
» Signal will have the Z value when not driven
– Variable, usually Reg
» The last value that was driven is stored until new
value is assigned
» The signal will have the X value if never driven
 Reg is not automatically a register

Basic Verilog
Intel Confidential

Net – Reg Interconnect


module

module module
0
0 1 5
1 5 a1 Vcc1 b1
a1 Vcc1 b1 2 6
2 6 a2 b2
a2 b2 3 7
3 7 a3 b3
a3 b3 4 8
4 8 a4 GND b4
a4 GND b4
0
0

always SET
assign
D Q

CLR
Q

always

reg net (wire)

Basic Verilog
Intel Confidential

Net types
 wire
– A simple net
– The default signal type
 tri
– used for nets with multiple sources
(busses)
 tri0/tri1
– has value of 0/1 if not driven
(pulldown/pullup)

Basic Verilog
Intel Confidential

Variable types
 reg
– The basic register type
 integer
– 2s-complement signed number
– 32 bits long

Basic Verilog
Intel Confidential

Variable types (cont.)


 time
time sim_time;
– An unsigned reg initial
sim_time = $time;
– At least 64 bits long
– Used to store simulation time data using
the system function $time:
 Real Time and real
types are not
– Used to store real types synthesizable

Basic Verilog
Intel Confidential

Vectors
 A vector (packed vector) is a multi-bit net or
reg
 The range is determined using square
brackets:
<signal type> [MSB:LSB] <signal name>
Most significant Least significant
bit index bit index

 The width will be: |MSB-LSB|+1


Basic Verilog
Intel Confidential

Vectors - example
module myencoder (in, out);
1 bit length input in;
input wire in;
3 bit length output [2:0] out;
output reg [2:0] out;

8 bit length reg [7:0] internal;


internal signal …
internal[0] = in;
bit 0 select
out[2:0] = internal[3:1];

3 bits range endmodule
select
Basic Verilog
Intel Confidential

Arrays / Memories
 Arrays (packed vectors) can be modeled as
an array of variables
 Each element of an array is called a word
 A word can be one or more bits
 Only single words can be approached from a
memory/array element. (sub-arrays can not
be accessed)
 An Array can have one dimension in Verilog
95 and an unlimited (1024) number of
dimensions in Verilog 2001

Basic Verilog
Intel Confidential

Arrays - example

8 words of // a vector not a memory


1 bit length reg[31:0] myreg;
each // a small memory
reg mem1 [0:7];
1024 words // larger memory
of 32 length reg [31:0] mem2 [1023:0];
each …
myreg[31:0] = mem2[333][31:0];
Reading a mem2[2:0][31:0]= mem2[5:3][31:0];
single word …

Illegal : trying to access a sub array


Basic Verilog
Intel Confidential

Selects
 Vector Bit select: Selects one bit of a vector
– Syntax: <vector_name>[<bit_num>]
 Vector Part select (slice) : Select a part of a vector
– Syntax: <vector_name>[<bit_num1>:<bit_num2>]
 Word Select : selects one word of an array
– Syntax: <array name> [<dim1 num>][<dim2 num>]…
reg [30:0] vec;
reg [200:0] arr1 [100:10];
8 ‘th bit of vec
wire res1 = vec[7];
Bits 16-4 of vec
wire [12:0] res2 = vec[16:4];
Word 20 of arr1 wire [200:0] res3 = arr1[20];
Basic Verilog
Intel Confidential

Parameters
 Parameters are constants
 Their value are determined at compile
time // state machine possible states
parameter
STATE1 = 1,
Parameters
STATE2 = 2,
declaration
STATE3 = 3;
// myreg width
parameter WIDTH 256;
reg [WIDTH-1:0] myreg;

Basic Verilog
Intel Confidential

A Short Quiz #2
 A black box model is a module that has no logic (only
an interface) it is used to represent the full module
before it’s logic is written (It is instantiated instead of
the real model)
 Write a module interface representing the following 4
bit clocked adder.
– Module name : a4_bit_clocked_adder
– Interface signals
» in1_or_res : a 4 bit sig. representing the first operand or the addition
result.
» In2 : a 4 bit signal representing the second operand .
» carry_out : a 1 bit signal representing the generated carry out.
» clk : a 1 bit signal representing the system clock.

Basic Verilog
Intel Confidential

A Short Quiz #2 (cont.)


 What is the value of the wires in the
following cases :
– wire [5:0] a;
– reg c; c = ___
– wire [8:0] b [1:0]
– assign a = {3{2’b11}}; a = ___
– assign b[1] = {a,2’b10,c}; b[1] = ___
– assign b[0] = b[1]; b[0] = ___

Basic Verilog
Intel Confidential

Hierarchies
 A module can contain other modules

TOP
DSP
FLOP
MUX

TOP, FLOP, DSP and MUX are modules


in different hierarchy levels
Basic Verilog
Intel Confidential

Instances
 Hierarchies are created through
instantiations
 Instance is the object created inside a
module
 Instances are modules
 Syntax :
– <module_name> [#(<parameter_values>)]
<instance_name>
– [(<list_of_port_arguments>)];

Basic Verilog
Intel Confidential

Instantiations – example1
module flop (clk, d, q);
input clk, d;
output q;

Module name Instance name Port arguments

flop myflop_inst1 (clk, ff1_in, ff1_out);


flop myflop_inst2 (clk, ff1_out, ff2_out);

What is implemented here ?


Basic Verilog
Intel Confidential

Instantiations – example2
module buffer (in, out);
parameter WIDTH = 3; // default
input [WIDTH-1 : 0] in;
output [WIDTH-1 : 0] out;

Parameter Values
Module name Instance name Port arguments

buffer #(3) my_buf (in, buf_out);

Basic Verilog
Intel Confidential

Parameter overloading -
Example
 Parameters in design can be changed when
instantiating them.
 The instantiated modules parameters can be
assigned by order list. In Verilog 2001 they
also can be assigned by name.
 An unassigned parameter keeps its default
value.
 Assigning instantiated modules parameters is
a very useful way to reuse code and work
with libraries.

Basic Verilog
Intel Confidential

Parameter overloading
module myflop (d,clk,q,reset);
parameter WIDTH = 256;
parameter RESET_VALUE = 0 Changing WIDTH to be 8
input clk, reset; Reset value is 0
input [WIDTH-1:0] d;
output [WIDTH-1:0] q;
… module mytop;
endmodule wire [7:0] indat8, outdat8;
myflop #(8,0)inst1(indat8,clk,outdat8,reset);
or
myflop #(.RESET_VALUE(0),.WIDTH(8))inst1(…);
or
myflop #(8) inst1(…);
or
myflop #(.WIDTH(8)) inst1(…);
endmodule Basic Verilog
Intel Confidential

Hierarchical names
 Unique name for each object:

TOP
DSP
inst1
MUX TOP.inst1
inst2
TOP.inst1.inst2

Basic Verilog
Intel Confidential

Connectivity
 Instances are connected to other
modules through their ports

TOP
in out
FLOP
clk

Basic Verilog
Intel Confidential

Connecting by order
module flop (d,clk,q);

endmodule

module mytop;

wire ff1_in, ff1_out, clk;

flop inst1 (ff1_in, clk, ff1_out);

endmodule

Connected Connected Connected


to port D Basic Verilog
to port Clk to port Q
Intel Confidential

Connecting by name
module myflop (d,clk,q);

endmodule

module mytop;

wire ff1_in, ff1_out, clk; •Better


•Avoid bugs !
myflop myflop_inst1 (.clk(clk),
.d(ff1_in), .q(ff1_out));

endmodule

Port name Signal name


Basic Verilog
Intel Confidential

Connectivity Signal Type rules


 Modules inputs are assumed to be steady

net input
or reg net
output net
inout net or reg
net net

Basic Verilog
Intel Confidential

A Short Quiz #3
Write the Verilog code for the module “TOP”

TOP
A

A ALU
B ADD O_1
A
B
FLOP
A Q OUT
B
MUX O RES D
ACT A B
SUB O_2 SEL
SEL B CLK
CLK

Basic Verilog
Intel Confidential

Behavioral Modeling
 Continuous Assignments
 Block Statements (always/initial)
 Blocking / Non-blocking Assignment
 Delays, Intra delays

Basic Verilog
Intel Confidential

Continuous Assignments
 To use for simple combinatorial logics that
drive nets.
 Syntax:
– assign <wire_signal> = <expression>;
 The value of the wire_signal is evaluated
each time that the value of one of the element
in the right side expression is changed.
Continuous
wire a, b, w; assignment
assign w = a & b;

Basic Verilog
Intel Confidential

Block Statements
 Block Statements are used to group a
number of statements
 Block statement begins with the keyword
begin and ends with the keyword end
 Block statements might be named
 Named block may use local signals
 Syntax :
begin [: <block name>]
<Statements>*;
end
Basic Verilog
Intel Confidential

Block Statements
reg x,y;
always
begin : DJ_block Block’s name
parameter a = 1;
reg b;
b = a;
end // DJ_block
always
begin
parameter e = 1; Illegal to declare a
x = y; signal in an
end unnamed block

Basic Verilog
Intel Confidential

Always Statements / Processes


 Always statements are used
– for sequential and combinatorial elements.
– to model a block of activities that is repeated
continuously.
– To drive variables, usually regs.
 Always statement can have a sensitivity list, and will
be evaluate once one of the list members had
changed his values. List members can be signal
names or signal edges. Non edged signals in
 Sensitivity list usage: sensitivity lists are
– @ (<signal> [or|, <signal>]* ) ignored in synthesis
– @ (<edge> <signal> [or|, <edge> <signal>]*)
- Where <edge> can be posedge or negedge.
Basic Verilog
Intel Confidential

Always Statements / Processes

 Syntax:
– Always [@ (<sensitivity_list>) ]
reg_signal = expression;
wire in1, in2;
reg out_a, out_b, out_c, out_d;
always @ (in1 or in2) Combinatorial
out_a = in1 | in2; Element
always @ (posedge clk)
out_b = out_a; Sequential
always begin Element
out_c = out_b;
out_d = ~ out_b; Always to be
end;
Basic Verilog evaluated
Intel Confidential

Initial Statements
 All initial statements are executed only once in time
0 of the simulation
 All the initial statements are executed concurrently
 Inside the initial statement, statements are executed
sequentially
 Syntax: initial <statement>;
wire in1, in2; Initial statements
reg out_a,out_b,out_c,out_d; aren’t
initial begin synthesizable
out_a = in1 | in2;
out_b = out_a;
end
initial
Basic Verilog
out_c = 1;
Intel Confidential

Blocking / Non-blocking
Assignment
 Assignments can appear in always / initial
statements, functions and tasks. They can not
appear in the module’s global space.
 Blocking assignments are executed in the order they
are specified (in a block). They are executed
sequentially
 Non-blocking assignments are executed concurrently
 Syntax:
– Blocking : operand = expression;
– Non-blocking : operand <= expression;
Basic Verilog
Intel Confidential

Blocking/Non-Blocking Assignments
reg b,c;
c
Blocking

always @(posedge clk) a D Q


begin flop
b = a;
clk
c = b;
end

reg b,c; b
Non-Blocking

always @(posedge clk) a D Q D Q c


begin
flop flop
b <= a;
c <= b;
end
clk clk
Order important ?
Basic Verilog
Intel Confidential

Delays
 Delays control the time between the change
in the right hand of the statement and when
the value is assigned to the left-hand.
Delays are not
synthesizable

 Syntax:
– #<number> <statement>

wire w1;
w1, w2, and w3 act the
assign #10 w1 = in1 && in2;
same and get the value
wire #10 w2 = in1 && in2; of the expression after
wire #10 w3; delay of 10.
assign w3 = in1 && in2;
Basic Verilog
Intel Confidential

Delays in Blocks
 The delay represents delta-time from the
previous event
reg a, b;
reg [1:0] c, d;
initial begin
a = 1’b1; // time = 0
#5 b = 1’b0; // time = 5
#10 c = {a,b}; // time = 15 (5+10)
#20 d = {b,a}; // time = 35 (15+20)
end

Basic Verilog
Intel Confidential

Delays in Blocks (cont’d)


 Reset and clock generation in Testbench
reg clk, rst_n;

// reset generation
initial begin
rst_n = 1’b0; // active low
#100 rst_n = 1’b1;
end

// clock generation
initial clk = 1’b0;
always #20 clk = !clk; // 40 ns period clock

Basic Verilog
Intel Confidential

Intra-Assignment Delay
 The expression on the right hand side is
evaluated immediately …
 … but left hand side is updated after the
delay
 Equivalent to buffer/line delay
 Syntax: <reg> = #<number> <expression>

// inverter with 10 ns delay


initial b = #10 ~a;

Basic Verilog
Intel Confidential

Statements

 “If”, “case”, “for” and “while” statements


 Procedural Continuous Assignment

Basic Verilog
Intel Confidential

If Statement
 If statements are used for making decision based
on certain conditions
 If condition yields on ‘x’ then the “if” is not taken
 Syntax:
– if (<condition expression>)
<statement>;
[else <statement>;]
– Needs “begin-end” if more than one statement
 Use else statements instead of different “if”
statements if possible

Basic Verilog
Intel Confidential

If Statements Example
if (enable)
out = in;
If statement
if (a > b)
smaller = b;
else
smaller = a;
If-else statement
if (state == 0)
y = a + b;
else if (state == 1)
y = a – b;
else If-else-if statement
y = a * b;
Basic Verilog
Intel Confidential

Case Statement
 The first alternative that matches the
expression is executed (‘x’ must match an ‘x’)
 The case may have a default statement. If
none of the alternatives match, then this
statement is executed
 Casez treats all z and ? values as don’t cares
 Casex treats all z, x and ? values as don’t
cares

Basic Verilog
Intel Confidential

Case Statements Example


Syntax:
case (<expression>)
[<alternative>: <statement>;]*
[default: <default statement>;]
endcase
casex statement of
case statement of ALU one-hot state machine.
state machine.
casex ({s0,s1,s2,s3})
4’b1xxx: state=0;
case (state) 4’bx1xx: state=1;
2’b00: y = a + b; 4’bxx1x: state=2;
2’b10: y = a – b; 4’bxxx1: state=3;
default: y = a * b; default: state=4;
endcase endcase
Basic Verilog
Intel Confidential

If Vs. Case
 If you have a long sequential nested if-else
chain, a case might be more appropriate than
a nested if
– when there is no need for a priority on any of the
case options

if (state == 2’b00) case (state)


y = a + b; 2’b00: y = a + b;
else if (state == 2’b01) 2’b01 : y = a – b;
y = a – b; default: y = a * b;
else endcase
y = a * b;

Basic Verilog
Intel Confidential

For Statement
 For loops are used for repeating logic.
 Syntax:
– for ( <init>; <condition>; <addition>)
<statement>;

integer a;
Assigning zero for each
reg [7:0] arr [13:0];
address of the arr
for (a=0; a<14; a=a+1)
arr[a] = {8{1’b0}};

Basic Verilog
Intel Confidential

While Statement
 Perform the statement as long that the
condition expression is true.
 Syntax:
– while (<condition expression>)
<statement>; While statements
are not
integer a = 0; synthesizable
reg [7:0] arr [13:0];
while (a<14)
begin
arr[a] = {8{1’b0}}; Assigning zero for
a = a + 1;
end each address of the arr
Basic Verilog
Intel Confidential

Procedural Continuous
Assignment
 Uses to perform an assignment in a
block (initial/always)
 Useful to force a value to reg/net in
simulation
– assign/deassign
– force/release
 “Force” overrides “assign”
Not synthesizable

Basic Verilog
Intel Confidential

assign/deassign statements
 assign: Assigns value to a reg
 deassign: retrieve original behavior
 Syntax
– assign <regname> = <expression> ;
– deassign <regname> ;

reg out;
always @(ctrl)
begin
if (ctrl == 1)
assign out = 1’b1;
else
deassign out;
end Basic Verilog
Intel Confidential

force/release statements
 force: Assigns value to a reg/net
 release: retrieve original behavior
 Syntax
– force <regname> = <expression> ;
– release <regname> ;

reg c;
initial
begin
# 100 force c = 1’b1;
# 100 release c;
end

Basic Verilog
Intel Confidential

Hardware Elements
 Flip-Flop
 Mux 2 to 1
 Adder
 Subtractor
 Counter
 4-bit Shift Register
 Tri-state bus

Basic Verilog
Intel Confidential

Flip-Flop
with asynchronous reset
The asynchronous signals should be in the
sensitivity list with the proper edge expression.
reg data_out;
always @(posedge clk or negedge rst)
if (!rst)
data_out <= 1’b0;
else if (en)
data_out <= data_in; rst_1

data_in data_out
D R O
Non-blocking flop
en
assignments are E
used
Basic Verilog clk
Intel Confidential

Mux 2 to 1
using reg
reg [5:0] data_out;
Blocking
always @(sel or data_in1 or data_in2)
if (sel) assignments are
data_out[5:0] = data_in1[5:0]; used
else
data_out[5:0] = data_in2[5:0];

data_in1[5:0] 6
1
data_out[5:0] 6
data_in2[5:0] 6 0
sel

Basic Verilog
Intel Confidential

Mux 2 to 1
using net
wire [5:0] data_out;

assign data_out = (sel == 1) ? data_in1 : data_in2;

data_in1[5:0] 6
1
data_out[5:0] 6
data_in2[5:0] 6 0
sel

Basic Verilog
Intel Confidential

Adder
reg [8:0] sum;
always @(in1[7:0] or in2[7:0])
sum[8:0] = {1’b0,in1[7:0]} + {1’b0,in2[7:0]};

in1[7:0] 8

sum[8:0] 9
+
in2[7:0] 8

(a+b)+(c+d)
(a+(b+(c+d)))

+
Use () wisely
+

+
+
+

+
Basic Verilog
Intel Confidential

Substractor
reg [7:0] sub;
always @(in1[7:0] or in2[7:0])
sub[7:0] = in1[7:0] - in2[7:0];

in1[7:0] 8

sub[7:0] 8
-
in2[7:0] 8

Basic Verilog
Intel Confidential

Counter
reg [3:0] count;
Synchronous reset
always @(posedge clk)
(not present in
if (reset)
sensitivity list)
count[3:0] <= 4’b0;
else if (en)
count[3:0] <= count[3:0] + 1;

count[3:0] 4 count[3:0]
+1 D O
en 4 flops
reset ER
clk
Basic Verilog
Intel Confidential

4-bit Shift Register


with asynchronous reset
reg [3:0] shift_reg;
always @(posedge clk or negedge rst)
if (!rst)
shift_reg <= 4’b0;
else if (shift)
shift_reg[3:0] <= { shift_reg[2:0], data_in };
// no need to use FOR loop !
assign data_out = shift_reg[3];

rst
data_in data_out
D R O

shift shift_reg
E

Basic Verilog clk


Intel Confidential

Tri-State Bus
wire bus[3:0];
assign bus[3:0] = en1 ? {in1[1:0],in2[1:0]} : 4’bzzzz;
assign bus[3:0] = en2 ? 4’b0000 : {4{1’bz}};
assign bus[3:0] = en3 ? in3[3:0] : 4’bzzzz;

in1[1:0] in2[1:0]

en1

bus[3:0]
4

en2 en3

4 Basic Verilog
4 in3[3:0]
4’h0
Intel Confidential

Compiler Directives
define, include, undef, ifdef, else, endif …
 The `undef \ `define is used to un\define text macros.
» Syntax: `define <macro_name>[(<arguments>)] <macro_example>
» `undef <macro_name>
– Usage: `<macro_name>[(arguments)]
 The `ifdef `ifndef `else `elsif `endif are used to control which
parts of text will be compiled
» Syntax: `ifdef <macro_name>
» …
» `else
» …
» `endif
 The `include is used to include a content of a Verilog source
file.
» Syntax: `include “<Verilog file>”
 In Verilog 2001 two new directives : ifndef, elsif
 Be aware : use left ‘
Basic Verilog
Intel Confidential

Compiler Directives Example


Defining the WORD_UPPER_BOUND macro
[Link]:
`define WORD_UPPER_BOUND(size) size - 1
`define WORD_REG reg [`WORD_UPPER_BOUND(2):0]

Using the macro WORD_UPPER_BOUND to define the macro WORD_REG.


`include “[Link]” Including the file [Link]
`WORD_REG a; `define ARITHMETIC_LEVEL
`ifdef ARITHMETIC_LEVEL
a = b + c;
reg [1:0] a; `else
a = b + c; a[0] = b ^ c; a[1] = b & c;
`endif
Basic Verilog
Intel Confidential

System Tasks/functions
 System tasks are used for certain
routine procedures.
 Syntax:
– $<system task name (keyword)>
 Some examples are added
– More information can be Most system
tasks are not
found in the Verilog HDL synthesizable
Language Reference Manual.

Basic Verilog
Intel Confidential

System Tasks/Functions List$sync$and$array


$async$and$plane $dist_poisson $finish $fwriteo $realtobits $sync$and$plane
$async$nand$array $dist_t $fmonitor $itor $rewind $sync$nand$array
$async$nand$plane $dist_uniform $fmonitorb $monitor $rtoi $sync$nand$plane
$async$nor$array $dumpall $fmonitorh $monitorb $same $sync$nor$array
$async$nor$plane $dumpfile $fmonitoro $monitorh $sformat $sync$nor$plane
$async$or$array $dumpflush $fopen $monitoro $signed $sync$or$array
$async$or$plane $dumpoff $fread $monitoroff $sscanf $sync$or$plane
$bitstoreal $dumpon $fscanf $monitoron $stime $test$plusargs
$display $dumpvars $fseek $q_add $stop $timeformat
$displayb $fclose $fstrobe $q_exam $strobe $ungetc
$displayh $fdisplay $fstrobeb $q_full $strobeb $unsigned
$displayo $fdisplayb $fstrobeh $q_initialize $strobeh $value$plusargs
$dist_chi_square $fdisplayh $fstrobeo $q_remove $strobeo $writeb
$dist_erlang $fdisplayo $ftell $readmemb $swrite $writeh
$dist_exponential $ferror $fwrite $readmemh $swriteb $writeo
$dist_normal $fflush $fwriteb $realtime $swriteh $sdf_annotate
$fgets $fwriteh $time $write $printtimescale
Basic Verilog $swriteo
Intel Confidential

General System Tasks


 $time – is used to provide the current
simulation time.
– Usage: $time;
 $random – generates random numbers
– Usage:
» <regname> = $random;
» <regname> = $random (<seed>);
 “seed” assure same random series every time
 “seed” must be a reg

Basic Verilog
Intel Confidential

Display System Tasks


 $display – is used for displaying values
of variables or strings or expressions.
– Usage: $display(p1, p2, …, pn);
 $write – same as $display but without
“return”
 $monitor – is used to monitor a signal
and present its value when it change.
– Usage: $monitor(p1, p2, …, pn);

Basic Verilog
Intel Confidential

Simulation Control
System Tasks
 $stop – is provided to stop the
simulation
– Usage: $stop;
 $finish – is provided to terminate the
simulation
– Usage: $finish;

Basic Verilog
Intel Confidential

Display System Tasks


Example
initial $display(“Hello World”); Output: Hello World
Output is the simulation time,
initial $display($time);
for example: 230
wire b = 1’b1;
initial $display(“At %d the value of b is %b in %m”,$time,b);
Output at time 230 when at module top.p1 is:
At 230 the value of b is 1 in top.p1
initial $monitor($time, “ the value of clock is %b”,clock);
If clock is toggle every 5 time units, the output will be:
0 the value of clock is 1
5 the value of clock is 0
10 the value of clock is 1
Basic Verilog
15 the value of clock is 0
Intel Confidential

Files Management - Read


 $readmemb, $readmemh – initializes
the contents of memory array from a
text file (in binary or hex format)
– Usage: $readmemb(“<file>”, <mem>);
reg [7:0] mem1 [0:3];
initial $readmemh(“[Link]”, mem1);

[Link] :
// my wonderful file !
01 // nice number
a5
fe
34 Basic Verilog
Intel Confidential

Files Management - Write


 $fopen, $fclose – open/close a test file
for writing
 Access is performed using a 32-bit
integer called “file handler” (pointer)
integer <file_handler>;
initial begin
<file_handler> = $fopen(“<text_file>”);

$fclose(<file_handler>);
end

Basic Verilog
Intel Confidential

Files Management - Write


 $fdisplay, $fmonitor, $fwrite – similar to
$display, $monitor, $write but data is
written into a file
 Usage:
– $fdisplay(file_handler, p1, p2, …, pn);
– $fwrite(file_handler, p1, p2, …, pn);
– $fmonitor(file_handler, p1, p2, …, pn);

Basic Verilog
Intel Confidential

State Machine Types


 This is an automat that changes its state every
clock edge according to its current state and to its
inputs
 Advantages:
– readability, scalability, maintenance,debug
 Main Types :
– Mealy : outputs depends on state and inputs
– Moore : outputs depends on state only
– One Hot : special Moore with single flop per state
– Sync. Mealy : same as Mealy with synchronous outputs

Basic Verilog
Intel Confidential

Mealy
 Outputs depends on state and inputs

 Long comb. path


Inputs Combinatorical Outputs
 Noise goes thru always

 Low real estate


Next State Current State

Synchronous
always
FFs

Basic Verilog
Intel Confidential

Mealy Implementation
module meally(clk, rst, in, out)

State encoding
reg [1:0] cur_st, nxt_st;
parameter [1:0] ST_IDLE=2’d0, ST_GO=2’d1 …
always @(cur_st or in)
nxt_st = ST_IDLE; // default Next State “case”
case (cur_st) (comb.)
ST_IDLE : if (in) nxt_st = ST_GO;

always @(posedge clk or negedge rst) Current state (sync)
if (!rst) cur_st <= ST_IDLE;
else cur_st <= nxt_st;
always @(cur_st or in) Output “case”
out = 1’b0; // default (comb.)
case (cur_st)
ST_IDLE : if (in) out = 1’b1;

endmodule Basic Verilog
Intel Confidential

Moore
 Outputs depends on state only
 Mid real estate
 Short comb. path
Inputs Combinatorical
always

Next State Current State

Synchronous
always Logic Outputs
FFs

Basic Verilog
Intel Confidential

Moore Implementation
module moore(clk, rst, in, out)

State encoding
reg [1:0] cur_st, nxt_st;
parameter [1:0] ST_IDLE=2’d0, ST_GO=2’d1 …
always @(cur_st or in)
nxt_st = ST_IDLE; // default Next State “case”
case (cur_st) (comb.)
ST_IDLE : if (in) nxt_st = ST_GO;

always @(posedge clk or negedge rst) Current state (sync)
if (!rst) cur_st <= ST_IDLE;
else cur_st <= nxt_st;
always @(cur_st) Output “case”
out = 1’b0; // default (comb.)
case (cur_st)
ST_IDLE : out = 1’b1;

endmodule Basic Verilog
Intel Confidential

One Hot
 Outputs depends on state only
 Single flop per state : always a single
flop is ‘1’ (hot), others ‘0’ (cold)
 Mid real estate
 Very Short comb. path (OR gates) Very fast

Basic Verilog
Intel Confidential

One Hot Implementation


module one_hot(clk, rst, in, out)

State encoding
reg [2:0] cur_st, nxt_st; (as shift-register)
parameter [1:0] IDLE=2’d0, GO=2’d1, DONE=2’d2 …
always @(cur_st or in) Next State “case”
nxt_st = 3’b0; // default (comb.)
case (1’b1)
cur_st[IDLE] : if (in) nxt_st[GO] = 1’b1;

always @(posedge clk or negedge rst) Current state
if (!rst) cur_st <= 3’b001; (sync)
else cur_st <= nxt_st;
always @(cur_st) Output “case”
out = 1’b0; // default (comb.)
case (1’b1)
cur_st[IDLE] : out = 1’b1;

endmodule Basic Verilog
Intel Confidential

Synchronous Mealy
 "Mealy" means that outputs is
determined by the current state and
the inputs
 "Synchronous" means that all of the
outputs of the FSM have a FF stage

INPUTS CURRENT STATE


LOGIC
("CASE-TREE")

OUTPUTS

Basic Verilog
Intel Confidential

Sync. Mealy Implementation


module sync_meally(clk, rst, in, out)

reg [1:0] cur_st; State encoding

parameter [1:0] ST_IDLE=2’d0, ST_GO=2’d1 …


always @(posedge clk or negedge rst)
begin Next State and
if (!rst) begin Output “case”
cur_st <= ST_IDLE; (sync)
out <= 1’b0;
end
else begin
out <= 1’b0; // output default
// cur_st default is to stay in the state
case (cur_st)
ST_IDLE : begin
if (in) cur_st <= ST_GO;
if (in) out <= 1’b1;
end

endmodule Basic Verilog
Intel Confidential

Simulation Flow
 Build a testbench (TB) with the unit instance
TB
unit

 Create a library (default name “work”)


 Compile the unit and the TB
– Compiler stages:
» Parsing: syntax check
» Database builder: build a database into the library
» Assembler: machine code file
 Simulate
Basic Verilog
Intel Confidential

Testbench
 Generate a “stimulus” to the unit inputs
 Checks unit outputs
 Controls simulation flow
 May use all the language constructs
– Timing control, System tasks etc.
 Special functional verification unit (e.g.
Specman) may be used for complex
designs simulation
Basic Verilog
Intel Confidential

Event Driven Simulation


 Event-driven is the typical algorithm
used by simulators
 Event is a change in a signal
 When a signal is changing the following
are re-evaluated:
– Assign statements with this signal in their
left hand side expression
– Always blocks with this signal in their
sensitivity list

Basic Verilog
Intel Confidential

Timescale Directive

 Time scale is used to define the delay time


units in a simulation, and can be defined for
each module.
 Syntax:
– `timescale <reference time> / <time precision>
 <reference time> - specify the unit
measurements for times and delays.
 <time precision> - specifies the precision to
which the delays are rounded off during
simulation.
Basic Verilog
Intel Confidential

Timescale Directive (Cont.)

Only 1,10 and 100 are valid for


specifying the reference time
and time precision.

`timescale 100 ns / 1 ns; 5 time units will be 500 ns.

`timescale 1 us / 10 ns;
5 time units will be 5 us.

`timescale 1 ps / 1 ps;
5 time units will be 5 ps.
Basic Verilog
Intel Confidential

Modelsim Simulator Flow


 Needs [Link] (library mapping &
config)
 Create library:
– vlib work
 Compile Verilog files (units + TB):
– vlog -work work <file1> <file2> …
 Run simulator:
– With GUI : vsim work.<tb_name> &
– Without GUI : vsim -c work.<tb_name> &

Basic Verilog
Intel Confidential

Hands On
 [Link]

 Modelsim Documentation:
 [Link]

Basic Verilog
Intel Confidential

Solution for Quiz #1


 Write the following numbers :
– 7 in a hexadecimal format : 3‘h7
– 9 in a binary format : 4’b1001

 What are the Decimal values of the following


expressions :
– 8’b11110000 ^ 8’h0f : ‘255’ represented by a 8 bit long
vector
– 4’d8 && 4’b1010 : ‘1’ represented by a single bit (logical
operator)
– 7 : ‘7’ represented by a 32 bit long vector
– 1’h8 : ‘1’ represented by a single bit

Basic Verilog
Intel Confidential

Solution for Quiz #2


module
a4_bit_clocked_adder(in1_or_res,in2,carry_out,clk);
inout [3:0] in1_or_res;
input [3:0] in2;
input clk;
output carry_out;
wire [3:0] in1_or_res,in2;
wire clk;
reg carry_out;
endmodule

Basic Verilog
Intel Confidential

Solution for Quiz #2 (cont.)


 What is the value of the wires in the
following cases :
– wire [5:0] a;
– reg c; c = 1’bx
– wire [8:0] b [1:0]
– assign a = {3{2’b10}}; a = 6’b101010
– assign b[1] = {a,2’b11,c}; b[1] = 9’b10101011x
– assign b[0] = b[1]; b[0] = 9’b10101011x

Basic Verilog
Intel Confidential

Solution for Quiz #3


module top (A, B, ACT, CLK, OUT);

input A, B, ACT, CLK;


output OUT;

wire OUT;
wire RES;

ALU myALU(.A(A),.B(B),.SEL(ACT),.RES(RES));
FLOP myflop (.D(RES), .OUT(OUT), .CLK(CLK));

endmodule;

Basic Verilog

You might also like