Verilog Types and Constants

22
Verilog Types and Constants The type names below are automatically defined. The types are reserved words thus you can not re-define them. Users can augment predefied type with modifiers, vectors and arrays. See Verilog Declarations for how to declare identifiers. Types and Constants value set net data types variable data types constants vectors arrays value set Beware of automatic type conversion. You may get a surprise. The value set for Verilog is: 0 - represents number zero, logic zero, logical false 1 - represents number one, logic one, logical true x - represents an unknown logic value z - represents high impedance logic value most data types can store all four values. net data types There are two groups of types, "net data types" and "variable data types." An identifier of "net data type" means that it must be driven. The value changes when the driver changes value. These identifiers basically represent wires and are used to connect components. "net data types" are: wire, supply0, supply1, tri, triand, trior, tri0, tri1, wand, wor

Transcript of Verilog Types and Constants

Verilog Types and Constants

The type names below are automatically defined.The types are reserved words thus you can not re-define them.Users can augment predefied type with modifiers, vectors and arrays.See Verilog Declarations for how todeclare identifiers.

Types and Constants

value set net data types variable data types constants vectors arrays

value set

Beware of automatic type conversion. You may get a surprise.

The value set for Verilog is: 0 - represents number zero, logic zero, logical false 1 - represents number one, logic one, logical true x - represents an unknown logic value z - represents high impedance logic value most data types can store all four values.

net data types

There are two groups of types, "net data types" and "variable data types."

An identifier of "net data type" means that it must be driven. Thevalue changes when the driver changes value. These identifiersbasically represent wires and are used to connect components."net data types" are: wire, supply0, supply1, tri, triand, trior,tri0, tri1, wand, wor

"net data types" can have strength modifiers: supply0, supply1,strong0, strong1, pull0, pull1, weak0, weak1,highz0, highz1, small, medium, large.

some "net data types" can take modifiers: signed, vectored, scalared.

variable data types

There are two groups of types, "net data types" and "variable data types."

An identifier of "variable data type" means that it changes value uponassignment and holds its value until another assignment. This is atraditional programming language variable and is used in sequentialstatements."variable data types" are: integer, real, realtime, reg, time.

integer is typically a 32 bit twos complement integer.

real is typically a 64 bit IEEE floating point number.

realtime is of type real used for storing time as a floating point value.

reg is by default a one bit unsigned value. The reg variable data type may have a modifier signed, and may have may bits by using the vector modifier [msb:lsb].

time is typically 64 bit unsigned value that is the simulation time The system function $time provides the simulation time.

constants

integer 3 123456 -7

real 1.0 0.1 123e-5 123.0E-5 -5.2 per IEEE 754-1985 typically 64 bit

string "a string" constant string, no extra characters, no terminator, may be stored into almost any type. There is no type 'char' or 'string'.

specifying radix and special values

The general structure is: width´radix value

width is integer, automatic extension to 16 bits

radix is d or D for integer (optional) h or H for hexadecimal o or O for octal b or B for bit

examples: ´h ff is 00ff hex // default 16 bit 16´h ff is 00ff hex 1´b 1 or just 1 1´b 0 or just 0 1´b x needed for x unknown (not just 'x') 1´b z needed for z high impedance 32´H 0XZ1FABX hexadecimal 32 bits in four bit groups 8´B 0110_1100 binary 01101100 8-bits 4´b 10xz four bits 10XZ 18´o 777777 octal, 18 bits of ones 7´d 123 just decimal 123 with length 7

vectors

Vectors are are multiple bit types. The next section covers arraysthat create multiple entries including arrays of vectors.

The "net data types" and the one variable type reg are bydefault one bit in length and by default unsigned.

wire will be used as representing all "net data types".

wire[31:0] is a vector type having 32 bits with the most significant bit numbered 31 and the least significant bit numbered zero. This type denotes 32 wires.

A declaration:

wire[31:0] a; declares a to be 32 wires. just 'a' is all 32 wires, a[31] is the most significant bit a[0] is the least significant bit

