Verilog Interview Questions
Verilog Interview Questions
Verilog Interview Questions
module delay(in,transport,inertial);
input in;
output transport;
output inertial;
reg transport;
wire inertial;
// behaviour of delays
always @(in)
begin
transport <= #10 in;
end
endmodule // delay
_______ __
transport _________| |_____||_____
_______
inertial _________| |____________
Non blocking assignment gives you transport delay. Whenever input changes, output is
immediately evaluated and kept in a event queue and assigned to output after specified
"transport" delay.
In Continuous assign statement the latest event overrides the earlier event in the queue.
module test;
reg in;
wire transport, inertial;
// apply inputs
initial
begin
in = 0;
#20 in = 1;
#20 in = 0;
#30 in = 1;
#5 in = 0;
#30 in = 1;
#30 $finish;
end
// monitor signals
initial
begin
$monitor($time," in = %b transport = %b inertial = %b",
in,transport, inertial);
end
endmodule // test
log file
Compiling source file "delay.v"
Highest level modules:
test
0 in = 0 transport = x inertial = x
10 in = 0 transport = 0 inertial = 0
20 in = 1 transport = 0 inertial = 0
30 in = 1 transport = 1 inertial = 1
40 in = 0 transport = 1 inertial = 1
50 in = 0 transport = 0 inertial = 0
70 in = 1 transport = 0 inertial = 0
75 in = 0 transport = 0 inertial = 0
80 in = 0 transport = 1 inertial = 0
85 in = 0 transport = 0 inertial = 0
105 in = 1 transport = 0 inertial = 0
115 in = 1 transport = 1 inertial = 1
L35 "delay.v": $finish at simulation time 135
81 simulation events
You could read back in the output of $system, by writing it to another file and reading it back in
using $readmemh() as illustrated in following example.
module top;
module bold;
initial begin
endmodule
Sample Verilog Questions asked in Interviews. Please contribute with your questions. If
you are looking for answers please refer to website Site FAQ
reg Var1;
initial begin
Var1<= "-"
end
In the below code, Assume that this statement models a flop with async reset. In
this, how does the synthesis tool, figure out which is clock and which is reset. Is the
statements within the always block is necessary to find out this or not ?
1 module which_clock (x,y,q,d);
2 input x,y,d;
3 output q;
4 reg q;
5
6 always @ (posedge x or posedge y)
7 if (x)
8 q <= 1'b0;
9 else
10 q <= d;
11
12 endmodule
1 module quest_for_in();
2
3 integer i;
4 reg clk;
5
6 initial begin
7 clk = 0;
8 #4 $finish;
9 end
10
11 always #1 clk = ! clk;
12
13 always @ (posedge clk)
14 begin
15 for (i=0; i < 8; i = i + 1) begin : FOR_IN
16 if (i == 5) begin
17 disable FOR_IN;
18 end
19 $display ("Current i : ‰g",i);
20 end
21 end
22 endmodule
Method #1
1 initial begin
2 clk = 0;
3 end
4
5 always begin
6 #5 clk = ~clk;
7
8 end
Method #2
1 initial begin
2 clk = 0;
3 forever begin
4 #5 clk = ~clk;
5 end
6 end
Method #3
1 initial begin
2 clk = 0;
3 end
4
5 always begin
6 #5 clk = 0;
7 #5 clk = 1;
8 end
There are many ways to generate clocks: you may introduce jitter, change duty cycle.
To test or verify or validate any design, you need to have a test bench; writing test
benches is as difficult as designing itself. Please refer to the Verilog tutorial section in
"Art of Writing Test Bench" for more details.
Please refer to tidbits section for the difference between wire and reg.
Latches are always bad (I don't like that statement); latches are caused when all the
possible cases of assignment to variable are not covered. Well this rule applies to
combinational blocks (blocks with edge sensitive lists are sequential blocks); let's look at
the following example.
Bad Code
1 always @ (b or c)
2 begin
3 if (b) begin
4 a = c;
5 end
6 end
In the code above, value of a is retained, and it gets changed only when b is set to '1'. This
results in a latch. (Need to phrase it right)
Good Code #1
1 always @ (b or c)
2 begin
3 a = 0;
4 if (b) begin
5 a = c;
6 end
7 end
In the code above, no matter what the value of b is, a gets value of '0' first and if b is set
to '1' and c is set to '1', only then a gets '1'. This is the best way to avoid latches.
Good Code #2
1 always @ (b or c)
2 begin
3 if (b) begin
4 a = c;
5 end else begin
6 a = 0;
7 end
8 end
In the above code, all the possible cases are covered (i.e. b = 1 and b = 0 case).
Well it is a long story; let me cover that in the synthesis part of Verilog tutorial. You can
refer to Actel HDL coding Style. One simple logic is: any code inside always blocks with
edge sensitive sensitivity list, results in flip-flops and assign; inside level sensitive always
blocks results in combo logic.
You can implement them by declaring 2-dimension arrays. More details can be found in
the Verilog tutorial section "Modeling memories and FSM".
To Read from a file we use $readmemh, where h stands for hex decimal. For writing we
use $writememh, $fdisplay, $fmonitor. You could refer to the Verilog tutorial section for
more details.
`timescale is used for specifying the reference time unit for the simulator. Syntax of the
`timescale is as below:
`timescale <reference_time_unit>/<time_precision>
Timescale directive tends to make more sense at gatelevel simulation than at RTL
simulation.
Yes, we can have both blocking and nonblocking code in same always block. Some
things that one should know to use this are:
Give the truth table for a Half Adder. Give a gate level implementation of it.
What is the output of the circuit below, assuming that value of 'X' is not known ?
Consider a circular disk as shown in the figure below with two sensors mounted X,
Y and a blue shade painted on the disk for an angle of 45 degree. Design a circuit with
minimum number of gates to detect the direction of rotation.
Design a 4:1 Mux using 2:1 Muxes and some combo logic.
What is metastable state ? How does it occur ?
What is metastability ?
Design a D and T flip flop using 2:1 mux; use of other components not allowed,
just the mux.
You are given a 100 MHz clock. Design a 33.3 MHz clock with and without
50% duty cycle.
What are FIFO's? Can you draw the block diagram of FIFO? Could you modify it
to make it asynchronous FIFO ?
How can you generate random sequences in digital circuits?
Verilog Answer 2
Since the "a = 0" is an active event, it is scheduled into the 1st
"queue".
The "a <= 1" is a non-blocking event, so it's placed into the 3rd queue.
Finally, the display statement is placed into the 4th queue.
Only events in the active queue are completed this sim cycle, so the "a
= 0"
happens, and then the display shows a = 0. If we were to look at the
value of
a in the next sim cycle, it would show 1.
Verilog Answer 3
A:
10 30 50 70 90 110 130
___ ___ ___ ___ ___ ___ ___
clk ___| |___| |___| |___| |___| |___| |___| |___
a ___________________________________________________________
This obviously is not what we wanted, so to get closer, you could use
"always @ (posedge clk)" instead, and you'd get
10 30 50 70 90 110 130
___ ___ ___ ___ ___ ___ ___
clk ___| |___| |___| |___| |___| |___| |___| |___
___ ___
a _______________________| |___________________| |_______
Verilog Answer 4
#5 a = b;
a = #5 b;
A:
#5 a = b; Wait five time units before doing the action for "a = b;".
The value assigned to a will be the value of b 5 time units
hence.
Verilog Answer 6
c = foo ? a : b;
and
if (foo) c = a;
else c = b;
A:
(Back)
Verilog Answer 7
reg clk;
reg a;
10 30 50 70 90 110 130
___ ___ ___ ___ ___ ___ ___
clk ___| |___| |___| |___| |___| |___| |___| |___
(3)a __________________________________________________________
Since the #delay cancels future events when it activates, any delay
over the actual 1/2 period time of the clk flatlines...
10 30 50 70 90 110 130
___ ___ ___ ___ ___ ___ ___
clk ___| |___| |___| |___| |___| |___| |___| |___
(6)a __________________________________________________________
Vera Answer 1
A:
Vera Answer 2
on Verilog vs Vera?
fork {
task_one();
#10;
task_one();
}
task task_one() {
cnt = 0;
for (i = 0; i < 50; i++) {
cnt++;
}
}
A:
(Back)
Programming Answer 1
Q: Given $a = "5,-3,7,0,-5,12";
A:
$a = "5,-5,-1,0,12,-3";
(@temp) = split (/,/, $a);
$lowest = $temp[0];
NOTE: You could also replace the for loop with this:
Programming Answer 2
A:
/* BEGIN C SNIPET */
} /* end if */
} /* end for j */
} /* end for i */
} /* end bubblesort */
/* END C SNIPET */
Some optimizations that can be made are that a single-element array does
not need to be sorted; therefore, the "for i" loop only needs to go from
0 to lim-1. Next, if at some point during the iterations, we go through
the entire array WITHOUT performing a swap, the complete array has been
sorted, and we do not need to continue. We can watch for this by adding
a variable to keep track of whether we have performed a swap on this
iteration.
Programming Answer 3
A:
sub factorial {
my $y = shift;
if ( $y > 1 ) {
return $y * &factorial( $y - 1 );
} else {
return 1;
}
}
Programming Answer 4
the * operator.
A:
Example:
In the following example, the pointer ip is assigned the
address of variable i (&i). After that assignment,
the expression *ip refers to the same object denoted by i:
int i, j, *ip;
ip = &i;
i = 22;
j = *ip; /* j now has the value 22 */
*ip = 17; /* i now has the value 17 */
Programming Answer 5
A:
/* BEGIN C SNIPET */
#include <string.h>
/* END C SNIPET */
Programming Answer 6
* *
*** ***
***** *****
*** *******
* *****
***
A:
General Answer 1
Q: Given the following FIFO and rules, how deep does the FIFO need to
be to
RULES:
1) frequency(clk_A) = frequency(clk_B) / 4
3) duty_cycle(en_B) = 25%
A:
From (2), period(en_B) = 40ns * 100 = 4000ns, but we only output for
1000ns,
due to (3), so 3000ns of the enable we are doing no output work.
General Answer 2
A:
General Answer 3
A:
If each block has only one place it can appear in the cache, the cache
is said to be direct mapped. The mapping is usually (block-frame
address)
modulo (number of blocks in cache).
A:
Basically, you can tie the inputs of a NAND gate together to get an
inverter, so...
(Back)
General Answer 5
Q: Draw the state diagram for a circuit that outputs a "1" if the
aggregate serial
output a "1" (since 101 is 5). If we then get a "0", the aggregate
total is 10, so
A:
From ASIC.co.in
1) Write a verilog code to swap contents of two registers with and without a
temporary register?
The Verilog language has two forms of the procedural assignment statement: blocking
and non-blocking. The two are distinguished by the = and <= assignment operators. The
blocking assignment statement (= operator) acts much like in traditional programming
languages. The whole statement is done before control passes on to the next statement.
The non-blocking (<= operator) evaluates all the right-hand sides for the current time unit
and assigns the left-hand sides at the end of the time unit. For example, the following
Verilog program
module blocking;
reg [0:7] A, B;
initial begin: init1
A = 3;
#1 A = A + 1; // blocking procedural assignment
B = A + 1;
$display("Blocking: A= %b B= %b", A, B ); A = 3;
#1 A <= A + 1; // non-blocking procedural assignment
B <= A + 1;
#1 $display("Non-blocking: A= %b B= %b", A, B );
end
endmodule
The effect is for all the non-blocking assignments to use the old values of the variables at
the beginning of the current time unit and to assign the registers new values at the end of
the current time unit. This reflects how register transfers occur in some hardware systems.
Function:
A function is unable to enable a task however functions can enable other functions.
A function will carry out its required duty in zero simulation time. ( The program time
will not be incremented during the function routine)
Within a function, no event, delay or timing control statements are permitted
In the invocation of a function their must be at least one argument to be passed.
Functions will only return a single value and can not use either output or inout
statements.
Tasks:
Tasks are capable of enabling a function as well as enabling other versions of a Task
Tasks also run with a zero simulation however they can if required be executed in a non
zero simulation time.
Tasks are allowed to contain any of these statements.
A task is allowed to use zero or more arguments which are of type output, input or inout.
A Task is unable to return a value but has the facility to pass multiple values via the
output and inout statements .
These commands have the same syntax, and display text on the screen during simulation.
They are much less convenient than waveform display tools like cwaves?. $display and
$strobe display once every time they are executed, whereas $monitor displays every time
one of its parameters changes.
The difference between $display and $strobe is that $strobe displays the parameters at the
very end of the current simulation time unit rather than exactly where it is executed. The
format string is like that in C/C++, and may contain format characters. Format characters
include %d (decimal), %h (hexadecimal), %b (binary), %c (character), %s (string) and
%t (time), %m (hierarchy level). %5d, %5b etc. would give exactly 5 spaces for the
number instead of the space needed. Append b, h, o to the task name to change default
format to binary, octal or hexadecimal.
Syntax:
$display (“format_string”, par_1, par_2, ... );
$strobe (“format_string”, par_1, par_2, ... );
$monitor (“format_string”, par_1, par_2, ... );
A "full" case statement is a case statement in which all possible case-expression binary
patterns can be matched to a case item or to a case default. If a case statement does not
include a case default and if it is possible to find a binary case expression that does not
match any of the defined case items, the case statement is not "full."
A "parallel" case statement is a case statement in which it is only possible to match a case
expression to one and only one case item. If it is possible to find a case expression that
would match more than one case item, the matching case items are called "overlapping"
case items and the case statement is not "parallel."
in a case statement if all the possible combinations are not compared and default is also
not specified like in example above a latch will be inferred ,a latch is inferred because to
reproduce the previous value when unknown branch is specified.
For example in above case if {s1,s0}=3 , the previous stored value is reproduced for this
storing a latch is inferred.
The same may be observed in IF statement in case an ELSE IF is not specified.
To avoid inferring latches make sure that all the cases are mentioned if not default
condition is provided.
Signals
The sensitivity list indicates that when a change occurs to any one of elements in the list
change, begin…end statement inside that always block will get executed.
Yes in a pure combinational circuit is it necessary to mention all the inputs in sensitivity
disk other wise it will result in pre and post synthesis mismatch.
// timescale directive tells the simulator the base units and precision of the simulation
`timescale 1 ns / 10 ps
module name (input and outputs);
// parameter declarations
parameter parameter_name = parameter value;
// Input output declarations
input in1;
input in2; // single bit inputs
output [msb:lsb] out; // a bus output
// internal signal register type declaration - register types (only assigned within always
statements). reg register variable 1;
reg [msb:lsb] register variable 2;
// internal signal. net type declaration - (only assigned outside always statements) wire net
variable 1;
// hierarchy - instantiating another module
reference name instance name (
.pin1 (net1),
.pin2 (net2),
.
.pinn (netn)
);
// synchronous procedures
always @ (posedge clock)
begin
.
end
// combinatinal procedures
always @ (signal1 or signal2 or signal3)
begin
.
end
assign net variable = combinational logic;
endmodule
Compilation
VHDL. Multiple design-units (entity/architecture pairs), that reside in the same system
file, may be separately compiled if so desired. However, it is good design practice to keep
each design unit in it's own system file in which case separate compilation should not be
an issue.
Verilog. The Verilog language is still rooted in it's native interpretative mode.
Compilation is a means of speeding up simulation, but has not changed the original
nature of the language. As a result care must be taken with both the compilation order of
code written in a single file and the compilation order of multiple files. Simulation results
can change by simply changing the order of compilation.
Data types
VHDL. A multitude of language or user defined data types can be used. This may mean
dedicated conversion functions are needed to convert objects from one type to another.
The choice of which data types to use should be considered wisely, especially enumerated
(abstract) data types. This will make models easier to write, clearer to read and avoid
unnecessary conversion functions that can clutter the code. VHDL may be preferred
because it allows a multitude of language or user defined data types to be used.
Verilog. Compared to VHDL, Verilog data types a re very simple, easy to use and very
much geared towards modeling hardware structure as opposed to abstract hardware
modeling. Unlike VHDL, all data types used in a Verilog model are defined by the
Verilog language and not by the user. There are net data types, for example wire, and a
register data type called reg. A model with a signal whose type is one of the net data types
has a corresponding electrical wire in the implied modeled circuit. Objects, that is signals,
of type reg hold their value over simulation delta cycles and should not be confused with
the modeling of a hardware register. Verilog may be preferred because of it's simplicity.
Design reusability
VHDL. Procedures and functions may be placed in a package so that they are avail able
to any design-unit that wishes to use them.
15) What are different styles of Verilog coding I mean gate-level,continuous level
and others explain in detail?
16) Can you tell me some of system tasks and their purpose?
In earlier version of Verilog ,we use 'or' to specify more than one element in sensitivity
list . In Verilog 2001, we can use comma as shown in the example below.
// Verilog 2k example for usage of comma
always @ (i1,i2,i3,i4)
Verilog 2001 allows us to use star in sensitive list instead of listing all the variables in
RHS of combo logics . This removes typo mistakes and thus avoids simulation and
synthesis mismatches,
Verilog 2001 allows port direction and data type in the port list of modules as shown in
the example below
module memory (
input r,
input wr,
input [7:0] data_in,
input [3:0] addr,
output [7:0] data_out
);
Synchronous reset, synchronous means clock dependent so reset must not be present in
sensitivity disk eg:
always @ (posedge clk )
begin if (reset)
. . . end
Asynchronous means clock independent so reset must be present in sensitivity list.
Eg
Always @(posedge clock or posedge reset)
begin
if (reset)
. . . end
20) There is a triangle and on it there are 3 ants one on each corner and are free to
move along sides of triangle what is probability that they will collide?
Ants can move only along edges of triangle in either of direction, let’s say one is
represented by 1 and another by 0, since there are 3 sides eight combinations are possible,
when all ants are going in same direction they won’t collide that is 111 or 000 so
probability of collision is 2/8=1/4
$deposit(variable, value);
This system task sets a Verilog register or net to the specified value. variable is the
register or net to be changed; value is the new value for the register or net. The value
remains until there is a subsequent driver transaction or another $deposit task for the
same register or net. This system task operates identically to the ModelSim
force -deposit command.
The force command has -freeze, -drive, and -deposit options. When none of these is
specified, then -freeze is assumed for unresolved signals and -drive is assumed for
resolved
signals. This is designed to provide compatibility with force files. But if you prefer
-freeze
as the default for both resolved and unresolved signals.
CASEZ :
Special version of the case statement which uses a Z logic value to represent don't-care
bits. CASEX :
Special version of the case statement which uses Z or X logic values to represent don't-
care bits.
CASEZ should be used for case statements with wildcard don’t cares, otherwise use of
CASE is required; CASEX should never be used.
This is because:
Don’t cares are not allowed in the "case" statement. Therefore casex or casez are
required. Casex will automatically match any x or z with anything in the case statement.
Casez will only match z’s -- x’s require an absolute match.
25) What is the difference between the following two lines of Verilog code?
#5 a = b;
a = #5 b;
#5 a = b; Wait five time units before doing the action for "a = b;".
a = #5 b; The value of b is calculated and stored in an internal temp register,After five
time units, assign this stored value to a.
c = foo ? a : b;
and
if (foo) c = a;
else c = b;
The ? merges answers if the condition is "x", so for instance if foo = 1'bx, a = 'b10, and b
= 'b11, you'd get c = 'b1x. On the other hand, if treats Xs or Zs as FALSE, so you'd
always get c = b.
A: The easiest and efficient way to generate sine wave is using CORDIC Algorithm.
// Port Declaration
input oe;
input clk;
input [7:0] inp;
output [7:0] outp;
inout [7:0] bidir;
reg [7:0] a;
reg [7:0] b;
assign bidir = oe ? a : 8'bZ ;
assign outp = b;
// Always Construct
always @ (posedge clk)
begin
b <= bidir;
a <= inp;
end
endmodule
wire [3:0] x;
always @(...) begin
case (1'b1)
x[0]: SOMETHING1;
x[1]: SOMETHING2;
x[2]: SOMETHING3;
x[3]: SOMETHING4;
endcase
end
The case statement walks down the list of cases and executes the first one that matches.
So here, if the lowest 1-bit of x is bit 2, then something3 is the statement that will get
executed (or selected by the logic).
35) Why is it that "if (2'b01 & 2'b10)..." doesn't run the true case?
This is a popular coding error. You used the bit wise AND operator (&) where you meant
to use the logical AND operator (&&).
Event Driven
Cycle Based
Event-based Simulator:
This Digital Logic Simulation method sacrifices performance for rich functionality: every
active signal is calculated for every device it propagates through during a clock cycle.
Full Event-based simulators support 4-28 states; simulation of Behavioral HDL, RTL
HDL, gate, and transistor representations; full timing calculations for all devices; and the
full HDL standard. Event-based simulators are like a Swiss Army knife with many
different features but none are particularly fast.
1.) Results are only examined at the end of every clock cycle; and
2.) The digital logic is the only part of the design simulated (no timing calculations). By
limiting the calculations, Cycle based Simulators can provide huge increases in
performance over conventional Event-based simulators.
Cycle based simulators are more like a high speed electric carving knife in comparison
because they focus on a subset of the biggest problem: logic verification.
Cycle based simulators are almost invariably used along with Static Timing verifier to
compensate for the lost timing information coverage.
Introduction
As ASIC and system-on-chip (SoC) designs continue to increase in size and complexity,
there is an equal or greater increase in the size of the verification effort required to
achieve functional coverage goals. This has created a trend in RTL verification
techniques to employ constrained-random verification, which shifts the emphasis from
hand-authored tests to utilization of compute resources. With the corresponding
emergence of faster, more complex bus standards to handle the massive volume of data
traffic there has also been a renewed significance for verification IP to speed the time
taken to develop advanced testbench environments that include randomization of bus
traffic.
Directed-Test Methodology
Scoreboards are used to verify that data has successfully reached its destination, while
monitors snoop the interfaces to provide coverage information. New or revised
constraints focus verification on the uncovered parts of the design under test. As
verification progresses, the simulation tool identifies the best seeds, which are then
retained as regression tests to create a set of scenarios, constraints, and seeds that provide
high coverage of the design.