SystemVerilog Array of Interfaces

// Viewing Array of interfaces in waveform viewer(dve)

// Notes added inline in the below example

interface my_if(input clk);
logic [31:0] addr;
logic [31:0] data;

module dut(input xx, my_if i[1:0], output o, my_if ii);
assign o = xx ? i[0].data :;

module tb;

bit o;
bit clk;

// Array of interface
// Visible where the actual instance is present
// interface signals can’t be seen as arguments of dut
// Visible under ‘tb’, NOT under ‘dut’
my_if i[1:0](clk);

// interface instance – not an array
// Visible under ‘tb’, as well as under ‘dut’
my_if ii(clk);

dut dut(.xx(1’b1), .i (i[1:0]) , .o, .ii);

initial forever #5 clk++;

initial begin
i[0].addr = 10;
i[0].data = ‘hff;
i[1].addr = 20;
i[1].data = ‘haa; = 0;
i[0].addr = 110;
i[0].data = ‘h1ff;
i[1].addr = 120;
i[1].data = ‘h1aa; = 1;
#100 $finish;

// Waveform dumping for VCS
// Change this for other simulators
initial begin


// Screenshot on waveform viewer (dve)



General Purpose Preprocessor in Perl

Here is a preprocessor in perl, primarily for Verilog, SystemVerilog, but may be used for any language.
There are programs with a lot of repetitive text. Language features like functions, objects can reduce typing.
Still, there is scope for putting it in lesser code using a text preprocessor.
Limitations in existing preprocessors prompted in writing a new one that addresses the issues
C preprocessor:
Every define has to be written in a single line.
Escape chars for special chars can make the macro unreadable
Very limited keywords. No loop operations
m4 preprocessor:
No escape characters
Difficult to write macros consisting special characters
Advantages of the new preprocessor:
Written in perl, no CPAN packages used, very portable
Very small – 50 lines of code; Only 7 keywords;
No escape characters. Can be used for any programming language.
Possible to emulate features of C-preprocessor as well as m4
Hook to insert perl keywords – shown in example at end of script.
More usage examples coming-up in later posts.
###### General Purpose Preprocessor (c) A.G.Raja ########
my @lines;
my $code;
my $t=0;
my $e;
sub tokenize {
  my $text = shift;
  my @spl  = split(/(\$get\s*\(\s*\w+)\s*\)/,$text);
  my $out  = “”;
  my $var  = “”;
  foreach my $s (@spl) {
    if($s =~ /\$get\s*\((.*)/) {
      $var = $1;
      if($var =~ /^\d+/) {
        $out .= “\$_[$var]”;
      } else { $out .= “\$$var”;
    } else {
      $out .= “\$lines[$#lines]”;
  return “\”$out\””;
while(<DATA>) {
  if(!length($_)) {
  } elsif(/^\s*\$macro\s+(.*)/) {
    $code .= “\nsub $1 {\n  my \$ret;\n”;
  } elsif(/^\s*\$endmacro\s*$/) {
    $code .= “return \$ret;\n}\n”;
  } elsif(/^\s*\$begin\s+(.*)/) {
    $code .= “$1 {\n”;
  } elsif(/^\s*\$end\s*$/) {
    $code .= “}\n”;
  } elsif(/\$set\s+(\$\w+)\s*=(.*)/) {
    $code .= “\n$1 = \”\@{[ $2 ]}\”;\n”;
  } else {
    $e = &tokenize($_);
    if($t==1) {
      $code .= ”  \$ret .= $e;\n”;
    } else {
      $code .= “print $e;\n”;
eval $code or die print “\n\n### ERROR: PREPROCESSING FAILED ###\n\n”;
############   TEXT after DATA can be edited   ############
$macro func               $dnl ### This is Start of Macro Definition
$get(0) $dnl              $dnl ### $dnl will Delete-till New-Line
$begin foreach $x (@_)    $dnl ### $begin will append { to perl code
argument is $get(x)       $dnl ##### Substitute perl variable, here $x
$end                      $dnl ### $end will append } to perl code
$endmacro                 $dnl ### This is End of Macro Definition
$set $a = func(1,2,3,4,5) $dnl ### Assign return value of a Macro
aa $begin                 $dnl ### Spaces before keywords not allowed
 $dnl this is a comment. newline+space will be printed here
$dnl ############################################
$dnl #### This Script translates TEXT to perl code and executes it.
$dnl #### Following are Keywords for TEXT to be preprocessed:
$dnl ####   $dnl $macro $endmacro $begin $end $set $get
$dnl #### Usage of the keywords are explained in above example.
$dnl #### $begin keyword can be exploited to get the power of perl.
$dnl ############################################

Difference between reg, wire, logic in SystemVerilog


Can be used for input, output, inout

Multiple drivers, No drivers cause x


Wire variable = value;

Assign variable = value;

Can be used to connect module instances



Can be used only for input

Can’t be used in ‘assign’ statement

It takes last assigned value, behaves like a variable


R <= 1;

R <= 0;

R takes value 0, even though there are multiple concurrent assignments



Can be used for input, output. Can’t be used for inout

Can be used in place of wire or reg;

First usage defines the behavior; can’t be changed later.


Assign l = 1; // Valid

Initial l = 1; // Valid

Assign l = 0; initial l = 1; // Invalid



Similar to logic; it is a two state variable.


Non-blocking assignment

No assignment happens to lhs till simulation timestamp is advanced.

Even after #0, the assigned value will not available


Blocking assignment

Lhs gets assigned immediately

Laptop plugged in, not charging

Laptop plugged in, but not charging:

This was a really annoying issue, since I had bought the laptop just 3 months back.

I searched in HP forums, (mine is a HP laptop), there were a range of suggestions

1) Uninstall Battery adapter from Device manager

2) Restart !!

3) Re-install the power manager software

4) Replace the battery

5) Contact the manufacturer

Mine has AMD processor, but the laptop was very hot; something very unusual.

Silly reason: the laptop was placed on a soft couch; there was absolutely no ventilation.

I don’t see a connection between ventilation to battery charging; Anyway, the below worked.

Solution: Lifted the laptop so that the air vents on the bottom, sides are not blocked. It started charging !!

OOP Design Patterns Summary

Summary of OOPs Design Patterns from GoF Book

Note: Syntax, keywords of C++ used in example snippets.

Download: DesignPatterns_Summary

Creational Patterns


Object is created only once using a static Create() method; new is not called directly.

First call of Create() method creates a static object using new.

Subsequent calls to the Create() method returns the pointer to static object already created.

Factory Method / Virtual Constructor

Objects are created using Create method instead of calling new directly.

BaseClass: abc

DerivedClasses: A,B,C


abc CreateChar(char id) {

switch(id) {

case ‘a’: return new A();

case ‘b’: return new B();

case ‘c’: return new C();



Abstract Factory

BaseClass has CreateChar, CreateNum virtual functions


abc CreateChar() {

return A;


num CreateNum() {

return N1;



abc CreateChar() {

return B;


num CreateNum() {

return N2;



It takes many steps to create a concrete object.

Eg. Creating a tree, linked list, etc.


Clone() method is used to copy self

Concrete objects are cloned from prototype and can be cloned again.

Inheritance: Derived class object can access base class variables, functions

Prototyping: Cloned object can access protype class variables only.

Structural Patterns


Convert interface of a class as clients expect.

Make systems work together after they are designed.


Similar to adapter but the interface is known in advance.

class systemA {

systemB *s;

void set(systemB *ss) { s = ss; }

void exec() { s->run(); }



Creating a hierarchical tree

Every node can create its own child(branch/leaf).

Each branch/leaf can be of a different type.

Decorator / Wrapper

Similar to Adapter. But interface doesn’t change. Wrapper can do additional operations.

class wrapper {

original o;

void func() {






Provide a higher level interface to combine many complex interfaces.

Eg. Compile() =  Scan() + Parse() + ByteCode() + Interpret()

Proxy / Surrogate

Smaller object acts on behalf of a larger object.

Eg. Document with an image. Proxy object can have only path to image file, pointer to ImageDisplay object. ImageDisplay object need not created unless Document.display() is called.


Use sharing to improve efficiency.



class character {

char c;

int row, col;


Instead of storing a character object for every position,

Store position of every character in the alphabet.


class position {  int row, col; }

class character {

char c;

position p_array[];



Behavioral Patterns


Chain of Responsibility

Request is passed along a chain until an object finally handles it.

Split complex tasks into simpler tasks and make the system modular.

Eg. BuildHouse() calls BuildRooms();

BuildRooms() calls BuildFloors(), BuildWalls();

BuildWalls() calls BuildDoors(), BuildWindows().


Encapsulate a request as an object. Each request type can have a different command object.

Iterator / Cursor

Provide a way to access elements without exposing underlying implementation.


int array[10]; // Every element can be accessed as array[i];

Iterator implementation:

class iterator {

int array[10];

int i=0;

int get() { return array[i]; i++; }

int end() { if(i<10) return 0; else return 1; }



Create a tree and execute each node recursively starting from root.


Defines an object that encapsulates how a set objects interact. Objects need not interact by referring the other object explicitly. In Bridge pattern, two systems know the interface of the other. In Mediator pattern each system knows its interface to Mediator object.

Memento / Token

Store internal state of an object to restore later.

Eg. Moving a cursor on screen needs the position fields to be changed without changing other fields.

Memento object can store the position using get_position() method of cursor.

Modify memento with new position. Again use the memento to set_position() of cursor.

Instead of accessing internal variables of cursor, get, set methods are used along with memento.

Observer / Publish-Subscribe

Every subject keeps a list of observers. Any change in the subject updates all the observers.

Eg. Same Data can be represented as table, bar-graph, pie-chart.


Equivalent of having a state object for every case in a switch statement.

A state object implements task in current state, returns name of next state.

Client initializes its state-variable, calls methods in every state, changes state variable after every state.

Strategy / Policy

Do similar task using different algorithms. The family of algorithms are encapsulated and made interchangeable.


Define skeleton of algorithm in an operation, Let sub-class define the algorithm without changing the algorithm’s structure.


Create a parallel tree with a visitor on each node.

Eg. Main tree does execution operation of a compiler. Visitor objects corresponding to each node does type-checking / syntax-checking.


  Design Patterns Summary
Creational Pattern Constructs
Singleton Object only once
Factory Method Object by ID
Abstract Factory Group of Objects by ID
Builder Object in many steps
Prototype Object by cloning another
Structural Pattern Connects
Adapter Two existing systems with different interfaces
Bridge Two systems by defining an interface
Composite Using same interface to create a tree
Wrapper To Object with same interface but more functions
Façade Multiple objects by merging interfaces
Flyweight Objects by separating fields that vary lesser
Proxy Object with light-weight interface
Behavioral Pattern Encapsulates
Chain-of-responsibility Modular sub-tasks to perform a complex task
Command Requests to perform different tasks
Iterator Private Data & Implementation with simpler interface
Interpreter Different tasks assigned to objects of a tree
Mediator Interfaces to different systems
Memento Interfaces to change private state variables
Observer Interface to tasks of different observers within broadcaster
State State specific tasks and next-state logic
Strategy Family of inter-changeable algorithms
Template Steps in algorithms by defining a skeleton
Visitor Auxiliary tasks for visitors of every node of a tree

Many-ism of System of Government


Democracy: Head of Government is elected by citizen’s votes.
Dictatorship: No voting rights. Corrupt voting mechanism in Democracy leads to Dictatorship.

Political Spectrum based on Economic Policy.
Left – Communism. Middle – Socialism. Right – Capitalism.

Capitalism: Open Competition in business.
Socialism: Government controls business by regulating competition.
Communism: Government owns everything. No Competition – No Rewards. No Crime – No Punishments.

Nationalism: To have a strong feeling for own nation. It promotes Secularism – Nation is valued above Class.
Communism is one step above Nationalism. It is about internationalism. Everyone belong to one universal family.
Liberals: Promote International open competition in business. Opposite to Communists in economic policy. But think Global instead of National.
Conservatives: Think Narrow. Protect minorities. Support Socialism.

Nazism: Nationalism + Socialism + Dictatorship.
Fascism: Nationalism + Dictatorship. Capitalism, Socialism, Liberals, Conservatives all can co-exist. Dictator can change economic policy based on need/context. The system has been misunderstood due to Mussolini(In Picture) and Hitler’s Evil Dictatorships.

Communism is the most ideal system. Corrupt dictator spoils the noble idea.
Democracy is close to ideal human-right system. As opposed to dictatorship, a ‘majority’ making wrong choice can spoil the idea.
Socialism is a practical economic policy. Also protects minority. Can exist under dictator or democracy. Every form of Government is becoming socialist to some extent.
Nascism/Fascism can be practical systems if the evils of Dictatorship can be eliminated.

List of Techniques to Generate Creative Ideas

6 Different Approaches to generate ideas

1. Extract the abstract:

Simplify to a skeleton. Pay attention to details and classify.

2. Observe the features:

Use SCAMPER on Attributes / Components / Processing-steps.

3. Visualize through others:

Use peripheral vision. Change Focus / Angle / Entry-point.

4. Look outside boundaries:

Challenge rules, assumptions, constraints, logic. Ask what-if.

5. Keep eyes wide open:

Look for inspiration. Apply random-stimulus, import / export.

6. Scan through alternatives:

Consciously generate ideas. 5W1H, Mindmap, Brainstorm.

Think like a person from another profession.

Approach a problem like a child or person from a different field. Imagine how they would look at the problem. Generate ideas by thinking in a different point-of-view.

Engineer – Add, Subtract, Combine, Modify

Salesman – Exaggerate, Magnify, Maximize

Driver – Find alternative routes, directions, shortcuts

Lawyer – Break rules, Challenge logic, Reverse assumptions

Player – Delay judgment, ignore mistakes till end

Artist – Random association, Inspiration from nature

List of other thinking tools:

BAR – Bigger Added, Remove/Replace

CAMPER – Consequences-Assumptions-Main Points, Prejudice-Evidence,Relevance

C&C – Compare and Contrast

C&S – Consequence and sequel

Directed Thinking – Consider All Factors; Why yes? Why no? Why Wait? What else? Way to go?

FIP – First Important Priority

OPV – Other People’s Point Of View

PCD – Possibilities-Consequences-Decision

PMI – Plus Minus and Interesting

POOCH -Problem-Options-Outcomes-Choices

Reversal – State the problem, reverse the problem, ask why? Brainstorm, seek the solution

SCAMPER – Substitute, Combine, Adapt, Modify (magnify/minimise),Put to other use, Eliminate, Remove/reverse.

SCUMPS – Size, colour, use, materials, parts, shape

SWOT – Strengths Weaknesses Opportunities and Threats