a[15:8] is eight wires, bits 15 to 8 of 'a'

wire[1:12] is a vector type having 12 bits with the most significant bit numbered 1 and the least significant bit numbered 12. This type denotes 12 wires that can connect components.

reg[-10:10] is a vector type having 21 bits with a most significant bit -10 and a least significant bit 10. This is a variable that can be assigned values.

reg signed [7:0] is a vector type for values from -128 to +127. In other words two´s complement values.

arrays

Arrays apply to identifiers. Identifiers have a type as covered inthe previous section.

type identifier array-definition; is the form used to define an array.

integer a[1:10]; is a typical array of integers a[1] is the first element, a[10] is the last element.

reg[31:0] mema[0:4095]; is a typical memory, 4096 words of 32 bits per word. mema[2] is the third word in memory mema[2][31] is the most significant bit of the third word in memory.

real matrix[1:20][1:20]; is a two dimensional array of real values. access as matrix[i][j]

wire[7:0] vid_mem[1:3][799:0][599:0]; 3D organized bytes access as vid_mem[rgb][horiz][vert] to wire memory bytes to components. Typically using the generate capability.

Restriction: You can not access an entire array. You can not accessa slice of an array. e.g. a[3:5] is illegal.

Verilog Design Structures

A structure may be the entire file or there may be more thanone structure in a file. No less than a structure may bein a file.

Verilog Design Structures

file structure module structure primitive structure configuration structure specify structure

file structure

File Structure

<compiler directives>

module ... // zero or more module definitions <module contents> endmodule

macromodule ... // zero or more macromodule definitions <macromodule contents> endmacromodule

primitive ... // zero or more primitive definitions <primitive contents> endprimitive

config ... // optional configuration specification <configuration statements> endconfig

module structure

The top of every design hierarchy must be a module.The module that is never instantiated is the top of the design.

The module structure defines the interface and the design.

Module Structure (same for macromodule)

module module_name(<port_name_list>); // (<port_name_list>) is optional input <some_port_names>; // any port names that are inputs output <some_port_names>; // any port names that are outputs inout <some_port_names>; // any port names that are both

<parameters> // optional parameters and overrides

<specify block> // optional specify block

<declarations> // optional variable declarations and // optional net declarations

<function definitions> // optional function definitions

<task definitions> // optional task definitions

<parallel statements> // optional module instantiations // and parallel statements

initial // zero or more initial blocks begin <sequential statements> end

always // zero or more always blocks begin <sequential statements> end

endmodule // identifier // physical end of module

// add32.v verilog 32 bit adder (Verilog 2001 style) module adder(input [31:0] a, // a input input [31:0] b, // b input input cin, // carry-in output [31:0] sum, // sum output output cout); // carry-out parameter d=2; assign #d {cout, sum} = a + b + cin; // after d units of time endmodule // adder

// add32.v verilog 32 bit adder (pre Verilog 2001 style) module adder(a, b, cin, sum, cout); parameter d=2;

input [31:0] a; // a input input [31:0] b; // b input input cin; // carry-in output [31:0] sum; // sum output output cout; // carry-out assign #d {cout, sum} = a + b + cin; // after d units of time endmodule // adder

primitive structure

Also called UDP, for User Defined Primitive.

primitive identifier(<parameters>); output <output identifier> ; input <input identifier list> ; table <input to output transition table> endtable endprimitive // identifier

Output symbols: 0, 1, x, X Input level symbols: 0, 1, x, X, b, B, ? Input edge symbols: f, F, n, N, p, P, r, R, *

primitive mux(out, ctrl, in1, in2); // sample primitive definition output out; input ctrl, in1, in2; table // ctrl in1 in2 : out 0 1 ? : 1; 0 0 ? : 0; 1 ? 0 : 0; 1 ? 1 : 1; x 0 0 : 0; x 1 1 : 1; // other cases output x endtable endprimitive // mux

configuration structure

config identifier; [ declarations , see allowed list below ] -- optional

[ statements , see allowed list below ] endconfig // identifier

specify structure

