Verilog HDL

§ HDL Languages and Design Flow § Introduction to Verilog HDL § Basic Language Concepts § Connectivity in Verilog § Modeling using Verilog § Race conditions § UDPs § Coding FSMs in Verilog

§ Verilog Logic Synthesis § Verilog Coding Guidelines § Electrical Properties § Macros, Conditional Compilation & Naming Conventions § Verilog for Logic Simulation § Introduction to PLI

HDL Languages and Design Flow

. § A Hardware Description Language is one that can describe circuit’s operation. conceptual design & organization and can test it by means of simulation.HDLs – WHAT-WHY-HOW § WHAT is a HDL? § HDLs – A class of programming/computer languages used for formal description of electronic circuits. § Usually deal with the design of digital logic circuits and systems.

§ Highly important to find potential functional bugs in the early stages of design. § These needs led to a the use of CAD techniques for digital design.HDLs – WHAT-WHY-HOW § WHY were HDLs required? § It is impractical to verify large circuits on breadboards or large chips after manufacturing. § The designers felt need for a flexible language that may help the design process by giving a complete framework for design. .

etc.) § Software Programming languages – Sequential in nature. FORTRAN.HDLs – WHAT-WHY-HOW § WHY were HDLs required? (contd. Pascal.. (C. § Traditional programming languages lack the capability for explicitly expressing time. Time consuming & Costlier. . § Using s/w programming languages to represent hardware is – Inconvenient.) § Digital logic circuits involve Concurrency of operations.

. performance. synthesis. power.HDLs – WHAT-WHY-HOW § HOW are HDLs advantageous? § Allows designer to talk about what the hardware should do without actually designing the hardware itself. and area earlier in the design process. § Designers can make decisions about cost. and optimization. § Designers can create tools which automatically manipulate the design for verification. § Designers can develop an executable functional specification that documents the exact behavior of all the components and their interfaces.

Design Hierarchy § Design Specification & Requirements § Behavioral/Architectural Design § Register Transfer Level (RTL) Design § Logic Design § Circuit Design § Physical Design § Manufacturing .

System Specification Functional (Architectural Design) Behavioral Representation Functional Verification Logic Design Logic (Gate-level) Representation Logic Verification Circuit Design Circuit Representation Circuit Verification Physical Design Layout Representation Layout Verification Fabrication & Testing .

.. Implementation CPU SubSystem RTL Gate level Treansistor level Arith Reg.Hardware Design Flow System Behavioral level . Mem. Design adder subtr .

Hardware Design Flow § HDLs and CAD tools are used to describe hardware for: § Design & Modeling § Simulation § Synthesis § Testing § Documentation .

Verilog HDL Introduction .

History § Invented by Phil Moorby & Prabhu Goel at Gateway Design Automation Systems in 1983/84. § In 1995. § Verilog 2001 – IEEE Standard 1364-2001. § Verilog 2005 – IEEE Standard 1364-2005. § Later . § Verilog-95 – IEEE Standard 1364-1995.Verilog HDL . § SystemVerilog – Extended from Verilog and C++. . Cadence published Verilog for public domain under OVI (Open Verilog International). Cadence took full proprietary in 1990.

§ Simulated to check functionality. § “Synthesis subset” § Can be translated using Synopsys’ Design Compiler or others into a netlist. . § Synthesized (netlist generated). § Design written in Verilog. § Allows different levels of abstraction to be mixed in the same design.How Verilog Is Used § It is a general purpose HDL with support for . § Static timing analysis.

§ Acceptable to logic synthesis tool. . § § § § Behavioral Level Dataflow Level Gate Level Switch level Behavioral Dataflow Gate Level Switch level Lowest Abstraction Level Highest Abstraction Level § Register Transfer Level (RTL) § A combination of both Behavioral & Dataflow constructs.Levels of Abstraction § Verilog supports a design at 4 different levels of abstraction.

§ Data Flow Level :.. § Gate Level :.Describes the flow of data between registers and how a design processes that data.Describes the logic gates and the connections between logic gates in a design. § Switch Level :.Describes the transistors and storage nodes in a device and the connections between :-describes them .) § Behavioral Level :.Used to model the behavior of a design without describing its actual hardware structure.Levels of Abstraction (Cont.

Design Methodologies § There are 2 types of design methodologies: § Top-down design methodology. We build bigger cells. and § Bottom-up design methodology. . § In a top-down design methodology. we define the top-level block and identify the sub-blocks necessary to build the top-level block. we first identify the building blocks that are available to us. § In a bottom-up design methodology. using these building blocks.

Design Methodologies (Cont.) Top-Level Block Subblock1 Subblock2 Subblock3 Leaf Cell Leaf Cell Leaf Cell Leaf Cell Leaf Cell Leaf Cell Top-Down Design Methodology ..

) Top-Level Block Macro Cell1 Macro Cell 2 Macro Cell 3 Leaf Cell Leaf Cell Leaf Cell Leaf Cell Leaf Cell Leaf Cell Bottom-Up Design Methodology .Design Methodologies (Cont..

§ A corresponding keyword endmodule must appear at the end of the module definition. § A module provides the necessary functionality to the higher-level block through its port interface (inputs and outputs). . § In Verilog a module is declared by the keyword module.Modules § A module is the basic building block in Verilog. § Elements are grouped into modules to provide the common functionality that is used at many places in the design.

§ Each instance of module has all the properties of that module. § Rather. .) § Modules CANNOT be nested. § Module instantiation is like creating actual objects (Instances) from the common template (module definition). and § connecting test bench to the design.. § Module instantiations are used for: § connecting different parts of the designs.Modules (Contd. one module can instantiate another module.

Design Hierarchy § One top level module § In which zero or more lower level modules can be instantiated. § Each low level module can further instantiate still lower level modules. . § Use them to make your design more readable and manageable. § Debugging individual module is a lot easier than debugging the whole system together. § Verilog modules are like modules in schematics or classes in C++.

inout // wire. end. <statements>. <declarations>. begin. output. etc. always // dataflow statements endmodule . // initial. // input.Structure of module module <mod name> (<port list>). register.

. always constructs. continuous assignments or instances of modules. memories and wires as wells as procedural constructs such as function s and tasks. § The <port list> is a list of input.) § The <module name> is an identifier that uniquely names the module. inout and output ports which are used to connect to other modules. § The <declares> section specifies data objects as registers.Structure of module (Contd. § The <statements> may be initial constructs. .


Basic Languages Concepts .

-4’b11 .3’b10x. ‘h8ff. digits.549.g. 4’b11.Lexical Conventions § Keywords § In lower case § Case sensitive § Delimit tokens. ‘o765. space § String with double quotes § Identifier § A letter or _ can be followed by letters.. $ and _ § Max 1024 characters § Numbers § [<sign>] [<size>] <base> <num> § e.

*/ input status. 2009 No unauthorized copying is allowed. // 0:ready. Block comment. Example /* Copyright Kacper Technologies Pvt Ltd. start with /*. // sync with clock mClock . Block comment cannot be nested.Verilog Comments Verilog supports 2 type of comment syntaxes § § Single line comment start with //. 1:not ready output data. and end with */. and end with newline.

Z. ?. ‘d. ‘B. (usually 32 bits) ‘b. This is an optional value & if not specified. Default is ‘decimal’ 0-9.Verilog Number Specifications § § Two representations: sized & unsized Format:<number of bits><base><number> <number of bits> <base> <number> Bit length in decimal. X. A-F. ‘D. a-f. ‘H. ‘O. ‘o. default is host machine word size. ‘h. _ .

Often _ (Underscore) is used in between digits of the number for readability. § Format: -<size><base><number> § <size> field is always +ve.. reg [5:0] Num. Num = -8’d4. . § // Negative number // 8 bit –ve number // Illegal !! // _ for readability .Verilog Numbers Specifications (Contd.) § Negative numbers: put minus sign before size. data = 32’h_1234_5678.. Num = ‘d-12. Reg [31:0] data. § Represented by 2’s complement internally. Num = -6.

reg [5:0] Num.. Num = 6’b_100x.) § § § Verilog numbers may have x or z as part of numbers. Num = ‘b11??1.. z ? high impedance value A question mark ‘?’ can also be used as an alternative to ‘z’. x ? unknown value. data = 32‘h_x5f3_2693. Reg [31:0] data. Num = ‘bz01. // Num = 6’b00100x // 32 bit no with all x bits // Num = 6’bzzzz01 // Num = 6’b011zz1 // data = 32’hX5f32693 . . data = 32’bx.Verilog Numbers Specifications (Contd.

