0% found this document useful (0 votes)
20 views26 pages

SV Questions

This document is a comprehensive compilation of over 1,000 frequently asked questions (FAQs) about SystemVerilog, providing concise answers and code examples. It covers various topics such as virtual functions, randomization, assertions, and OOP concepts, along with best practice tips. The format includes question/answer boxes and 'Pro Tip' sections to highlight important information and practices.

Uploaded by

DevikaRani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views26 pages

SV Questions

This document is a comprehensive compilation of over 1,000 frequently asked questions (FAQs) about SystemVerilog, providing concise answers and code examples. It covers various topics such as virtual functions, randomization, assertions, and OOP concepts, along with best practice tips. The format includes question/answer boxes and 'Pro Tip' sections to highlight important information and practices.

Uploaded by

DevikaRani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Frequently Asked Questions

SystemVerilog

Version 1.0
April 27, 2025

Created by Kittu Patel


SystemVerilog FAQs VeriCore

Introduction
This document compiles 1,000+ SystemVerilog FAQs with concise answers and code
examples. How to use: Each entry is wrapped in a question/answer box. “ Pro Tip”
boxes highlight best practices.

FAQs
Question
1. What is a virtual function?

Answer
A virtual function in SystemVerilog allows a base class to declare a method signa-
ture that derived classes must or may override, enabling runtime polymorphism.
// Base class
virtual class Packet;
pure virtual function void send(bit[31:0] data);
endclass

// Derived class
class UdpPacket extends Packet;
virtual function void send(bit[31:0] data);
// custom UDP send implementation
endfunction
endclass

Pro Tip
Use virtual functions in UVM components to make your testbench flexible
without changing base classes.

Question
2. Static vs. dynamic casting—what’s the difference?

Answer
• Static casting (\$cast): Compile-time check. Fast but unsafe if types mis-
match.

• Dynamic casting: Runtime check (e.g., using DPI/UVM); safer but with
slight overhead.

Question
3. What is a pure virtual function?

1
SystemVerilog FAQs VeriCore

Answer
A pure virtual (abstract) function has no base implementation. Derived classes
must implement it or remain abstract.
virtual class Base;
pure virtual function int compute(int a, int b);
endclass

Question
4. Why do we need randomization in SystemVerilog?

Answer
Constrained-random testing generates diverse stimuli, uncovering corner-case bugs
and increasing verification coverage beyond directed tests.

Question
5. While vs. do-while loops—how do they differ?

Answer
Aspect while do. . . while
Entry test Checks before body Executes once before test
Minimum runs Zero if false Always at least one
Use case Skip if unmet Guarantee first run

Question
6. What are bidirectional constraints?

Answer
They define relationships that the solver enforces both ways:
class Handshake;
rand bit valid, ready;
constraint c { valid == ready; }
endclass

Question
7. Difference between integer and int.

Answer
• integer: 32-bit 4-state (0,1,X,Z)

• int: 32-bit 2-state (0,1)

2
SystemVerilog FAQs VeriCore

Question
8. Constraint: variable divisible by 5.

Answer

class DivBy5;
rand bit [3:0] x;
constraint c { x % 5 == 0; }
endclass

Question
9. What are parameterized classes?

Answer
SV generics—classes templated on types/values:
class Queue #(type T=int, int SIZE=16);
T data[SIZE];
//
endclass

Question
10. How do monitor and scoreboard communicate?

Answer
Via a mailbox :
// In monitor
mailbox #(trans) mb = new();
mb.put(trans);

// In scoreboard
trans = mb.get();

Question
11. Is it possible to override existing constraints?

3
SystemVerilog FAQs VeriCore

Answer
Yes. You can override constraints in two ways:

• Inline override:
obj.randomize() with { x == 8; };

• Inheritance:
class SubClass extends BaseClass;
constraint c_new { x inside {[0:5]}; }
endclass

Pro Tip
Use inline overrides for quick one-off tests; use subclassed constraints for lasting
behavior changes.

Question
12. Functional coverage 100% but code coverage low—what’s your ap-
proach?

Answer
1. Review coverage report to locate un-hit code.

2. Add directed tests for those branches.

3. Introduce assertion-based tests for corner cases.

4. Employ coverage-driven randomization to target missing areas.

Pro Tip
Leverage coverage groups in UVM to dynamically adjust your stimulus based on
real-time coverage gaps.

Question
13. What are the types of assertions?

Answer
• Immediate: Checked at the point of execution, e.g., assert(sig==1);.

• Concurrent: Monitored over time, often clock-synchronous:


property p; @(posedge clk) req |-> ##1 ack; endproperty
assert property(p);

