Wednesday, March 16, 2011

SystemVerilog struct assignment

You may have occasion to initialize a structure in SystemVerilog:

typedef struct {
int f1;
int f2;
int f3;
} set_of_values_T;

set_of_values_T set_of_values = {1, 2, -3};


This might seem fine, but the above assignment is actually a concatenation. The simulator will take the set of values and pack them into one big bit vector.

In my experience, Modelsim was okay with positive values, or a mix of positive and negative values. In compilation, it would note that it was promoting an assignment to a concatenation. But if all the values were negative, it would give an error that a packed value was being assigned to an unpacked value.

A quick Google search turned up a book preview that showed an example of how to initialize a structure. Very simple, really. Just add a tick (') before the assignment:


set_of_values_T set_of_values = '{1, 2, 3};


This does the trick, and the notes and errors go away. SystemVerilog uses the '{} construct to differentiate a list of values from a concatenation, {}.

EDIT: Another example, this time with a dynamic array or queue:


bit [0:2] values[$]= '{3,5,6};

6 comments:

  1. This is just what I was looking for. I also discovered that you can use the colon construct to assign fields by name, just like with arrays (this works in Synplify):

    set_of_valuesT set_of_values = '{f1:5,f3:-6,f2:7};

    And now I see that this blog is hosted by Jason! That's a coincidence. It's a long time since I've seen you. Still in Chicago?

    ReplyDelete
    Replies
    1. Yep, still in the same office in Arlington Heights, but we're now Nokia Siemens Networks.

      What are you up to? Last I heard, you were off to travel or something.

      Delete
    2. This comment has been removed by the author.

      Delete
    3. Yeah, I took two years off and I lived in the mountains for two seasons and snowboarded every day. And I lived in Berlin for a couple of months. Now I'm in south Denver doing FPGAs for satellites, which I've been doing almost a year now. It's nice to be doing Verilog again.

      Delete
  2. Is there any way to use structure element through concatenation like assignment pattern?
    Like : set_of_valuesT set_of_values = {f1:5,f3:-6,f2:7}

    ReplyDelete
    Replies
    1. That should work, but again, you will probably need the tick:

      set_of_valuesT set_of_values = '{f1:5,f3:-6,f2:7};

      This has the advantage that if you change the order of the fields in your structure, you will still assign the values to the correct places.

      Delete