if (status == 1’b1) … endmodule // 8’b0001_0000 // two’s complement of 4 // 8’bxxxx_xxxx // 8’b0000_000x // 8’b0000_010x // status == 32’h0001 // status == 1’b1 . Num = ‘bx. … Num = 16. if (status == 1) Num = 8’b1010_0101. Num = -8’d4. Num = ‘b0x. Num = ‘b10x. wire status.Verilog Numbers: Example module Verilog_number. reg [7:0] Num.

k = r. k. B. C.0 Reg[7:0] B. § . z § Use as registers (inside procedures) i = 1. // k is rounded to 3 § Integers are not initialized in Vector: Verilog!! Reg[0:7] A. Default: 1-bit (Scalar) r = 2. § Reals are initialized to 0.9. x. Possible Values: 0. real r. reg A.Data Types § reg: Register § § § § Integer & Real Data Types § Declaration wire: Wire/net integer i. 1.

wor. tri. § Usually. § Default value for any net type variable is ‘z’. § wire is the most common of all. declared by the keyword wire.Nets § Nets represent the connections between hardware elements. wand. triand. § They are always driven by some source. trior. . etc. trireg. § Different types: wire.


registers do not need any drivers.Registers § These correspond to variables in the C language. § Register data types always retain their value until another value is placed on them. . § A reg type variable is the one that can hold a value. § DO NOT confuse with hardware registers built with flip-flops. § Unlike nets.

§ It can be sure they do not have to store if their outputs is based only on their present inputs.Registers (Contd. the compiler will generate latches or flip-flops for them.) § In synthesis. However. if it can be sure their output does not need to be stored it will synthesize them into wires. ..

) § So. .” § Verilog register data types: reg / time / integer / real / realtime / event (reg is the most common of all. § Structural code continuous assignment statements start with the keyword assign.”All other variables are of net type. § A variable is declared of type wire if it appears on the left side of an continuous assignment statement.Rules for reg and wire § The common rule in Verilog: “A variable on the Left Hand Side (LHS) of a procedural block assignment is always declared as a register data type. reg is assigned within always or initial blocks.

§ Usually preferred for arithmetic manipulations over reg. § Default width: host machine word size (minimum 32 bits).Integers § A general purpose register data type with default value having all x bits. § Differs from reg type as it stores signed quantities as opposed to reg storing unsigned quantities. § Declared with keyword integer. .

§ Real numbers CANNOT have a range declaration. § Two notations: Decimal & Scientific notation. .Real Numbers § Real number constants declared with a keyword real. § Real constants have default value of 0. the real number is rounded off to the nearest integer. § When a real value is assigned to an integer.

Usually. realtime provides the simulation time with the fractional part with given precision. it is used to store the simulation time.Time & Realtime Data types § time – A special register data type used mainly to store simulation time. § Depending upon the timescale specified. . § realtime is similar to time except that it has initial value of 0. § time is an unsigned 64-bit by default.

NOR Reduction AND .Logical Operators Operator ~& | ~| ^ ~^ or ^~ == or === != or !== > >= < <= ?: Operation Reduction NAND Reduction OR Reduction NOR Reduction XOR Reduction XNOR Logical Inequality Logical Inequality Relational Conditional Operator Operation ! && || ~ & | ^ ^~ or ~^ & Logical Negation Logical AND Logical OR Bit-wise Negation Bit-wise AND Bit-wise OR Bit-wise Exclusive OR Bit-wise Ex.

Logical Operation Example operand1 operand2 1 2 3 4 5 6 7 8 && A B C D E F G H True (“1”). False (“0”) or Unknown (“X”) Examples 1’b1 && 1’b0 2’b11 && 2’b10 2’b1X && 2’b11 0 0 X 1’b1 || 1’b0 2’b11 || 2’b10 2’b1X || 2’b11 1 1 1 .

Bitwise Operators § & § | § ~ → bitwise AND → bitwise OR → bitwise NOT § ^ → bitwise XOR § ~^ or ^~ → bitwise XNOR § Operation on bit by bit basis 8 & A B C D E F G H 1 2 3 4 5 6 7 1 & A 2 & B 3 & C 4 & D 5 & E 6 & F 7 & G 8 & H .

~^. ^. $displayb(| b). (same as 1&1&1&1) // evaluates to 1 // bitwise or (evaluates to 1) . ^~. xnor and an alternative xnor. end // bitwise and. c = 4'b0011. § The reduction operators are and. nor. They take one operand and perform a bit-bynext-bit operation. b = 4'b0101. starting with the two leftmost bits.Reduction operators § Key symbols: &. ~&. |. $displayb(& a). giving a 1bit result. or. xor. nand. initial begin a = 4'b1111. ~|.

Reduction operation & 1 2 3 4 5 6 7 8 1 & 2 3 & & 4 5 & 6 7 & & 8 & .

Shift operators § Key symbols: >>. end endmodule // shiftTest // shift left by 1. <<. § The shift operators are shift left and shift right. module shiftTest. $displayb(a << 1). displays 0010 . $displayb(a >> 2). initial begin a = 4'b1010. § The empty bits caused by shifting are filled with zeros. reg [3:0] a. The shift operator takes a vector and a number indicating the shift. displays 0100 //shift right by 2.

Conditional Operator § cond_expr ? true_expr : false_expr § A ternary operator § Acts like a 2-to-1 mux. A B 1 0 sel Y Y = (sel)? A : B. Y = A if sel is ‘1’ B if sel is 0 .

1}. 2’b11. // WRONG !! … . catx = {a..Concatenation Operator § {op1. op2. .c. reg [2:0] b. op2. § Operands must be sized !! … reg a. a}.b = 3’b 010. c = 3’b 101. c}.. a = 1’b1. b. // caty = 010_11_1 catz = {b. . to single number. // catx = 1_010_101 caty = {b.} → concatenates op1.

