Upload
ngoduong
View
252
Download
4
Embed Size (px)
Citation preview
1
CSE 467 1Verilog Digital System Design
Verilog Verilog LanguageLanguageConceptsConcepts
Adapted from Z. Adapted from Z. NavabiNavabiPortions Copyright Z. Navabi, 2006
CSE 467 2Verilog Digital System Design
Verilog Verilog Language ConceptsLanguage Concepts Characterizing Hardware LanguagesCharacterizing Hardware Languages
TimingTiming ConcurrencyConcurrency Timing and concurrency exampleTiming and concurrency example
Module BasicsModule Basics Code formatCode format Logic value systemLogic value system Wires and variablesWires and variables ModulesModules
Module portsModule ports NamesNames NumbersNumbers
2
CSE 467 3Verilog Digital System Design
Verilog Verilog Language ConceptsLanguage Concepts Module Basics (cont.)Module Basics (cont.)
ArraysArrays Verilog Verilog operatorsoperators Verilog Verilog data typesdata types Array indexingArray indexing
Verilog Verilog Simulation ModelSimulation Model Continuous assignmentsContinuous assignments Procedural assignmentsProcedural assignments
CSE 467 4Verilog Digital System Design
Verilog Verilog Language ConceptsLanguage Concepts Compiler DirectivesCompiler Directives
‘‘timescaletimescale ‘‘default-nettypedefault-nettype ‘‘includeinclude ‘‘definedefine ‘‘ifdefifdef, , ‘‘else,else,‘‘endifendif ‘‘unconnected-driveunconnected-drive
‘‘celldefinecelldefine, , ‘‘endcelldefineendcelldefine ‘‘resetallresetall
3
CSE 467 5Verilog Digital System Design
Verilog Verilog Language ConceptsLanguage Concepts System Tasks and FunctionsSystem Tasks and Functions
Display tasksDisplay tasks File I/O tasksFile I/O tasks Timescale tasksTimescale tasks Simulation control tasksSimulation control tasks Timing check tasksTiming check tasks PLA modeling tasksPLA modeling tasks
Conversion functions for Conversion functions for realsreals Other tasks and functionsOther tasks and functions
SummarySummary
CSE 467 6Verilog Digital System Design
Timing and concurrency are the main characteristics of hardwareTiming and concurrency are the main characteristics of hardwaredescription languages.description languages.
TimingTiming is associated with values that are assigned to hardware carriers. is associated with values that are assigned to hardware carriers.
ConcurrencyConcurrency refers to simultaneous operation of various hardware refers to simultaneous operation of various hardwarecomponents.components.
Characterizing HardwareCharacterizing HardwareLanguagesLanguages
4
CSE 467 7Verilog Digital System Design
Characterizing HardwareCharacterizing HardwareLanguagesLanguagesCharacterizing Characterizing
HardwareHardwareLanguagesLanguages
TimingTiming ConcurrencyConcurrency
Timing & ConcurrencyTiming & Concurrency
ExampleExample
CSE 467 8Verilog Digital System Design
TimingTiming
Characterizing Characterizing
HardwareHardware
LanguagesLanguages
TimingTiming ConcurrencyConcurrency
Timing & ConcurrencyTiming & Concurrency
ExampleExample
TimingTiming
5
CSE 467 9Verilog Digital System Design
Transfer of data is done through wires or busses and some of delays areTransfer of data is done through wires or busses and some of delays areassociated with transfer of data through wires.associated with transfer of data through wires.
Variables in Variables in Verilog Verilog may be used for representation of wires andmay be used for representation of wires andvariable assignments can include timing specification.variable assignments can include timing specification.
TimingTiming
CSE 467 10Verilog Digital System Design
TimingTiming
An AND-OR CircuitAn AND-OR Circuit
The circuit can be written like this:The circuit can be written like this:
assignassign w1 = a & b | c & w1 = a & b | c & ~b~b;;
assignassign #6 n = ~b; #6 n = ~b;assignassign #3 m = a & b; #3 m = a & b;assignassign #3 p = n & c; #3 p = n & c;assignassign #2 w2 = m | p; #2 w2 = m | p;
A sharp-sign (#)A sharp-sign (#)followed by a numberfollowed by a numberspecifies the delay ofspecifies the delay of
the left hand sidethe left hand sidesignal.signal.
A more accurate assignment:A more accurate assignment:
w
ab
c p
m Td = 3ns
Td =2ns
Td = 6 ns
n
Td = 3ns
Because of the 6 nsBecause of the 6 nsdelay of inverter indelay of inverter insecond path from second path from bb
to to w w a 6 ns glitcha 6 ns glitchappears on appears on w.w.
In this simpleIn this simpleassignment Glitchesassignment Glitchesthat may appear onthat may appear onww due to different due to different
delay paths from delay paths from bb to toww are not considered. are not considered.
An assign statementAn assign statementdrives the signal on thedrives the signal on the
left-hand side of theleft-hand side of theequal sign with theequal sign with the
booleanboolean expression on expression onits right.its right.
6
CSE 467 11Verilog Digital System Design
TimingTiming
Output GlitchOutput Glitch
When When b b changes from 1changes from 1to 0 the final value of to 0 the final value of wwremains at 1. However,remains at 1. However,because of the inverterbecause of the inverterdelay in forwarding a 1delay in forwarding a 1
to the output, a 6 nsto the output, a 6 nsglitch appears on glitch appears on ww..
w1w1, which is the result, which is the resultof the single assignof the single assignstatement, does notstatement, does not
show the delayshow the delay
w2 w2 shows bothshows bothpropagation delays andpropagation delays andglitches that may occurglitches that may occur
on the on the w w output of circuitoutput of circuit
CSE 467 12Verilog Digital System Design
ConcurrencyConcurrency
Characterizing Characterizing
HardwareHardwareLanguagesLanguages
TimingTiming ConcurrencyConcurrency
Timing & ConcurrencyTiming & Concurrency
ExampleExample
ConcurrencyConcurrency
7
CSE 467 13Verilog Digital System Design
Concurrency is an essential feature of any language for description ofConcurrency is an essential feature of any language for description ofhardware.hardware.
Functionality of a hardware system is described by concurrent sub-Functionality of a hardware system is described by concurrent sub-components or by a program in a sequential manner.components or by a program in a sequential manner.
By using concurrent sub-components Verilog simulator makes us thinkBy using concurrent sub-components Verilog simulator makes us thinkthat simulation of components is being done concurrently.that simulation of components is being done concurrently.
ConcurrencyConcurrency
CSE 467 14Verilog Digital System Design
w
a
b
c p
m Td = 3ns
Td =2ns
Td = 6 ns
n
Td = 3ns
An AND-OR CircuitAn AND-OR Circuit
ConcurrencyConcurrencyThe gates areThe gates are
concurrently active.concurrently active.We cannot decide on aWe cannot decide on apre-determined order inpre-determined order in
which gates of this circuitwhich gates of this circuitperform their operations.perform their operations.
assignassign #6 n = ~b; #6 n = ~b;assignassign #3 m = a & b; #3 m = a & b;assignassign #3 p = n & c; #3 p = n & c;assignassign #2 w2 = m | p; #2 w2 = m | p;
Regarded as concurrent.Regarded as concurrent.The order in which theseThe order in which these
statements appear in astatements appear in aconcurrent body of Verilogconcurrent body of Verilog
is not important.is not important.
8
CSE 467 15Verilog Digital System Design
Timing & Concurrency ExampleTiming & Concurrency Example
Characterizing Characterizing
HardwareHardwareLanguagesLanguages
TimingTiming ConcurrencyConcurrency
Timing & ConcurrencyTiming & Concurrency
ExampleExampleTiming & ConcurrencyTiming & Concurrency
ExampleExample
CSE 467 16Verilog Digital System Design
`timescale`timescale 1ns/100ps 1ns/100ps
modulemodule FullAdderFullAdder ( (inputinput a, b, a, b, cici, , outputoutput co, s); co, s);assignassign #4 co = a & b | a & #4 co = a & b | a & cici | b & | b & cici;;assignassign #3 s = a ^ b ^ #3 s = a ^ b ^ cici;;
endmoduleendmodule
Module headerModule headerdeclares inputs anddeclares inputs andoutputs of circuit.outputs of circuit.
The two assignThe two assignstatements drive statements drive ss
(sum) and (sum) and coco (carry- (carry-out) outputs of circuit.out) outputs of circuit.
Full Adder Concurrent DescriptionFull Adder Concurrent Description
Timing & Concurrency ExampleTiming & Concurrency Example
Propagation DelayPropagation Delayof Assignmentof Assignment
Because of the delay values,Because of the delay values,if an input change causesif an input change causesboth outputs to change, both outputs to change, sschanges before changes before co co does.does.
9
CSE 467 17Verilog Digital System Design
Fulladder Fulladder Tester Procedural DescriptionTester Procedural Description
`timescale`timescale 1ns/100ps 1ns/100psmodulemodule FullAdderTesterFullAdderTester;;
regreg a = 0, b = 0, a = 0, b = 0, cici = 0; = 0;wirewire co, s; co, s;parameterparameter tlimittlimit = 500; = 500;FullAdderFullAdder MUT (a, b, MUT (a, b, cici, co, s);, co, s);................................................................................................................................
Timing & Concurrency ExampleTiming & Concurrency Example
Declaration andDeclaration andinitialization ofinitialization ofvariables, wires,variables, wires,and constantsand constants
Instantiation statementInstantiation statementto instantiate the fullto instantiate the full
adder that is the moduleadder that is the moduleunder testunder test
CSE 467 18Verilog Digital System Design
always always beginbeginifif (($time$time >= >= tlimittlimit) ) $stop$stop;;elseelse beginbegin
#17;#17;a = ~a;a = ~a;#13;#13;cici = ~ = ~cici;;#19;#19;b = ~b;b = ~b;
endendendend
endmoduleendmodule
After a wait of 17ns inputAfter a wait of 17ns inputaa is complemented is complemented
Fulladder Tester Procedural Description (Continued)Fulladder Tester Procedural Description (Continued)
Timing & Concurrency ExampleTiming & Concurrency Example
Applies test data toApplies test data tothe ports of thethe ports of the
circuit being tested.circuit being tested.
A concurrent structureA concurrent structureon the outside, but hason the outside, but has
a procedural body.a procedural body.Checks the simulationChecks the simulationtime and if it exceedstime and if it exceeds
tlimittlimit it stops theit stops thesimulation.simulation.
10
CSE 467 19Verilog Digital System Design
Now we are going to see:Now we are going to see: How modules are developedHow modules are developed How names, numbers and operators are usedHow names, numbers and operators are used
Module BasicsModule Basics
CSE 467 20Verilog Digital System Design
Module BasicsModule BasicsModuleModule
BasicsBasics
Wires andWires andVariablesVariables ModulesModules
CodeCodeFormatFormat
Logic ValueLogic ValueSystemSystem
ModuleModulePortsPorts NamesNames NumbersNumbers
ArraysArrays VerilogVerilogOperatorsOperators
VerilogVerilogData TypesData Types
ArrayArrayIndexingIndexing
11
CSE 467 21Verilog Digital System Design
Code FormatCode FormatModuleModule
BasicsBasics
Wires andWires andVariablesVariables ModulesModules
CodeCodeFormatFormat
Logic ValueLogic ValueSystemSystem
ModuleModulePortsPorts NamesNames NumbersNumbers
ArraysArrays VerilogVerilogOperatorsOperators
VerilogVerilogData TypesData Types
ArrayArrayIndexingIndexing
CodeCodeFormatFormat
CSE 467 22Verilog Digital System Design
Code FormatCode Format
Verilog code is free format.Verilog code is free format. Spaces and new lines are served as separators.Spaces and new lines are served as separators. It is case sensitive.It is case sensitive. Language keywords use lowercase characters.Language keywords use lowercase characters. A comment designator start with // makes the rest of line comment.A comment designator start with // makes the rest of line comment. The symbols /* The symbols /* …… */ bracket the section of code which is in between */ bracket the section of code which is in between
as a comment.as a comment.
12
CSE 467 23Verilog Digital System Design
Logic Value SystemLogic Value SystemModuleModule
BasicsBasics
Wires andWires andVariablesVariables ModulesModules
CodeCodeFormatFormat
Logic ValueLogic ValueSystemSystem
ModuleModulePortsPorts NamesNames NumbersNumbers
ArraysArrays VerilogVerilogOperatorsOperators
VerilogVerilogData TypesData Types
ArrayArrayIndexingIndexing
Logic ValueLogic ValueSystemSystem
CSE 467 24Verilog Digital System Design
Bit type, or bits of vectors or arrays, of Bit type, or bits of vectors or arrays, of Verilog Verilog wires and variables takewires and variables takethe the 4-value logic4-value logic value system. value system.
Values in this system areValues in this system are 0 0, , 11, , ZZ and and XX..
The values The values 00 and and 11 have Three modes: have Three modes: ForcingForcing,, Resistive Resistive and andCapacitiveCapacitive..
The The Z Z value represents an value represents an undrivenundriven, high impedance value., high impedance value.
The The XX value represent a conflict in multiple driving values, an unknown value represent a conflict in multiple driving values, an unknownor value of a variable not initialized.or value of a variable not initialized.
Logic Value SystemLogic Value System
13
CSE 467 25Verilog Digital System Design
Logic Values and ExamplesLogic Values and Examples
Logic Value SystemLogic Value System
0X 0
1 0
X0 1
1x 1
0 :
1 :
Z or z :
X or x :
0
z1
CSE 467 26Verilog Digital System Design
Wires and VariablesWires and VariablesModuleModule
BasicsBasics
Wires andWires andVariablesVariables ModulesModules
CodeCodeFormatFormat
Logic ValueLogic ValueSystemSystem
ModuleModulePortsPorts NamesNames NumbersNumbers
ArraysArrays VerilogVerilogOperatorsOperators
VerilogVerilogData TypesData Types
ArrayArrayIndexingIndexing
Wires andWires andVariablesVariables
14
CSE 467 27Verilog Digital System Design
Wires and Variables:Wires and Variables: netnet: represents a wire driven by a hardware structure or output of a: represents a wire driven by a hardware structure or output of a
gate.gate. regreg: represents a variable that can be assigned values in behavior: represents a variable that can be assigned values in behavior
description of a component in a Verilog procedural block.description of a component in a Verilog procedural block.
Wires and VariablesWires and Variables
CSE 467 28Verilog Digital System Design
ModulesModulesModuleModule
BasicsBasics
Wires andWires andVariablesVariables ModulesModules
CodeCodeFormatFormat
Logic ValueLogic ValueSystemSystem
ModuleModulePortsPorts NamesNames NumbersNumbers
ArraysArrays VerilogVerilogOperatorsOperators
VerilogVerilogData TypesData Types
ArrayArrayIndexingIndexing
ModulesModules
15
CSE 467 29Verilog Digital System Design
Module is the main structure of definition of hardware components andModule is the main structure of definition of hardware components andtestbenchstestbenchs..
Begins with Begins with modulemodule keyword and end with keyword and end with endmoduleendmodule.. Immediately following the Immediately following the modulemodule keyword, port list of the module keyword, port list of the module
appears enclosed in parenthesis.appears enclosed in parenthesis.
ModulesModules
CSE 467 30Verilog Digital System Design
`timescale`timescale 1ns/100ps 1ns/100psmodulemodule FlipFlopFlipFlop (preset, reset, din, (preset, reset, din, clkclk, , qoutqout););
input input preset, reset, din, preset, reset, din, clkclk;;outputoutput qoutqout;;regreg qoutqout;;alwaysalways @ ( @ (posedgeposedge clkclk) ) beginbegin
ifif (reset) (reset) qoutqout <= #7 0; <= #7 0;else ifelse if (preset) (preset) qoutqout <= #7 1; <= #7 1;elseelse qoutqout <= #8 din; <= #8 din;
endendendmoduleendmodule
Ports are only listed in thePorts are only listed in theport list and declared asport list and declared as
separate input and outputseparate input and outputports inside the body ofports inside the body ofthe Flip-Flop module.the Flip-Flop module.
ModulesModules
Separate Port Declarations StatementsSeparate Port Declarations Statements
16
CSE 467 31Verilog Digital System Design
Module PortsModule PortsModuleModule
BasicsBasics
Wires andWires andVariablesVariables ModulesModules
CodeCodeFormatFormat
Logic ValueLogic ValueSystemSystem
ModuleModulePortsPorts NamesNames NumbersNumbers
ArraysArrays VerilogVerilogOperatorsOperators
VerilogVerilogData TypesData Types
ArrayArrayIndexingIndexing
ModuleModulePortsPorts
CSE 467 32Verilog Digital System Design
Inputs and outputs of a model must be declared as:Inputs and outputs of a model must be declared as: inputinput outputoutput inoutinout
By default, all declared ports are regarded as By default, all declared ports are regarded as netnets and the default nets and the default nettype is used for the ports.type is used for the ports.
Ports declared as Ports declared as outputoutput may be declared as may be declared as regreg..This way they can be assigned values in procedural blocks.This way they can be assigned values in procedural blocks.
An An inoutinout port can be used only as a port can be used only as a net net. To assign values to an . To assign values to an inoutinoutport in procedural bodies, a port in procedural bodies, a regreg corresponding to the port must becorresponding to the port must bedeclared and used.declared and used.
For an output, a For an output, a regreg specification can follow the specification can follow the outputoutput keyword in the keyword in theport list of the module.port list of the module.
Module PortsModule Ports
17
CSE 467 33Verilog Digital System Design
NamesNamesModuleModule
BasicsBasics
Wires andWires andVariablesVariables ModulesModules
CodeCodeFormatFormat
Logic ValueLogic ValueSystemSystem
ModuleModulePortsPorts NamesNames NumbersNumbers
ArraysArrays VerilogVerilogOperatorsOperators
VerilogVerilogData TypesData Types
ArrayArrayIndexingIndexing
NamesNames
CSE 467 34Verilog Digital System Design
A stream of characters starting with a letter or an underscore forms aA stream of characters starting with a letter or an underscore forms aVerilog identifier.Verilog identifier.
The $ character and underscore are allowed in an identifier.The $ character and underscore are allowed in an identifier.
Verilog uses Verilog uses keywordskeywords that are all formed by streams of that are all formed by streams of lowercaselowercasecharacterscharacters..
The names of The names of system taskssystem tasks and and functionsfunctions begin with a begin with a $$ character. character. Compiler directive namesCompiler directive names are preceded by the are preceded by the `̀ (back single quote) (back single quote)
character. Example: character. Example: `timescale`timescale
NamesNames
18
CSE 467 35Verilog Digital System Design
The following are valid names for identifiers:The following are valid names for identifiers:
a_namea_name , name1 , _name , Name, , name1 , _name , Name,Name$ , name55 , _55name , setup,Name$ , name55 , _55name , setup,_$name._$name.
The following are Verilog keywords or system tasks.The following are Verilog keywords or system tasks.
$display$display, , defaultdefault, , $setup$setup,,beginbegin, , tri1tri1,, small small..
NamesNames
CSE 467 36Verilog Digital System Design
NumbersNumbersModuleModule
BasicsBasics
Wires andWires andVariablesVariables ModulesModules
CodeCodeFormatFormat
Logic ValueLogic ValueSystemSystem
ModuleModulePortsPorts NamesNames NumbersNumbers
ArraysArrays VerilogVerilogOperatorsOperators
VerilogVerilogData TypesData Types
ArrayArrayIndexingIndexing
NumbersNumbers
19
CSE 467 37Verilog Digital System Design
Constants in Verilog are Constants in Verilog are integerinteger or or realreal.. Specification of integers can include Specification of integers can include X X and and ZZ in addition to the in addition to the
standard standard 00 and and 11 logic values. logic values. Integers may beIntegers may be
Sized: Sized: Begins with the number of equivalent bitsBegins with the number of equivalent bits Unsized: Unsized: Without the number of bits specificationWithout the number of bits specification
The general format for a sized integers is:The general format for a sized integers is:number_of_bitsnumber_of_bits ‘‘ base_identifierbase_identifier digits digits
example: 6example: 6’’b101100b101100The base The base specifierspecifier is a single lower or uppercase character is a single lower or uppercase character bb, , dd, , oo or or hhwhich respectively stand forwhich respectively stand for binarybinary, , decimaldecimal, , octaloctal and and hexadecimalhexadecimalbases.bases.
NumbersNumbers
CSE 467 38Verilog Digital System Design
Optionally, the base-identifier can be preceded by the single characterOptionally, the base-identifier can be preceded by the single characterss (or (or S S) to indicate a) to indicate a signed signed quantity.quantity.
A A plus or minusplus or minus operator can be used on the left of the number operator can be used on the left of the numberspecification to change the specification to change the signsign of the number. of the number.
The The underscoreunderscore character (_) can be used anywhere in a number for character (_) can be used anywhere in a number forgroupinggrouping its bits or digits for readability purposes. its bits or digits for readability purposes.
Real constants in Verilog use the standard format as described byReal constants in Verilog use the standard format as described byIEEE std 754-1985, the IEEE standard for IEEE std 754-1985, the IEEE standard for double precision floating-double precision floating-pointpoint numbers. Examples: 1.9, 2.6E9, 0.1e-6, 315.96-12. numbers. Examples: 1.9, 2.6E9, 0.1e-6, 315.96-12.
NumbersNumbers
20
CSE 467 39Verilog Digital System Design
This is a positive constant.1001010100596
The 2’s complement (because of the minus sign)4-bit A is regarded as a signed number.
Signed 0110-4’shA
This is an 8-bit number treated as a 2’scomplement signed number.
Signed11111010011012’shA6
Hexadecimal XA is expanded to 12 bits byextending the left X.xxxxxxxx101012’hXA
Hexadecimal F is expanded to 8 bits by paddingzeros to its left.
11118’hF
This is the octal 752 with a 0 padded to its left tomake it a 10-bit number.11110101010’o752
This is the 2’s complement of the number in theabove example.11111011-8’b101
Binary equivalent of hex; underscore is ignored.1011011001112’h5B_3
Binary 101 is turned into an 8-bit number.1018’b101
Decimal 5 is interpreted as a 4-bit number.1014’d5
ExplanationBinaryEquivalentNumber representation
4’d5 101 Decimal 5 is interpreted as a 4-bitnumber. 8’b101 101 Binary 101 is turned into an 8-bitnumber. 12’h5B_3 10110110011 Binary equivalent of hex;
underscore is ignored.
12’shA6 Signed 111110100110 This is an 8-bit number treatedas
a 2’s complement signed number.
596 1001010100 This is a positive constant.
NumbersNumbers
-8’b101 11111011 This is the 2’scomplement of the number in the above example.10’o752 0111101010 This is the octal 752 with a 0 padded
to itself to make it a 10-bit number.
8’hF 00001111 Hexadecimal F is expanded to 8 bits by padding zeros to its left.
12’hxA xxxxxxxx1010 Hexadecimal XA is expanded to 12 bits by extending the left x.
-4’shA Signed 0110 The 2’s complement (because of the minus sign) 4-bit A is regarded as a
signed number.
Number RepresentationNumber RepresentationExamplesExamples
CSE 467 40Verilog Digital System Design
Integer ConstantsInteger Constants
NumbersNumbers`timescale`timescale 1ns/100ps 1ns/100ps
modulemodule NumberTestNumberTest;; regreg [11:0] a = 8'shA6; [11:0] a = 8'shA6; initialinitial $$displaybdisplayb ("a=", a); ("a=", a);
// a=111110100110// a=111110100110 regreg [11:0] b = 8'sh6A; [11:0] b = 8'sh6A; initialinitial $$displaybdisplayb ("b=", b); ("b=", b);
// b=000001101010// b=000001101010 regreg [11:0] c = 'shA6; [11:0] c = 'shA6; initialinitial $$displaybdisplayb ("c=", c); ("c=", c);
// c=000010100110// c=000010100110 regreg [11:0] d = 'sh6A; [11:0] d = 'sh6A; initialinitial $$displaybdisplayb ("d=", d); ("d=", d);
// d=000001101010// d=000001101010 regreg [11:0] e = -8'shA6; [11:0] e = -8'shA6;initialinitial $$displaybdisplayb ("e=", e); ("e=", e);
// e=000001011010// e=000001011010 .............................................. ..............................................
Variables Variables a a through through llare declared and initialized.are declared and initialized.$$displaybdisplayb tasks display the tasks display the
binary values .binary values .Display ResultsDisplay Results
21
CSE 467 41Verilog Digital System Design
Integer Constants (Continued)Integer Constants (Continued)
NumbersNumbers ......................................................................................................
regreg [11:0] f = -'shA6; [11:0] f = -'shA6; initialinitial $$displaybdisplayb ("f=", f); ("f=", f);// f=111101011010// f=111101011010
regreg [11:0] g = 9'shA6; [11:0] g = 9'shA6; initialinitial $$displaybdisplayb ("g=", g); ("g=", g);// g=000010100110// g=000010100110
regreg [11:0] h = 9'sh6A; [11:0] h = 9'sh6A; initialinitial $$displaybdisplayb ("h=", h); ("h=", h);// h=000001101010// h=000001101010
regreg [11:0] i = -9'shA6; [11:0] i = -9'shA6;initialinitial $$displaybdisplayb ("i=", i); ("i=", i);// i=111101011010// i=111101011010
regreg [11:0] j = -9'sh6A; [11:0] j = -9'sh6A;initialinitial $$displaybdisplayb ("j=", j); ("j=", j);// j=111110010110// j=111110010110
regreg [11:0] k = 596; [11:0] k = 596; initialinitial $$displaybdisplayb ("k=", k); ("k=", k);// k=001001010100// k=001001010100
regreg [11:0] l = -596; [11:0] l = -596; initialinitial $$displaybdisplayb ("l=", l); ("l=", l);// l=110110101100// l=110110101100
endmoduleendmodule
CSE 467 42Verilog Digital System Design
ArraysArraysModuleModule
BasicsBasics
Wires andWires andVariablesVariables ModulesModules
CodeCodeFormatFormat
Logic ValueLogic ValueSystemSystem
ModuleModulePortsPorts NamesNames NumbersNumbers
ArraysArrays VerilogVerilogOperatorsOperators
VerilogVerilogData TypesData Types
ArrayArrayIndexingIndexing
ArraysArrays
22
CSE 467 43Verilog Digital System Design
Verilog allows declaration and usage of multidimensional arrays forVerilog allows declaration and usage of multidimensional arrays fornetnets or s or regregss..
The following declares The following declares a_arraya_array as a two-dimensional array of 8-bitas a two-dimensional array of 8-bitwords:words: regreg [7:0] [7:0] a_arraya_array [0:1023][0:511]; [0:1023][0:511];
In an array declaration, the address range of the elements of the arrayIn an array declaration, the address range of the elements of the arraycomes after the name of the array.comes after the name of the array.
Range specificationsRange specifications are enclosed in are enclosed in square bracketssquare brackets.. The size and range specification of the elements of an array come afterThe size and range specification of the elements of an array come after
the the netnet type (e.g., type (e.g., wirewire) or) or regreg keyword. keyword. In the absence of a range specification before the name of the array, anIn the absence of a range specification before the name of the array, an
element size of one bit is assumed.element size of one bit is assumed.
ArraysArrays
CSE 467 44Verilog Digital System Design
ArraysArrays
Array SArray Structurestructures
07
Areg
7
0
Amem
// An 8-bit vector
reg [7:0] Areg;
// A memory of 8 one -bit elements
reg Amem [7:0];
23
CSE 467 45Verilog Digital System Design
7
0
0
7
3
// A two-dimensional memory of one -bit elements
reg Bmem [7:0] [0:3];
// A memory of four 8-bit words
reg [7:0] Cmem [0:3];
Bmem
Cmem
ArraysArrays
Array SArray Structurestructures (Continued) (Continued)
CSE 467 46Verilog Digital System Design
ArraysArrays
Array SArray Structurestructures
4
0
0
3
12
3
reg [2:0] Dmem [0:3] [0:4];
// A two-dimensional memory of 3-bit elements
Dmem
24
CSE 467 47Verilog Digital System Design
Verilog Verilog OperatorsOperatorsModuleModule
BasicsBasics
Wires andWires andVariablesVariables ModulesModules
CodeCodeFormatFormat
Logic ValueLogic ValueSystemSystem
ModuleModulePortsPorts NamesNames NumbersNumbers
ArraysArrays VerilogVerilogOperatorsOperators
VerilogVerilogData TypesData Types
ArrayArrayIndexingIndexing
VerilogVerilogOperatorsOperators
CSE 467 48Verilog Digital System Design
Verilog OperatorsVerilog Operators
Verilog OperationsVerilog Operations
Basic OPERATION DESCRIPTION RESULT
Relational
Arithmetic
OPERATION DESCRIPTION RESULT
Logical
Case
Equality
Boolean OPERATION DESCRIPTION RESULT
Logical
Bit -wise
Reduction
Concatenation
Replication
Concat
&& !
~ & ̂ ̂ ~ ~^
& ~& ~ ̂
^~ ~^
Simple logic
Vector logic
operation
Perform operation
on all bits
One-bit
One-bit
One-bit
One-bit
One-bit
Equality
not including Z , X
Equality
including Z , X
! =
!
Multi -bit
One-bitcompare
Basic arithmetic+ - * / **
> > = < <=
Logical Right
Logical Left
Arithmetic Right
Arithmetic Left
OPERATION DESCRIPTION RESULTShift
>>n
<<n
>>>n
<<<n
Zero-fill
Shift n places
Zero-fill
Shift n places
Multi -bit
Multi -bit
Multi -bit
Multi -bit
RESULT
Multi -bit
Multi -bit
OPERATION DESCRIPTION
{ }
{{ }}
Join bits
Join & Replicate
Conditional
Condition RESULT
Multi -bit
OPERATION DESCRIPTION
? : If -then-else
Basic OPERATION DESCRIPTION RESULT
Relational
Arithmetic Multi-bit
One-bitcompare
Basic arithmetic+ - * / **
> >= < <=OPERATION DESCRIPTION RESULT
Logical
Case
Equality
One-bit
One-bit
Equality
not including Z, X
Equality
including Z, X
!=
!==
===
==
Boolean OPERATION DESCRIPTION RESULT
Logical
Bit-wise
Reduction
&& !
~ & ^ ^~
~^
& ~& ~ ^
^~ ~^
Simple logic
Vector logic
operation
Perform operation
on all bits
One-bit
One-bit
One-bit
Logical Right
Logical Left
Arithmetic Right
Arithmetic Left
OPERATION DESCRIPTION RESULTShift
>>n
<<n
>>>n
<<<n
Zero-fill
Shift n places
Zero-fill
Shift n places
Multi-bit
Multi-bit
Multi-bit
Multi-bit
Concatenation
Replication
Concat RESULT
Multi-bit
Multi-bit
OPERATION DESCRIPTION
{ }
{{ }}
Join bits
Join & Replicate
Conditional
Condition RESULT
Multi-bit
OPERATION DESCRIPTION
? : If-then-else
25
CSE 467 49Verilog Digital System Design
Verilog Verilog OperatorsOperatorsVerilogVerilog
OperatorsOperators
BasicBasicOperatorsOperators
EqualityEqualityOperatorsOperators
BooleanBooleanOperatorsOperators
ShiftShiftOperatorsOperators
ConcatenationConcatenationOperatorsOperators
ConditionalConditionalOperatorsOperators
CSE 467 50Verilog Digital System Design
Basic OperatorsBasic OperatorsVerilogVerilog
OperatorsOperators
BasicBasicOperatorsOperators
EqualityEqualityOperatorsOperators
BooleanBooleanOperatorsOperators
ShiftShiftOperatorsOperators
ConcatenationConcatenationOperatorsOperators
ConditionalConditionalOperatorsOperators
BasicOperators
26
CSE 467 51Verilog Digital System Design
Arithmetic Operations in Verilog take bit, vector, integer and realArithmetic Operations in Verilog take bit, vector, integer and realoperands.operands.
Basic operators of Verilog are Basic operators of Verilog are ++, , --, , **, , // and and ****..
An An XX or a or a Z Z value in a bit of either of the operands of a multiplicationvalue in a bit of either of the operands of a multiplicationcauses the entire result of the multiply operation to become causes the entire result of the multiply operation to become XX..
Unary plus (+) and minus (Unary plus (+) and minus (−)−) are allowed in Verilog. These operators are allowed in Verilog. These operatorstake precedence over other arithmetic operators.take precedence over other arithmetic operators.
If any of the operands of a relational operator contain an If any of the operands of a relational operator contain an XX or a or a ZZ, then, thenthe result becomes the result becomes XX..
Basic OperatorsBasic Operators
CSE 467 52Verilog Digital System Design
Basic OperatorsBasic Operators
Examples of Basic OperationsExamples of Basic Operations
Example Results in25 * 8’b6 15025 + 8’b7 3225 / 8’b6 422 % 7 18'b10110011 > 8’b0011 14’b1011 < 10 04’b1Z10 < 4’b1100 x4’b1x10 < 4’b1100 x4’b1x10 <= 4’b1x10 x
27
CSE 467 53Verilog Digital System Design
Equality OperatorsEquality OperatorsVerilogVerilog
OperatorsOperators
BasicBasicOperatorsOperators
EqualityEqualityOperatorsOperators
BooleanBooleanOperatorsOperators
ShiftShiftOperatorsOperators
ConcatenationConcatenationOperatorsOperators
ConditionalConditionalOperatorsOperators
EqualityOperators
CSE 467 54Verilog Digital System Design
Equality operators are categorized into two groups:Equality operators are categorized into two groups: Logical:Logical: Compare their operands for equality (==) or inequality (!=) Compare their operands for equality (==) or inequality (!=)
Return a one-bit result, Return a one-bit result, 00,, 1 1, or , or ZZ
An An XX ambiguity arises when an ambiguity arises when an XX or a or a ZZ occurs in one of the operands. occurs in one of the operands.
Case: Case: Consider Consider XX and and ZZ values in comparing their operands. values in comparing their operands. The result is always The result is always 00 or or 11..
Equality OperatorsEquality Operators
28
CSE 467 55Verilog Digital System Design
Equality OperatorsEquality Operators
Example Results in8’b10110011 == 8’b10110011 18’b1011 == 8’b00001011 14’b1100 == 4’b1Z10 04’b1100 != 8’b100X 18’b1011 !== 8’b00001011 08’b101X === 8’b101X 1
Examples of Equality OperationsExamples of Equality Operations
CSE 467 56Verilog Digital System Design
Boolean OperatorsBoolean OperatorsVerilogVerilog
OperatorsOperators
BasicBasicOperatorsOperators
EqualityEqualityOperatorsOperators
BooleanBooleanOperatorsOperators
ShiftShiftOperatorsOperators
ConcatenationConcatenationOperatorsOperators
ConditionalConditionalOperatorsOperators
BooleanOperators
29
CSE 467 57Verilog Digital System Design
Boolean OperatorsBoolean Operators
If an If an X X or a or a Z Z appears in an operand of a logical operator, an appears in an operand of a logical operator, an XX will willresult.result.
The complement operatorThe complement operator ~ ~ results in results in 11 and and 00 for for 00 and and 11 inputs and inputs and XXfor for XX and and ZZ inputs. inputs.
CSE 467 58Verilog Digital System Design
Boolean OperatorsBoolean Operators
Bit-by-bit Bitwise and Reduction OperatorsBit-by-bit Bitwise and Reduction Operators
&
0
^~^0
0 1
0 0 0
0 1 x x
1 x x
1 1 1 1
1 x x
1 x0 x0
0
1
x
x x
x
0
x
0
1
x
x
x
x
x xx
x x x
1 x x
xx1
x
x
x
x
x
x
x
x
x
x
x
x
X
1
0
0 Z
Z
1
X
If an If an X X or a or a Z Z appears in an operand of a logical operator, an appears in an operand of a logical operator, an XX will willresult.result.
The complement operatorThe complement operator ~~ results in results in 11 and and 00 for for 00 and and 11 inputs and inputs and XXfor for XX and and ZZ inputs. inputs.
30
CSE 467 59Verilog Digital System Design
Boolean OperatorsBoolean Operators Complement reduction operations (Complement reduction operations (~&~&, , ~|~|, and , and ~^~^) perform reduction) perform reduction
first and then complement the result.first and then complement the result.
Logical, Bit-wise, and ReductionLogical, Bit-wise, and Reduction
Example Results in8’b01101110 && 4’b0 08’b01101110 || 4’b0 18’b01101110 && 8’b10010001 1! (8’b10010001) 18’b01101110 & 8’bxxzz1100 8’b0xx011008’b01101110 | 8’bxxzz1100 8'bx11x1110~& (4’b0xz1) 1~| (4’b0xz1) 0
CSE 467 60Verilog Digital System Design
Shift OperatorsShift OperatorsVerilogVerilog
OperatorsOperators
BasicBasicOperatorsOperators
EqualityEqualityOperatorsOperators
BooleanBooleanOperatorsOperators
ShiftShiftOperatorsOperators
ConcatenationConcatenationOperatorsOperators
ConditionalConditionalOperatorsOperators
Shift Operators
31
CSE 467 61Verilog Digital System Design
Shift OperatorsShift Operators
Logical shift operators (Logical shift operators (>>>> and and <<<< for shift right and left) fill the for shift right and left) fill thevacated bit positions with zeros.vacated bit positions with zeros.
Fill values for arithmetic shift operators depend on the type of theirFill values for arithmetic shift operators depend on the type of theirresults being signed or unsignedresults being signed or unsigned . .
Shift OperatorsShift Operators
Example Results in8’b0110_0111 << 3 8’b0011_1000
8’b0110_0111 << 1’bz 8’bxxxx_xxxx
Signed_LHS = 8’b1100_0000>>>2 8’b1111_0000
CSE 467 62Verilog Digital System Design
Concatenation OperatorsConcatenation OperatorsVerilogVerilog
OperatorsOperators
BasicBasicOperatorsOperators
EqualityEqualityOperatorsOperators
BooleanBooleanOperatorsOperators
ShiftShiftOperatorsOperators
ConcatenationConcatenationOperatorsOperators
ConditionalConditionalOperatorsOperators
ConcatenationOperators
32
CSE 467 63Verilog Digital System Design
Concatenation OperatorsConcatenation Operators
The notation used for this operator is a pair of curly brackets (The notation used for this operator is a pair of curly brackets ({...}{...}))enclosing all scalars and vectors that are being concatenated.enclosing all scalars and vectors that are being concatenated.
If a is a 4-bit If a is a 4-bit regreg and and aaaa is a 6-bit reg, is a 6-bit reg, the following assignment placesthe following assignment places1101 in a and 001001 in 1101 in a and 001001 in aaaa::
{a, {a, aaaa} = 10} = 10’’b1101001001b1101001001
CSE 467 64Verilog Digital System Design
Concatenation OperatorsConcatenation Operators
If the a and If the a and aaaa registers have the values assigned to them above, and registers have the values assigned to them above, andaaaaaa is a 16-bit reg data type, then the assignment, is a 16-bit reg data type, then the assignment,
aaaaaa = { = {aaaa, {2{a}}, 2, {2{a}}, 2’’b11}b11}
puts 001001_1101_1101_11 in puts 001001_1101_1101_11 in aaaaaa..
{a, 2{b,c}, 3{d}} {a, 2{b,c}, 3{d}} is equivalent to: {a, b, c, b, c, d, d, d} is equivalent to: {a, b, c, b, c, d, d, d}
{2{2’’b00, 3{2b00, 3{2’’01}, 201}, 2’’b11}b11} results in: 10 results in: 10’’b0001010111b0001010111
33
CSE 467 65Verilog Digital System Design
Conditional OperatorsConditional OperatorsVerilogVerilog
OperatorsOperators
BasicBasicOperatorsOperators
EqualityEqualityOperatorsOperators
BooleanBooleanOperatorsOperators
ShiftShiftOperatorsOperators
ConcatenationConcatenationOperatorsOperators
ConditionalConditionalOperatorsOperators
ConditionalOperators
CSE 467 66Verilog Digital System Design
Conditional OperatorsConditional Operators
expression1 expression1 ?? expression2 expression2 : : expression3 expression3
If If expression1expression1 is is XX or or ZZ, both expressions 2 and 3 will be evaluated, and, both expressions 2 and 3 will be evaluated, andthe result becomes the bit-by-bit combination of these two expressions.the result becomes the bit-by-bit combination of these two expressions.
If If expression1expression1 is true, then is true, then expression2expression2 is isselected as the result of theselected as the result of the
operation; otherwise operation; otherwise expression3expression3 is isselected.selected.
……assign a = (b == c)? 1 : 0;assign a = (b == c)? 1 : 0;……
34
CSE 467 67Verilog Digital System Design
Conditional OperatorsConditional Operators
Conditional OperatorsConditional Operators
Example Results in
1 ? 4’b1100 : 4’b|ZX0 4’b1100
0 ? 4’b1100 : 4’b1ZX0 4’b1ZX0
X ? 4’b1100 : 4’b1ZX0 4’b1XX0
CSE 467 68Verilog Digital System Design
Precedence of OperatorsPrecedence of Operators
Operator PrecedenceOperator Precedence
+ - ! ~
* *
* / %+ -
<< >> <<< >>>
< <= > >=
== ! = === !==
& ~ &
^ ^~ ~^
~
& &
? :
Highest
Lowest
35
CSE 467 69Verilog Digital System Design
Precedence of OperatorsPrecedence of Operators
Precedence ExamplesPrecedence Examples
W & X + Y
+
&
+&
&&
A & B C D+&&
CSE 467 70Verilog Digital System Design
Verilog Verilog Data TypesData TypesModuleModule
BasicsBasics
Wires andWires andVariablesVariables ModulesModules
CodeCodeFormatFormat
Logic ValueLogic ValueSystemSystem
ModuleModulePortsPorts NamesNames NumbersNumbers
ArraysArrays VerilogVerilogOperatorsOperators
VerilogVerilogData TypesData Types
ArrayArrayIndexingIndexing
VerilogVerilogData TypesData Types
36
CSE 467 71Verilog Digital System Design
Verilog Data TypesVerilog Data Types
VerilogVerilogData TypesData Types
Net Net DeclarationsDeclarations
RegRegDeclarationsDeclarations
SignedSignedDataData ParametersParameters
CSE 467 72Verilog Digital System Design
Net DeclarationsNet Declarations
VerilogVerilogData TypesData Types
Net Net DeclarationsDeclarations
RegRegDeclarationsDeclarations
SignedSignedDataData ParametersParameters
Net Declarations
37
CSE 467 73Verilog Digital System Design
Net DeclarationsNet Declarations
Types Types wirewire and and tritri, , wandwand and and triandtriand, and , and worwor and and triortrior are equivalent.are equivalent.
Types Types supply0supply0 and and supply1supply1 are used for declaring signal names for supply are used for declaring signal names for supplyvoltages.voltages.
The The triregtrireg net type declares three-state capacitive signals.net type declares three-state capacitive signals.
Other net types (Other net types (wirewire, , wandwand and and worwor or their equivalents, or their equivalents, tritri, , triandtriandand and triortrior ) declare state signals that allow multiple driving sources.) declare state signals that allow multiple driving sources.
CSE 467 74Verilog Digital System Design
Net DeclarationsNet Declarations
This statement declares wires used between gates or BooleanThis statement declares wires used between gates or Booleanexpressions representing logic structures.expressions representing logic structures.
wirewire w, n, m, p; w, n, m, p;
By default, ports of a module are net of By default, ports of a module are net of wirewire type. type.
The The Z Z value is the weakest and is overridden by non-Z values fromvalue is the weakest and is overridden by non-Z values fromother driving sources.other driving sources.
38
CSE 467 75Verilog Digital System Design
Net DeclarationsNet Declarations
Driving a Driving a wirewire with multiple 0 and 1 conflicting values resolves in the X with multiple 0 and 1 conflicting values resolves in the Xvalue for the value for the wirewire..
The The wandwand and and worwor type nets signify wired-and and wired-or functions,type nets signify wired-and and wired-or functions,respectively.respectively.
For For wandwand type, a 0 value on a driving source overrides all other source type, a 0 value on a driving source overrides all other sourcevalues and value Z is treated as null and is overridden by any othervalues and value Z is treated as null and is overridden by any othervalue driving a value driving a wandwand net. net.
In In worwor operation, logic value 1 on one source overrides all other sourceoperation, logic value 1 on one source overrides all other sourcevalues. As in values. As in wandwand, the Z value is the weakest and is overridden by 0, 1, the Z value is the weakest and is overridden by 0, 1and X values.and X values.
CSE 467 76Verilog Digital System Design
Net DeclarationsNet Declarations
net net Types and Properties Types and Properties
NET TYPES PROPERTIES INITIAL
0
1
Driven: XNot Driven: Z
Not Driven: Z
Driven: X
Driven: X
Not Driven: Z
X
Driven: 0
Driven: 1
Tri -state wired
logic
Wired-and
logic
Wired-orlogic
Hold old value
supply0
supply1
wire (tri)
wand (triand)
wor (trior)
trireg
Supply
Three-state
Capacitive
39
CSE 467 77Verilog Digital System Design
Net DeclarationsNet Declarations
wire netwire net type type
s1
s2
wire value
s1
s2 0 1 X Z
0
1
X
Z
0 X X 0
X
X
0 1
1 1
X X X
X
X
Z
CSE 467 78Verilog Digital System Design
wand value
wor value
s1
s1
s2
s2
s1
s2 0 1 X Z
0
1
X
Z
0 0 0 0
0
0
0 1
1 1
X X X
X
X
Z
s1
s2 0 1 X Z
0
1
X
Z
0 1 X 0
1
X
0 1
1 1
1 X X
X
1
Z
Net DeclarationsNet Declarations
(a) (a) wand netwand net Types, (b) Types, (b) worwor net net Type Type
40
CSE 467 79Verilog Digital System Design
Net DeclarationsNet Declarations
The The triregtrireg type net behaves as a capacitive wire and holds its old value type net behaves as a capacitive wire and holds its old valuewhen a new resolved value is to become Z. As long as there is at leastwhen a new resolved value is to become Z. As long as there is at leastone driver with 0, 1, or X value, one driver with 0, 1, or X value, triregtrireg behaves the same as wire. When all behaves the same as wire. When alldrivers are turned off (Z), a drivers are turned off (Z), a triregtrireg net retains its previous value. net retains its previous value.
The amount of time a The amount of time a triregtrireg net holds a value is specified by a delay net holds a value is specified by a delayparameter in its declaration. Delay parameters will be discussed next.parameter in its declaration. Delay parameters will be discussed next.Chapter 7 shows examples of using Chapter 7 shows examples of using triregtrireg for CMOS flip-flop modeling. for CMOS flip-flop modeling.
CSE 467 80Verilog Digital System Design
Net DeclarationsNet Declarations
Three delay values for net switching to 1, to 0, and to Z are specified inThree delay values for net switching to 1, to 0, and to Z are specified ina set of parenthesis that are followed by a # sign after the net typea set of parenthesis that are followed by a # sign after the net typekeyword. A simpler format contains a single delay value.keyword. A simpler format contains a single delay value.
wirewire #3 w, n, m, p; #3 w, n, m, p;
41
CSE 467 81Verilog Digital System Design
Net DeclarationsNet Declarations
triregtrireg net types may also be declared with three delay parameters. net types may also be declared with three delay parameters.Unlike the case with other nets, in this case the third timing parameterUnlike the case with other nets, in this case the third timing parameteris not delay for the Z transition. Instead, this specifies the time that ais not delay for the Z transition. Instead, this specifies the time that adeclared declared triregtrireg net holds an old value when driven by Z. net holds an old value when driven by Z.
The initial value for all net types except The initial value for all net types except supply0supply0 and and supply1supply1 with at least with at leastone driver is X. A net with no driver assumes the Z value, except forone driver is X. A net with no driver assumes the Z value, except fortriregtrireg, which has the initial value X., which has the initial value X.
CSE 467 82Verilog Digital System Design
Reg DeclarationsReg Declarations
VerilogVerilogData TypesData Types
Net Net DeclarationsDeclarations
RegRegDeclarationsDeclarations
SignedSignedDataData ParametersParameters
RegDeclarations
42
CSE 467 83Verilog Digital System Design
Reg DeclarationsReg Declarations
regreg is a variable for holding intermediate signal values or is a variable for holding intermediate signal values or nonhardwarenonhardwareparameters and function values.parameters and function values.
The The regreg declaration shown below declares a, b and declaration shown below declares a, b and cici as as regreg types with types with0 initial values.0 initial values.
regreg a=0, b=0, a=0, b=0, cici=0;=0;
The default initial value of a declared The default initial value of a declared regreg is (X). is (X).
CSE 467 84Verilog Digital System Design
Reg DeclarationsReg Declarations
Other reg types are integer and time. An integer declaration declares aOther reg types are integer and time. An integer declaration declares asigned 2s-complement number, and a time declaration declares ansigned 2s-complement number, and a time declaration declares anunsigned reg variable of at least 64 bits.unsigned reg variable of at least 64 bits.
Verilog also allows declaration of real and realtime variables. TheseVerilog also allows declaration of real and realtime variables. Thesevariables are similar in use to integer and time variables, but do notvariables are similar in use to integer and time variables, but do nothave direct bit-to-bit correspondence with reg type registers.have direct bit-to-bit correspondence with reg type registers.
43
CSE 467 85Verilog Digital System Design
Signed DataSigned Data
VerilogVerilogData TypesData Types
Net Net DeclarationsDeclarations
RegRegDeclarationsDeclarations
SignedSignedDataData ParametersParameters
SignedData
CSE 467 86Verilog Digital System Design
Signed DataSigned Data
Verilog net and reg types can be declared as signed. In below exampleVerilog net and reg types can be declared as signed. In below examplearegareg is declared as a signed reg. is declared as a signed reg.
regreg signedsigned [15:0] [15:0] aregareg;;
A signed reg that is shifted right by the >>> operator is sign filled,A signed reg that is shifted right by the >>> operator is sign filled,whereas an unsigned reg shifted by this operator is zero-filled.whereas an unsigned reg shifted by this operator is zero-filled.
If the right-hand side of an assignment is determined as signed, it isIf the right-hand side of an assignment is determined as signed, it issign extended to the size of its left hand side and is placed on the leftsign extended to the size of its left hand side and is placed on the lefthand side reg or net.hand side reg or net.
44
CSE 467 87Verilog Digital System Design
ParametersParameters
VerilogVerilogData TypesData Types
Net Net DeclarationsDeclarations
RegRegDeclarationsDeclarations
SignedSignedDataData ParametersParametersParameters
CSE 467 88Verilog Digital System Design
ParametersParameters
Parameters in Verilog do not belong to either the variable or the netParameters in Verilog do not belong to either the variable or the netgroup. Parameters are constants and cannot be changed at runtime.group. Parameters are constants and cannot be changed at runtime.Parameters can be declared as signed, real, integer, time or realtime.Parameters can be declared as signed, real, integer, time or realtime.
Example Explanationparameter p1=5, p2=6; 32 bit parametersparameter [4:0] p1=5, p2=6; 5 bit parameters parameter integer p1=5; 32 bit parametersparameter signed [4:0] p1=5; 5 bit signed parameters
Parameter ExamplesParameter Examples
45
CSE 467 89Verilog Digital System Design
Array IndexingArray IndexingModuleModule
BasicsBasics
Wires andWires andVariablesVariables ModulesModules
CodeCodeFormatFormat
Logic ValueLogic ValueSystemSystem
ModuleModulePortsPorts NamesNames NumbersNumbers
ArraysArrays VerilogVerilogOperatorsOperators
VerilogVerilogData TypesData Types
ArrayArrayIndexingIndexing
ArrayArrayIndexingIndexing
CSE 467 90Verilog Digital System Design
Array IndexingArray Indexing
Array Array IndexingIndexing
BitBitSelectionSelection
PartPartSelectionSelection
StandardStandardMemoryMemory
Multi Multi DimensionalDimensional Memories Memories
46
CSE 467 91Verilog Digital System Design
Bit SelectionBit Selection
Array Array IndexingIndexing
BitBitSelectionSelection
PartPartSelectionSelection
StandardStandardMemoryMemory
Multi Multi DimensionalDimensional Memories Memories
BitSelection
CSE 467 92Verilog Digital System Design
Bit SelectionBit Selection
Bit-select and part-select operators are used for extracting a bit or aBit-select and part-select operators are used for extracting a bit or agroup of bits from a declared array.group of bits from a declared array.
regreg [7:0] [7:0] AregAreg;; regreg AmemAmem [7:0]; [7:0]; regreg DmemDmem [7:0][0:3]; [7:0][0:3]; regreg [7:0] [7:0] CmemCmem [0:3]; [0:3]; regreg [2:0] [2:0] DmemDmem [0:3][0:4]; [0:3][0:4];
Bit-selection is done by using the addressed bit number in a set ofBit-selection is done by using the addressed bit number in a set ofsquare brackets. For example Areg[5] selects bit 5 of the square brackets. For example Areg[5] selects bit 5 of the AregAreg array. array.
47
CSE 467 93Verilog Digital System Design
Part SelectionPart Selection
Array Array IndexingIndexing
BitBitSelectionSelection
PartPartSelectionSelection
StandardStandardMemoryMemory
Multi Multi DimensionalDimensional Memories Memories
PartSelection
CSE 467 94Verilog Digital System Design
Part SelectionPart Selection
Verilog allows constant and indexed part-select. For example, Areg[7:3]Verilog allows constant and indexed part-select. For example, Areg[7:3]selects the upper five bits of selects the upper five bits of AregAreg..
AregAreg [5:3] [5:3] //selects bits 5, 4 and 3//selects bits 5, 4 and 3AregAreg [5-:4] [5-:4] //selects bits 5, 4, 3 and 2//selects bits 5, 4, 3 and 2AregAreg [2+:4] [2+:4] //selects bits 5, 4, 3 and 2//selects bits 5, 4, 3 and 2
48
CSE 467 95Verilog Digital System Design
Standard MemoryStandard Memory
Array Array IndexingIndexing
BitBitSelectionSelection
PartPartSelectionSelection
StandardStandardMemoryMemory
Multi Multi DimensionalDimensional Memories Memories
StandardMemory
CSE 467 96Verilog Digital System Design
Standard MemoryStandard Memory
The standard format for declaring a memory in The standard format for declaring a memory in Verilog Verilog is to declare itis to declare itas an array of a vector.as an array of a vector.
regreg [7:0] [7:0] Emem Emem [0:1023];[0:1023]; Cmem Cmem [[AregAreg[7:6]][7:6]] Emem Emem [[EmemEmem[0]][0]] Emem Emem [355][3:0][355][3:0] Emem Emem [355][3-:4][355][3-:4] Emem Emem [355:358][355:358]
EmemEmem as a byte-oriented as a byte-orientedmemory with a 10 bit addressmemory with a 10 bit address
(1024 address space)(1024 address space)
extracts extracts CmemCmem word wordaddressed byaddressed by
Areg[7:6]Areg[7:6]
4 bits starting4 bits startingfrom 3, downfrom 3, down
4 LSB of location 355
Extracts Extracts EmemEmem word wordaddressed byaddressed by
Emem[0]Emem[0]
Illegal; Does not addressIllegal; Does not addressa 4-word blocka 4-word block
49
CSE 467 97Verilog Digital System Design
Multi-Dimensional MemoriesMulti-Dimensional Memories
Array Array IndexingIndexing
BitBitSelectionSelection
PartPartSelectionSelection
StandardStandardMemoryMemory
Multi Multi DimensionalDimensional
Memory Memory
Multi Dimensional Memories
CSE 467 98Verilog Digital System Design
Multi-Dimensional MemoriesMulti-Dimensional Memories
For accessing such memories (e.g. For accessing such memories (e.g. DmemDmem declared before), simple declared before), simpleindexing are allowed for specifying a word in the memory, and bit-indexing are allowed for specifying a word in the memory, and bit-select and part-select are allowed for accessing bit or bits of theselect and part-select are allowed for accessing bit or bits of theaddressed word.addressed word.
50
CSE 467 99Verilog Digital System Design
Array Addressing & Selection Array Addressing & Selection
Multi-Dimensional MemoriesMulti-Dimensional Memories 07
Areg
7
0
Amem
0
7
0
3
0
07
3
// declaration : reg [7 :0 ] Areg ;
Areg [7 :5]
// declaration : reg Amem [ 7 :0 ];
Amem [3]
// declaration : reg Bmem [7:0][0 :3]
Bmem [2] [1 ]
// declaration : reg [7:0 ] Cmem [0:3]
Cmem [1] [6 -: 4]
// declaration : reg [ 2 :0 ] Dmem [0:3][0 :4]
Dmem [0] [2]
Bmem
Cmem
Dmem
3
0
01
23
4
7
Areg// declaration : reg [7:0] Areg;
Areg [7:5]7
0
Amem// declaration : reg Amem [ 7 :0 ];
Amem [3]
0
7
0
// declaration : reg Bmem [7:0][0:3]
Bmem [2] [1]
Bmem
0
07
3
// declaration : reg [7:0 ] Cmem [0:3]
Cmem [1] [6 -: 4] Cmem
// declaration : reg [ 2:0] Dmem [0:3][0:4]Dmem [0] [2]
Dmem
3
0
01
23
4
CSE 467 100Verilog Digital System Design
Verilog Simulation ModelVerilog Simulation Model
Verilog Verilog Simulation Simulation
ModelModel
ContinuousContinuousAssignmentsAssignments
ProceduralProceduralAssignmentsAssignments
51
CSE 467 101Verilog Digital System Design
Continuous AssignmentsContinuous Assignments
Verilog Verilog Simulation Simulation
ModelModel
ContinuousContinuousAssignmentAssignment
ProceduralProceduralAssignmentsAssignments
ContinuousAssignments
CSE 467 102Verilog Digital System Design
Continuous AssignmentsContinuous AssignmentsContinuousContinuous
AssignmentsAssignments
SimpleSimpleAssignmentsAssignments
DelayDelaySpecificationSpecification
StrengthStrengthSpecificationSpecification
Net DeclarationNet DeclarationAssignmentsAssignments
MultipleMultipleDrivesDrives
52
CSE 467 103Verilog Digital System Design
Simple AssignmentsSimple AssignmentsContinuousContinuous
AssignmentsAssignments
SimpleSimpleAssignmentsAssignments
DelayDelaySpecificationSpecification
StrengthStrengthSpecificationSpecification
Net DeclarationNet DeclarationAssignmentsAssignments
MultipleMultipleDrivesDrives
SimpleSimpleAssignmentsAssignments
CSE 467 104Verilog Digital System Design
Simple AssignmentsSimple Assignments
A continuous assignment in Verilog is used only in concurrent VerilogA continuous assignment in Verilog is used only in concurrent Verilogbodies.bodies.
This assignment represents a net driven by a gate output or a logicThis assignment represents a net driven by a gate output or a logicfunction. function.
assignassign w = m | p; w = m | p;
53
CSE 467 105Verilog Digital System Design
Delay SpecificationDelay SpecificationContinuousContinuous
AssignmentsAssignments
SimpleSimpleAssignmentsAssignments
DelayDelaySpecificationSpecification
StrengthStrengthSpecificationSpecification
Net DeclarationNet DeclarationAssignmentsAssignments
MultipleMultipleDrivesDrives
DelayDelaySpecificationSpecification
CSE 467 106Verilog Digital System Design
Delay SpecificationDelay Specification
assignassign #2 w = m | p; #2 w = m | p;
This assignment becomes active when m or p changes. At this time,This assignment becomes active when m or p changes. At this time,the new value of the m | p expression is evaluated, and after a wait timethe new value of the m | p expression is evaluated, and after a wait timeof 2 time units, this new value is assigned to w.of 2 time units, this new value is assigned to w.
54
CSE 467 107Verilog Digital System Design
Delay SpecificationDelay Specification
`timescale `timescale 1ns/100ps1ns/100ps
module module Mux2to1 (Mux2to1 (input input a, b, c,a, b, c, output output w);w); wire wire n, m, p;n, m, p; assign assign #3 m = a & b;#3 m = a & b; assign assign #3 p = n & c;#3 p = n & c; assign assign #6 n = ~b;#6 n = ~b; assign assign #2 w = m | p;#2 w = m | p;endmoduleendmodule
Regardless of position in theRegardless of position in thecode, each assignment waits forcode, each assignment waits for
a right-hand-side variable toa right-hand-side variable tochange for it to execute.change for it to execute.
ConcurrentConcurrent ContinuousContinuous AssignmentsAssignments
CSE 467 108Verilog Digital System Design
Delay SpecificationDelay Specification
Simulation Run Showing a GlitchSimulation Run Showing a Glitch
The simulation of the previousThe simulation of the previouscircuit results in a glitch due to acircuit results in a glitch due to a1-hazard on w. The event driven1-hazard on w. The event driven
simulation of concurrent statementssimulation of concurrent statementsmakes this simulation to correspondmakes this simulation to correspond
to events in the actual circuit.to events in the actual circuit.
55
CSE 467 109Verilog Digital System Design
Strength SpecificationStrength SpecificationContinuousContinuous
AssignmentsAssignments
SimpleSimpleAssignmentsAssignments
DelayDelaySpecificationSpecification
StrengthStrengthSpecificationSpecification
Net DeclarationNet DeclarationAssignmentsAssignments
MultipleMultipleDrivesDrives
StrengthStrengthSpecificationSpecification
CSE 467 110Verilog Digital System Design
Simple AssignmentsSimple Assignments
Net strengths are specified by a pair of strength values bracketed by aNet strengths are specified by a pair of strength values bracketed by aset of parenthesis, as shown below.set of parenthesis, as shown below.
assignassign ( (strong0strong0, , strong1strong1) w = m | p;) w = m | p;
One strength value is for logic 1 and one is for logic 0, and the order inOne strength value is for logic 1 and one is for logic 0, and the order inwhich the strength values appear in the set of parenthesis is notwhich the strength values appear in the set of parenthesis is notimportant.important.
Strength value names for logic 1 end with a 1 (Strength value names for logic 1 end with a 1 (supply1supply1,,strong1strong1, , pull1pull1, , weak1weak1, , ……) and those for logic 0 end with a 0 () and those for logic 0 end with a 0 (supply0supply0, , strong0strong0,,pull0pull0, , weak0weak0, , ……).).
56
CSE 467 111Verilog Digital System Design
Wires (tri) wand (triand),Wor ( trior), tri0, tri1
Strength value
Supply 0
Strong 0
Pull 0
Weak 0
Highz 0
Highz 1
Weak 1
Pull 1
Strong1
Supply 1
trireg
Level Strength values
7
6
5
4
3
2
1
0
0
1
2
3
4
5
6
7
Large
Medium (0)
Small (0)
Small (1)
Medium (1)
Large (1)
Strength 0
Strength 1
Weak values
Strength SpecificationStrength Specification
net Types and Their Strengthsnet Types and Their Strengths
For wire and tri type nets, driveFor wire and tri type nets, drivestrength values are used, and forstrength values are used, and for
storage nets charge strength is used.storage nets charge strength is used.
Default values for these netsDefault values for these netsare strong0 and strong1 forare strong0 and strong1 for
logic 0 and logic 1 respectively.logic 0 and logic 1 respectively.
Three strength values, large, medium,Three strength values, large, medium,and small, are used for and small, are used for triregtrireg net types, net types,
and the default is medium.and the default is medium.
CSE 467 112Verilog Digital System Design
Net Declaration AssignmentsNet Declaration AssignmentsContinuousContinuous
AssignmentsAssignments
SimpleSimpleAssignmentsAssignments
DelayDelaySpecificationSpecification
StrengthStrengthSpecificationSpecification
Net DeclarationNet DeclarationAssignmentsAssignments
MultipleMultipleDrivesDrives
Net DeclarationNet DeclarationAssignmentsAssignments
57
CSE 467 113Verilog Digital System Design
Net Declaration AssignmentsNet Declaration Assignments
`timescale `timescale 1ns/100ps1ns/100ps
module module Mux2to1 (Mux2to1 (input input a, b, c,a, b, c, output output w);w); wire wire #3#3 m = a & b, m = a & b, p = n & c, p = n & c, n = ~b, n = ~b, w = m | p; w = m | p;endmoduleendmodule
In this code, all the continuousIn this code, all the continuousassignments of previous code areassignments of previous code are
replaced by a list of net declarationreplaced by a list of net declarationassignments providing drivers forassignments providing drivers for
ww, , nn, , mm and and pp signals. signals.
Using Using net_declaration_assignmentnet_declaration_assignment
CSE 467 114Verilog Digital System Design
Multiple DrivesMultiple DrivesContinuousContinuous
AssignmentsAssignments
SimpleSimpleAssignmentsAssignments
DelayDelaySpecificationSpecification
StrengthStrengthSpecificationSpecification
Net DeclarationNet DeclarationAssignmentsAssignments
MultipleMultipleDrivesDrives
MultipleMultipleDrivesDrives
58
CSE 467 115Verilog Digital System Design
Multiple DrivesMultiple Drives
`timescale `timescale 1ns/100ps1ns/100ps
module module Mux2to1 (Mux2to1 (input input a, b, c,a, b, c, output output w);w); wire wire n; n; worwor #2 w; #2 w; assignassign #3 w = a & b; #3 w = a & b; assignassign #3 w = n & c; #3 w = n & c; assignassign #6 n = ~b; #6 n = ~b;endmoduleendmodule
A value assigned toA value assigned to w w is first is firstdelayed by continuous assignmentdelayed by continuous assignmentdelay. Before this value appears ondelay. Before this value appears on
ww, it is further delayed by 2 ns, it is further delayed by 2 nsspecified in specified in worwor declaration. declaration.
AA netnet with Multiple Driverswith Multiple Drivers
CSE 467 116Verilog Digital System Design
Multiple DrivesMultiple Drives
Simulation Run of Assignment StatementsSimulation Run of Assignment Statements
59
CSE 467 117Verilog Digital System Design
Procedural AssignmentsProcedural Assignments
Verilog Verilog Simulation Simulation
ModelModel
ContinuousContinuousAssignmentAssignment
ProceduralProceduralAssignmentAssignmentProcedural
Assignments
CSE 467 118Verilog Digital System Design
Procedural AssignmentsProcedural Assignments
Procedural assignments in Verilog take place in the Procedural assignments in Verilog take place in the initialinitial and and alwaysalwaysprocedural constructs, which are regarded as procedural bodies.procedural constructs, which are regarded as procedural bodies.
60
CSE 467 119Verilog Digital System Design
Procedural AssignmentsProcedural AssignmentsProceduralProcedural
AssignmentsAssignments
ProceduralProcedural Flow Control Flow Control
ProceduralProceduralBlockingBlocking
AssignmentsAssignments
ProceduralProceduralNon-blockingNon-blockingAssignmentsAssignments
MultipleMultipleAssignmentsAssignments
ProceduralProceduralContinuousContinuous
AssignmentsAssignments
ForceForceandand
ReleaseRelease
CSE 467 120Verilog Digital System Design
Procedural Flow ControlProcedural Flow ControlProceduralProcedural
AssignmentsAssignments
ProceduralProcedural Flow Control Flow Control
ProceduralProceduralBlockingBlocking
AssignmentsAssignments
ProceduralProceduralNon-blockingNon-blockingAssignmentsAssignments
MultipleMultipleAssignmentsAssignments
ProceduralProceduralContinuousContinuous
AssignmentsAssignments
ForceForceandand
ReleaseRelease
ProceduralProcedural Flow Control Flow Control
61
CSE 467 121Verilog Digital System Design
Procedural Flow ControlProcedural Flow Control
Statements in a procedural body are executed when program flowStatements in a procedural body are executed when program flowreaches them.reaches them.
Flow control statements are classified as delay control and eventFlow control statements are classified as delay control and eventcontrol.control.
An event or delay control statement in a procedural body causesAn event or delay control statement in a procedural body causesprogram flow to be put on hold temporarily.program flow to be put on hold temporarily.
CSE 467 122Verilog Digital System Design
Procedural Flow ControlProcedural Flow Control
Procedural Flow ControlProcedural Flow Control
always..
.@ (reset )
.
.
.end
always always..
.
.
.
.
.
.
.
.
.
.end end
#10@ (posedge CLK)
program flow stops when itprogram flow stops when itreaches the reaches the @ (reset)@ (reset)
statement and resumes whenstatement and resumes whenthe value of the value of resetreset changes. changes.
Program flow resumesProgram flow resumesafter the positive edge ofafter the positive edge of
the the clkclkProgram flow resumesProgram flow resumesafter being put on holdafter being put on hold
for 10 time units.for 10 time units.
62
CSE 467 123Verilog Digital System Design
Procedural Blocking AssignmentsProcedural Blocking AssignmentsProceduralProcedural
AssignmentsAssignments
ProceduralProcedural Flow Control Flow Control
ProceduralProceduralBlockingBlocking
AssignmentsAssignments
ProceduralProceduralNon-blockingNon-blockingAssignmentsAssignments
MultipleMultipleAssignmentsAssignments
ProceduralProceduralContinuousContinuous
AssignmentsAssignments
ForceForceandand
ReleaseRelease
ProceduralProceduralBlockingBlocking
AssignmentsAssignments
CSE 467 124Verilog Digital System Design
A blocking assignment uses a A blocking assignment uses a regreg data type on the left-hand side and data type on the left-hand side andan expression on the right-hand side of an equal sign.an expression on the right-hand side of an equal sign.
The syntax of intra-assignment control constructs is similar to that ofThe syntax of intra-assignment control constructs is similar to that ofprocedural flow control statements, but these constructs appear on theprocedural flow control statements, but these constructs appear on theright-hand side of an equal sign in a procedural assignment.right-hand side of an equal sign in a procedural assignment.
. . .; #200 a = #100 b;. . .; #200 a = #100 b;
Procedural Blocking AssignmentsProcedural Blocking Assignments
The procedural assignment thatThe procedural assignment thatis delayed by 200 time units by ais delayed by 200 time units by adelay control statement and bydelay control statement and by
100 time units by an intra-100 time units by an intra-assignment delay control.assignment delay control.
63
CSE 467 125Verilog Digital System Design
Procedural Blocking AssignmentsProcedural Blocking Assignments
initial begininitial begin : : Blocking_Assignment_to_bBlocking_Assignment_to_b b = 1; b = 1; #100 #100 b = #80 0; b = #120 1; b = #80 0; b = #120 1; #100 #100 $display$display ("Initial Block with Blocking Assignment ("Initial Block with Blocking Assignment
to b Ends at:", to b Ends at:", $time$time););endend The $displayThe $display
statement displays 400statement displays 400
Blocking Procedural AssignmentsBlocking Procedural Assignments
CSE 467 126Verilog Digital System Design
Procedural Non-blocking AssignmentsProcedural Non-blocking Assignments
ProceduralProceduralAssignmentsAssignments
ProceduralProcedural Flow Control Flow Control
ProceduralProceduralBlockingBlocking
AssignmentsAssignments
ProceduralProceduralNon-blockingNon-blockingAssignmentsAssignments
MultipleMultipleAssignmentsAssignments
ProceduralProceduralContinuousContinuous
AssignmentsAssignments
ForceForceandand
ReleaseRelease
ProceduralProceduralNon-blockingNon-blockingAssignmentsAssignments
64
CSE 467 127Verilog Digital System Design
Procedural Non-blockingProcedural Non-blockingAssignmentsAssignments
A non-blocking assignment uses the left arrow notation <= (leftA non-blocking assignment uses the left arrow notation <= (leftangular bracket followed by the equal sign) instead of the equal signangular bracket followed by the equal sign) instead of the equal signused in blocking assignments.used in blocking assignments.
When flow reaches a non-blocking assignment, the right-hand side ofWhen flow reaches a non-blocking assignment, the right-hand side ofthe assignment is evaluated and will be scheduled for the left-hand sidethe assignment is evaluated and will be scheduled for the left-hand sideregreg to take place when the intra-assignment control is satisfied. to take place when the intra-assignment control is satisfied.
CSE 467 128Verilog Digital System Design
Procedural Non-blockingProcedural Non-blockingAssignmentsAssignments
initial begininitial begin : : Non_blocking_Assignment_to_aNon_blocking_Assignment_to_a a = 1; a = 1; #100 #100 a <= #80 0; a <= #120 1; a <= #80 0; a <= #120 1; #100 #100 $display$display ("Initial Block with Non-blocking ("Initial Block with Non-blocking
Assignment to a Ends at:", Assignment to a Ends at:", $time$time););endend
The $displaystatement displays 200
Non-blocking Procedural AssignmentsNon-blocking Procedural Assignments
65
CSE 467 129Verilog Digital System Design
Procedural Non-blockingProcedural Non-blockingAssignmentsAssignments
Comparing Blocking and Non-blocking Procedural AssignmentsComparing Blocking and Non-blocking Procedural Assignments
CSE 467 130Verilog Digital System Design
Multiple AssignmentsMultiple AssignmentsProceduralProcedural
AssignmentsAssignments
ProceduralProcedural Flow Control Flow Control
ProceduralProceduralBlockingBlocking
AssignmentsAssignments
ProceduralProceduralNon-blockingNon-blockingAssignmentsAssignments
MultipleMultipleAssignmentsAssignments
ProceduralProceduralContinuousContinuous
AssignmentsAssignments
ForceForceandand
ReleaseRelease
MultipleMultipleAssignmentsAssignments
66
CSE 467 131Verilog Digital System Design
Multiple AssignmentsMultiple Assignments
If several assignments appear at the same real time in a proceduralIf several assignments appear at the same real time in a proceduralbody, the last assignment overrides all others.body, the last assignment overrides all others.
If program flow in two procedural bodies reaches assignments to theIf program flow in two procedural bodies reaches assignments to thesame same regreg at exactly the same time, the outcome of the value assigned to at exactly the same time, the outcome of the value assigned tothe left-hand side of the assignment will not be known.the left-hand side of the assignment will not be known.
CSE 467 132Verilog Digital System Design
initial begininitial begin clkclk = 0; = 0;endend
always beginalways begin clkclk = ~ = ~clkclk;; #17; #17;endend
Multiple AssignmentsMultiple Assignments
This code works properly only ifcomplementing of the clk is
delayed until the clk is initializedto 0 in the initial block.
Multiple Multiple regreg Assignments Assignments
67
CSE 467 133Verilog Digital System Design
initial begininitial begin clkclk = 0; = 0;endend
always beginalways begin #0;#0; clkclk = ~ = ~clkclk;; #17; #17;endend
Multiple AssignmentsMultiple Assignments
One way to correct this problemOne way to correct this problemis to delay complementing theis to delay complementing theclock by one simulation cycle.clock by one simulation cycle.
This can be done by inserting #0.This can be done by inserting #0.
Multiple Multiple regreg Assignments; Delay Used for Deterministic Results Assignments; Delay Used for Deterministic Results
CSE 467 134Verilog Digital System Design
Procedural Continuous AssignmentsProcedural Continuous Assignments
ProceduralProceduralAssignmentsAssignments
ProceduralProcedural Flow Control Flow Control
ProceduralProceduralBlockingBlocking
AssignmentsAssignments
ProceduralProceduralNon-blockingNon-blockingAssignmentsAssignments
MultipleMultipleAssignmentsAssignments
ProceduralProceduralContinuousContinuous
AssignmentsAssignments
ForceForceandand
ReleaseRelease
ProceduralProceduralContinuousContinuous
AssignmentsAssignments
68
CSE 467 135Verilog Digital System Design
Using a procedural continuous assignment construct, an assignment toUsing a procedural continuous assignment construct, an assignment toa a regreg type variable can be made to stop all other assignments to this type variable can be made to stop all other assignments to thisvariable from taking place.variable from taking place. deassigndeassign qoutqout <= 0; <= 0;
Unlike assign and Unlike assign and deassigndeassign, which apply to , which apply to regreg type variables, force type variables, forceand release constructs apply to net and and release constructs apply to net and regreg types. types.
Procedural ContinuousProcedural ContinuousAssignmentsAssignments
While qout is not deassigned,no other assignmentsto it affect its value.
CSE 467 136Verilog Digital System Design
`timescale 1ns/100ps`timescale 1ns/100ps
module module FlipflopAssignFlipflopAssign ( (input input reset, din, reset, din, clkclk,, output outputqoutqout););
regreg qoutqout;; always always @(reset)@(reset) begin begin if if (reset) (reset) assignassign qoutqout <= 0; <= 0; else else deassigndeassign qoutqout;; end end always always @(@(posedgeposedge clkclk)) begin begin qoutqout <= din; <= din; end endendmoduleendmodule
Procedural ContinuousProcedural ContinuousAssignmentsAssignments
If reset is not active (it is 0), theflip-flop output qout is deassigned.Only after qout is deassigned canother assignments to qout change
its value.
Procedural Continuous AssignmentsProcedural Continuous Assignments
Assignment takes place only whenreset is 0. While an assign is in
effect, another assign to the samevariable, deassigns the one that isin effect and then assigns a new
value to the variable.
69
CSE 467 137Verilog Digital System Design
Force and ReleaseForce and ReleaseProceduralProcedural
AssignmentsAssignments
ProceduralProcedural Flow Control Flow Control
ProceduralProceduralBlockingBlocking
AssignmentsAssignments
ProceduralProceduralNon-blockingNon-blockingAssignmentsAssignments
MultipleMultipleAssignmentsAssignments
ProceduralProceduralContinuousContinuous
AssignmentsAssignments
ForceForceAndAnd
ReleaseRelease
ForceForceandand
ReleaseRelease
CSE 467 138Verilog Digital System Design
Force and ReleaseForce and Release
Unlike Unlike assignassign and and deassigndeassign, which apply to , which apply to regreg type variables, type variables, forceforce,,and and release release constructs apply to constructs apply to netnet and and regreg types. types.
Forcing a value on a Forcing a value on a net net overrides all values assigned to the overrides all values assigned to the netnet through throughcontinuous assignments or connected to it through gate outputs.continuous assignments or connected to it through gate outputs.
70
CSE 467 139Verilog Digital System Design
Compiler DirectivesCompiler Directives
Compiler Compiler DirectivesDirectives
‘‘ifdefifdef, , ‘‘else, else, ‘‘endifendif
‘‘unconnectedunconnected-drive-drive
‘‘celldefinecelldefine, , ‘‘endcelldefineendcelldefine ‘‘resetallresetall
‘‘default-default-nettypenettype ‘‘includeinclude‘‘timescaletimescale ‘‘definedefine
CSE 467 140Verilog Digital System Design
`timescale`timescale
Compiler Compiler DirectivesDirectives
‘‘ifdefifdef, , ‘‘else, else, ‘‘endifendif
‘‘unconnectedunconnected_drive_drive
‘‘celldefinecelldefine, , ‘‘endcelldefineendcelldefine ‘‘resetallresetall
‘‘default_nettypedefault_nettype ‘‘includeinclude‘‘timescaletimescale ‘‘definedefine‘‘timescaletimescale
71
CSE 467 141Verilog Digital System Design
Including the Including the ‘‘timescaletimescale 1ns/100 1ns/100 psps directive before a module directive before a moduleheader causes all time-related numbers to be interpreted as having aheader causes all time-related numbers to be interpreted as having a1-ns time unit.1-ns time unit.
`timescale`timescale
CSE 467 142Verilog Digital System Design
`default-nettype`default-nettype
Compiler Compiler DirectivesDirectives
‘‘ifdefifdef, , ‘‘else, else, ‘‘endifendif
‘‘unconnectedunconnected_drive_drive
‘‘celldefinecelldefine, , ‘‘endcelldefineendcelldefine ‘‘resetallresetall
‘‘default-default-nettypenettype ‘‘includeinclude‘‘timescaletimescale ‘‘definedefine‘‘default_nettypedefault_nettype
72
CSE 467 143Verilog Digital System Design
`default-`default-nettypenettype
The default The default wirewire type can be changed by the type can be changed by the ‘‘default_nettypedefault_nettype. For. Forexample,example,
‘‘default_nettypedefault_nettype worwor
at the beginning of a module causes undeclared nets in constructs suchat the beginning of a module causes undeclared nets in constructs suchas the terminal list of a module instance to be assumed to be as the terminal list of a module instance to be assumed to be worwor type typenets.nets.
CSE 467 144Verilog Digital System Design
`include`include
Compiler Compiler DirectivesDirectives
‘‘ifdefifdef, , ‘‘else, else, ‘‘endifendif
‘‘unconnectedunconnected_drive_drive
‘‘celldefinecelldefine, , ‘‘endcelldefineendcelldefine ‘‘resetallresetall
‘‘default_nettypedefault_nettype ‘‘includeinclude‘‘timescaletimescale ‘‘definedefine‘‘includeinclude
73
CSE 467 145Verilog Digital System Design
`include`include
Because Verilog does not provide a common library of parts andBecause Verilog does not provide a common library of parts andutilities, a shared code must be explicitly inserted in modules that useutilities, a shared code must be explicitly inserted in modules that usethe code.the code.
CSE 467 146Verilog Digital System Design
`define`define
Compiler Compiler DirectivesDirectives
‘‘ifdefifdef, , ‘‘else, else, ‘‘endifendif
‘‘unconnectedunconnected_drive_drive
‘‘celldefinecelldefine, , ‘‘endcelldefineendcelldefine ‘‘resetallresetall
‘‘default_nettypedefault_nettype ‘‘includeinclude‘‘timescaletimescale ‘‘definedefine‘‘definedefine
74
CSE 467 147Verilog Digital System Design
`define`define
`define`define word_lengthword_length 32 32`define`define begin_fetch_statebegin_fetch_state 3 3’’b101b101
‘‘undefundef directive directive undefinesundefines a previously defined text macro a previously defined text macro
if ‘begin_fetch_state isused anywhere in aVerilog code, it isreplaced by 3’b101.
CSE 467 148Verilog Digital System Design
`̀ifdefifdef, `else, `, `else, `endifendif
Compiler Compiler DirectivesDirectives
‘‘ifdefifdef, , ‘‘else, else, ‘‘endifendif
‘‘unconnectedunconnected_drive_drive
‘‘celldefinecelldefine, , ‘‘endcelldefineendcelldefine ‘‘resetallresetall
‘‘default_nettypedefault_nettype ‘‘includeinclude‘‘timescaletimescale ‘‘definedefine
‘‘ifdefifdef, , ‘‘else,else,‘‘endifendif
75
CSE 467 149Verilog Digital System Design
`̀ifdefifdef, `else, `, `else, `endifendif
Because Verilog does not provide a common library of parts andBecause Verilog does not provide a common library of parts andutilities, a shared code must be explicitly inserted in modules that useutilities, a shared code must be explicitly inserted in modules that usethe code.the code.
CSE 467 150Verilog Digital System Design
`̀ifdefifdef, `else, `, `else, `endifendif
If the next macro has been defined, the group of lines bracketedIf the next macro has been defined, the group of lines bracketedbetween between ‘‘ifdefifdef and and ‘‘elseelse is compiled. is compiled.
If the text macro has not been defined, the group of lines bracketedIf the text macro has not been defined, the group of lines bracketedbetween between ‘‘elseelse and and ‘‘endifendif is compiled. is compiled.
76
CSE 467 151Verilog Digital System Design
`unconnected-drive`unconnected-drive
Compiler Compiler DirectivesDirectives
‘‘ifdefifdef, , ‘‘else, else, ‘‘endifendif
‘‘unconnectedunconnected-drive-drive
‘‘celldefinecelldefine, , ‘‘endcelldefineendcelldefine ‘‘resetallresetall
‘‘default_nettypedefault_nettype ‘‘includeinclude‘‘timescaletimescale ‘‘definedefine
‘‘unconnectedunconnected_drive_drive
CSE 467 152Verilog Digital System Design
`unconnected-drive`unconnected-drive
Changes port value left open in the connection list of a moduleChanges port value left open in the connection list of a moduleinstantiation which is assumed to have the default net value.instantiation which is assumed to have the default net value.
The only arguments allowed with this directive are The only arguments allowed with this directive are pull0pull0 or or pull1pull1 for forunconnected values 0 and 1, respectively.unconnected values 0 and 1, respectively.
77
CSE 467 153Verilog Digital System Design
`̀celldefinecelldefine, `, `endcelldefineendcelldefine
Compiler Compiler DirectivesDirectives
‘‘ifdefifdef, , ‘‘else, else, ‘‘endifendif
‘‘unconnectedunconnected_drive_drive
‘‘celldefinecelldefine, , ‘‘endcelldefineendcelldefine ‘‘resetallresetall
‘‘default_nettypedefault_nettype ‘‘includeinclude‘‘timescaletimescale ‘‘definedefine
‘‘celldefinecelldefine,,‘‘endcelldefineendcelldefine
CSE 467 154Verilog Digital System Design
`̀celldefinecelldefine, `, `endcelldefineendcelldefine
The The ‘‘celldefinecelldefine and and ‘‘endcelldefineendcelldefine directives bracket modules that are directives bracket modules that areto be considered as cells.to be considered as cells.
78
CSE 467 155Verilog Digital System Design
`̀resetallresetall
Compiler Compiler DirectivesDirectives
‘‘ifdefifdef, , ‘‘else, else, ‘‘endifendif
‘‘unconnectedunconnected_drive_drive
‘‘celldefinecelldefine, , ‘‘endcelldefineendcelldefine ‘‘resetallresetall
‘‘default_nettypedefault_nettype ‘‘includeinclude‘‘timescaletimescale ‘‘definedefine
‘‘resetallresetall
CSE 467 156Verilog Digital System Design
`resetall`resetall
Using this directive at the beginning of every module guarantees thatUsing this directive at the beginning of every module guarantees thatno previous setting affects compilation of modules and that all defaultsno previous setting affects compilation of modules and that all defaultsare set.are set.
79
CSE 467 157Verilog Digital System Design
The names of system tasks and functions begin with a dollar sign, The names of system tasks and functions begin with a dollar sign, $$,,followed by a task followed by a task specifierspecifier
System Tasks and FunctionsSystem Tasks and Functions
CSE 467 158Verilog Digital System Design
System TasksSystem Tasksand Functionsand Functions
Display TasksDisplay Tasks File I/O TasksFile I/O Tasks
Timescale TasksTimescale Tasks Simulation ControlSimulation ControlTasksTasks
Timing CheckTiming CheckTasksTasks
PLA ModelingPLA ModelingTasksTasks
Conversion FunctionsConversion FunctionsFor For RealsReals
Other TasksOther Tasksand Functionsand Functions
System Tasks and FunctionsSystem Tasks and Functions
80
CSE 467 159Verilog Digital System Design
System TasksSystem Tasksand Functionsand Functions
Display TasksDisplay Tasks File I/O TasksFile I/O Tasks
Timescale TasksTimescale Tasks Simulation ControlSimulation ControlTasksTasks
Timing CheckTiming CheckTasksTasks
PLA ModelingPLA ModelingTasksTasks
Conversion FunctionsConversion FunctionsFor For RealsReals
Other TasksOther Tasksand Functionsand Functions
Display TasksDisplay Tasks
Display TasksDisplay Tasks
CSE 467 160Verilog Digital System Design
Display TasksDisplay Tasks
Display tasks include those for monitoring and outputting variableDisplay tasks include those for monitoring and outputting variablevalues as they change (the values as they change (the $monitor$monitor group of tasks) and those for group of tasks) and those fordisplaying variables at a selected time (the displaying variables at a selected time (the $display$display tasks). tasks).
Display tasks can display in binary, hexadecimal, or octal formats. TheDisplay tasks can display in binary, hexadecimal, or octal formats. Thecharacter b, h, or o at the end of the task name specifies the data type acharacter b, h, or o at the end of the task name specifies the data type atask handles.task handles.
81
CSE 467 161Verilog Digital System Design
System TasksSystem Tasksand Functionsand Functions
Display TasksDisplay Tasks File I/O TasksFile I/O Tasks
Timescale TasksTimescale Tasks Simulation ControlSimulation ControlTasksTasks
Timing CheckTiming CheckTasksTasks
PLA ModelingPLA ModelingTasksTasks
Conversion FunctionsConversion FunctionsFor For RealsReals
Other TasksOther Tasksand Functionsand Functions
File I/O TasksFile I/O Tasks
File I/O TasksFile I/O Tasks
CSE 467 162Verilog Digital System Design
File I/O TasksFile I/O Tasks
The The $$fopenfopen function opens a file and assigns an integer file function opens a file and assigns an integer filedescription. The file descriptor will be used as an argument for alldescription. The file descriptor will be used as an argument for allfile I/O tasks.file I/O tasks.
There are string write tasks (There are string write tasks ($$swriteswrite) that write their formatted) that write their formattedoutputs to a string.outputs to a string.
Verilog also provides tasks for inputting data from files or strings.Verilog also provides tasks for inputting data from files or strings.Examples of these tasks are Examples of these tasks are $$fgetcfgetc, , $$fscanffscanf, and , and $$sscanfsscanf for getting for gettingcharacter from file, reading formatted data from file, and readingcharacter from file, reading formatted data from file, and readingformatted data from string, respectively.formatted data from string, respectively.
82
CSE 467 163Verilog Digital System Design
File I/O TasksFile I/O Tasks
Other input tasks exist for reading memory data directly into a declaredOther input tasks exist for reading memory data directly into a declaredmemory. Examples of such tasks are memory. Examples of such tasks are $$freadfread and and $$readmemhreadmemh..
File positioning tasks, File positioning tasks, $$fseekfseek and and $$frewindfrewind are available for positioning are available for positioningfile pointer for read or write.file pointer for read or write.
CSE 467 164Verilog Digital System Design
System TasksSystem Tasksand Functionsand Functions
Display TasksDisplay Tasks File I/O TasksFile I/O Tasks
Timescale TasksTimescale Tasks Simulation ControlSimulation ControlTasksTasks
Timing CheckTiming CheckTasksTasks
PLA ModelingPLA ModelingTasksTasks
Conversion FunctionsConversion FunctionsFor For RealsReals
Other TasksOther Tasksand Functionsand Functions
Timescale TasksTimescale Tasks
Timescale TasksTimescale Tasks
83
CSE 467 165Verilog Digital System Design
Timescale TasksTimescale Tasks
The The $$printtimescaleprinttimescale task displays the timescale and precision of the task displays the timescale and precision of themodule whose hierarchical name is being passed to it as its argument.module whose hierarchical name is being passed to it as its argument.
The The $$timeformattimeformat task formats time for display by file IO and display task formats time for display by file IO and displaytasks.tasks.
CSE 467 166Verilog Digital System Design
System TasksSystem Tasksand Functionsand Functions
Display TasksDisplay Tasks File I/O TasksFile I/O Tasks
Timescale TasksTimescale Tasks Simulation ControlSimulation ControlTasksTasks
Timing CheckTiming CheckTasksTasks
PLA ModelingPLA ModelingTasksTasks
Conversion FunctionsConversion FunctionsFor For RealsReals
Other TasksOther Tasksand Functionsand Functions
Simulation ControlSimulation ControlTasksTasks
Simulation Control TasksSimulation Control Tasks
84
CSE 467 167Verilog Digital System Design
Simulation Control TasksSimulation Control Tasks
The The $finish$finish task ends the simulation and exits. task ends the simulation and exits.
The The $stop$stop task suspends the simulation and does not exit the task suspends the simulation and does not exit thesimulation environment.simulation environment.
CSE 467 168Verilog Digital System Design
System TasksSystem Tasksand Functionsand Functions
Display TasksDisplay Tasks File I/O TasksFile I/O Tasks
Timescale TasksTimescale Tasks Simulation ControlSimulation ControlTasksTasks
Timing CheckTiming CheckTasksTasks
PLA ModelingPLA ModelingTasksTasks
Conversion FunctionsConversion FunctionsFor For RealsReals
Other TasksOther Tasksand Functionsand Functions
Timing CheckTiming CheckTasksTasks
Timing Check TasksTiming Check Tasks
85
CSE 467 169Verilog Digital System Design
Timing Check TasksTiming Check Tasks
In general, timing check tasks check the timing on one signal or theIn general, timing check tasks check the timing on one signal or therelative timing of several signals for certain conditions to hold.relative timing of several signals for certain conditions to hold.
$$nochangenochange ( (posedgeposedge clock, clock, d_inputd_input, 3, 5);, 3, 5);
Uses the $Uses the $nochangenochange timing timingcheck task to report acheck task to report a
violation if violation if d_inputd_input changes in changes inthe period of 3 time unitsthe period of 3 time units
before and 5 time units afterbefore and 5 time units afterthe positive edge of the the positive edge of the clockclock..
CSE 467 170Verilog Digital System Design
System TasksSystem Tasksand Functionsand Functions
Display TasksDisplay Tasks File I/O TasksFile I/O Tasks
Timescale TasksTimescale Tasks Simulation ControlSimulation ControlTasksTasks
Timing CheckTiming CheckTasksTasks
PLA ModelingPLA ModelingTasksTasks
Conversion FunctionsConversion FunctionsFor For RealsReals
Other TasksOther Tasksand Functionsand Functions
PLA ModelingPLA ModelingTasksTasks
PLA Modeling TasksPLA Modeling Tasks
86
CSE 467 171Verilog Digital System Design
PLA Modeling TasksPLA Modeling Tasks
The general format that we use for describing these tasks is:The general format that we use for describing these tasks is: $$sync_asyncsync_async: : can be either sync or can be either sync or asyncasync $$and_orand_or: : can be and, or, can be and, or, nandnand, or nor, or nor $$array_planearray_plane: : in place ofin place of array_planearray_plane, array or plane can be used., array or plane can be used.
$$asyncasync $ $nandnand $array $array(mem8by4,(mem8by4,{a1, a2, a3, a4, a5, a6, a7, a8},{a1, a2, a3, a4, a5, a6, a7, a8},
{b1, b2, b3, b4}} {b1, b2, b3, b4}} An asynchronous PLA with aAn asynchronous PLA with anandnand logical function, logical function, a1a1 to to a7a7inputs, and inputs, and b1b1 to to b4b4 outputs. outputs.PLA PLA nandnand-plane fuses are-plane fuses are
determined by the contents ofdetermined by the contents ofthe the mem8by4mem8by4 declared memory declared memory
CSE 467 172Verilog Digital System Design
(a) Contents of mem8by4, (b) Corresponding PLA NAND Plane(a) Contents of mem8by4, (b) Corresponding PLA NAND Plane
b1
b2
b3
b4
b1
b2
b3
b4
a8a7a6a5a4a3a2a1
a1 a2 a3 a4 a5 a6 a7 a8
0 0 1 1 0 0 0 1
1 1 0 0 1 0 0 0
0 0 0 0 1 1 0 0
0 1 0 1 0 0 0 0
PLA Modeling TasksPLA Modeling Tasks
PLA Output EquationsPLA Output Equationsb1 = ~(a3 & a4 & a8)b1 = ~(a3 & a4 & a8)b2 = ~(a1 & a2 & a5)b2 = ~(a1 & a2 & a5)b3 = ~(a5 & a6)b3 = ~(a5 & a6)b4 = ~(a2 & a4)b4 = ~(a2 & a4)
87
CSE 467 173Verilog Digital System Design
System TasksSystem Tasksand Functionsand Functions
Display TasksDisplay Tasks File I/O TasksFile I/O Tasks
Timescale TasksTimescale Tasks Simulation ControlSimulation ControlTasksTasks
Timing CheckTiming CheckTasksTasks
PLA ModelingPLA ModelingTasksTasks
Convention FunctionsConvention FunctionsFor For RealsReals
Other TasksOther Tasksand Functionsand Functions
Conversion Functions for Conversion Functions for RealsReals
Conversion FunctionsConversion Functionsfor for RealsReals
CSE 467 174Verilog Digital System Design
Conversion Functions for Conversion Functions for RealsReals
Verilog provides four system functions for converting from real toVerilog provides four system functions for converting from real tointeger or bit, and for converting between bit or integer and real.integer or bit, and for converting between bit or integer and real.
The functions areThe functions are $ $bitstorealbitstoreal, , $$realtobitsrealtobits, , $$itoritor, and , and $$rtoirtoi..
88
CSE 467 175Verilog Digital System Design
System TasksSystem Tasksand Functionsand Functions
Display TasksDisplay Tasks File I/O TasksFile I/O Tasks
Timescale TasksTimescale Tasks Simulation ControlSimulation ControlTasksTasks
Timing CheckTiming CheckTasksTasks
PLA ModelingPLA ModelingTasksTasks
Conversion FunctionsConversion FunctionsFor For RealsReals
Other TasksOther Tasksand Functionsand Functions
Other Functions and TasksOther Functions and Tasks
Other TasksOther Tasksand Functionsand Functions
CSE 467 176Verilog Digital System Design
Other Functions and TasksOther Functions and Tasks
$random$random is a useful function for random data generation. is a useful function for random data generation.
There are three time functions, There are three time functions, $$realtimerealtime, , $time$time, and , and $$stimestime, that return, that returnthe simulation time in various formats.the simulation time in various formats.
89
CSE 467 177Verilog Digital System Design
SummarySummary
This chapter presented:This chapter presented: General timing and concurrency concepts that are particular toGeneral timing and concurrency concepts that are particular to
hardware description languages.hardware description languages. Utilities found in Utilities found in Verilog Verilog for describing hardware and hardware testfor describing hardware and hardware test
environments.environments. General syntax of the language its operators, names, and data types.General syntax of the language its operators, names, and data types. Simulation of hardware described in Simulation of hardware described in Verilog Verilog using languageusing language
constructs and utilities of this language.constructs and utilities of this language. Tasks and compiler directives, that are part of the language utilitiesTasks and compiler directives, that are part of the language utilities
for hardware and for hardware and testbench testbench modeling, but are secondary to thosemodeling, but are secondary to thosediscussed in Section 3.2.discussed in Section 3.2.
Most of Most of Verilog Verilog without presenting a lot of examples and specificwithout presenting a lot of examples and specificapplications of the language constructs.applications of the language constructs.