specify identifier; [ declarations , see allowed list below ] -- optional [ statements , see allowed list below ] endspecify // identifier

Verilog Sequential StatementsThese behavioral statements are for use in:initial block, always block, task, function

Sequential Statements

if statement case statement for statement repeat statement while statement forever statement unnamed block statement fork - join statements wait statement event triggered statement delay statement disable statement assign - deassign statements force - release statements

if statement

Conditional execution of sequential statements if(<condition>)

begin <statements> end Example: if(a > max && b == 0) begin max = a; b = a-1; end if(<condition1>) begin <statements> end else if(<condition2>) begin <statements> end // any number of optional "else if" clauses else // optional "else" clause begin <statements> end Example: if(a < 5) // only execute the statements for the first true condition begin a = a+5; b = a/c; end else if(a < 10) begin a = a-5; c = b/a; end else if(b != a) begin b = a; c = c/2; end else begin // execute only if none of the conditions above are true b = 0;

c = 0; end

case statement

Execute the selected sequential statements case(<expression>) // or casex or casez for == accepting x or z <expression1> : <statement> <expression2> : begin <statements> end <expression3>, // note comma <expression4>: <statement> // for both expression==expression3 // and expression==expression4 ... default : <statement> // optional endcase

for statement

Iteration statement semantics: var = initial_expression exit loop if condition false (zero) execute statements var = update_expression jump to exit loop test

for(var=initial_expression ; condition; var=update_expression) begin <statements> end

Example:

for(i=1 ; i<=10; i=i+1) begin A[i] = B[i-1]; B[i-1] = B[i-1]*2 + i; end

repeat statement

repeat(<count>) // block of statements repeated <count> times begin <statements> end

while statement

while(<condition>) // block of statements repeated while <condition> is true begin <statements> end

forever statement

forever // loop forever begin <statements> end

unnamed block statement

begin // just an unnamed sequential block <statements> // executed sequentially end

fork - join statements

fork <statements> // executed in parallel join // wait until all statements finish

fork begin // block of statements executing in parallel <statements> end begin // any number of parallel blocks <statements>

end join // wait until all blocks have finished

wait statement

Cause execution of sequential statements to wait.

wait(<condition>) #(<optional_delay) <statement> wait(<condition>) // waits for condition to become true (non-zero)

event triggered statement

Cause a sequential statement or block to execute when <some_event> occurs

@(<some_event>) <statement>

@(<some_event>) begin <statements> end

Example:

@(negedge clock) a_out = a-in;

@(posedge reset) begin clear_reg = 1; running = 0; end

delay statement

"#20;" // delay 20 time units

disable statement

assign - deassign statements

force - release statements

Verilog Concurrent StatementsThese statements are for use in ???.

Concurrent Statements

block statement process statement concurrent procedure call statement concurrent assertion statement concurrent signal assignment statement conditional signal assignment statement selected signal assignment statement component instantiation statement generate statement

block statement

Used to group concurrent statements, possibly hierarchically.

label : block [ ( guard expression ) ] [ is ] [ generic clause [ generic map aspect ; ] ] [ port clause [ port map aspect ; ] ] [ block declarative items ] begin concurrent statements end block [ label ] ;

clump : block begin A <= B or C; D <= B and not C; end block clump ;

maybe : block ( B´stable(5 ns) ) is port (A, B, C : inout std_logic ); port map ( A => S1, B => S2, C => outp ); constant delay: time := 2 ns; signal temp: std_logic; begin

temp <= A xor B after delay; C <= temp nor B; end block maybe;

Verilog Reserved Words (key words)

