Systemverilog Interview Questions
Systemverilog Interview Questions
scbd.save_expected_packet(packet);
endtask // pre_tx
endclass
(3.2)wr_monitor,
//Need to declare the callback first
wif_wr_data_callbacks wr_data_cbs;
`vmm_callback(wif_wr_data_callbacks, post_tx(pkt));
(3.3)mvc_scoreboard,
//Need to declare and define the function
function mvc_scoreboard::save_expected_packet(data_to_sb wr_pkt);
(3.4)in UVM,
class uvm_callbacks #(
type T = uvm_object,
type CB = uvm_callback
) extends uvm_typed_callbacks#(T)
2. What is factory pattern?
Factory pattern as the name suggest, is aimed at solving the issue of creation of object. (Factory pattern
is not the only pattern to deal with creation of objects -> creational patterns)
class TOY; // Common data memeber string type;
string type;
virtual function string get_type();
endclass
class TOY_Tank extends TOY;
function new();
this.string = "Toy Tank";
endfunction
string function string get_type();
return this.string;
endfunction
endclass
class TOY_Bus extends TOY;
function new();
this.string = "Toy Bus";
endfunction
string function string get_type();
return this.string;
endfunction
endclass
Now we are done with the bothering about the objects to be created. The next problem that we need to
solve is to write the toy factory class itself. For simplicity, let's consider the case where we will want to
pass 1 to get an instance of tank class and 2 for getting an instance of bus class from the factory. Now
the factory class will look like this.
class TOY_factory;
Toy my_toy
// Common methods
function toy get_toy(int type);
if(type == 1)
this.my_toy = new TOY_Tank();
if(type == 2)
this.my_toy = new TOY_Bus();
return this.my_toy;
endfunction
endclass
Note that we are using virtual function for bringing polymorphism in action and save us from having an
(2. Functional Coverage: Functional coverage is tied to the design intent and is sometimes called
specification coverage, while code coverage measures the design implementation.
(3. Assertion coverage: We can measure how often these assertions are triggered during a test by using
assertion coverage. A cover property observes sequences of signals, whereas a cover group (described
below) samples data values and transactions during the simulation
Using Cover Groups: Variables, expressions and their cross
Using Cover Properties
7. What is the need of virtual interfaces?
Interface can't be instantiated inside non-module entity in SystemVerilog. But they needed to be driven
from verification environment like class. Virtual interface is a data type (can be instantiated in a class)
which hold reference to an interface (that implies the class can drive the interface using the virtual
interface). It provides a mechanism for separating abstract models and test programs from the actual
signals made up the design. Another big advantage of virtual interface is that class can dynamically
connect to different physical interfaces in run time.
8. Explain Abstract classes and virtual methods.
A set of classes can be created that can be viewed as all being derived from a common base class. A
base class sets out the prototype for the subclasses. Because the base class is not intended to be
instantiated and can only be derived, it can be made abstract by specifying the class to be virtual:
A virtual method overrides a method in all the base classes, whereas a normal method only overrides a
method in that class and its descendants. Virtual methods provide prototypes for subroutines. In
general, if an abstract class has any virtual methods, all of the methods must be overridden for the
subclass to be instantiated.
Polymorphism: dynamic method lookup
Polymorphism allows to reference the methods of those subclasses directly from the super class
variable. The OOP term for multiple methods sharing a common name is "polymorphism".
9. What is the use of the abstract class?
Sometimes it make sense to only describe the properties of a set of objects without knowing the actual
behavior beforehand. Abstract classes are those which can be used for creation of handles. However
their methods and constructors can be used by the child or extended class. The need for abstract classes
is that you can generalize the super class from which child classes can share its methods. The subclass
of an abstract class which can create an object is called as "concrete class".
10. What is the difference between mailbox and queue?
(2 pre_randomize
(3 post_randomize
e.g.
$cast( col, 2 + 3 );
19. How to call the task which is defined in parent object into derived class ?
super.task();
20. What is the difference between rand and randc?
rand - Random Variable, same value might come before all the the possible value have been returned.
Analogous
to
throwing
a
dice.
randc - Random Cyclic Variable, same value doesn't get returned until all possible value have been
returned. Analogous to picking of card from a deck of card without replacing.
21. What is $root?
The instance name $root allows you to unambiguously refer to names in the system, starting with the
top-level scope.
1.package ABC;
2.$root.A; // top level instance A
3.$root.A.B.C; // item C within instance B within top level instance A
22. What is $unit?
SystemVerilog introduces the compilation unit, which is a group of source files that are compiled
together. The scope outside the boundaries of any module, macromodule, interface, program, package,
or primitive is known as the compilation unit scope, also referred to as $unit. For tools such as VCS
that compile all files at once, $root and $unit are equivalent.
23. What are bi-directional constraints?
Constraints by-default in SystemVerilog are bi-directional. That implies that the constraint solver
doesn't follow the sequence in which the constraints are specified. All the variables are looked
simultaneously. Even the procedural looking constrains like if ... else ... and -> (implication operator)
constrains, both if and else part are tried to solve concurrently. For example (a==0) -> (b==1) shall be
solved as all the possible solution of (!(a==0) || (b==1)).
24. What is solve...before constraint ?
In the case where the user want to specify the order in which the constraints solver shall solve the
constraints, the user can specify the order via solve before construct.
25. Without using randomize method or rand, generate an array of unique values?
int UniqVal[10];
foreach(UniqVal[i])
UniqVal[i] = i;
UniqVal.shuffle();
26. Explain about pass by ref and pass by value?
Pass by value is the default method through which arguments are passed into functions and tasks. Each
subroutine retains a local copy of the argument. If the arguments are changed within the subroutine
declaration, the changes do not affect the caller.
In pass by ref, functions and tasks directly access the specified variables passed as arguments. It's like
passing pointer of the variable. For passing Array to the routines, always use ref to improve
performance, otherwise, array is coped on stack. If you do not want array value changed, use const ref.
The second benefit of ref arguments is that a task can modify a variable and is
instantly seen by the calling function. This is useful when you have several threads
executing concurrently and want a simple way to pass information. See Chap. 7 for
more details on using fork-join.
27. Whats the static variable?
class Transaction;
static int count = 0; // Number of objects created
int id; // Unique instance ID
function new();
id = count++; // Set ID, bump count
endfunction
endclass
Transaction t1, t2;
initial begin
t1 = new(); // 1st instance, id=0, count=1
t2 = new(); // 2nd instance, id=1, count=2
$display("Second id=%d, count=%d", t2.id, t2.count);
end
In Sample 5.9, there is only one copy of the static variable count, regardless of how
many Transaction objects are created. You can think that count is stored with the
class and not the object.
28. What is the difference between bit[7:0] sig_1; and byte sig_2;
byte is signed whereas bit [7:0] is unsigned.
29. What is the difference between program block and module ?
Program block is newly added in SystemVerilog. It serves these purposes
(1. It separates testbench from DUT
(2. It helps in ensuring that testbench doesn't have any race condition with DUT
(3. It provides an entry point for execution of testbench
(4. It provides syntactic context (via program ... endprogram) that specifies scheduling in the Reactive
Region.
The major difference between module and program blocks are
(1. Program blocks can't have always block inside them, modules can have.
(2. Program blocks can't contain UDP, modules, or other instance of program block inside them.
Modules don't have any such restrictions.
(3. Inside a program block, program variable can only be assigned using blocking assignment and nonprogram variables can only be assigned using non-blocking assignments. No such restrictions on
module
(4. Program blocks get executed in the re-active region of scheduling queue, module blocks get
executed in the active region
(5. A program can call a task or function in modules or other programs. But a module cannot call a task
or function in a program.
30. How to implement always block logic in program block ?
always @(posedge clk or negedge reset) begin
if(!reset) begin
data <= '0;
end else begin
data <= data_next;
end
end
// Using forever : slightly complex but doable
forever begin
fork
begin
@ (negedge reset);
data <= '0;
end
begin
@ (posedge clk);
if(!reset)
else
end
join_any
disable fork
end
cg;
cover_point_y : coverpoint y {
option.auto_bin_max
endgroup
cg
cg_inst
initial
foreach(values[i])
begin
y
cg_inst.sample();
end
endprogram
4
=
//gather
}
new();
values[i];
coverage
47. How can I model a bi-directional net with assignments influencing both source and destination?
The assign statement constitutes a continuous assignment. The changes on the RHS of the statement
immediately reflect on the LHS net. However, any changes on the LHS don't get reflected on the RHS.
System Verilog has introduced a keyword alias, which can be used only on nets to have a two-way
assignment. For example, in the following code, any changes to the rhs is reflected to the lhs , and vice
versa.
module
test
();
wire
rhs,
lhs;
alias lhs=rhs;
endmodule
48. What is the need to implement explicitly a copy() method inside a transaction , when we can
simple assign one object to other ?
If you assign one object to other then both the handles will point to the same object. This will not
copy the transaction. By defining copy(), we can use the deep copy but not the shallow copy.
49. How different is the implementation of a struct and union in SV.
Struct:
To be able to share struct using ports and routines, you should create a type.
initial begin
typedef struct {
int a;
byte b;
shortint c;
int d;
} my_struct_s;
my_struct_s st = '{
32'haaaa_aaaad,
8'hbb,
16'hcccc,
32'hdddd_dddd
};
$display("str = %x %x %x %x ", st.a, st.b, st.c, st.d);
end
Union
Unlike structures, the components of a union all refer to the same location in memory. In this way, a
union can be used at various times to hold different types of objects, without the need to create a
separate object for each new type.
typedef union { int i; real f; } num_u;
num_u un;
un.f = 0.0; // set value in floating point format
Unions are useful when you frequently need to read and write a register in several different formats.
But class is more oftenly used.
50. What is "this"?
When we use a variable name, SystemVerilog looks in the current scope for it, and then in the parent
scopes until the variable is found. This removes the ambiguity to let SystemVerilog know that you
are assigning the local variable, to the class variable.
class Scoping;
string oname;
function new(string oname);
this.oname = oname; // class oname = local oname
endfunction
endclass
51. What is tagged union ?
A tagged union contains an implicit member that stores a tag, which represents the name of the last
union member into which a value was stored/written. If value is read from a different union member
than the member into which a tagged expression value was last written, an error message will shown.
union tagged {
int i;
real r;
} data;
data data_un;
data_un = tagged i 5; //store the 5 in data.i, and set it as the implicit tag.
d_out = data_un.i; //read value
d_out = data_un.r;//ERROR: memeber doesnt match the union's implicit tag
52. What is "scope resolution operator"?
Extern keyword allows out-of-body method declaration in classes. Scope resolution operator ( :: ) links
method construction to class declaration.
class XYZ;
extern void task SayHello();
endclass
void task XYZ :: SayHello();
$Message("Hello !!!\n");
endtask
53. What is the difference between?
(1.logic data_1;
(2.var logic data_2; //same as logic data_1
(3.wire logic data_3j;
(4.bit data_4;
(5.var bit data_5; //same as bit data_5
(6.var data_6; //same as logic data_6
For "Var", if a data type is not specified, then the data type logic shall be inferred
54. What is the difference between bits and logic?
bits: 2 states, default value is 0; logic: single bit, 4 states, default value is X
55. What is the difference between $rose and posedge?
always @(posedge clk)
reg1 <= a & $rose(b);
In this example, the clocking event (posedge clk) is applied to $rose. $rose is true at the clock ticks
when the sampled value of b changed to 1 from its sampled value at the previous tick of the clocking
event.
(1 $rose returns true if the LSB of the expression changed to 1. Otherwise, it returns false.
(2 $fell returns true if the LSB of the expression changed to 0. Otherwise, it returns false.
(3 $stable returns true if the value of the expression did not change. Otherwise, it returns false.
posedge return an event, whereas $rose returns a Boolean value. Therefore they are not
interchangeable.
56. What is advantage of program block over clock block w.r.t race condition?
Program schedules events in the Reactive region, the clocking block construct is very useful to
automatically sample the steady-state values of previous time steps or clock cycles. Programs that read
design values exclusively through clocking blocks with #0 input skews are insensitive to read-write
races, for single clock.
63. What data structure is used to store data in your environment and why ?
Mailbox or queue. Because especially for the scoreboard, for each cycle, we have to collect data and
drop these data from the driver and monitor respectively. Therefore, queue or mailbox would be more
convenient than array.
64. Explain how the timescale unit and precision are taken when a module does not have any time scalar
declaration in RTL?
In SV
timeunit 100ps;
timeprecision 10fs;
is as same as `timescale 100ps/10fs in Verilog
If a timeunit is not specified in the module, program, package, or interface definition, then the time unit
shall be determined using the following rules of precedence:
a) If the module or interface definition is nested, then the time unit shall be inherited from the enclosing
module or interface (programs and packages cannot be nested).
b) Else, if a `timescale directive has been previously specified (within the compilation unit), then the
time unit shall be set to the units of the last `timescale directive.
c) Else, if the compilation-unit scope specifies a time unit (outside all other declarations), then the time
unit shall be set to the time units of the compilation unit.
d) Else, the default time unit shall be used.
65. What is streaming operator and what is its use?
When used on the right side of an assignment, the streaming operators << and >> take an
expression, structure, or array, and packs it into a stream of bits. The >> operator streams data from left
to right while << streams from right to left.
66. What are void functions ?
The functions without return value, but they are still functions, thus no timing control allowed.
67. How to make sure that a function argument passed has ref is not changed by the function?
const ref
68. What is the difference between initial block and final block?
(1. the most obvious one: Initial blocks get executed at the beginning of the simulation, final block at
the end of simulation
(2. Final block has to be executed in zero time, which implies it can't have any delay, wait, or nonblocking assignments.
(3. Final block can be used to display statistical/general information regarding the status of the
execution
69. How to check weather a handles is holding object or not ?
It is basically checking if the object is initialized or not. In SV all uninitialized object handles
have a special value of null. E.g assert(obj == NULL)
70. What are semaphores?
Ans: A semaphore is like a bucket and used in synchronization, which is also known as a
"mutex"(mutually exclusive access) and is used to control access to a resource. When a semaphore is
allocated, the keys are allocated to each and every bucket. The number is fixed. The keys are not
identical. Processes using semaphores must definitely have a key from bucket before they start the
execution process.
71. Why is reactive scheduler used?
Ans: Code specified in program blocks and pass/fail code from property expressions are scheduled in
reactive scheduler.
always_latch: SystemVerilog also provides a special always_latch procedure for modeling latched logic
behavior. Using "<="
always_latch
begin : ADDER
if (enable) begin
sum <= b + a;
parity <= ^(b + a);
end
end
always_ff: The SystemVerilog always_ff procedure can be used to model synthesizable sequential logic
behavior
E.g.:
int
reg r[7:0] //unpacked array
[7:0]
c1;
//packed
array
80. How we can have #delay which is independent of time scale in system verilog?
Ans: We can mention it as #5ns.
81. What are the different types of constraints in systemverilog?
Ans: Random constraints, user defined constraints, inline constraints, if-else constraints and global
constraints.
count
match
Error
count
idle
count
(!obj.randomize())
randomization");
<
test
expression
<
complex
sequence
endproperty;
assert_name_of_property: assert property (name_of_property);
>
expressions
or
>
concurrent
assertion
there
are
three
main
components.
113.Implication
Two
(1. Overlapping ( )
operators
only
types
used
inside
of
the
property.
operators
Packed array:
For some data types, you may want both to access the entire value and also to divide it into smaller
elements. A SystemVerilog packed array is treated as both an array and a single value. It is stored as a
contiguous set of bits with no unused space, unlike an unpacked array.
The packed bit and array dimensions are specified as part of the type, before the variable
name.
bit [3:0] [7:0] bytes; // 4 bytes packed into 32-bits
bytes = 32'hCafe_Dada;
With a single subscript, you get a word of data, barray[2]. With two subscripts, you
get a byte of data, barray[0][3]. With three subscripts, you can access a single bit,
barray[0][1][6].
Advantages of packed array:
(1. A packed array is handy if you need to convert to and from scalars. For example, you might need to
reference a memory as a byte or as a word.
(2. If you need to wait for a change in an array, you have to use a packed array. Perhaps your testbench
might need to wake up when a memory changes value, and so you want to use the @ operator. This is
however only legal with scalar values and packed arrays. In the sample above you can block on
barray[0], but not the entire array barray unless you expand it: @(barray[0] or barray[1] or barray[2]).
118.Dynamic array
int dyn[];
initial begin
dyn = new[5]; // A: Allocate 5 elements
foreach (dyn[j]) dyn[j] = j; // B: Initialize the elements
dyn = new[20](dyn); // F: Allocate 20 ints & copy
dyn = new[100]; // G: Allocate 100 new ints, Old values are lost
dyn.size();
dyn.delete(); // H: Delete all elements
end
119.Associate array
(1. When the size of the collection is unknown or the data space is sparse, an associateive array is a
better option.
(2. Associative arrays do not have any storage allocated until it is used and the index expression is not
restricted to integral expressions, but can be any type.
int power_of_2[int] = '{0:1, 1:2, 2:4 }; //0, 1, 2 serve as the index
initial begin
for (int i=3; i<5; i++)
power_of_2[i] = 1<<i;//result would be {1,2,4,8,16}
end
(3. power_of_2.exist(4) //check if 4 (element) has been allocated
120.Queue
Like a linked list, you can add or remove elements anywhere in a queue, without the performance hit of
a dynamic array that has to allocate a new array and copy the entire contents. Like an array, you can
directly access any element with an index, without linked lists overhead of stepping through the
preceding elements.
int j, q2[$] = {3,4}, q[$] = {0,2,5};// Queue literals do not use '
bit [4:0] ack_que[$];
initial begin
q.insert(1, j); // {0,1,2,5} Insert 1 before 2
q.insert(3, q2); // {0,1,2,3,4,5} Insert queue in q1
q.delete(1); // {0,2,3,4,5} Delete elem. #1
// These operations are fast
q.push_back(8); // {0,2,3,4,8} Insert at back
j = q.pop_front; // {2,3,4,8} j = 0
j = q[$]; //j=8
foreach (q[i])
$display(q[i]); // Print entire queue
q.delete(); // {} Delete entire queue
end
121.Automatic routine
In verilog-1995, if you tried to call a task from multiple places in your testbench, the local variables
shared common, static storage, and so the different threads stepped on each others values. In Verilog2001 you can specify that tasks, functions, and modules use automatic storage, which causes the
simulator to use the stack for local variables.
program automatic test;
task wait_for_mem(input [31:0] addr, expect_data, output success);
while (bus.addr !== addr)
@(bus.addr);
success = (bus.data == expect_data);
endtask
...
endprogram
You can call this task multiple times concurrently, as the addr and expect_data arguments are stored
separately for each call. Without the automatic modifier, if you called wait_for_mem a second time
while the first was still waiting, the second call would overwrite the two arguments.
122.Variable:Scope & lifetime
(1 Static
-Allocated & initialize at time 0;
-Exist for entire simulation.
(2 Automatic
-Enable recursive tasks and funtion
-Reallocated and initialized each time entering block
-Should not be use to trigger an event
(3Global Variable
-Defined under $root (outside any module)
-Must be static
-Accessible from anywhere
-Task and function can be global
(4 Local Variable
-Default to static. Can be automatic
-Accessible at where they are defined and below
-Accessible through hierarchical path
123.clocking skew
(1 inputs are sampled skew time units before clock
$range = 100000000;
$random_number = int(rand($range));
+ntb_random_seed = $random_number; ##doesnt apply to Verilog $random
2.
+ntb_random_seed_automatic
132.How to call the task which is defined in parent object into derived class ?
Answer:
The super keyword is used from within a derived class to refer to members of the parent class. It is
necessary to use super to access members of a parent class when those members are overridden by
the derived class
int a_m;
function new();
a_m = 0;
endfunction
(1) Shadow copy
SAMPLE a, b;
a = new;
a.a_m = 40;
b = new a; //function new will not copy
b.a_m = 50; //a and b point to different handle but share the same a_m.
//a_m will be 50
(2) Shadow copy also
SAMPLE a, b;
a = new;
b = a; //b and a point to the same handle
a = new; //b point to the first handle, a point to the second one
(3) Bad OOP
SAMPLE a, b;
a = new;
b = a; //b and a point to the same handle, any variable change in one
will affect the other
140. OOP questions
(1) Class A;
Constraint key_con {a == 6;}
endclass
Class B extends A;
Constraint key_con {a ==5;} //overwrite should use the same name
endclass
A a = new;
Assert(!a.randomize(with {a == 7})) //will give you compile error
(2) Class B //think it as a uvm component
Uvm_build_phase
Build_funtion..
Endphase
Class C extends B
Build_phase
Endphase
141.In uvm
In driver, how did you do pipelining?
Answer:
In systemverilog, you are using mailbox
In UVM, you should explicitly build queues to do pipelining.
instance
Reference
1.
2.
http://www.asic-world.com/
http://www.testbench.in/