4
SystemVerilog FAQs VeriCore

Pro Tip
Use concurrent assertions for protocol checks and immediate assertions for simple
sanity tests.

Question
14. How to find indices associated with associative array items?

Answer
Use the find_index method:
int A[string];
string idx_q[$];
A["apple"]=5; A["pear"]=5; A["mango"]=3;
idx_q = A.find_index with (5);

Pro Tip
Chaining with filters allows powerful one-line queries on complex data.

Question
15. Give an example of a function call inside a constraint.

Answer

function int rand_range(int a, int b);


return $urandom_range(a, b);
endfunction

class C;
rand int x;
constraint cx { x == rand_range(0, 10); }
endclass

Pro Tip
Keep helper functions out of the class body with extern declarations for clarity.

Question
16. What are pass-by-value and pass-by-reference methods?

Answer
• By-value: function void f(int a); passes a copy.

• By-reference: function void f(ref int a); modifies the original.

5
SystemVerilog FAQs VeriCore

Pro Tip
Use ref sparingly—too many references can obscure data flow.

Question
17. Difference between initial and final blocks.

Answer
• initial: Executes once at simulation start (time 0).

• final: Executes once just before simulation end (SV only).

Pro Tip
Reserve final for cleanup and report printing so it never interferes with functional
tests.

Question
18. What are the default values of variables in SystemVerilog?

Answer
• 2-state (bit, int): default 0.

• 4-state (logic, reg): default X.

• Unconnected nets: default Z.

Pro Tip
Explicitly initialize critical signals in your testbench to avoid hidden X-state bugs.

Question
19. What is polymorphism and its advantages?

Answer
Polymorphism lets you call overridden methods via a base-class handle. Advan-
tages: code reuse, flexible extensions, clearer architecture.

Pro Tip
Design base classes with clear virtual interfaces—this makes extension safer and
more predictable.

Question
20. What is the purpose of the this pointer in SystemVerilog?

6
SystemVerilog FAQs VeriCore

Answer
this refers to the current object instance, disambiguating members when names
collide.

Pro Tip
Use this. only when necessary—overuse signals unclear code.

Question
21. What is a SystemVerilog interface?

Answer
An interface groups signals and modports for modular DUT connections:
interface Bus_if(input logic clk);
logic [7:0] data;
modport MASTER (output data, input clk);
endinterface

Pro Tip
Parameterize interfaces for width and protocol variants to maximize reuse.

Question
22. Difference between reg and logic.

Answer
Both 4-state, but logic supports both continuous and procedural assignments; reg
is procedural only.

Pro Tip
Prefer logic in new code—only use reg when simulating legacy Verilog modules.

Question
23. Difference between :/ and := in random distributions.

Answer
• :/: even weight spread across a range.

• :=: full weight to each element in the range.

Pro Tip
Use := when you need explicit control of weights per element.

7
SystemVerilog FAQs VeriCore

Question
24. How to disable randomization for a field?

Answer

obj.field.rand_mode(0); // disable
obj.field.rand_mode(1); // re-enable

Pro Tip
Disable randomization only during debug—re-enable before final coverage runs.

Question
25. What are the different types of code coverage?

Answer
Statement, branch, expression, toggle, FSM, and assertion coverage.

Pro Tip
Aim for balanced coverage goals—100% in one metric doesn’t guarantee thorough
verification.

Question
26. Write a constraint to detect odd numbers of ones in an 8-bit se-
quence.

Answer

class OddOnes;
rand bit [7:0] data;
constraint c { $countones(data) % 2 == 1; }
endclass

Pro Tip
Built-in functions like $countones simplify complex constraints.

Question
27. What are local and protected access qualifiers?

8
SystemVerilog FAQs VeriCore

Answer
• local: visible only in the declaring class.

• protected: visible to the class and its subclasses.

Pro Tip
Favor protected to let subclasses extend functionality without exposing internals
publicly.

Question
28. How do OOP concepts help in verification?

Answer
OOP enables modular testbench architecture, code reuse via inheritance, and flex-
ible behavior through polymorphism.

Pro Tip
Keep classes single-purpose—this simplifies maintenance and boosts reuse.

Question
29. What is a virtual interface?

Answer
A handle to an interface instance for class-based testbenches:
interface Bus_if(...);
// signals
endinterface
class Monitor;
virtual Bus_if vif;
function new(virtual Bus_if vif_p); vif = vif_p; endfunction
endclass

Pro Tip
Pass interfaces virtually into all UVM components for maximum flexibility.

Question
30. Why was logic introduced in SystemVerilog?

Answer
logic unifies reg and wire, supporting both continuous and procedural usage.