always starts an always begin ... end sequential code blockand gate primitive, andassign parallel continuous assignmentautomatic a function attribute, basically reentrant and recursivebegin starts a block that ends with end (no semicolon)buf gate primitive, bufferbufif0 gate primitive, buffer if control==0bufif1 gate primitive, buffer if control==1case starts a case statementcasex starts a case statement where x matchescasez starts a case statement where z matchescell library, cell identifier, in configurationcmos switch primitive, cmosconfig starts a configurationdeassign stops the corresponding assign from accepting new valuesdefault optional last clause in a case statementdefparam used to over-ride parameter valuesdesign top level module, in configurationdisable a task or blockedge edge control specifierelse execute if no previous clause was trueend end of a block, paired with a beginendcase end of a case statementendconfig end of a configurationendfunction end of a function definitionendgenerate end of a generateendmodule end of a module definitionendprimitive end of a primitive definitionendspecify end of a specifyendtable end of a table definitionendtask end of a task definitionevent data typefor starts a for statementforce starts net or variable assignmentforever starts a loop statementfork begin parallel execution of sequential codefunction starts a function definitiongenerate starts a generate blockgenvar defines a generate variable

highz0 drive strength 0highz1 drive strength 0if starts an if statement, if(condition) ...ifnone state dependent path declarationincdir file path for libraryinclude include file specificationinitial starts an initial begin ... end sequential blockinout declares a port name to be both input and outputinput declares a port name to be inputinstance specify instance name, in configurationinteger variable data type, 32 bit integerjoin end of a parallel forklarge charge strength, 4, of triregliblist library search order for modules, in configurationlibrary location of modules, libraries and fileslocalparam starts a local parameter statement, not over-riddenmacromodule same as module with possibly extra meanings medium charge strength, 2, of triregmodule begin a module definition, also called a cell or componentnand gate primitive, nandnegedge event expression, negative edgenmos switch primitive, nmosnor gate primitive, nornoshowcancelledno report trailing edge precedes leading edge, in specifynot gate primitive, notnotif0 gate primitive, not if control==0notif1 gate primitive, not if control==1or gate primitive, oroutput declares a port name to be an outputparameter starts a parameter statementpmos switch primitive, pmosposedge event expression, positive edgeprimitive starts the definition of a primitive modulepull0 drive strength 5pull1 drive strength 5pulldown gate primitivepullup gate primitivepulsestyle_oneventglitch detection, in specifypulsestyle_ondetectglitch detection, immediate change to x, in specifyremos switch primitive, remosreal variable data type, implementation defined floating pointrealtime variable data type, floating point timereg variable data type, starts a declaration of name(s)release release a forced net or variable assignmentrepeat starts a loop statementrnmos switch primitive, rnmosrpmos switch primitive, rpmos

rtran bidirectional switch primitive, rtranrtranif0 bidirectional switch primitive, rtranif0rtranif1 bidirectional switch primitive, rtranif1scalared property of a vector typeshowcancelled report trailing edge precedes leading edge, in specifysigned type modifier, reg signedsmall charge strength, 1, of triregspecify starts a specify blockspecparam starts a parameter statement for timing delaysstrong0 drive strength 6strong1 drive strength 6supply0 net data type, and drive strength 7supply1 net data type, and drive strength 7table start a table definition in a primitivetask starts a task definitiontime variable data type, 64 bit integertran bidirectional switch primitive, trantranif0 bidirectional switch primitive, tranif0tranif1 bidirectional switch primitive, tranif1tri net data typetri0 net data type, connected to VSStri1 net data type, connected to VDDtriand net data type, tri state wired andtrior net data type, tri state wired ortrireg register data type associates capacitance to the netunsigned type modifier, unsigneduse library, cell identifier, in configurationvectored property of a vector typewait starts a wait statementwand net data type, wired andweak0 drive strength 3weak1 drive strength 3while starts a sequential looping statement, while(condition) wire net data type, a basic wire connectionwor net data type, wired orxnor gate primitive, xnor not of exclusive orxor gate primitive, xor exclusive or

"net data type" means it starts a declaration of name(s) that must be driven"variable data" means it starts a declaration of name(s) that hold values

Verilog Operators and Special Characters+ addition- subtraction* multiplication

