Lecture #2: Verilog HDL

3m ago
17 Views
0 Downloads
212.68 KB
18 Pages
Transcription

Lecture #2: Verilog HDLKunle OlukotunStanford EE183January 10, 2003Why Verilog? Why use an HDL?– Describe complex designs (millions of gates)– Input to synthesis tools (synthesizable subset)– Design exploration with simulation Why not use a general purpose language––––Support for structure and instantiation (objects?)Support for describing bit-level behaviorSupport for timingSupport for concurrency Verilog vs. VHDL– Verilog is relatively simple and close to C– VHDL is complex and close to Ada– Verilog has 60% of the world digital design market (larger share inUS) Verilog modeling range– From gates to processor level– We’ll focus on RTL (register transfer level)1

EE183 Design Process Understand problem and generate block diagramof solution (datapath control decomposition) Code block diagram in verilog Synthesize verilog Create verification script to test design Run static timing tool to make sure timing is met Design is mapped, placed, routed, and *.bit file iscreated download to FPGAEvent Driven Simulation Verilog is really a language for modeling eventdriven systems– Event : change in stateEventqueue0t t 1 Events– Simulation starts at t 0– Processing events generates new events– When all events at time t have been processedsimulation time advances to t 1– Simulation stops when there are no more events in thequeue2

Modeling Structure: Modules The module is the basic building block in Verilog– Modules can be interconnected to describe the structureof your digital system– Modules start with keyword module and end withkeyword endmoduleModule AND port list Module CPU port list endmoduleendmodule– Modules have ports forinterconnection with other modulesModeling Structure: Ports Module Ports– Similar to pins on a chip– Provide a way to communicate with outside world– Ports can be input, output or inoutModule AND (i0, i1, o);input i0, i1;output 0;i0oi1 endmodule3

Modeling Structure Module instances– Verilog models consist of a hierarchy of moduleinstances– In C speak: modules are classes and instances areobjectsAND3Module AND3 (i0, i1, i2, o);input i0, i1, i2 ;output 0;i0wire tempi1i2oAND a0 (i0, i1, temp);AND a1 (i2, temp, 0);endmoduleLogic Values 0: zero, logic low, false, ground 1: one, logic high, power X: unknown Z: high impedance, unconnected, tri-state4

Data Types Nets– Nets are physical connections between devices– Nets always reflect the logic value of the driving device– Many types of nets, but all we care about is wire Registers– Implicit storage – unless variable of this type ismodified it retains previously assigned value– Does not necessarily imply a hardware register– Register type is denoted by reg– int is also usedVariable Declaration Declaring a netwire [ range ] net! name [ net name *];Range is specified as [MSb:LSb]. Default is one bit wide Declaring a registerreg [ range ] reg! name [ reg name *]; Declaring memoryreg [ range ] memory! name [ start addr : end addr ]; Examplesreg r; // 1-bit reg variablewire w1, w2; // 2 1-bit wire variablereg [7:0] vreg; // 8-bit registerreg [7:0] memory [0:1023]; a 1 KB memory5

Ports and Data Types Correct data types for etnetinoutnetExample ModuleBuses are created asvectors. For n bit bus usemodule synchronizer (in, out, clk);convention: [n-1:0]parameter SIZE 1;input [SIZE-1:0] ininput clk;output [SIZE-1:0] out;wire [SIZE-1:0] x;All Input and Output portsmust be declared as such.Can also be “inout” for tristate but rarely usedAll internal variables must beexplicitly declared.“wire” is one type of net used toconnect thingsdff #(SIZE) dff 1(.d(in[SIZE-1:0]), .clk(clk), .q(x[SIZE1:0]));dff #(SIZE) dff 2(.d(x[SIZE-1:0]), .clk(clk), .q(out[SIZEInstantiation: “dff” is name of module1:0]));“#(SIZE)” overwrites parameters“.port in called module(signal in this model)”endmodule6

Modeling Behavior Behavioral ModelingDescribes functionality of a module Module BehaviorCollection of concurrent processes1. Continuous assignments2. Initial blocks3. Always blocksVerilog OperatorsArithmetic: , , *, /, %Binary bitwise: , &, , , Unary reduction: &, &, , , , Logical: !, &&, , , , ! , ! returns x if any of the input bits is xor z compares xs and zsRelational: . , , Logical shift: , Conditional: ?:Concatenation: {}7