9
SystemVerilog FAQs VeriCore

Pro Tip
Use logic by default, reserving wire for legacy net-based modules.

Question
31. Write a function to push 10 unique values (0–50) into a queue.

Answer

function void unique_push(ref int q[$]);


int temp;
while (q.size() < 10) begin
temp = $urandom_range(0,50);
if (!(temp inside {q})) q.push_back(temp);
end
endfunction

Pro Tip
Query queues with inside for concise uniqueness checks.

Question
32. Constraint to pick a 16-byte block outside reserved region
(0x0–0x100, reserved 0x20–0xE0), 4-byte aligned.

Answer

rand bit [31:0] addr;


int size = 16;
constraint c {
addr inside {[0:’h100]};
!(addr inside {[’h20:’hE0]});
addr % 4 == 0;
(addr + size) inside {[0:’h20],[’hE0:’h100]};
}

Pro Tip
Group related constraints and comment each clause for future maintainability.

Question
33. Randomize an address in [0x2000:0x4000], 4-byte aligned.

10
SystemVerilog FAQs VeriCore

Answer

bit [31:0] addr;


constraint c {
addr inside {[32’h2000:32’h4000]} &&
addr % 4 == 0;
}

Pro Tip
Combine conditions with && for short constraints when readability permits.

Question
34. Difference between a mailbox and a queue.

Answer
• Queue: In-class, variable-size buffer.

• Mailbox: IPC mechanism with blocking put()/get().

Pro Tip
Use mailboxes in UVM for synchronized transaction passing between components.

Question
35. What is the difference between rand and randc?

Answer
• rand: May repeat values before exhausting the domain.

• randc: Cycles through all values before repeating.

Pro Tip
Prefer randc for coverage-driven tests requiring all possible values.

Question
36. How to reference parent class variables/methods from a child?

11
SystemVerilog FAQs VeriCore

Answer
Use super:
class Child extends Parent;
function void example();
super.do_something();
endfunction
endclass

Pro Tip
Explicit super calls improve readability in deep hierarchies.

Question
37. Where is the extern keyword used?

Answer
extern declares methods/constraints outside the class body for cleaner definitions.

Pro Tip
Use extern to keep class headers concise and move bulky definitions to a separate
file.

Question
38. One way to avoid race conditions between DUT and testbench.

Answer
Use a clocking block to control sample/driving phases with defined skew.

Pro Tip
Define separate input/output clocking blocks to clearly separate read/write phases.

Question
39. Difference between logic and bit.

Answer
• bit: 2-state (0,1)

• logic: 4-state (0,1,X,Z)

12
SystemVerilog FAQs VeriCore

Pro Tip
Use bit for performance-sensitive signals that never require X/Z.

Question
40. How to check if any bit of a signal is X or Z?

Answer

if ($isunknown(sig)) $display("Contains X or Z");


if (sig === ’Z) $display("All bits Z");

Pro Tip
Prefer \$isunknown over manual bitwise checks for brevity and clarity.

Question
41. Puzzle: Determine base class for unknown derived instances.

Answer
Use \$cast to test inheritance:
if ($cast(A_ptr, D_obj)) $display("D extends A");
if ($cast(B_ptr, C_obj)) $display("C extends B");

Pro Tip
Check the Boolean result of \$cast—it’s safer than relying on implicit failures.

Question
42. Write SV code to wait for a random delay (100–500 ns).

Answer

int d;
assert(std::randomize(d) with { d inside {[100:500]}; });
#(d) $display("Delayed %0dns", d);

Pro Tip
Wrap your randomize call in assert to catch unsatisfiable constraints early.

Question
43. Difference between parameter and typedef.

13
SystemVerilog FAQs VeriCore

Answer
• parameter: compile-time constant.

• typedef: defines a new type alias.

Pro Tip
Use typedef for complex structs to improve code readability and maintenance.

Question
44. What is constraint solve-before?

Answer
A solver directive that enforces one constraint to solve before another:
constraint A before B { ... }
constraint B { ... }

Pro Tip
Use solve-before to manage dependencies among interrelated constraints.

Question
45. What is an alias?

Answer
alias declares an alternate name for a net or variable:
wire [7:0] byte;
alias bits = byte[3:0];

Pro Tip
Use aliases for common bus slices to reduce repetitive indexing.

Question
46. Extract 5 elements at a time from a queue.

14
SystemVerilog FAQs VeriCore

Answer

bit [7:0] q[$], subset[$];


for (int i=0; i<q.size(); i+=5) begin
subset = q[i +: 5];
// process subset
end

Pro Tip
The [i +: 5] slice operator is ideal for windowed queue processing.