b.b = 3’b 010. catr = {4{a}.c. … reg a. // catr = 1111_010_101101 … . c = 3’b 101. reg [2:0] b. a = 1’b1. 2{c}}.Replication Operator § <no> { <variable/sized_number> } § <no> is an integer.

. 1 or x === → case equality !== → case inequality Return 0 or 1 e.Relational & Equality Operators § § § § § § § § § > → greater than < → less than >= → greater or equal than <= → less or equal than Result is one bit value: 0.4’b1z0x == 4’b1z0x → x 4’b1z0x === 4’b1z0x → 1 .g. 1 or x == → logical equality != → logical inequality Return 0.

! ~ * / % + >> << < <= >= > == != === !== & ~& ^ ^~ | ~| && || ?: Lowest Precedence Highest Logical Conditional . Modulus Add.Operator precedence Operators Unary Multiply. Subtract Shift Relational Equality Reduction Operator Symbols + . Divide.

// little-endian notation // big-endian notation . reg [1:4] busB.Vectors § Vectors have multiple bits and are often used to represent buses. § There are 2 representations for vectors: § A little-endian notation: [high# : low#] § A big-endian notation: [low# : high#] wire [3:0] busA. § The left most number is an MSB (Most Significant Bit). reg [0:15] busC.

reg [3:0] dest_addr.. = out[61]. § Slice management reg [63:0] out. inter_carry = carry[1:3]. initial begin dest_addr = out[63:60]. = out[63]. .Vectors (Contd.) § Vector Part Select data[15:8] = 8’h_12. = out[62]. end // Accessing only bits 16 to 9 of data = dest_addr[0] dest_addr[1] dest_addr[2] dest_addr[3] = out[60].

Vectors (Contd. bus_A[1] = bus_B[1]. . initial begin bus_A = bus_B. end … = bus_A[2] = bus_B[0]. reg [0:2] bus_B. bus_A[0] = bus_B[2]..) § Vector assignment ( by position!! ) … reg [2:0] bus_A.

[31:28] byte1 = data1[24-:8]. reg [3:0] nibble1. // selects data2[28:31] . reg [0:3] nibble2.Vectors (Contd. reg [7:0] byte1. // selects 4 bits from 31 to down. // selects data1[24:17] byte2 = data2[10+:8]. … nibble1 = data1[31-:4].. i. reg [0:31] data2.e. // selects data2[10:17] nibble2 = data2[28+:4]. reg [0:7] byte2.) § Variable Vector Part Select § [<starting_bit>+ : <width>] § [<starting_bit>.: <width>] reg [31:0] data1.

// “I ” is truncated … .. string_val = “hello”. // can hold up to 13 chars .. string_val = “Hello Verilog”. § Escaped chars: \n for newline \\ for \ \t for tab %% for % \” for “ \ooo characters as octal … reg [8*13:1] string_val.Strings § Implemented with regs. // MS Bytes are filled with 0 string_val = “I am overflowed”.

// array of buses reg [31:0] payload [34:0]. integer ary1 [19:0]. // array of real numbers .Arrays § Declaration: <type> <vector_size> <ary_name> <ary_size>. // array of check-points real results [39:0]. // array of vectors time checkpoints [1:50]. § Elements are accessed by: <ary_name> [<index>]. reg array1 [99:0]. § Verilog supports multi-dimensional arrays. § <ary_size> is declared as a range. // array1 is an array with 100 elements // each element is of 1 bit. // array of integers with 20 elements wire [3:0] y [10:1].

.) //Multi-dimensional arrays reg [7:0] sonet_frame [89:0][8:0].Arrays (Contd. reg [7:0] matrix3d [9:0] [24:0] [3:0]. // 3-dimentional array of integers . // a 2-dimentional array representing the SONET frame.

… reg [7:0] string_val [99:0]. reg [7:0] ray2d [4:0] [49:0].Memories § Declaration: reg <vector_width> <ary_name> <no_of_locations>. // a memory with 100 elements // each of 1 byte // 2-dimentional array reg [31:0] mem32 [`DEPTH-1:0]. // 32-bit memory … .

Connectivity in Verilog .


output. § Bidirectional ports cannot be assigned to procedurally. . § An output port must be a wire if it is generated by a submodule.Port assignments § Modules contain functional descriptions and have input. § An output port must be § a reg if it is assigned to procedurally. § An output port must be a wire if it is generated declaratively. § The following are true of module interfaces: § An input or inout port is a wire type within its module. § A wire if it is assigned through continuous assignment. and inout (bidirectional ports) for interfaces.


. § Port named instantiation lists the port name and signal connected to it. § There are two methods of making connections between signals specified in the modules and their input/output ports. in any order. module instantiation is used to make connections between different parts of the design. Unconnected ports are designated by two commas with no signal listed. § Port ordered instantiation lists signal connections in the same order as the port list in the module definition.Module Instantiations § As we saw earlier.

) § Connections by Ordered List <module_name> < instance_name> [instance_array_range] ( signal . ).. ).port_name(signal).. . ..Module Instantiations (Contd. . signal . .port_name(signal)... § Connections by Named List <module_name> < instance_name> [instance_array_range] ( .

are used for connecting different modules ..Module Instantiations (Contd.) § A module can be seen as a template which allows any other modules to incorporate its functionality without writing the same logic repeatedly. the instance will have all the properties of the lower level module. § Instantiations together. § When a module instance is created in higher level module. § Modules allow instances & hierarchy.

Hierarchical Naming
§ As modules instantiate one another, there forms a hierarchy of them. And them and their internal variables, etc. can be accessed from higher levels using hierarchical naming.

TB_TOP dff



Hierarchical Naming (Contd..)
TB_TOP dff1 Q, QB D (Signals)



§ Signals of the dff may be accessed using hierarchical naming as shown below: TB_TOP TB_TOP.dff1.Q TB_TOP.nand1 TB_TOP.nand1.o1 TB_TOP.dff1.QB

Modeling using Verilog

or. buf bufif1.and. bufif0. § These are rarely used for in design work. notif0 . xor. transmission gates.Gate Level Modeling § Verilog has built in primitives like gates. nor. notif1. but are used in post synthesis world for modeling the ASIC/FPGA cells. xnor not. and switches. These cells are then used for gate level simulation or what is called as SDF simulation. § Ex:. nand.

// 3 input AND gate or(z. b). data_enable_low ). a.) § The gates have one scalar output and multiple scalar inputs. b. a. nand n1(z. in). // 2 input NAND gate xor x1(z. d). a. // Buffer not n1(out. § The first terminal in the list of gate terminals is an output and the other terminals are inputs. . // Instance name is optional buf b1(out. b).. // 4 input XOR gate and x2(z. a. c). // Inverter bufif0 U1( data_bus. b. c. data_drive. § Gate instance name is optional.Gate Level Modeling (Contd. in).







Gate Delays § Rise Delay: associated with a gate output transition to 1 from another value. § If the output of gate changes to ‘x’. § Fall Delay: associated with a gate output transition to 0 from another value. . § Turn-off Delay: associated with a gate output transition to z from another value. the minimum of the three delays is considered.


fall_time. § Min. turnoff_delay) § The gate delay can be specified with only one delay time or rise and fall times or with all 3 delay values. ..Gate Delays (Contd. maximum and typical delay value that a designer expects the gate to have. typ or max values can be chosen at runtime by options provided in the simulator. § The gate delay cam be specified as follows: <gate_primitive> #(rise_time.) § Min / Max / Typ delay values: They represent the minimum.

in1.) // rise. 3. i2.. i3 ). a.Gate Delays (Contd. fall and turnoff delays // For transition to x. the delay is taken as min(1. // delay time or #(14. 5) // examples for #(min : typ : max) values not #(2:3:5) inv(out.16) OR( op. in). // rise. // min delay=2 // typ delay = 3 // max delay = 5 . b ). 5) xg( o. fall & turnoff delays and #(10) a1( and_out. // rise & fall times xor #(1. i1. in2 ). 3.

in2 ). 0:1:3 ) inv( out. typ fall delay=3. max rise delay=5 // min fall delay=1. max fall delay=5 buf #( 2:3:5. /* min rise delay=2.) nor #( 2:3:5. // min rise delay=2. 1:4:7. typ rise delay=3.Gate Delays (Contd.max turnoff delay=3 */ . max rise delay=5 min fall delay=2. typ rise delay=3. in ). 1:4:7 ) inv( out. in1. typ fall delay=4. max fall delay=5 min turnoff delay=0. typ turnoff delay=1..

Gate Level Modeling Examples // 1-bit Half Adder module ha( sum. b ). endmodule . b. fall and turnoff delay and #(1. input a. b ). carry. a.2. xor #5 x1( sum. a. b ). output sum. a. // rise. carry.3) a1( carry.

input D.Q_BAR.CLK.Q.CLK) .X). Q_BAR.Y).X. output Q. nand U4 (Q_BAR.Gate Level Modeling Examples (Contd. endmodule .) module dff ( Q.Q_BAR. CLK ). // Four Instantiations of nand gates nand U1 (X. nand U2 (Y. D. nand U3 (Q..CLK) .D.

§ Syntax: assign <drive_strength> #<delay> <list_of_assignments>. § assign is used to drive value on the net by continuos assignment. § Dataflow modeling involves continuous assignments.Dataflow Modeling § The data flow between registers and the way that data gets processes is modeled using dataflow modeling. . that is driving values to the net.

.Dataflow Modeling (Cont. // Same effect is achieved by an implicit continuous assignment wire out = var1 & var2. assign out = var1 & var2..) // Regular continuous assignment wire out.

logic gates have delays associated with them. § The delay is represented using #. A number followed by # shows the delay value. e. Verilog provides the mechanism to associate delays with gates.g. § In real circuits . .Delays § A delay control expression specifies the time duration between initially encountering the statement and when the statement actually executes.#10 A = A + 1. § There are different ways to specify delays in continuous assignments.

g. § e.Delays (Cont.assign #10 q = x + y.g. . – wire #10 q = a ^ b.) § Regular Assignment Delay: § This is the most commonly used method.. § Implicit Continuous Assignment Delay: § Similar to implicit assignment statement with delay added. // which is equivalent to the following: // wire out. // assign #10 out = a ^ b. § e.

) § Net Declaration Delay: § The delay can be put on the net in declaration itself. § e. assign out = a & b. // which is equivalent to the following: // wire out. – wire #10 out.Delays (Cont. . // assign #10 out = a & b.g..

assign ao = a & b. xoo. assign #1 nao = a ~& b. output ao. nao. assign noo = #3 a ~| b. oo. input a. ao. #10 assign oo = a | b. noo. a. xno. xoo. oo. endmodule . b ). assign xoo = a ^ b. nao. assign invo = ~a. assign xno = a ~^ b.Dataflow Modeling Examples // All basic logic gates module gates( invo. xno. noo. b.

) // 2:1 Multiplexer module mux21(op. sel ). b. a.Dataflow Modeling Examples (Contd. assign op = sel ? a : b. input sel. input [3:0] a.. output op. endmodule . b.

input data received data data ready request data overflow acknowledge data . The states are cycle-to-cycle accurate.Behavioral Modeling § In RTL and Gate level implementation. the details of the handshake mechanism between different processes are implied.

§ In behavioral modeling. input data received data data ready request data .) § The behavioral model provides the ability to describe design functionality in an algorithmic manner or in higher level of modeling where behavior of logic is modeled.Behavioral Modeling (Contd.. The details of implementation is based on the application. you can use events for synchronizing.

hardware circuitry is concurrent in nature. Basic) are sequential in natural.Behavioral Modeling (Contd. All the circuitries are active in parallel. Each “always” and “initial” block run concurrently. C.g. § Verilog supports parallelism by allowing any number of “always” and “initial” blocks. § always and initial blocks are called procedural blocks. . Assignment inside procedural blocks are called procedural assignment.) § Most of the programming languages (e.. or only one active process at any one time. However.

initial begin … imperative statements … end § Runs when simulation starts § Terminates when control reaches the end § Good for providing stimulus always begin … imperative statements … end § Runs when simulation starts § Restarts when control reaches the end § Good for modeling / specifying hardware .Procedural Blocks § Procedural blocks are the basic components for behavioral modeling.

) § Run until they encounter a delay. always begin wait(i). end . wait(~i). end § or a wait for an event always @(posedge clk) q = d. a = 0.. initial begin #10 a = 1. b = 0.Procedural Blocks (Contd. #10 a = 0. a = 1. b = 1.