Lexical Conventions The lexical conventions are close to the programminglanguage C . Comments are designated by // to the end of a line or by /*to */ across several lines. Keywords, e. g., module, are reserved and in all lower caseletters. The language is case sensitive, meaning upper and lowercase letters are different. Spaces are important in that they delimit tokens in thelanguage.Number specification Numbers are specified in the traditional form of a series ofdigits with or without a sign but also in the following form: size base format number – where size contains decimal digits that specify the size of the constantin the number of bits. The size is optional. The base format is thesingle character ' followed by one of the following characters b, d, o andh, which stand for binary, decimal, octal and hex, respectively. The number part contains digits which are legal for the base format .Some examples:– 4'b0011 // 4-bit binary number 0011– 5'd3// 5-bit decimal number– 32’hdeadbeef // 32 bit hexadecimal number8

Bitwise/Logical Operators Bitwise operators operate on the bits of the operand oroperands.– For example, the result of A & B is the AND of each corresponding bitof A with B. Operating on an unknown (x) bit results in the expectedvalue. For example, the AND of an x with a FALSE is an FALSE. TheOR of an x with a TRUE is a TRUE. Operator & & or NameBitwise negationBitwise ANDBitwise ORBitwise XORBitwise NANDBitwise NOREquivalence (Bitwise NOT XOR)Miscellaneous Operators { , } Concatenation of nets Joins bits together with 2 or more comma-separated expressions, e, g.{A[0], B[1:7]} concatenates the zeroth bitof A to bits1 to 7 of B. Shift left (Multiplication by power of 2) Vacated bit positions are filled with zeros, e. g., A A 2; shifts Atwo bits to left with zero fill. Shift right (Division by power of 2) Vacated bit positions are filled with zeros. ?:Conditional(Creates a MUX) Assigns one of two values depending on the conditional expression.E.g., A C D ? B 3 : B-2; means if C greater than D, the value ofA is B 3 otherwise B-2.9

Unary Reduction Operators Unary reduction operators produce a single bit result fromapplying the operator to all of the bits of the operand. Forexample, &A will AND all the bits of A. Operator& & NameAND reductionOR reductionXOR reductionNAND reductionNOR reductionXNOR reduction I have never used these, if you find a realistic application,let me know JRelational Operators Relational operators compare two operands and return alogical value, i. e., TRUE(1) or FALSE(0)—what do thesesynthesize into? If any bit is unknown, the relation is ambiguous and the result isunknown – should never happen!Operator ! NameGreater thanGreater than or equalLess thanLess than or equalLogical equalityLogical inequality10

Logical Operators Logical operators operate on logical operands andreturn a logical value, i. e., TRUE(1) or FALSE(0).– Used typically in if and while statements. Do not confuse logical operators with the bitwise Booleanoperators. For example , ! is a logical NOT and is a bitwiseNOT. The first negates, e. g., !(5 6) is TRUE. The secondcomplements the bits, e. g., {1,0,1,1} is 0100.––––Operator!&& NameLogical negationLogical ANDLogical ORContinuous AssignmentContinually drive wire variablesUsed to model combinational logic or make connectionsbetween wiresModule half adder(x, y, s, c)input x, y;output s, c;assign s x y;assign c x & y;–Anytime right hand side(RHS) changes, left handside (LHS) is updated–LHS must be a “net”endmoduleModule adder 4(a, b, ci, s, co)input [3:0] a, b;input ci;output [3:0]s;output co;assign {co, s} a b ci;endmodule11

Initial and Always Multiple statements per blockProcedural assignmentsTiming controlcontrol Initial blocks execute once at t 0 Always blocks execute continuously at t 0 and repeatedly thereafterinitialbeginalwaysbegin endendProcedural assignments Blocking assignment Regular assignment inside procedural blockAssignment takes place immediatelyLHS must be a registeralwaysbeginA B;B A;endA B, B B Nonblocking assignment Compute RHSAssignment takes place at end of blockLHS must be a registeralwaysbeginA B;B A;endswap A and B12