Question
47. Clocking block vs. modport—what’s the difference?

Answer
• Clocking block: Defines timing and phases for signals.

• Modport: Specifies direction and grouping of interface ports.

Pro Tip
Define separate clocking blocks for input and output to prevent inadvertent con-
flicts.

Question
48. Difference between $random and $urandom.

Answer
• $random: returns signed 32-bit values.

• $urandom: returns unsigned 32-bit values.

Pro Tip
Use $urandom to avoid negative values when generating addresses or indices.

Question
49. Why can’t program blocks have an always block?

Answer
Program blocks execute in the reactive region and must terminate; an always block
never ends.

15
SystemVerilog FAQs VeriCore

Pro Tip
Keep long-running processes outside program blocks to ensure testbench comple-
tion.

Question
50. What are the advantages of cross-coverage?

Answer
Cross-coverage combines multiple coverage points:

• Improves granularity by covering interactions.

• Reduces total point count vs. separate coverage.

• Reveals complex corner-case correlations.

Pro Tip
Plan cross-coverage early to guide your constrained-random stimulus toward critical
multi-variable scenarios.

Question
61. What is the difference between always comb and always ff?

Answer
• always comb infers combinational logic; no latches, automatically infers sen-
sitivity list.

• always ff infers sequential logic; must contain exactly one clock and optional
reset in its sensitivity list.

always_comb begin
out = a & b; // pure combinational
end

always_ff @(posedge clk or posedge rst) begin


if (rst) q <= 0; // sequential register
else q <= d;
end

Pro Tip
Use always comb for pure logic and always ff for registers to leverage lint checks
and avoid accidental latches.

16
SystemVerilog FAQs VeriCore

Question
62. How do you call a C function from SystemVerilog using DPI-C?

Answer
Declare the import and call it like a task/function:
// SV side
import "DPI-C" function int c_compute(int a, int b);

module tb;
initial begin
int result = c_compute(5, 7);
$display("Result = %0d", result);
end
endmodule
On the C side:
#include "svdpi.h"
int c_compute(int a, int b) {
return a + b;
}

Pro Tip
Always match C and SV data types precisely and compile the DPI shared library
with simulator’s DPI flags.

Question
63. What is the difference between struct and union in SystemVerilog?

Answer
• struct: Aggregates multiple fields stored simultaneously.

• union: All fields share the same memory; only one field is valid at a time.

typedef struct {
logic [7:0] addr;
logic [15:0] data;
} packet_t;

typedef union {
logic [23:0] raw;
packet_t pkt;
} overlay_t;

17
SystemVerilog FAQs VeriCore

Pro Tip
Use union for efficient overlays or reinterpretation of bit-level data; use struct for
safety and clarity.

Question
64. How do you define and use an enum in SystemVerilog?

Answer
Define named states or codes:
typedef enum logic [1:0] { IDLE=2’d0, READ=2’d1, WRITE=2’d2 } state_t;

module fsm(input logic clk, rst,


output state_t state);
state_t state_reg;
always_ff @(posedge clk or posedge rst) begin
if (rst) state_reg <= IDLE;
else state_reg <= next_state;
end
assign state = state_reg;
endmodule

Pro Tip
Always size your enum explicitly to avoid unintended width mismatches during
synthesis.

Question
65. How do you constrain a dynamic array to have unique elements?

Answer
Use the unique qualifier in a constraint:
class C;
rand int da[];
constraint len { da.size == 5; }
constraint uniq_e { unique { da }; }
endclass

Pro Tip
Combine unique with size constraints to generate permutations without duplicates
efficiently.

18
SystemVerilog FAQs VeriCore

Question
66. How do you specify weighted random distributions?

Answer
Use the dist operator in a constraint:
class C;
rand int code;
constraint c { code dist { [0:3] := 70, [4:7] := 30 }; }
endclass
This makes 0–3 occur 70% of the time and 4–7 30%.

Pro Tip
Use dist to bias your tests toward important ranges while still allowing full cover-
age.

Question
67. What do $stable and $changed system tasks do?

Answer
• $stable(x) returns true if x did not change since the last time step.

• $changed(x) returns true if x changed in the current time step.

if (!$stable(data)) $display("Data changed!");

Pro Tip
Use these in coverage or assertions to detect glitches or unintended toggles.

Question
68. What is the difference between blocking (=) and non-blocking (<=)
assignments?

19
SystemVerilog FAQs VeriCore

Answer
• blocking (¯
): executes in order; can introduce race conditions.

• non-blocking (=): schedules the assignment for end of time step; models
registers.

always_ff @(posedge clk) begin


a <= b; // non-blocking for registers
end