/ division** exponentiation% modulus> greater than relation // relations are 0 if false< less than relation // 1 if true and possibly x>= grater than or equal relation<= less than or equal relation== logical equality relation != logical inequality relation=== case equality // x must match x, z must match z!== case not equal // comparison is made bit-wise&& logical and|| logical or! logical negation& bit-wise and (also unary reduction and)~& unary reduction nand| bit-wise or (also unary reduction or, event or)~| reduction nor^ bit-wise exclusive or (unary reduction xor)~^ bit-wise equivalence (^~) (also unary reduction xnor)~ bit-wise complement >> bit-wise logical right shift<< bit-wise logical left shift>>> bit-wise arithmetic right shift<<< bit-wise arithmetic left shift? : condition ? value-if-true : value-if-false? compare equal on this bit* compare equal on group of bits= substitution<= non blocking substitution: separator, separator. selector .parameter(actual) module_name.local_name ; statement terminator

( ) grouping parenthesis, module instantiation, function and task call[ ] subscript, range as in [31:0]{ } concatenation" " pair of quotes around strings

@ event control` compiler directive$ system task and functions

/* start comment*/ end comment// start comment to end of line

(* start non simulation attribute*) end non simulation attribute

' constant width'radix value base is b B d D h H o O % format indication b B c C d D e E f F g G h H l L m M o O s S t T u U v V z Z %10.5E %0d\ escape sequences, quoted characters in strings \n \t \\ \" \ddd %%

Verilog System Tasks and Functions

$display("<format>", exp1, exp2, ...); // formatted write to display format indication %b %B binary %c %C character (low 8 bits) %d %D decimal %0d for minimum width field %e %E E format floating point %15.7E %f %F F format floating point %9.7F %g %G G general format floating point %h %H hexadecimal %l %L library binding information %m %M hierarchical name, no expression %o %O octal %s %S string, 8 bits per character, 2´h00 does not print %t %T simulation time, expression is $time %u %U unformatted two value data 0 and 1 %v %V net signal strength %z %Z unformatted four value data 0, 1, x, z escape sequences, quoted characters in strings \n newline \t tab \\ backslash \" quote \ddd octal %% percent

any other characters between the quotes are displayed the expressions are taken in order of the format indication ,, in the expression list inserts one space in the output

$write // same as $display except no automatic insertion of newline$strobe // same as $display except waits until all events finished$monitor // same as $display except only displays if an expression changes$monitoron // only one $monitor may be active at ant time,$monitoroff // turn current $monitor off

$displayb // same as $display using binary as default format

$writeb // same as $write using binary as default format$strobeb // same as $strobe using binary as default format$monitorb // same as $monitor using binary as default format$displayo // same as $display using octal as default format$writeo // same as $write using octal as default format$strobeo // same as $strobe using octal as default format$monitoro // same as $monitor using octal as default format$displayh // same as $display using hexadecimal as default format$writeh // same as $write using hexadecimal as default format$strobeh // same as $strobe using hexadecimal as default format$monitorh // same as $monitor using hexadecimal as default format

fd = $fopen("<file name>"); // open a file for writing, // fd is an integer file descriptorfd = $fopen("<file name>", file_type); // open a file for file_type action: // open for reading "r", "rb" binary // open for writing "w", "wb" binary // open for append "a", "ab" binary // open for read/write "r+", "r+b", "rb+" // open for write/read "w+", "w+b", "wb+" // open for append update "a+", "a+b", "ab+"$fclose(fd); // close an opened file$frewind(fd); // rewind an opened file$fflush(fd); // flush pending output to an open file$fseek($ftell(

$fdisplay(fd, $fwrite(fd,$swrite(??$fstrobe(fd,$fmonitor(fd,$fread(fd,$fscanf(fd,

$fdisplayb // same as $fdisplay using binary as default format$fwriteb // same as $fwrite using binary as default format$swriteb // same as $swrite using binary as default format$fstrobeb // same as $fstrobe using binary as default format$fmonitorb // same as $fmonitor using binary as default format$fdisplayo // same as $fdisplay using octal as default format$fwriteo // same as $fwrite using octal as default format$swriteo // same as $swrite using octal as default format$fstrobeo // same as $fstrobe using octal as default format$fmonitoro // same as $fmonitor using octal as default format$fdisplayh // same as $fdisplay using hexadecimal as default format$fwriteh // same as $fwrite using hexadecimal as default format

$swriteh // same as $swrite using hexadecimal as default format$fstrobeh // same as $fstrobe using hexadecimal as default format$fmonitorh // same as $fmonitor using hexadecimal as default format

$sscanf$sdf_annotate

Verilog Compiler Directives

Compiler directives begin with "`" an accent grave, not an apostropheSome of these would be called preprocessor commands in "C"