Using Procedural Assignments We will only use them to define combinationallogic– as a result, blocking ( ) and nonblocking assignment( ) are the same Example:LHS must be of type regDoes NOT mean this is a DFFreg out;always @(in1 or in2)beginout in1 & in2;endAll input signals must be insensitivity list (fully qualified)Begin and End define a blockin VerilogIf-Else Conditional Just a combinational logic mux Every if must have matching else or state element will beinferred—why?always @(control or in1 or in2)beginif (control 1’b1) beginout in1;endelse beginout in2;endend Watch nestings—make life easy, always use begin end13

Case Statement ProceduralAssignmentmodule mux4 to 1 (out, i0, i1, i2,output out;input i0, i1, i2, i3;input s1, s0;reg out;always @(s1 or s0 or i0 or i1 orbegincase ({s1, s0})2'b00: out i0;2'b01: out i1;2'b10: out i2;2'b11: out i3;default: out 1'bx;endcaseendendmodulei3, s1, s0);Note how all nets that are inputs to thealways block are specified in thesensitivity list (fully qualified)i2 or i3)Make sure all 2 n cases are covered orinclude a “default:” statement or elsestate elements will be inferredX is don’t careAfter initial synchronous resetthere should never be any X’s inyour designLoop Statements Repeati 0;repeat (10)begini i 1; display( “i %d”, i);end Whilei 0;while (i 10)begini i 1; display( “i %d”, i);end Forfor (i 0; i 10; i i 1)begini i 1; display( “i %d”, i);end14

Verilog Coding Rules Coding rules eliminate strange simulationbehavior– When modeling sequential logic, use nonblockingassignments– When modeling combinational logic with alwaysblock, use blocking assignments. Make sure all RHSvariables in block appear in @ expression– If you mix sequential and combinational logic withinthe same always block use nonblocking assignments– Don’t mix blocking and nonblocking assignments inthe same always block– Don’t make assignments to same variable from morethan one always block– Don’t make assignments using 0# delaysSo how do I get D-FlipFlops? Use 183lib.v to instantiate them– dff, dffr, dffre These are the only state elements (except forCoreGen RAMs) allowed in your designFFdff,dffr,dffreCombinational logic (NS, O)wireModules withfully qualifiedalways blockswire15

Dffre guts// dffre: D flip-flop with active high enable and reset// Parametrized width; default of 1module dffre (d, en, r, clk, q);parameter WIDTH 1;input en;input r;input clk;input [WIDTH-1:0] d;output [WIDTH-1:0] q;reg [WIDTH-1:0] q;always @ (posedge clk)Only change LHS on “posedge clk”if ( r )Note that if statement is missing an elseq {WIDTH{1'b0}};else if (en)q d;Replicator Operator.else q q;How cute!! JendmoduleNo Behavioral Code No “initial” statements– Often used to reset/initialize design No system tasks– “ ” commands (ie, “ display()”) For both, use Xilinx simulator and scripts16

Use Case Statement for FSM Instantiate state elements as dffX Put next state logic in always @() block– Input is curstate (.q of dffX) and other inputs– Output is nextstate which goes to .d of dffX– Use combined case and if statements “If” good for synchronous resets and enables Synthesis tools auto-magically minimizes allcombinational logic.– Three cheers for synthesis!! J8-bit Countermodule counter 8 (clk, reset, en, cntr q);input clk;input reset;input en;output [7:0] cntr q;reg [7:0] cntr d;wire [7:0] cntr q;// Counter next state logicalways @(cntr q)begincntr d cntr q 8'b1;end// Counter state elementsdffre #(8) cntr reg (.clk(clk), .r(reset), .en(en),.d(cntr d), .q(cntr q));Endmodule17

CoreGen Tools ‡ Design Entry ‡ Core Generator– Useful info appears in “language assistant”—Read it! Only use this for memories for now– Do you need anything else? I really cannot think of anything now Caveat: Block Memory does not simulatecorrectly with initial values.– Must create gate netlist by completing synthesis andimplementation.– Simulate by loading time sim.edn into SimulatorMonday Jan 13 Lab project #1 The Game of Life18