online Verilog-1995 Quick Reference Guide
by Stuart Sutherland of Sutherland HDL, Inc., Portland, Oregon, USA

copyright 1995, Sutherland HDL, Inc., all rights reserved.  Permission is granted to use this document for personal purposes only.$nbsp; You may not reproduce or distribute any portion of this document by any means without first obtaining permission from Sutherland HDL, Inc.
Professionally printed copies of this reference guides are available for purchase.  See www.sutherland-hdl.com for details.

1.0 Hierarchy Scopes

Verilog HDL constructs that represent hierarchy scope are:
bulletModule definitions
bulletFunction definitions
bulletTask definitions
bulletNamed statement blocks ( begin- end or fork- join)
bulletSpecify blocks

Each scope has its own name space. An identifier name defined within a scope is unique to that scope. References to an identifier name will search first in the local scope, and then search upward through the scope hierarchy up to a module boundary.

2.0 Concurrency

The following Verilog HDL constructs are independent processes that are evaluated concurrently in simulation time:
bulletModule instances
bulletPrimitive instances
bulletContinuous assignments
bulletProcedural blocks

3.0 Reserved Keywords

always
and
assign
attribute
begin
buf
bufif0
bufif1
case
casex
casez
cmos
deassign
default
defparam
disable
edge
else
end
endattribute
endcase
endfunction
endmodule
endprimitive
endspecify
endtable
endtask
event
for
force
forever
fork
function
highz0
highz1
if
ifnone
initial
inout
input
integer
join
medium
module
large
macromodule
nand
negedge
nmos
nor
not
notif0
notif1
or
output
parameter
pmos
posedge
primitive
pull0
pull1
pulldown
pullup
rcmos
real
realtime
reg
release
repeat
rnmos
rpmos
rtran
rtranif0
rtranif1
scalared
signed
small
specify
specparam
strength
strong0
strong1
supply0
supply1
table
task
time
tran
tranif0
tranif1
tri
tri0
tri1
triand
trior
trireg
unsigned
vectored
wait
wand
weak0
weak1
while
wire
wor
xnor
xor

 

4.0 Lexical Conventions

4.1 White Space Characters

blanks, tabs, newlines (carriage return), formfeeds and EOF (end-of-file).

4.2 Comments

// begins a single line comment, terminated by a newline.

/* begins a multi-line comment, terminated by a */.

4.3 Case Sensitivity

Verilog is case sensitive.

4.4 Identifiers (names)

bulletMust begin with alphabetic or underscore characters a-z A-Z _
bulletMay contain the characters a-z A-Z 0-9 _ and $
bulletMay use any character by escaping with a backslash ( \ ) at the beginning of the identifier, and terminating with a white space.

Examples

Notes

adder

legal identifier name

XOR

uppercase identifier is unique from xor keyword

\reset*

an escaped identifier (must be followed by a white space)

 

4.5 Logic Values

The Verilog HDL has 4 logic values.

Logic Value

Description

0

zero, low, or false

1

one, high, or true

z or Z

high impedance (tri-stated or floating)

x or X

unknown or uninitialized

 

4.6 Logic Strengths

The Verilog HDL has 8 logic strengths: 4 driving, 3 capacitive, and high impedance (no strength).

Strength Level

Strength Name

Specification Keyword

Display Mnemonic

7

Supply Drive

supply0

supply1

Su0

Su1

6

Strong Drive

strong0

strong1

St0

St1

5

Pull Drive

pull0

pull1

Pu0

Pu1

4

Large Capacitive

large

La0

La1

3

Weak Drive

weak0

weak1

We0

We1

2

Med. Capacitive

medium

Me0

Me1

1

Small Capacitive

small

Sm0

Sm1

0

High Impedance

highz0

highz1

HiZ0

HiZ1

 

4.7 Literal Integer Numbers

Syntax

size'base value Sized integer in a specific radix (base)
bulletsize (optional) is the number of bits in the number. Unsized integers default to at least 32-bits.
bullet'base (optional) represents the radix. The default base is decimal.

Base

Symbol

Legal Values

binary

b or B

0, 1, x, X, z, Z, ?, _

octal

o or O

0-7, x, X, z, Z, ?, _

decimal

d or D

0-9, _

hexadecimal

h or H

0-9, a-f, A-F, x, X, z, Z, ?, _
bulletThe ? is another way of representing the Z logic value.
bulletAn _ (underscore) is ignored (used to enhance readability).
bulletValues are expanded from right to left (lsb to msb).
bulletWhen size is less than value, the upper bits are truncated.
bulletWhen size is larger than value, and the left-most bit of value is 0 or 1, zeros are left-extended to fill the size.
bulletWhen size is larger than value, and the left-most bit of value is Z or X, the Z or X is left-extended to fill the size.

Examples

Size

Base

Binary Equivalent

10

unsized

decimal

0...01010 (32-bits)

'o7

unsized

octal

0...00111 (32-bits)

1'b1

1 bit

binary

1

8'Hc5

8 bits

hex

11000101

6'hF0

6 bits

hex

110000 (truncated)

6'hF

6 bits

hex

001111 (zero filled)

6'hZ

6 bits

hex

ZZZZZZ (Z filled)

 

4.8 Literal Real Numbers

Syntax

value.value decimal notation
baseEexponent scientific notation (the E is not case sensitive)
bulletReal numbers are limited to the values 0-9 and underscore.
bulletThere must be a value on either side of the decimal point.

Examples

Notes

0.5

must have value on both sides of decimal point

3e4

3 times 104 (30000)

5.8E-3

5.8 times 10-3 (0.0058)

5.0 Module Definitions

Verilog HDL models are represented as modules.

Syntax

Implicit Internal Connection

module module_name (port_name, port_name, ... );

module_items

endmodule

Explicit Internal Connection

module module_name (.port_name (signal_name ), .port_name (signal_name ), ... );

module_items

endmodule