always_comb begin
x = y; // blocking for combinational
end

Pro Tip
Use non-blocking in sequential blocks (always ff) and blocking in combinational
(always comb) to avoid races.

Question
69. What’s the difference between $stop and $finish?

Answer
• $stop: suspends simulation and enters interactive debug (if supported).

• $finish: ends simulation cleanly and exits.

Pro Tip
Use $stop for breakpoints during debug and $finish at the end of your testbench
main thread.

Question
70. What is the difference between parameter and localparam?

Answer
• parameter: can be overridden during instantiation.

• localparam: cannot be overridden, used for internal constants.

module M #(
parameter WIDTH = 8,
localparam DEPTH = WIDTH*2
) (...);

20
SystemVerilog FAQs VeriCore

Pro Tip
Use localparam for derived values to prevent accidental overrides and maintain
consistency.

Question
71. What is the difference between hard and soft constraints?

Answer
• Hard constraints must be satisfied; if unsatisfiable, randomize() fails.

• Soft constraints are prefixed with soft; solver treats them as preferences and
may violate them if needed to satisfy all hard constraints.

class C;
rand int x;
constraint hard_c { x inside {[0:10]}; }
soft constraint soft_c { x > 5; }
endclass

Pro Tip
Use soft constraints to guide randomization toward preferred values without risking
unsatisfiability.

Question
72. How do you seed the random number generator for reproducibility?

Answer
Use std::randomize with a seed or call $urandom(seed) before tests:
initial begin
int seed = 32’hDEADBEEF;
std::randomize() with { /* ... */ } randomize(seed);
// or set global seed:
$urandom(seed);
end

Pro Tip
Log your seed value so you can reproduce any failing random test exactly.

Question
73. How to query the size of a dynamic array, queue, and associative
array?

21
SystemVerilog FAQs VeriCore

Answer
• Dynamic array (da[]): da.size()

• Queue (q[]) : q.size()Associative array(aa[string]) : aa.num()

Pro Tip
Use these methods in assertions or coverage to verify container utilization and edge
cases.

Question
74. How do you declare and use an associative array?

Answer
Associate keys of arbitrary type to values:
module tb;
int aa[string];
string keys[$];
initial begin
aa["one"] = 1;
aa["three"] = 3;
keys = aa.keys();
$display("Keys: %p", keys);
end
endmodule

Pro Tip
Iterate with foreach (aa[key]) to process key–value pairs elegantly.

Question
75. How to implement a parameterized function in SystemVerilog?

22
SystemVerilog FAQs VeriCore

Answer
Use a function automatic with type parameter:
function automatic #(type T = int) T add(T a, T b);
return a + b;
endfunction

module tb;
initial begin
int x = add#(int)(2, 3);
real y = add#(real)(1.5, 2.5);
$display("x=%0d, y=%0f", x, y);
end
endmodule

Pro Tip
Parameterize functions for maximum reuse across data types without code dupli-
cation.

Question
76. How do you use the generate block with if conditions?

Answer
Use generate. . . endgenerate with if:
genvar i;
generate
if (WIDTH == 8) begin : gen8
// 8-bit specific instantiation
end else begin : gen_other
// other width instantiation
end
endgenerate

Pro Tip
Name each conditional block to keep hierarchy clear in synthesis and simulation
views.

Question
77. How do you enforce a random constraint only when a condition is
true?

23
SystemVerilog FAQs VeriCore

Answer
Use if inside a constraint block:
class C;
rand bit flag;
rand int value;
constraint cond_c {
if (flag) value inside {[10:20]};
}
endclass

Pro Tip
Wrap conditional constraints in braces to avoid parser ambiguity in complex cases.

Question
78. How to write a packed vs. unpacked array?

Answer
• Packed array: bits contiguous logic [7:0] arr1 [3:0];

• Unpacked array: array of words logic arr2 [3:0] [7:0];

Pro Tip
Use packed arrays for synthesis-friendly bit-vectors and unpacked arrays for data
structures.

Question
79. How do you specify timescale and precision in a file?

Answer
At the top of the file:
‘timescale 1ns/1ps
Here, time unit is 1 ns and precision is 1 ps.

Pro Tip
Set precision fine enough for your smallest delay but not so fine as to slow simulation
excessively.

Question
80. How do you use the with clause in randomize() for inline constraints?

24
SystemVerilog FAQs VeriCore

Answer
Call randomize() with an inline block:
if (!obj.randomize() with {
obj.x > 0;
obj.y < 10;
}) begin
$error("Randomization failed");
end

Pro Tip
Check the Boolean return of randomize() to handle failures gracefully in test-
benches.

25

You might also like