§ initial block § Executes only once. (unless delay is specified) § All blocks execute in parallel.Procedural Blocks (Contd. It must have timing control.) § Procedural blocks are like concurrent processes. but all within one unit of simulated time. § Statements in a block are executed sequentially. § always block § Executes repeatedly.. otherwise it become INFINITE LOOPS .

. § always procedural blocks process statements repeatedly.. The sensitivity list is used to model combinational and sequential logic behavior. § sensitivity_list (optional) is an event timing control that controls when all statements in the procedural block should be evaluated.) § Syntax: type_of_block @(sensitivity_list) statement_group: group_name local_variable_declarations timing_control procedural_statements end_of_statement_group § type_of_block is either initial or always.Procedural Blocks (Contd. § initial procedural blocks process statements one time.

§ fork & join are used to two or more statements together in parallel. so that statements are evaluated in the order they are listed.) § statement_group--end_of_statement_group is used to group two or more procedural statements together and control the execution order § begin--end groups two or more statements together sequentially. ..Procedural Blocks (Contd. § Each timing control is relative to the previous statement. so that all statements evaluated concurrently. § Each timing control is absolute to when the group started.

(they execute sequentially) § This can be expressed in two types of blocks: § initial → they execute only once § always → they execute for ever § The RHS expression is evaluated and assigned to LHS variable before next statement executes. § RHS expression may contain wires and regs § Two possible sources for data § LHS must be a reg (rooy) type data type.Procedural Assignment § Procedural statements are statements inside a procedure. § Primitives or cont. assignment may set wire values .

It is a way of blocking the further statements until the current statement execution is completed.Blocking & Non-blocking Assignments § There are two types of assignment statements are there in Verilog: § Blocking statements § Non-blocking statements. assignments until the . § The assignment is said to "block" other current assignment has completed. § A blocking assignment must evaluate the RHS arguments and complete the assignment without interruption from any other Verilog statement. § Blocking Assignment:.

§ Execution of non-blocking assignments can be viewed as a two-step process: § Evaluate the RHS of non-blocking statements at the beginning of the time step. .Blocking & Non-blocking Assignments § Non Blocking assignments allow scheduling of assignments without blocking execution of the statements that follow in a sequential block. § Update the LHS of non-blocking statements at the end of the time step.

and § both equations are scheduled to execute in the same simulation time step. such as on the same clock edge. § A problem with blocking assignments occurs when § the RHS variable of one assignment in one procedural block is also the LHS variable of another assignment in another procedural block. . which is considered to be a poor coding style. § The blocking assignment with timing delays on the RHS of the blocking operator.Blocking Assignments § The blocking assignment operator is an equal sign (=).

) § If blocking assignments are not properly ordered. . § When blocking assignments are scheduled to execute in the same time step. a race condition can occur.Blocking Assignments (Contd. § Evaluate the RHS (right-hand side equation) and update the LHS (left-hand side expression) of the blocking assignment without interruption from any other Verilog statement. the order execution is unknown..

reg y1. // reset else y1 = y2. y2. always @( posedge clk or posedge rst ) if (rst) y2 = 1. input clk. clk.Blocking Assignments Example module fbosc1 ( y1. rst ). always @(posedge clk or posedge rst ) if (rst) y1 = 0. y2. y2. rst. endmodule . output y1. // preset else y2 = y1.

the order of execution becomes tool-specific. endmodule § Because of all blocking assignments in different always blocks. always @(posedge clk) d4 = d3. always @(posedge clk) d3 = d2. d3. So. always @(posedge clk) d2 = d1. d4. reg d1. the design won’t behave like shift register! .A Flawed Shift Register § The following code doesn’t work as one may expect: module flawed_sr. d2.

Non-blocking Assignments § The non-blocking assignment operator is the same as the lessthan-or-equal-to operator ("<="). . § Between evaluation of the RHS expression and update of the LHS expression. and § schedules the LHS update to take place at the end of the time step. other Verilog statements can be evaluated and updated. § They are called “non-blocking” because§ the assignment evaluates the RHS expression of a it at the beginning of a time step.

. § Verilog statements from being evaluated. Execution of nonblocking assignments can be viewed as a two-step process: § Evaluate the RHS of non-blocking statements at the beginning of the time step.) § Also. . The non-blocking assignment does not block other. § Update the LHS of non-blocking statements at the end of the time step.Non-blocking Assignments (Contd. the RHS expression of other Verilog non-blocking assignments can also be evaluated and LHS updates scheduled.

y2. y2. rst ). y2. always @( posedge clk or posedge rst ) if (rst) y2 <= 1.. input clk. always @( posedge clk or posedge rst ) if (rst) y1 <= 0.Non-blocking Assignments (Contd. // preset else y2 <= y1. rst. // reset else y1 <= y2.) module fbosc2 ( y1. output y1. clk. reg y1. endmodule .

d2. LHS updated only after all events for the current instant have run RHS evaluated when assignment runs .) Nonblocking rule: This version works: reg d1.Non-blocking Assignments (Contd. always @(posedge clk) d4 <= d3. always @(posedge clk) d3 <= d2. always @(posedge clk) d2 <= d1. d3. d4..

b <= a. “ a 1 b c ” 1 a <= 1.Non-blocking Looks Like Latches a = 1. a b c “ ” . c <= b. b = a. c = b.

while(i<`MEMSIZE) begin mem[i] = 8’b0. i=i+1) begin mem[i] = 8’b0. end . end // example of “while” loop i = 0.Looping Flow Control Verilog supports “for”. i<`MEMSIZE. “while” and “repeat” and “forever” loop // example of “for” loop for( i=0.

i = i + 1. repeat (`MEMSIZE) begin mem[i] = 8’b0.// example of “repeat” loop i = 0. end . end // example of “forever” loop i = 0. i = i + 1. if (i == `MEMSIZE) disable mem_init. forever begin : mem_init mem[i] = 8’b0.

.Task and Function § Verilog support encapsulation of a piece of code into a task or a function. § A code that is expected to be issued interactively. § Break long procedural blocks into smaller parts in order to improve readability and maintenance of the code. with possibility different inputs. § Use task or function when: § A section of the code that is used more than once.

§ The code that initiated a task has to wait for that task to complete or disabled before continuing execution. A function can only model combinatorial functionality. whereas function must have at least one input and only one output. (which is the name of the function itself) .Difference between task and function § A task can have timing control constructs. § A task can have inputs and outputs. whereas function cannot.

function_example = in1 & in2. endtask Example of a function function [1:0] function_example. out2. input [1:0] in1. #1 out1 = in1 & in2. #1 out2 = in1 | in2. in2. output [1:0] out1. in2. input [1:0] in1. endfunction .Example of a task task task_example.

it displays the formatted string specified within double quotes. § $monitor : It continuously monitors the changes in any of the variable/signal specified in the parameter list. It inserts a newline at end of display text automatically.System Tasks § Verilog has some of the inbuilt task as part of the language itself. § $display : This system task is used to display the text and formatted data on the screen. any one of them changes. . Whenever. § $stop: It stops /suspends the simulation.

) § $finish: It terminates the simulation.System Tasks (Contd. it is a good practice to display them using $strobe. .. It is used mainly in test bench. When one wants to display the values of the variables which are assigned within non-blocking statements. § $write: It is similar to $display except that it does not insert a newline at the end of the formatted output by default. § $strobe: It is used for strobing purpose. § $random: It generates a 32-bit signed integer randomly.

. .) § $time: It returns the current simulation time.System Tasks (Contd. § $realtime: Same as $time excepts it shows the fraction part as well.

It has two parts: reference time unit & time precision. § `timescale: It is used to specify the timescale for simulation.Compiler Directives § All compiler directives are preceded by a ‘back tick’ ( ` ). First one specifies the time unit and the later determines the minimum unit that is considered for any round off. § `define : It is used to define a text macro in Verilog. § `include: It is used to include content of some other file inside a Verilog code. `timescale <ref_time_unit>/<precision> .

monitor($time. a). endmodule .System Tasks & Compiler Directives Example `timescale 10ns/1ns `define A 10 module abc().\nA = %d”. a). end always #25 a = $random. $display(“Initializing…. initial begin a = 3. reg [3:0] a. “ \tA = %d”. #300 $finish.

Synchronization Verilog support the following type of process synchronization § § § event fork and join disable .

Synchronization .Event § # <expression> suspends execution of the process for a fixed time period § @event-expression suspends the execution of the process until the specified event occurs § wait (expression) suspends the execution of the process until the expression become true .

event e1.Synchronization (Contd. … endmodule § Trigger an event using “ ->event_variable” § Wait for an event using “@event_variable ” . module event_example..) § Verilog supports “event” data type. e2.

Synchronization – fork and join module barrel_sync. join <statement S>. end endmodule <statement 1> to <statement N> are executed in parallel <statement S> is executed only when <statement 1> to <statement N> are completed . always begin … fork <statement 1>. … <statement N>. <statement 2>.

Synchronization – disable disable <block_name> § remove pending events from <block_name> § will not continue to execute the rest of the <block_name> § if <block_name> is in the always block. end … if “write_through”is true.g. all pending events (e. out=#10 ram[index] from the previous cycle) will be removed. … if ( write_through ) disable write_block. Execution start from <statement 1> . execution continues from the start of the always block … always begin : write_block <statement 1>. out = #10 ram[index].

as shown in an example: § Syntax. § An infinite loop that continuously executes the statement or statement group. § You must break up an infinite loop with an @(posedge clock) or @(negedge clock). § expression to prevent combinational feedback.Forever Statement § This loop executes continuously and never completes. forever #50 clock=~clock. end . § Infinite loops in Verilog use the keyword forever. forever<execution statement> initial begin clock=0.

§ Generate case. § There are three methods to create generate statements: § Generate loop. § All generate instantiations are coded with a module scope and require keywords generate – endgenerate. § Generate conditional. functions and tasks as well as control over instantiations. . § Generate statements allow control over the declaration of variables.Generate Statements § Generate statements are used when the same operation or module instance is repeated for multiple bits of vector.

.Generate Statements (Contd.) § Generate loop: It permits one or more of the following to be instantiated multiple times using a for loop. § Generate conditional :It is like an if-else-if generate construct that permits the following Verilog constructs to be conditionally instantiated based on an expression. .

Parameters § A parameter is defined by Verilog as a constant value declared within the module structure. parameter <identifier> = constant. The value can be used to define a set of attributes for the module which can characterize its behavior as well as its physical representation. . parameter byte_size = 8. reg[byte_size-1:0] A. § Used to pass information globally.

Race Conditions .

. § It can be eliminated by using non-blocking assignments instead of blocking assignments. § It would give different results when the order of statement execution is changed.Race conditions in Verilog § A Verilog race condition occurs when two or more statements that are scheduled to execute in the same simulation timestep. as permitted by the Verilog Standard.

$display with a #0 delay: initial begin #10 if (a) initial begin $display(“may not print”). endmodule end § In this example. . reg a.Race Conditions & their Solutions module race. so it is ambiguous whether the $display statement will be executed. initial begin a=0. § The solution is to delay the end. two parallel blocks have no guaranteed ordering. #10 a=1. #10 if (a) end #0 $display ("may not print").

output out. dff dff1( out. clk. in. a. input d. clk ). endmodule module dff( q. clk. wire a. input in. reg q. always @(posedge clk) q = d. clk ). dff dff0( a.Flip-Flop Race Condition module test( out. d. output q. in. // race! endmodule . clk ). clk ).

§ The following is the example of it in which an intermediate node a between two Flip-flops is set and sampled at the same time. .§ It is very common to have race conditions near latches or flipflops. always @(posedge clk) q <= d. § The solution for this is to use the non-blocking assignment in the flip-flop to guarantee the ordering of assignment to the output of the flip-flop and sampling of that output. always @(posedge clk) q <= #1 d. always @(posedge clk) q = #1 d.

UDPs .

or. . nor. designers occasionally like to use their own custombuilt primitives when developing a design. § However. such as and. § Verilog provides the ability to define User-Defined Primitives (UDP). These are also commonly known as built-in primitives.User Defined Primitives § Verilog provides a standard set of primitives. as a part of the language. and not. nand.

.) § There are two types of UDPs: § Combinational UDPs § Sequential UDPs § Combinational UDPs are defined where the output is solely determined by a logical combination of the inputs. The value of the output is also the internal state of the UDP. A good example is a 4-to-1 multiplexer.User Defined Primitives (Contd. § Sequential UDPs take the value of the current inputs and the current output to determine the value of the next output. Good examples of sequential UDPs are latches and flip-flops..

The inputs are declared with the keyword input. In the declarations section. § § § § . The terminal must always appear first in the terminal list.Rules to Define UDP § UDPs can take only scalar input terminals (1 bit). Since sequential UDPs store state. Multiple output terminals are not allowed. the output terminal must also be declared as a reg. the output terminal is declared with the keyword output. Multiple input terminals are permitted. UDPs can have only one scalar output terminal (1 bit).

Rules to Define UDP (Contd..)
§ The state in a sequential UDP can be initialized with an initial statement. This statement is optional. A 1-bit value is assigned to the output, which is declared as reg. § The state table entries can contain values 0, 1, or x. UDPs do not handle z values. z values passed to a UDP are treated as x values. § UDPs are defined at the same level as modules. UDPs cannot be defined inside modules. They can be instantiated only inside modules. UDPs are instantiated exactly like gate primitives. § UDPs do not support inout ports.

Combinational UDP-Example
primitive mux4_to_1 ( output out, input i0, i1, i2, i3, s1, s0); table // i0 i1 i2 i3, s1 s0 : out 1 ? ? ? 0 0 : 1; 0 ? ? ? 0 0 : 0; ? 1 ? ? 0 1 : 1; ? 0 ? ? 0 1 : 0; ? ? 1 ? 1 0 : 1; ? ? 0 ? 1 0 : 0; ? ? ? 1 1 1 : 1; ? ? ? 0 1 1 : 0; ? ? ? ? x ? : x; ? ? ? ? ? x : x; endtable endprimitive I0 I1 I2 I3 S0



Sequential UDP - Examples
//Define level-sensitive latch by using UDP. primitive latch(q, d, clock, clear); output q; reg q; input d, clock, clear; //sequential UDP initialization //only one initial statement allowed initial q = 0; //initialize output to value 0 //state table table //d clock clear : q : q+ ; ? ? 1 : ? : 0 ; //clear condition,q+ is the new o/p value 1 1 0 : ? : 1 ; //latch q = data = 1 0 1 0 : ? : 0 ; //latch q = data = 0 ? 0 0 : ? : - ; //retain original state if clock = 0 endtable endprimitive

//Define an edge-sensitive sequential UDP; primitive edge_dff(output reg q = 0, input d, clock, clear); table // d clock clear : q : q+ ; ? ? 1 : ? : 0 ; //output = 0 if clear = 1 ? ? (10) : ? : - ; //ignore negative transition of clear 1 (10) 0 : ? : 1 ; //latch data on negative transition of 0 (10) 0 : ? : 0 ; //clock ? (1x) 0 : ? : - ; //hold q if clock transitions to unknown //state ? (0?) 0 : ? : - ; //ignore positive transitions of clock ? (x1) 0 : ? : - ; //ignore positive transitions of clock (??) ? 0 : ? : - ; //ignore any change in d when clock //is steady endtable endprimitive (10) àNegative edge transition from 1 to 0
(1x) àTransition from 1 to unknown (0?) àTransition from 0 to 0,1,x.potential +ve edge transition (??) àTransition in signal value 0,1, or x to 0, 1, or x

Modelling FSMs in Verilog .

Output may change if inputs change during clock period.FSM Classification Mealy: Output is a function of present state and inputs. due to this the outputs may have momentary false values because of the delay encountered from the time the input change and the time that the FF output change. Input Next state Decoder Memory Output Decoder Output Clock .

FSM Classification Moore: Output is a function of present state only that are synchronized with the clock. Input Next state Decoder Output Decoder Output Memory Clock Input Next state Decoder Output Memory Clock .

FSM encoding Encoding the states is assigning unique binary numbers to the states State Initial S1 S2 S3 S4 Binary 000 001 010 011 100 Gray 000 001 011 010 110 One-hot 00001 00010 00100 01000 10000 .

there will be only one switching between adjacent states. This reduces glitches at the outputs due to unequal delays of storage devices. § Gray If it is gray encoded. .FSM encoding § Binary The number of storage devices (Flip-flops) is minimum.

clock frequency) is not limited by the combinational logic. Hence Faster FSM. the speed of the FSM (Max. § Use “casex” for output and next state decoder .FSM encoding § One-hot § only one of the state variables will be ‘1’ and all others will be ‘0’s for a state. § Complexity of Next state Decoder and Output Decoder is reduced § Due to reduced complexity of Decoders .

Modeling Mealy FSM § always@(in or pres_state) //Next //State Decoder § always@(posedge clock) //Memory § always@(in or pres_state) //Output //Decoder Ex: “101” Sequence detector .

Modeling Moore FSM § always@(in or pres_state) //NS Dec § always@(posedge clock) //Memory § always@(pres_state) //Output Dec Ex: 3-bit counter with output ‘1’ when count is “111” .

Verilog Logic Synthesis .

RTL Synthesis What is RTL Register Transfer Level : storage element. like flip-flop. output and register : level of abstraction . latches : transfer between input.

.RTL Synthesis RTL synthesis RTL Synthesis is a process to transform design description from RTL abstraction to the gate abstraction.

RTL Synthesis VHDL/Verilog RTL level Optimization Structural representation. Logic Level Optimization Fixed Synchronous logic. Boolean equation representation of combinational logic Netlist . Control-Data Flow Graph Gate level Optimization Cell from a technology specific library.

Why is RTL synthesis important? § It is an important tool to improve designers’ productivity to meet today’s design complexity. or almost 2 years for 10 designers. § If a designer can design 150 gates a day. it will take 6666 man’s day to design a 1 million gate design. This is assuming a linear grow of complexity when design get bigger. .

Synthesis Process Synthesis RTL Cell Library § § § § § § § § § § § § § § § Operating Condition Design Constraint Area Timing Power Design Rule DFT Cell Name Cell Type Cell Function Cell Area Cell Timing Cell Power Cell Pin Cell Pin Loading Cell design rule Wire Load Table Gate .

Synthesis Process § Not all Verilog commands synthesize easily. § However in hardware only variables stored in flip-flops are easy to initialize. § For example initial initializing variables is easy to do in a program where all variables are stored. . These presentation will concentrate on that subset. For this reason only a subset of Verilog is synthesizable.

time and resistance units. § A library may contain: § The timing and electrical characteristics of the cells § Net delay and net parasitic information § Definition of capacitance. They can be understood by the tools. § Most libraries are compiled before delivery. § Technology libraries are created by the silicon vendor. but are unreadable to you. Not by the synthesis tools. .Technology Library § A Technology Library contains a set of primitive cells which can be used by synthesis tools to build a circuit.

is normally only used in test benches § Variables on the left-hand side should be of type reg in a procedural code . In a structural code the LHS variable should be of type wire .Verilog Procedure § initial is not synthesizable and is used for test benches. § always without @ condition. or at least not of type wire.

Example 1 Example 2 .it will infer a latch.Only Put Latches If Necessary § Many procedures do not need to store values. nothing needs to be stored. § In example2 we have initialized the value before the if statement so that it need not have to remember the value where as in example1. If all left-hand values can be calculated from a single procedure entry. since it has to remember the values when enable =0 .

else z=4. Later on different values can overwrite those values. z=0. every path must evaluate all outputs. always @(. Else synthesis will insert latches to hold the old value of those unevaluated outputs. elseif (b) y=3. y=0. begin x=0. § If the procedure has several paths. if (a) x=2. end Method 1: .Only Put Latches If Necessary § Every time one executes a procedure all of the variables defined anywhere in the procedure must be calculated. . Set all outputs to some value at the start of the procedure. .

always @(. . y=3. end else begin x=0. end elseif (b) begin x=0. .Method 2 Be sure every branch of every if and case generate every output. y=0. y=0. z=0. end end end . z=0. z=4. begin if (a) begin x=2.

always @ Can infer: flip-flops. .This may generate a latch.Procedural synthesis Logic Inference Deciding what logic to synthesize from code is called inference. latches. Latches and Combinational always @(C or D) :. It may just result in combinational logic. and/or combinational logic. always @(posedge Clk) This is the statement that tells the logic compiler to generate flip flops.

end //No Latch Inference from if reg Z. end . //Initialize if (Ck) Z <= D. always @(Ck or D) begin Z<=1’b0.Latch Inference Inserting Latches With or Without Your Asking Latches form if //Latch Inference form if reg Q. always @(Clk or D) begin if (Clk) Q <= D.

RTL level Optimization § Code related processing is first performed when a model is synthesized. A + 3 + 2 becomes A + 5 § Loop unrolling . . § Constant folding .subprograms are in-lie expanded. Some of the steps are: § Expansion .loop statements are unrolled to a series of individual § Dead code removal .any unused code is discarded.

operator bit width. VHDL state encoding.RTL level Optimization § Bit minimization . etc. ‘+’ operator can be carry look-forward (fastest). carry look-ahead or ripple carry (smallest). or assignments of different widths in Verilog. etc.for example. . § Common sub-expression sharing. § Operator reordering. § Different implementations of arithmetic operators have different area and timing characteristics. § Resource sharing.g. E.

N=A+C SELECT . end. If (S == 1’b0) begin L <= A + B. N <= A .C. L=A+B M=L+L FORK N=A-C JOIN MERGE CDFG level optimization techniques will be used. M <= L + L.CDFG format § The control data flow graph is often used by synthesis tools for highest internal representation. end if. else N <= A + C.

only combinational logic is optimized. . § Optimization at this level involves restructuring of equations according to the rules of Boolean law.Logic level optimization § All registered elements are fixed. § The types of logic optimization include: § minimization § equation flattening § equation factorization § The algorithms used work on multiple equations and multiple outputs.

D Y2=A.D Y2=A.B.B.C+A.B.B.C Y1=L+M.B+C+D flatten equations Y1=A.B N=C+D Y1=M.Logic level optimization L = A.C Y1=L+A.N Y2=M+N .B+C+D factorize factorize M=A.B L=M.D Y2=M+C+D M=A.

If the optimization effort is increased then the optimizer will look at a slightly larger area each time. .Gate Level Optimization § Gate level optimization consists of § Combinational mapping § Sequential mapping § Gate level optimization is a process of looking at local area of logic containing a few cells and trying to replace them by other cells from the technology library that fit the constraints better. § It then looks at another local area with an overlap with the first local area.

Mapped circuit before gate level optimization. .

5 equivalent gates .After gate level optimization 3 cells 14 transistors 3.

Verilog Coding Guidelines .

Guideline #4: When modeling both sequential and combinational logic within the same always block.Verilog Coding Guidelines Guideline #1: When modeling sequential logic. use nonblocking assignments. Guideline #2: When modeling latches. use nonblocking assignments . Guideline #3: When modeling combinational logic with an always block. use nonblocking assignments. use blocking assignments.

Guideline #6: Do not make assignments to the same variable from more than one always block. Guideline #8: Do not make assignments using #0 delays.Verilog Coding Guidelines Guideline #5: Do not mix blocking and nonblocking assignments in the same always block. Guideline #7: Use $strobe to display values that have been assigned using nonblocking assignments. .

Verilog "stratified event queue" .

Electrical Properties .

Signal Types § § § § 0 : Logical 0. Can be 0. 1 or Z . or false condition Z : High impedance state X : Unknown logic condition. or false condition 1 : Logical 1.

Signal Types(cont) 0 0 X Z 0 1 1 Z X Z Z 1 X X .

Signals (cont) 0 X 1 X 1 X 0 X 0 S0 S1 SEL X S0 1 X X 0 X 1 S1 X X 0 1 SEL 0 1 X X Z S0 S1 0 1 Z .

Signal Strength (cont) Logic 0 strength Logic 1 strength 7 6 5 4 3 Su0 St 0 Pu0 La0 We0 2 1 0 Me0 Sm 0 HiZ 0 0 HiZ 1 1 Sm1 2 3 4 5 6 7 Me1 We 1 La1 Pu1 St 1 Su1 Su1(7) Su1(7) La0(4) .

weak0.Verilog Syntax for Strength Only for gate instantiation // and gate with weak pull up and (supply0. strong1. supply0. weak1. highz1. strong0. pull1. highz0. weak1) (out. in1. pull0. in2). . Note: Valid strength keywords are supply1.

rpmos. rtranif0. rnmos.Support for transmission gate rcmos.rtrainif1 reduce the output strength as follow: Input Strength Supply drive Strong drive Pull drive Weak drive High impedance Output Strength Pull drive Pull drive Weak drive Medium capacitor High impedance in0 in1 sel out . rtran.

specify specparam A1_to_Z=12. (A1 => Z) = A1_to_Z. A1.Timing Delay in ASIC library Pin-to-Pin delay module AND2 (Z. A2_to_Z=14. input A1. A1. output Z. A2). and (Z. A2). (A2 => Z) = A2_to_Z. endspecify endmodule A1 to Z delay A1 Z A2 A2 to Z delay . A2.

Timing Delay in Gate Back-annotation Verilog Delay Calculation SDF Physical Information .

Timing Delay Calculation RC network Delay Load Cell Library Output skew Load Input skew Table Look-up Skew SDF .

Timing Delay .sdf”). . Note: $sdf_annotate() can be placed anywhere in the HDL code. mod1. “mod1_sdf. $sdf_annotate(“mod1.sdf”.SDF Back-Annotation Using system task $sdf_annotate(). However. it make no sense to put it after time 0 . Example § § $sdf_annotate(“full_chip.log”).

Macros. Conditional Compilation & Naming Convention .

Keyword cannot be used as macro name. (e. (It does not make sense).v +define+regressionSuit=“4” ) .g. Macro can be re-define.Macro § § § § § § Macro names and the names used in the design are different Macro definition is global. There is not scope restriction. One line comment (//) will be excluded in the text substituted. The last definition read is used. Macro can also be defined in the command line. verilog design. These macro has the highest priority.

‘define WORD 8 //word size ‘define CLOCKMUX ssmux8 module register(…) reg [‘WORD-1 : 0] cpu_reg.Macro Cont. … endmodule .. … ‘CLOCKMUX hand_clockMux (…).

c). b. § Verilog simulator does not keep record of the ignored text.Conditional Compilation § ‘ifdef. c). ‘else and ‘endif can be nested § Syntax for the ignored Verilog texts are not checked. reg [8:0] a. 7)i0 (a.g. module adder(a. input [7:0] b. output [8:0] a. c. profiling and encryption) from the simulation does not retain the full Verilog input. Thus any output (e. ‘endif end endmodule . ‘else gateAdder #(8. 7. always @ (b or c) begin ‘ifdef BEHAVIOURAL a = b + c. b.

Unique pre-fix for modules belong to the same circuit partition.Good Naming Convention § § § § § § Use all upper-case for constants specified by ‘define macro and code inclusion control name defined by ‘ifdef and ‘define. . Use very short name in ASIC library. Use short instance name. Use the same port name and wire name when the signal goes through different hierarchy. Do not use port names that are used in the ASIC library.

Verilog for Logic Simulation .

Introduction Input command line Simulation Waveform Testbench Log Design Key Log .

dat”). $pli_currentDateTime() ). $fdisplay(fileID. initial begin fileID = $fopen(“capture.File Output $display(). “Start Simulation %s”. end . $write() and $monitor() have a counterpart to write to a specific file. integer fileID. if (fileID == 0) $finish. beside the log file.

§ § § § § § timing control input stimulus device under test reference model diagnostic logging assertion checking .Test bench § The following things are essentially required to be provisioned a test bench.

inputC=1’b0. #9 {inputA.Test bench – timing control initial begin #10 inputA = 1’b1. end initial begin clock = 1’b0. end . inputB} = 2’b00. #12 inputB = 1’b1. forever #10 clock = !clock. inputD=1’b1.

A VCD waveform viewer can show the result in the form of waveform display.<module or variable>>*). Specify VCD filename $dumpfile(“<fileName>”).Waveform Probing using VCD Verilog supports Value Change Dump (VCD) output. . $dumpvars(<level> <. Specify dump variable Start/Stop dumping $dumpon. / $dumpoff.

§ Dump all variables in the module top.net1 is also dumped.mod1 in the design hierarchy. § Dump all variables in top.mod2. top.mod1.mod1. § Dump all variables in the design.mod1). $dumpfile(0.mod1. top. $dumpfile(1. Net top.mod1 and all modules instantiate below top. top. <level> only affect module.Waveform Probing using VCD $dumpfile.mod1). . not variable. $dumpfile(0.mod1. § Dump all variables in the module top. top.mod2.net1). and in all module instances below top.

gate and primitive in the design .Interactive Debugging Simulation control (depends on simulator) § § § § § § $finish() $stop() . .. $reset : finish the simulation : stop simulation and enter interactive mode : continue simulation : step : restart the simulation $reset_count : number of times $reset is called Some useful system tasks § $showvars() : show unresolved values of specified variables § $system() : execute a system command § $showallinstance(): show number of instances of each module.

// reset is 1 #10 a = 1. input reset. reg a.Simulation Tips 1 Zero-delay loop A common mistake in big design. module top(reset). always begin if ( !reset ) begin // what happen when #10 a = 0. end end endmodule . Usually indicates a logic error.

#10 reset = 1.c. endmodule .d}=13’b0. reg clk. else d = !d. forever #10 clk = !clk. d. c. always @(a or d) begin b = b + 1’b1. if (d) res = b + d. end always @(posedge clk or posedge reset) if(reset) {a. res. initial begin clk = 0.A more complicated zero delay loop module top. #10 reset = 0. end initial begin reset = 0. always @(c) a = a + 1’b1. reg [3:0] a.b. end always @(b) c = c + 1’b1. b. reset. #1000 $finish.

parameter delay=10 assign #delay a = b. assign j = k + m. … Accelerated continuous assignment Non-accelerated continuous assignment . assign #var h = i. Non-accelerated Construct … reg var. assign e = f & g.Simulation Tips 2 Accelerated vs. assign #(delay + 1) c = d.

Simulation Tips 3 Timing violation in register when crossing timing domains unSyncD syncD clk1 clk2 unSyncD clk2 syncD .

The “X”state get propagated to the rest of the circuit. unSyncD sel clk1 clk2 . and the simulation becomes meaningless.The timing violation can “kill” the simulation.

Introduction to PLI .

§ PLI is used to customize the capability of the Verilog language by defining their own system tasks and functions for which designers need to interact with the internal representation of the design and the simulation environment in the Verilog simulator. User-defined system tasks and functions can be created with this predefined set of PLI interface routines.Where PLI is Used § The Programming Language Interface (PLI) provides a set of interface routines to read internal data representation. write to internal data representation. . and extract information about the simulation environment.

Simulation Flow Using PLI routines .

and writing data to output devices. . § Verilog Procedural Interface (vpi_) routines make up the thirdgeneration PLI. These routines can be used to access and modify a wide variety of objects in the Verilog HDL description. callback mechanism. These routines are provide object-oriented access directly into a Verilog HDL structural description. These routines are primarily used for operations involving userdefined task/function arguments. utility functions.Generations of Verilog PLI § Task/Function (tf_) routines make up the first generation PLI. § Access (acc_) routines make up the second-generation PLI. These routines are a superset of the functionality of acc_ and tf_ routines.

logic connectivity. source level browsers. and complex operations that cannot be implemented with standard Verilog constructs.Uses Of PLI § PLI can be used to define additional system tasks and functions. stimulus tasks. Typical examples are monitoring tasks. Waveform viewers can use this file to generate waveforms. . § Application software like translators and delay calculators can be written with PLI. fanout. connectivity. and hierarchy information. debugging tasks. and number of logic elements of a certain type. § PLI can be used to write special-purpose or customized output display routines. § PLI can be used to extract design information such as hierarchy.

The stimulus could be automatically generated or translated from some other form of stimulus.) § Routines that provide stimulus to the simulation can be written with PLI.. .Uses Of PLI (Contd. § General Verilog-based application software can be written with PLI routines. This software will work with all Verilog simulators because of the uniform access provided by the PLI interface.

This process is called linking the PLI routines into the Verilog simulator. . } § Whenever the task $hello_verilog is invoked in the Verilog code.Linking and Invocation of PLI Tasks example of a simple system task $hello_verilog #include "veriuser. the C routine hello_verilog must be executed. The simulator needs to be aware that a new system task called $hello_verilog exists and is linked to the C routine hello_verilog.h" /*include the file provided in release dir */ int hello_verilog() { io_printf("Hello Verilog World\n").

§ Once the user-defined task has been linked into the Verilog simulator.§ At the end of the linking step. instead of the usual simulator binary executable. a new binary executable hverilog is produced. A Verilog module hello_top. it can be invoked like any Verilog system task by the keyword $hello_verilog. For example. //Invoke the user-defined task $hello_verilog endmodule Output of the simulation is as follows: Hello Verilog World . To simulate. which calls the task $hello_verilog. is defined in file hello.v as shown below: module hello_top. initial $hello_verilog. run hverilog instead of your usual simulator executable file. a special binary executable containing the new $hello_verilog system task is created.


Summary of Verilog
§ Systems described hierarchically § Modules with interfaces § Modules contain instances of primitives, other modules § Modules contain initial and always blocks § Based on discrete-event simulation semantics § Concurrent processes with sensitivity lists § Scheduler runs parts of these processes in response to changes

Modeling Tools
§ Switch-level primitives CMOS transistors as switches that move around charge. § Gate-level primitives Boolean logic gates § User-defined primitives Gates and sequential elements defined with truth tables § Continuous assignment Modeling combinational logic with expressions § Initial and always blocks Procedural modeling of behavior

Language Features
§ Nets (wires) for modeling interconnection § Non state-holding § Values set continuously § Regs for behavioral modeling § Behave exactly like memory for imperative modeling. § Do not always correspond to memory elements in synthesized netlist. § Blocking vs. nonblocking assignment § Blocking behaves like normal “C-like” assignment § Nonblocking updates later for modeling synchronous behavior

Language Uses
§ Event-driven simulation § Event queue containing things to do at particular simulated times. § Evaluate and update events. § Compiled-code event-driven simulation for speed. § Logic synthesis § Translating Verilog (structural and behavioral) into netlists. § Register inference: whether output is always updated. § Logic optimization for cleaning up the result.

Little-used Language Features
§ Switch-level modeling § Much slower than gate or behavioral-level models. § Insufficient detail for modeling most electrical problems. § Delicate electrical problems simulated with a SPICE-like differential equation simulator. § Delays § Simulating circuits with delays does not improve confidence enough. § Hard to get timing models accurate enough. § Never sure you’ve simulated the worst case. § Static timing analysis has taken its place.

Verilog Strengths and Weaknesses
§ Verilog is widely used because it solves a problem § Good simulation speed that continues to improve. § Designers use a well-behaved subset of the language. § Makes a reasonable specification language for logic synthesis. § Logic synthesis one of the great design automation success stories. § Verilog is a deeply flawed language § Non-deterministic. § Often weird behavior due to discrete-event semantics. § Vaguely defined synthesis subset. § Many possible sources of simulation/synthesis mismatch.

asic-world. Palnitkar. IEEE Standard Hardware Description Language Based on the Verilog Hardware Description Language. Verilog HDL: A Guide to Design and Synthesis Samir.References § § § § http://www.sunburst-design. IEEE Computer Society. . IEEE Std

ThanQ .

Sign up to vote on this title
UsefulNot useful