bulletImplicit internal connections connect the port to an internal net or register of the same name.
bulletExplicit internal connections connect the port to an internal signal with a different name, or a bit select, part select, or concatenation of internal signals.
bulletThe keyword macromodule is a synonym for module. Some EDA tools may optimize tool execution performance by flattening macromodule hierarchy.
bulletmodule_items are:
bulletmodule_port_declarations
bulletdata_type_declarations
bulletmodule_instances
bulletprimitive_instances
bulletprocedural_blocks
bulletcontinuous_assignments
bullettask_definitions
bulletfunction_definitions
bulletspecify_blocks
bulletModule functionality may be:
bulletBehavioral - modeled with procedural blocks or continuous assignment statements.
bulletStructural - modeled as a netlist of module instances or primitive instances.
bulletA combination of behavioral and structural.
bulletModule definitions may not be nested. Instead, modules instantiate other modules. bulletModule definitions may be expressed using parameter constants. Each instance of a module may redefine the parameters to be unique to that instance. bulletModule items may appear in any order, but port declarations and data type declarations should be listed before the ports or signals are referenced.

6.0 Module Port Declarations

Syntax

port_direction [port_size] port_name, port_name, ... ;

port_direction is declared as:
bulletinput for scalar or vector input ports.
bulletoutput for scalar or vector output ports.
bulletinout for scalar or vector bi-directional ports.

port_size is a range from [ msb : lsb ] (most-significant-bit to least-significant-bit).
bulletThe msb and lsb must be literal integers, integer parameters, or an expression that resolves to an integer constant.
bulletEither little-endian convention (the lsb is the smallest bit number) or big-endian convention (the lsb is the largest bit number) may be used.
bulletThe maximum port size may be limited, but will be at least 256 bits.

 

Examples

Notes

input a,b,sel; 3 scalar ports
output [7:0] result; little endian convention
inout [0:15] data_bus; big endian convention
input [15:12] addr; msb:lsb may be any integer
parameter word = 32;
input [word-1:0] addr;
constant expressions may be used

 

7.0 Data Type Declarations

Syntax

register_type [size] variable_name , variable_name , ... ;
register_type [size] memory_name [array_size];
net_type [size] #(delay) net_name , net_name , ... ;
net_type (drive_strength) [size] #(delay) net_name = continuous_assignment ;
trireg (capacitance_strength) [size] #(delay, decay_time) net_name, net_name, ... ;
parameter constant_name = value, constant_name = value, ... ;
specparam constant_name = value, constant_name = value, ... ;
event event_name, event_name, ... ;

delay (optional) may only be specified on net data types. The syntax is the same as primitive delays.

size is a range from [msb : lsb] (most-significant-bit to least-significant-bit).
bulletThe msb and lsb must be integers, integer parameters or an expression that resolves to an integer constant.
bulletEither little-endian convention (the lsb is the smallest bit number) or big-endian convention (the lsb is the largest bit number) may be used.
bulletThe maximum vector size is at least 65,536 bits (216).

array_size is from [ first_address : last_address].

first_address and last_address must be integers, integer parameters, or an expression that resolves to integer.
bulletEither ascending or descending address order may be used.
bulletThe maximum array size is at least 16,777,216 words (224).

strength (optional) is specified as (strength1, strength0) or (strength0, strength1). See Logic Strengths for keywords.

decay_time (optional) specifies the amount of time a trireg net will store a charge after all drivers turn-off, before decaying to logic X. The syntax is (rise_delay, fall_delay, decay_time). The default decay is infinite.

7.1 Register Data Types

Keyword

Functionality

reg

unsigned variable of any bit size

integer

signed 32-bit variable

time

unsigned 64-bit variable

real or realtime

double-precision floating point variable

Register data types are used as variables in procedural blocks.
bulletRegisters store logic values only (no logic strength).
bulletA register data type must be used when the signal is on the left-hand side of a procedural assignment.

7.2 Net Data Types

Keyword

Functionality

wire or tri Simple interconnecting wire
wor or trior Wired outputs OR together
wand or triand Wired outputs AND together
tri0 Pulls down when tri-stated
tri1 Pulls up when tri-stated
supply0 Constant logic 0 (supply strength)
supply1 Constant logic 1 (supply strength)
trireg Stores last value when tri-stated (capacitance strength)

Net data types connect structural components together.
bulletNets transfer both logic values and logic strengths.
bulletA net data type must be used when:
bulletA signal is driven by the output of some device.
bulletA signal is also declared as an input port or inout port.
bulletA signal is on the left-hand side of a continuous assignment.

7.3 Other Data Types

Other Types

Functionality

parameter

Run-time constant for storing integers, real numbers, time, delays, or ASCII strings. Parameters may be redefined for each instance of a module.

specparam

Specify block constant for storing integers, real numbers, time, delays or ASCII strings

event

A momentary flag with no logic value or data storage. Often used for synchronizing concurrent activities within a module.

 

7.4 Data Type Declaration Examples

Data Type Examples

Notes

wire a, b, c; 3 scalar nets
tri1 [7:0] data_bus; 8-bit net, pulls-up when tri-stated
reg [1:8] result; an 8-bit unsigned variable
reg [7:0] RAM [0:1023]; a memory array; 8-bits wide, with 1K of addresses
wire #(2.4,1.8) carry; a net with rise, fall delays
wire (strong1,pull0) sum = a+b; net with drive strength and a continuous assignment
trireg (small) #(0,0,35) ram_bit; net with small capacitance and 35 time unit decay time

 

8.0 Module Instances

Syntax

Port Order Connections

module_name instance_name [instance_array_range] (signal, signal, ... );

Port Name Connections