Compilers may add additional compiler directives. They may not beportable and may not invoke the same actions. These are from theVerilog 2001 Standard.

`include file_name // include source code from another file`define macro_name macro_code // substitute macro_code for macro_name`define macro_name(par1, par2,...) macro_code // parameterized macro`undef macro_name // undefine a macro

`ifdef macro_name1 // include source lines1 if macro_name1 is defined <source lines1> // the source lines1`elsif macro_name2 // any number of elsif clauses, the first defined <source lines2> // macro_name includes the source lines `else // include source lines3 when no prior macro_name defined <source lines3> // the source lines 3 `endif // end the construct `ifndef macro_name // like `ifdef except logic is reversed, // true if macro_name is undefined

`timescale 1ns/1ns // units/precision for time e.g. for %t `celldefine // marks beginning of a cell `endcelldefine // marks end of a cell

`default_nettype net_type // sets the default net type for implicit // net declarations, net_type is one of: // wire, tri, tri0, tri1, triand, trior, trireg, wand, wor, none

`resetall // reset all directives to default state, // undefine all macros `line number "filename" level // over rides the compilers information `unconnected_drive pull0 // set unconnected inputs to 0 `unconnected_drive pull1 // set unconnected inputs to 1

`nounconnected_drive // terminates either of the above directives `default_decay_time a_time // sets all undefined trireg net decay times, // a_time is integer, real or infinite `default_trireg_strength val // default trireg net strength 0 to 250 `delay_mode_distributed // sets distributed delay mode `delay_mode_path // sets path delay mode `delay_mode_unit // sets unit delay mode `delay_mode_zero // sets zero-delay mode

Verilog Delays and EventsContents

Delays Events

Delays

Typical uses of delay

 #20; // delay 20 time units  #10 <statement> // the statement execution takes 10 time units // (blocking, next statement waits the 10 time units)  #10 var <= expression; // non blocking statement, var takes 10 time units // to update but next statement proceeds with no delay  #(12.5 : 15 : 18.2) <statement> // minimum : typical : maximum time units  #(12.5 : 15 ; 18.2 , 15.2 : 20.1 : 30) <statement> //rising times, falling times each minimum : typical : maximum  #(3:4:5 ; 4:5:6 ; 5:6:7) <statement> //rising times; falling times; transport times each having minimum : typical : maximum

and #5 (out, in1, in2, ...); // delay from input to output and #(5,6) (out, in1, in2, ...); // rising and falling delay and #(4:5:6) (out, in1, in2, ...); // min : typical : max delay and #(4:5:6 , 5:6:7) (out, in1, in2, ...); // min:typ:max on rise and fall buf #(4, 5 , 10) (out, in); // rising, falling, and transport delay buf #(4:5:6 , 5:6:7 , 6:7:8) (out, in); // full timing specification //rising times; falling times; transport times each having minimum : typical : maximum

Events

Event triggers are of the form:

@event_identifier statement; // trigger on event_identifier @(event_expression) statement; // trigger on event_expression @* statement; // trigger on any change @(*) statement; // trigger on input change

Typical examples of event triggering

always @reset_event // assumes a declaration event reset_event; begin // triggered upon a -> reset_event; <statements to reset the circuit> end

always @(posedge clear or negedge clk or reset_event) begin <statements to be executed> end

always @* // same as @(a or b or c or x) begin a = b + c; d = a - funct(x); end

always @(*) // same as @(b or c or x) begin a = b + c; d = a - funct(x); end