module_name instance_name [instance_array_range] (.port_name(signal), (.port_name(signal), ...);

Explicit Parameter Redefinition

defparam heirarchy_path.parameter_name = value;

Implicit Parameter Redefinition

module_name #(value) instance_name (signals);

 

A module may be instantiated using port order or port names.
bulletPort order instantiation lists signal connections in the same order as the port list in the module definition. Unconnected ports are designated by two commas with no signal listed.
bulletPort name instantiation lists the port name and signal connected to it, in any order.

instance_name (required) is used to make multiple instances of the same module unique from one another.

instance_array_range (optional) instantiates multiple modules, each instance connected to separate bits of a vector.
bulletThe range is specified as [lhi:rhi] (left-hand-index to right-hand-index).
bulletIf the bit width of a module port in the array is the same as the width of the signal connected to it, the full signal is connected to each instance of the module port.
bulletIf the bit width of a module port is different than the width of the signal connected to it, each module port instance is connected to a part select of the signal, with the right-most instance index connected to the right-most part of the vector, and progressing towards the left.
bulletThere must be the correct number of bits in each signal to connect to all instances (the signal size and port size must be multiples).

Parameters in a module may be redefined for each instance.
bulletExplicit redefinition uses a defparam statement with the parameter's hierarchical name.
bulletImplicit redefinition uses the # token as part of the module instantiation. Parameters must be redefined in the same order they are declared within the module.

 

Module Instance Examples

module reg4 (q, d, clock);
  output [3:0] q;
  input [3:0] d;
  input clock;
  wire [3:0] q, d;
  wire clock;
  
  //port order connection,2nd port not connected
  dff u1 (q[0], , d[0], clock);

  //port name connection, qb not connected
  dff u2 (.clk(clock),.q(q[1]),.data(d[1]));

  //explicit parameter redefine
  dff u3 (q[2], ,d[2], clock);
  defparam u3.delay = 3.2;

  //implicit parameter redefine
  dff #(2) u4 (q[3], , d[3], clock);
endmodule
module dff (q, qb, data, clk);
  output q, qb;
  input data, clk;

  parameter delay = 1; //default delay parameter

  dff_udp #(delay) (q, data, clk);
  not (qb, q);
endmodule

 

Array of Instances Example

module tribuf64bit (out, in, enable);
  output [63:0] out;
  input [63:0] in;
  input enable;
  wire [63:0] out, in;
  wire enable;
  
  //array of 8 8-bit tri-state buffers; each instance is connected
  //to 8-bit part selects of the 64-bit vectors; The scalar
  //enable line is connected to all instances

  tribuf8bit i[7:0] (out, in, enable);

endmodule
module tribuf8bit (out, in, enable);
  output [7:0] y;
  input [7:0] a;
  input en;
  wire [7:0] y, a;
  wire en;
  
  //array of 8 Verilog tri-state primitives each bit of the
  //vectors is connected to a different primitive instance
  bufif1 u[7:0] (y, a, en);
endmodule

 

9.0 Primitive Instances

Syntax

gate_type (drive_strength) #(delay) instance_name [instance_array_range] (terminal, terminal, ... );
switch_type #(delay) instance_name [instance_array_range] (terminal, terminal, ... );

 

Gate Type

Terminal Order

and
or
xor
nand
nor
xnor
(1_output, 1-or-more_inputs)
buf not (1-or-more_outputs, 1_input)
bufif0
bufif1
notif0
notif1
(1_output, 1_input, 1_control)
pullup pulldown (1_output)
user-defined-primitives (1_output, 1-or-more_inputs)

 

Switch Type

Terminal Order

pmos
nmos
rpmos
rnmos
(1_output, 1_input, 1_control)
cmos rcmos (1_output, 1_input, n_control, p_control)
tran rtran (2_bidirectional-inouts)
tranif0
rtranif0
rtranif1
rtranif1
(2_bidirectional-inouts, 1_control)

 

Primitive Delay Syntax

#delay or #(delay)
   Single delay for all output transitions
#(delay, delay)
   Separate delays for (rising, falling) transitions
#(delay, delay, delay)
   Separate delays for (rising, falling, turn-off) transitions
#(min_delay:typ_delay:max_delay)
   Minimum to maximum range of delays for all transitions
#(min_delay:typ_delay:max_delay, min_delay:typ_delay:max_delay)
   Min. to max. range of delays for (rising, falling) transitions
#(min_delay:typ_delay:max_delay, min_delay:typ_delay:max_delay, min_delay:typ_delay:max_delay)
   Min. to max. range of delays for (rising, falling, turn-off) transitions

 

delay (optional) represents the propagation delay through a primitive. The default delay is zero. Integers or real numbers may be used.

strength (optional) is specified as (strength1, strength0) or (strength0, strength1) Refer to Logic Strengths for strength keywords.
bulletOnly gate primitives may have drive strength specified. Switch primitives pass the input strength to the output. Resistive switches reduce the strength as it passes through.

instance_name (optional) may used to reference specific primitives in debugging tools, schematics, etc.

instance_array_range (optional) instantiates multiple primitives, each instance connected to separate bits of a vector.
bulletThe range is specified as [lhi:rhi] (left-hand-index to right-hand-index).
bulletThe primitive instances are connected with the right-most instance index connected to the right-most bit of each vector, and progressing towards the left.
bulletVector signals must be the same size as the array.
bulletScalar signals are connected to all instances in the array.

 

Primitive Instance Examples

Notes

and i1 (out,in1,in2); zero delay gate primitive
and #5 (o,i1,i2,i3,i4); same delay for all transitions
not #(2,3) u7(out,in); separate rise & fall delays
buf (pull0,strong1)(y,a); output drive strengths model ECL
wire [31:0] y, a;
buf #2.7 i[31:0] (y,a);
array of 32 buffers

 

10.0 Procedural Blocks

Syntax

type_of_block @(sensitivity_list)
  statement_group: group_name
  local_variable_declarations
  timing_control procedural_statements
end_of_statement_group
  

 

type_of_block is either initial or always
bulletinitial procedural blocks process statements one time.
bulletalways procedural blocks process statements repeatedly.

sensitivity_list (optional) is an event timing control that controls when all statements in the procedural block will start to be evaluated. The sensitivity list is used to model combinational and sequential logic behavior.

statement_group--end_of_statement_group is used to group two or more procedural statements together and control the execution order.
bulletbegin--end groups two or more statements together sequentially, so that statements are evaluated in the order they are listed. Each timing control is relative to the previous statement.
bulletfork--join groups two or more statements together in parallel, so that all statements are evaluated concurrently. Each timing control is absolute to when the group started.

group_name (optional) creates a local scope in a statement group. Named groups may have local variables, and may be disabled with the disable keyword.

local_variable_declarations (optional) must be a register data type (may only be declared in named statement groups).

timing_control is used to control when statements in a procedural block are executed. Refer to Procedural Timing

procedural_statement is a procedural assignment to a register variable or a programming statement.

Procedural Block Examples

Notes

initial
  fork
    bus = 16'h0000;
    #10 bus = 16'hC5A5;
    #20 bus = 16'hFFAA;
  join
    
initial procedure executes statements one time; The fork--join group places statements in parallel.
always @(a or b or ci)
  begin
    sum = a + b + ci;
  end
    
always procedure executes statements repeatedly.
always @(posedge clk)
  q <= data; 
a statement group is not required when there is only one statement

 

10.1 Timing Controls

#delay
Delays execution for a specific amount of time. The delay may be a literal number, a variable, or an expression.
@(edge signal or edge signal or ... )
Delays execution until there is a logic transition on a signal.
bulletedge (optional) maybe either posedge or negedge. If no edge is specified, then any logic transition is used.
bulletor is used to specify events on any of several signals.
bulletsignal may be scalar or vector, and any data type.
wait (expression)
Delays execution until the expression evaluates as true.

10.2 Procedural Assignments

register_data_type = expression;
Blocking procedural assignment. Expression is evaluated and assigned when the statement is encountered. In a begin--end sequential statement group, execution of the next statement is blocked until the assignment is complete. In the sequence begin m=n; n=m; end, the 1st assignment changes m before the 2nd assignment evaluates m.
register_data_type <= expression;
Non-blocking procedural assignment. Expression is evaluated when the statement is encountered, and assignment is postponed until the end of the time-step. In a begin--end sequential statement group, execution of the next statement is not blocked; and may be evaluated before the assignment is complete. In the sequence begin m<=n; n<=m; end, both assignments will be evaluated before m or n changes.
timing_control register_data_type = expression;
timing_control register_data_type <= expression;
Delayed procedural assignments. Evaluation of the assignment is delayed by the timing control.
register_data_type = timing_control expression;
Blocking intra-delayed assignment. Expression is evaluated in the time-step in which the statement is encountered, and assigned in a non-deterministic order in the time-step specified by the timing control.
register_data_type <= timing_control expression;
Non-blocking intra-delayed assignment. Expression is evaluated in the time-step in which the statement is encountered, and assigned at the end of the time-step specified by the timing control. Models transport delay.
assign register_data_type = expression;
Procedural continuous assignment. Overrides any other procedural assignments to a register variable.
deassign register_data_type;
De-activates a procedural continuous assignment.
force net_or_register_data_type = expression;
Forces any data type to a value, overriding all other logic.
release net_or_register_data_type;
Removes the effect of a force.

10.3 Programming Statements

if (expression)
   statement or statement_group
Executes the next statement or statement group if expression evaluates as true.
if (expression)
   statement or statement_group
else
   statement or statement_group
Executes the first statement or statement group if expression evaluates as true. Executes the second statement or statement group if expression evaluates as false or unknown.
case (net_or_register_or_literal)
   case_match1: statement or statement_group
   case_match2,
   case_match3: statement or statement_group
   default: statement or statement_group
endcase
Compares the net, register or literal value to each case and executes the statement or statement group associated with the first matching case. Executes the default if none of the cases match (a default case is optional).
casez (net_or_register_or_literal)
Special version of the case statement which uses a Z logic value to represent don't-care bits.
casex (net_or_register_or_literal)
Special version of the case statement which uses Z or X logic values to represent don't-care bits.
forever statement or statement_group
An infinite loop that continuously executes the statement or statement group.
repeat (number) statement or statement_group
A loop that executes the statement or statement group a set number of times. Number may be an integer, a variable, or an expression (a variable or expression is only evaluated when the loop is first entered).
while (expression) statement or statement_group
A loop that executes a statement or statement group as long as an expression evaluates as true.
for (initial_assignment; expression; step_assignment) statement or statement_group

bulletExecutes initial_assignment once when the loop starts.
bulletExecutes the statement or statement group as long as the expression evaluates as true.
bulletExecutes the step_assignment at the end of each pass through the loop.
disable group_name;
Discontinues execution of a named group of statements. Simulation of that group jumps to the end of the group without executing any scheduled events.

Procedural Statement Examples

//A 50 ns clock oscillator that starts after 1000 time units
initial
  begin
    clk = 0;
    #1000 forever #25 clk = ~clk;
  end
    
//sensitivity list models sequential logic
always @(posedge clk)
  begin
    //Non-blocking assignments avoid race conditions in the byte swap
    word[15:8]<= word[7:0];
    word[7:0] <= word[15:8];
  end
    
//sensitivity list models combinational logic
always @(a or b or sel)
  if (sel==0) y = a + b;
  else y = a * b;
    
//sensitivity list models sequential logic
always @(posedge clk)
  begin
    casez (opcode) //casez makes Z a don't care
      //? in literal integer is same as Z
      2'b1??: alu_out = accum;
      2'b000: while (bloc_xfer) //loop until false
                repeat (5) @(posedge clk)
                  begin //loop 5 clock cycles
                    RAM[address] = data_bus;
                    address = address + 1;
                  end
      3'b011: begin : load //named group
                integer i; //local variable
                for (i=0; i<=255; i=i+1)
                  @(negedge clk)
                    data_bus = RAM[i];
              end
      default: $display("illegal opcode");
    endcase
  end
    

 

11.0 Operators

Operators perform an operation on one or two operands:
bulletUnary expressions
operator operand
bulletBinary expressions
operand operator operand
bulletThe operands may be either net or register data types. bulletOperands may be scalar, vector, or bit selects of a vector. bulletOperators which return a true/false result will return a 1-bit value where 1 is true, 0 is false, and X is indeterminate.

 

 

Usage

Description

Arithmetic Operators

+

m + n

Add n to m

-

m - n

Subtract n from m

-

-m

Negate m (2's complement)

*

m * n

Multiply m by n

/

m / n

Divide m by n

%

m % n

Modulus of m / n

Bitwise Operators

~

~m

Invert each bit of m

&

m & n

AND each bit of m with each bit of n

|

m | n

OR each bit of m with each bit of n

^

m ^ n

Exclusive OR each bit of m with n

~^
^~

m ~^ n
m ^~ n

Exclusive NOR each bit of m with n

Unary Reduction Operators

&

&m

AND all bits in m together (1-bit result)

~&

~&m

NAND all bits in m together (1-bit result)

|

|m

OR all bits in m together (1-bit result)

~|

~|m

NOR all bits in m together (1-bit result)

^

^m

Exclusive OR all bits in m (1-bit result)

~^
^~

~^m
^~m

Exclusive NOR all bits in m (1-bit result)

Logical Operators

!

!m

Is m not true? (1-bit True/False result)

&&

m && n

Are both m and n true? (1-bit True/False result)

||

m || n

Are either m or n true? (1-bit True/False result)

Equality Operators (compares logic values of 0 and 1

==

m == n

Is m equal to n? (1-bit True/False result)

!=

m != n

Is m not equal to n? (1-bit True/False result)

Identity Operators (compares logic values of 0, 1, X and Z

===

m === n

Is m identical to n? (1-bit True/False results)

!==

m !== n

Is m not identical to n? (1-bit True/False result)

Relational Operators

<

m < n

Is m less than n? (1-bit True/False result)

>

m > n

Is m greater than n? (1-bit True/False result)

<=

m <= n

Is m less than or equal to n? (True/False result)

>=

m >= n

Is m greater than or equal to n? (True/False result)

Logical Shift Operators

<<

m << n

Shift m left n-times

>>

m >> n

Shift m right n-times

Miscellaneous Operators

? :

sel?m:n

If sel is true, select m: else select n

{}

{m,n}

Concatenate m to n, creating larger vector

{{}}

{n{m}}

Replicate m n-times

->

-> m

Trigger an event on an event data type

 

Operator Precedence

  !     ~     +     - (unary)

  *     /     %

  +     - (binary)

  <<    >>

  <     <=    >    >=

  ==    !=   ===   !==

  &     ~&

  ^     ~^

  |     ~|

  &&

  ||

  ?:
 highest precedence






















 lowest precedence

 

12.0 Continuous Assignments

Syntax

 

Explicit Continuous Assignment

net_type [size] net_name;
assign #(delay) net_name = expression;

Implicit Continuous Assignment

net_type (strength) [size] net_name = expression;

bulletExplicit continuous assignments require two statements: one to declare the net, and one to continuously assign a value to it.
bulletImplicit continuous assignments combine the net declaration and continuous assignment into one statement.
bulletnet_type may be any of the net data types except trireg.
bulletstrength (optional) may only be specified when the continuous assignment is combined with a net declaration. The default strength is (strong1, strong0).
bulletdelay (optional) follows the same syntax as primitive delays. The default is zero delay.
bulletexpression may include any data type, any operator, and calls to functions.
bulletContinuous assignments model combinational logic. Each time a signal changes on the right-hand side, the right-hand side is re-evaluated, and the result is assigned to the net on the left-hand side.
bulletContinuous assignments are declared outside of procedural blocks. They automatically become active at time zero, and are evaluated concurrently with procedural blocks, module instances, and primitive instances.

 

Continuous Assignment Examples

//A 32-bit wide 2:1 MUX
wire [31:0] mux_out;
assign mux_out = sel? a : b;
    
//A 16-bit wide tri-state buffer with delay
tri [0:15] #2.8 buf_out = en? in: 16'bz;
    
//A 64-bit ALU with ECL output strengths
wire [63:0] (strong1,pull0) alu_out = alu_function(opcode,a,b);
    

 

13.0 Task Definitions

Syntax

task task_name;
   input, output, and inout declarations
   local variable declarations
   procedural_statement or statement_group
endtask
    

 

Tasks are subroutines.
bulletMay have any number of inputs, outputs or inouts.
bulletMay contain timing controls (#, @, or wait).

 

Example of a Task

task read_mem;                 //TASK DEFINITION
  input [15:0] address;          //declaration order
  output [31:0] data;            // determines order
  begin                          // of arguments when
    read_request = 1;            // task is called
    wait (read_grant) addr_bus = address;
    data = data_bus;
    #5 addr_bus = 16'bz; read_request = 0;
  end
endtask
    
read_mem(PC, IR);              //TASK CALL
    

 

14.0 Function Definitions

Syntax

function [size_or_type] function_name;
   input declarations
   local variable declarations
   procedural_statement or statement_group
endfunction
    

 

Functions return the value that is assigned to the function name.
bulletMust have at least one input; may not have outputs or inouts.
bulletMay not contain timing controls (#, @, or wait).
bulletsize_or_type (optional) is the return bit range as [msb:lsb], or the keywords integer or real. The default size is 1-bit.

 

Example of a Function

function [7:0] GetByte;        //FUNCTION DEFINITION
  input [63:0] Word;             //declaration order
  input [3:0] ByteNum;           //determines order
  integer Bit;                   //of arguments when
  reg [7:0] temp;                //called
  begin
    for (Bit=0; Bit<=7; Bit=Bit+1)
    temp[Bit] = Word[((ByteNum-1)*8)+Bit];
    GetByte = temp;              //A function returns
  end                            // the value assigned
endfunction                      // to its name
    
this_byte = GetByte(data,4);   //FUNCTION CALL
    

 

15.0 Specify Blocks

Syntax

specify
   specparam_declarations
   timing_constraint_checks
   simple_pin-to-pin_path_delay
   edge-sensitive_pin-to-pin_path_delay
   state-dependent_pin-to-pin_path_delay
endspecify
    

 

15.1 Specparam Declarations

specparam param_name = value, param_name = value, ...;
bulletspecparams are constants used to store delays, delay calculation factors, synthesis factors, etc.
bulletvalue may be interger, real, delay, or quoted string.

15.2 Timing Constraint Checks

Timing constraint checks are system tasks that model restrictions on input changes, such as setup times and hold times.

Timing Check Syntax

$setup(data_event, reference_event, setup_limit, notifier);
$hold(reference_event, data_event, hold_limit, notifier);
$setuphold(reference_event, data_event, setup_limit, hold_limit, notifier);
$skew(reference_event, data_event, skew_limit, notifier);
$recovery(reference_event, data_event, limit, notifier);
$period(reference_event, period_limit, notifier);
$width(reference_event, width_limit, width_threshold, notifier);
bulletTiming checks may only be used in specify blocks.
bulletThe reference_event is and edge of an input signal that establishes a reference point for changes on the data event.
bulletThe data_event is the input signal that is monitored for changes.
bulletThe data_event and reference_event signals must be module input ports.
bulletThe limit and threshold are delay values and use the same syntax as single primitive delays.
bulletThe notifier (optional) is a reg variable used as a flag. When a timing violation occurs, the model functionality can use the notifier flag to modify the model outputs.

 

15.3 Pin-to-pin Path Delays

bulletSimple path delay statement:

(input_port polarity:path_token output_port) = (delay);

bulletEdge-sensitive path delay:

(edge input_port path_token (output_port polarity:source)) = (delay);

bulletedge (optional) may be either posedge or negedge. If not specified, all input transitions are used.
bulletsource (optional) is the input port or value the output will receive. The source is ignored by most logic simulators, but may be used by timing analyzers.
bulletState-dependent path delay:

if (first_condition) simple_or_edge-sensitive_path_delay
if (next_condition) simple_or_edge-sensitive_path_delay
ifnone simple_path_delay


bulletAllows different delays for the same path to be specified, based on other input conditions.
bulletcondition may only be based on input ports.
bulletMost operators may be used with the condition, but should resolve to true/false (a logic X or Z is considered true; if the condition resolves to a vector, only the lsb is used).
bulletEach state-dependent delay for the same path must have a different condition or a different edge-sensitive edge.
bulletThe ifnone condition (optional) may only be a simple path delay, and serves as a default if no other condition evaluates as true.
bulletpolarity (optional) is either + or −, and indicates whether-or-not the input will be inverted. The polarity token is ignored by most logic simulators, but may be used by timing analyzers. bulletpath_token is either *> for full connection or => for parallel connection.
bulletFull connection path delay indicates every input bit may have a delay path to every output bit.
bulletParallel connection path delay indicates each input bit is connected to its corresponding output bit (bit 0 to bit 0, bit 1 to bit 1, ...)
bulletdelay can represent 1, 2, 3, 6 or 12 transitions may be specified. Each transition may have a single delay or a min:typ:max delay range.

Delays

Transitions represented (in order)

1

all output transitions

2

rise, fall output transitions

3

rise, fall, turn-off output transitions

6

rise, fall, 0->Z, Z->1, 1->Z, Z->0

12

rise, fall, 0->Z, Z->1, 1->Z, Z->0,
0->X, X->1, 1->X, X->0, X->Z, Z->X

 

Specify Block Examples

Notes

(a => b) = 1.8; parallel connection path; one delay for all output transitions
(a -*> b) = 2:3:4; full connection path; one min:typ:max delay range for all output transitions; b receives the inverted value of a
specparam t1 = 3:4:6,
          t2 = 2:3:4;
(a => y) = (t1,t2);
different path delays for rise, fall transitions
(a *> y1,y2) = (2,3,4,3,4,3); different delays for 6 output transitions
(posedge clk => (qb -: d)) = (2.6, 1.8); edge-sensitive path delay; timing path is positive edge of clock to qb; qb receives the inverted value of data
if (rst && pst) (posedge clk=>(q +: d))=2; state-dependent edge sensitive path delay
if (opcode = 3'b000)
       (a,b *> o) = 15;
if (opcode = 3'b001)
       (a,b *> o) = 25;
ifnone (a,b *> o) = 10;
state-dependent path delays; an ALU with different delays for certain operations (default delay has no condition)

 

16.0 User Defined Primitives (UDPs)

 

Syntax

primitive primitive_name (output, input, input, ... );
  output terminal_declaration;
  input terminal_declaration;
  reg output_terminal;
  initial output_terminal = logic_value;
  table
    table_entry;
    table_entry;
  endtable
endprimitive

 

User Defined Primitives define new primitives, which are used exactly the same as built-in primitives.
bulletAll terminals must be scalar (1-bit).
bulletOnly one output is allowed, which must be the first terminal.
bulletThe maximum number of inputs is at least 9 inputs for a sequential UDP and 10 inputs for a combinational UDP.
bulletLogic levels of 0, 1, X and transitions between those values may be represented in the table. The logic value Z is not supported with UDPs.
bulletreg declaration (optional) defines a sequential UDP by creating internal storage. Only the output may be a reg.
bulletinitial (optional) is used to define the initial (power-up) state for sequential UDP's. Only the logic values 0, 1, and X may be used. The default state is X.

16.1 UDP Table Entries

input_logic_values : output_logic_value ;
bulletCombinational logic table entry. Only logic level values may be specified (0, 1, X and don't care).

input_logic_values : previous_state : output_logic_value ;
bulletSequential logic table entry. May only be used when the output is also declared as a reg data type. Both input logic level and input logic transition values may be specified.
bulletA white space must separate each input value in the table.
bulletThe input values in the table must be listed in the same order as the terminal list in the primitive statement.
bulletAny combination of input values not specified in the table will result in a logic X (unknown) value on the output.
bulletOnly one signal may have an edge transition specified for each entry in the table.
bulletIf an edge transition is specified for one input, the UDP becomes sensitive to transitions on all inputs. Therefore, all other inputs must have table entries to cover transitions, or when the transition occurs the UDP will output an X.
bulletLevel sensitive table entries have precedence over edge sensitive table entries.

16.2 UDP Table Symbols

 

Truth Table Symbol

Definition

0

logic 0 on input or output

1

logic 1 on input or output

x or X

unknown on input or output

-

no change on output (may only be used with sequential UDPs)

?

don't care if an input is 0, 1, or X

b or B

don't care if and input is 0 or 1

(vw)

input transition from logic v to logic w
e.g.: (01) represents transition from 0 to 1

r or R

rising input transition: same as (01)

f or F

falling input transition: same as (10)

p or P

positive input transition: (01), (0X) or (X1)

n or N

negative input transition: (10), (1X) or (X0)

*

any possible input transition: same as (??)

 

 

UDP Examples

primitive mux (y, a, b, sel); //COMBINATIONAL UDP
  output y;
  input sel, a, b;
  table  //table order for inputs matches primitive statement
  // a  b  sel : y
     0  ?   0  : 0;  //select a; don't care about b
     1  ?   0  : 1;  //select a; don't care about b
     ?  0   1  : 0;  //select b; don't care about a
     ?  1   1  : 1;  //select b; don't care about a
  endtable
endprimitive
primitive dff (q,d,clk,rst); //SEQUENTIAL UDP
  output q;
  input clk, rst, d;
  reg q; //declaring output as reg defines
         //sequential device with an internal
         //storage state
  initial q = 0; //powers up in reset state
  table
  // d  clk rst:state:q
     ?   ?   0 :  ?  :0; //low true reset
     0   R   1 :  ?  :0; //clock in a 0
     1   R   1 :  ?  :1: //clock in a 1
     ?   N   1 :  ?  :-; //ignore negedge of clk
     *   ?   1 :  ?  :-; //ignore all edges on d
     ?   ?   P :  ?  :-; //ignore posedge of rst
     0 (0X)  1 :  0  :-; //reduce pessimism
     1 (0X)  1 :  1  :-; //reduce pessimism
    endtable
 endprimitive

 

17.0 Synthesis Supported Constructs

Following is a list of Verilog HDL constructs supported by most synthesis tools.
bulletThis list is not specific to any one tool - each synthesis tool supports a unique subset of the Verilog language.
bulletThe constructs listed in this section represent a subset of the Verilog HDL that are supported by most synthesis tools.
bulletVerilog constructs not listed in this section may be supported by some synthesis tools - refer to the specific synthesis tool documentation.

Verilog HDL Constructs

Notes

module declarations both module and macromodule keywords fully supported
port declarations
input output inout
fully supported; any vector size supported
net data types
wire wand wor
supply0 supply1
scalars and vectors fully supported
register data types
reg integer
register variables:
bulletmay be scalar or vector or register array
bulletmay be restricted to only making assignments to a register from just one procedure
bulletintegers default to 32 bits
parameter constants limited to integers; parameter redefinition may not be supported
module instances fully supported; both port order and port name instantiation supported
primitive instances
and nand or nor
xor buf not
bufif1 bufif0
notif1 notif0
only gate primitives are supported
assign
continuous assignment
fully supported; both explicit and implicit forms supported
function definitions may only use supported constructs; must be defined before being referenced
task definitions may only use supported constructs; must be defined before being referenced
always procedural block must have a sensitivity list
begin--end
statement groups
fully supported; named and unnamed blocks supported
disable statement group must be used within the same named block that is being disabled
= blocking procedural assignment
<= non-blocking procedural assignment
fully supported; may be restricted to using only one type of assignment for all assignments to the same register variable
assign procedural continuous assignment fully supported; the deassign keyword may not be supported
integer values fully supported; all sizes and bases
if if-else
case casex casez

decision statements
logic X and Z only supported as don't care bits
for loops the step assignment must be an increment or decrement (+ -)
while loops
forever loops
loop must take one clock cycle for each loop cycle (i.e.: an @(posedge clk) or @(negedge clk) must be within the loop)
operators
& ~& | ~| ^ ^~ ~^
== != < > <= =>
! && ||
<< >> {} {{}} ?:
+ - * /
operands may be:
bulletscalar or vector
bulletconstant or variable
bulletThe divisor for divide operator may be restricted to constants and a power of 2
bulletthe === and !== operators are not supported
vector bit selects
vector part selects
fully supported on the right-hand side of an assignment; restricted to constant bit or part selects on the left-hand side of an assignment

 

18.0 System Tasks and Functions

EDA tool vendors and tool users may define tasks and functions specific to their tool, such as text output or waveform displays.
bulletSystem tasks and functions begin with the $ (dollar sign).
bulletUsers may define additional built-in tasks and functions using the Verilog Programming Language Interface (PLI).
bulletA few of the most common system tasks and functions are listed in this section.

 

Text Formatting Codes

%b
%o
%d
%h
%e
%f
%t
binary values
octal values
decimal values
hex values
real values-exponential
real values-decimal
formatted time values
%s
%m
\t
\n
\"
\\
%%
character strings
hierarchical names
print a tab
print a newline
print a quote
print a backslash
print a percent sign
A zero in format codes (e.g.: %0d) displays the value using the
minimum field width required. The %e and %f may specify the
field width for both sides of the decimal point (e.g.: %5.2f)
$monitor("text_with_format_specifiers", signal, signal, ... );
Invokes a background process that continuously monitors the signals listed, and prints the formatted message whenever one of the signals changes. A newline is automatically added to the text printed.
$display("text_with_format_specifiers", signal, signal, ... );
Prints the formatted message once when the statement is executed during simulation. A newline is automatically added to the text printed.
$write("text_with_format_specifiers", signal, signal, ... );
Like $display statement, except that no newline is added.
$strobe("text_with_format_specifiers", signal, signal, ... );
Like the $display statement, except that the printing of the text is delayed until all simulation events in the current time step have executed.
mcd = $fopen("file_name");
A function that opens a disk file for writing, and returns a 32-bit integer multi-channel-descriptor (mcd) pointer to the file.
$fclose(mcd);
A function that closes a disk file that was opened by $fopen.
$monitor(mcd, "text_with_format_specifiers", signal, signal, ... );
$display(mcd, "text_with_format_specifiers", signal, signal, ... );
$write(mcd, "text_with_format_specifiers", signal, signal, ... );
$strobe(mcd, "text_with_format_specifiers", signal, signal, ... );
Variations of the text display tasks that write to files which have been opened with $fopen.
$time
Returns the current simulation time as a 64-bit integer.
$stime
Returns the lower 32-bits of simulation time as an integer.
$realtime
Returns the current simulation time as a real number.
$timeformat(unit, precision, "suffix", min_field_width);
Controls the format used by the %t text format specifier.
bulletunit is the base that time is to be displayed in, from 0 to -15
bulletprecision is the number of decimal points to display.
bulletsuffix is a string appended to the time, such as " ns".
bulletmin_field_width is the minimum number of characters that will be displayed.
  0 =   1 sec
 -1 = 100 ms
 -2 =  10 ms
 -3 =   1 ms 
 
 -4 = 100 us
 -5 =  10 us
 -6 =   1 us 
 
 -7 = 100 ns
 -8 =  10 ns
 -9 =   1 ns 
 
-10 = 100 ps
-11 =  10 ps
-12 =   1 ps 
 
-13 = 100 fs
-14 =  10 fs
-15 =   1 fs 

Example: $timeformat(-9, 2, " ns", 10);

$printtimescale(module_hierarchical_name);
Prints the time scale of the specified module, or the scope from which it is called if no module is specified.
$random(seed);
Returns a random 32-bit signed integer.
$readmemb("file_name", register_array, start, end);
$readmemh("file_name", register_array, start, end);
Opens a file for reading, and loads the contents into a register memory array. The file must be an ASCII file with values represented in binary ($readmemb) or hex ($readmemh). The start and end address values are optional.
$finish;
Finishes a simulation and exits the simulation process.
$stop;
Halts a simulation and enters an interactive debug mode.

 

19.0 Compiler Directives

Compiler directives provide a method for EDA tool vendors to control how their tool will interpret Verilog HDL models.
bulletCompiler directives begin with the grave accent character ( ` ).
bulletCompiler directives are not Verilog HDL statements; there is no semi-colon at the end of compiler directives.
bulletCompiler directives are not bound by modules or by files. When a tool encounters a compiler directive, the directive remains in effect until another compiler directive either modifies it or turns it off.
bulletA few of the most common compiler directives are listed in this section.

`reset_all
Resets all compiler directives that have a default back to the default. Directives that have no default are not affected.
`timescale time_unit base / precision base
Specifies the time units and precision for delays:
bullettime_unit is the amount of time a delay of 1 represents. The time unit must be 1 10 or 100
bulletbase is the time base for each unit, ranging from seconds to femtoseconds, and must be: s ms us ns ps or fs
bulletprecision and base represent how many decimal points of precision to use relative to the time units.

Example: `timescale 1 ns / 10 ps
Indicates delays are in 1 nanosecond units with 2 decimal points of precision (10 ps is .01 ns).

Note: There is no default timescale in Verilog; delays are simply relative numbers
  until a timescale directive declares the units and base the numbers represent.
`define macro_name text_string
`define macro_name (arguments) text_string (arguments)
Text substitution macro. Allows a text string to be defined as a macro name.
bullettext_string will be substituted in place of the macro_name where ever the macro name is used.
bullettext_string is terminated by a carriage return. The string must be on one line.
bulletarguments are evaluated before text is substituted.
bulletmacro_name must also be preceded by the grave accent mark ( ` ) each time the macro name is used.
bulletComments may be used. They are not substituted into the place of the macro name.


Examples:

   `define cycle 20 //clock period
   always #(`cycle/2) clk = ~clk;

   `define NAND(dval) nand #(dval)
   `NAND(3) i1 (y,a,b);
   `NAND(3:4:5) i2 (o,c,d);

`include "file_name"
File inclusion. The contents of another Verilog HDL source file is inserted where the `include directive appears.
`ifdef macro_name
     verilog_source_code
`else
     verilog_source_code
`endif
Conditional compilation. Allows Verilog source code to be optionally included, based on whether or not macro_name has been defined using `define or an invocation option.

Examples:

   `ifdef RTL
      wire y = a & b;
   `else
      and #1 (y,a,b);
   `endif
`celldefine
`endcelldefine

Flags the Verilog source code between the two directives as a cell. Some tools, such as a delay calculator for an ASIC design, need to distinguish between a module that represents an ASIC cell and other modules in the design.
`default_nettype net_data_type
Changes the net data type to be used for implicit net declarations. Any of the net data types may be specified. By default, the implicit net data type is wire.
`unconnected_drive pull1
`unconnected_drive pull0
`nounconnected_drive

Determines what logic value will be applied to unconnected module inputs. The default is `nounconnected_drive, which floats unconnected inputs and nets to high impedance.
`delay_mode_zero
`delay_mode_unit
`delay_mode_path
`delay_mode_distributed

Specifies the simulation delay mode.
`uselib file=file dir=directory libext=extension
Specifies the Verilog source library file or directory in which the compiler should search for the definitions of modules or UDPs instantiated in a design. A `uselib directive with no arguments removes any preceding library search directives.

Examples:

   `uselib file=/models/rtl_lib
      ALU i1 (y1,a,b,op);   //RTL model
   `uselib dir=/models/gate_lib libext=.v
      ALU i2 (y2,a,b,op);   //Gate model
   `uselib   //turn off `uselib searching

 

online Verilog HDL Quick Reference Guide
by Stuart Sutherland of Sutherland HDL, Inc. - Portland, Oregon, USA

copyrighted material - do not reproduce any portion by any means
professionally printed reference guides are available - see www.sutherland.com for details