Verilog, How to pass different parameters when I use generate to instantiation module? - parameter-passing

I have a question about parameters passing. I used generate for to do module instantiation. But how to pass different parameters to each module?
For example:
generate
for (i=0;i<N;i=i+1) begin:ModIns
Mod #(.p1(?),.p2(?)) M (
// Signal connection
);
end
endgenerate
For N modules, each with different p1 and p2. How to do that? By the way, the number of parameters is very large, can I pass parameters as a file?
Thanks!

Here are my 2 cents.
Declare a 2-D register and store all the parameters there.
reg [31:0] param_mem1 [N-1:0]; //Assuming parameter size to be 32 bit wide
reg [31:0] param_mem2 [N-1:0];
always#(posedge clk)
begin
for(i=0;i<N;i=i+1)
begin
param_mem1[i] <= i; //Here replace 'i' with your actual parameter value
param_mem2[i] <= i+1; //Dummy assignment, please use intended values
end
end
generate
for (i=0;i<N;i=i+1) begin:ModIns
Mod #(.p1(param_mem1[i]),.p2(param_mem2[i])) M (
// Signal connection
);
end
endgenerate

First: No you can't read it from a file. Parameters have to be known at compile time and a file is only readable in run time.
You can derive them from a genvar or pass them through a hierarchy, but then it more or less stops. Maybe what you are trying to do can be solved in a different way but the scope of the problem you have outlined for us here is rater limited.
As always: Tell us your problem, not your solution.

It would be easier to do this in SystemVerilog because a parameter can be an array, and your generate loop could select an element for each iteration of the loop.
In Verilog, you can pack your elements into a bit-vector, and your generate loop could select a slice for each iteration of the loop.
parameter A1={8'd1, 8'd2, 8'd3, 8'd4, ...};
parameter A2={8'd9, 8'd8, 8'd7, 8'd6, ...};
generate
for (i=0;i<N;i=i+1) begin:ModIns
Mod #(.p1(A1[i*8+:8),.p2(A2[i*8+:8])) M (
// Signal connection
);
end
endgenerate
If you want to define the parameters from a file, you can put the parameter declarations in a separate file and `include the file.

This compiles with VCS:
genvar port_idx;
generate
for (port_idx = 0; port_idx < 5; port_idx++) begin : intf
xactor_t xactor (core_clk, core_rst);
defparam xactor.intf_id = 18 + port_idx;
end

Related

Passing parameters between Verilog modules

I fairly new to Verilog and learning the ropes. I have some code which generates an 8 bit up-counter (module counter.v), which is then called by a top module (top_module.v). There is a simulation test fixture (test_fixture.v) which calls the top module for testing.
I was trying to define the width of the counter using a parameter (parameter COUNTER_WIDTH) and was having difficulty doing so. A colleague fixed the code for me and it does now indeed work, but I want to understand a few things so I can understand what is actually going on.
Here is the code for the counter module:
module counter
#(parameter COUNTER_WIDTH = 8)
(
input wire CLK,
input wire RST,
input wire CE,
output reg[COUNTER_WIDTH-1:0] out = {COUNTER_WIDTH{1'b0}}
);
always #(posedge CLK) begin
if (RST == 1) begin
out <= {COUNTER_WIDTH{1'b0}};
end else begin
if (CE == 1) begin
out <= out + 1'b1;
end
end
end
endmodule
The top module:
module top_module
#(parameter COUNTER_WIDTH = 8)
(
input wire CLK,
input wire CE,
input wire RST,
output wire[COUNTER_WIDTH-1:0] out
);
counter #(
.COUNTER_WIDTH(COUNTER_WIDTH)
)
counter_inst(
.CLK(CLK),
.RST(RST),
.CE(CE),
.out(out)
);
endmodule
And the test fixture:
module test_fixture();
parameter COUNTER_WIDTH = 8;
// inputs
reg CLK = 0;
reg RST = 0;
reg CE = 0;
// outputs
wire [COUNTER_WIDTH-1:0] Q;
// instance of top module to be tested
top_module #(
.COUNTER_WIDTH(COUNTER_WIDTH)
)
test_inst(
.CLK(CLK),
.RST(RST),
.CE(CE),
.out(Q)
);
endmodule
I think I'm fine with the counter module, but have a question about what is going on in top module/test fixture:
It looks like the parameter COUNTER_WIDTH is declared in each module (#(parameter COUNTER_WIDTH = 8)), and then "connected to" (if that is the correct expression) the parameter declaration in the other module (e.g. #(.COUNTER_WIDTH(COUNTER_WIDTH) )
Is that understanding correct? If so, why do we have to declare the parameter within a module and connect it to a parameter within another module?
Thanks in advance for your help!
Think of a parameter as a special kind of constant input whose value is fixed at compile time. Originally, in Verilog, parameters were constants that could be overridden from outside a module (using the now deprecated defparam statement). So, a Verilog parameter had two roles:
a local constant
a way of customising a module from outside
Then, in the 2001 version of the standard (IEEE 1364-2001), the syntax you're using below was introduced (the so-called "ANSI style"). Also IEEE 1364-2001 introduced localparams (which fulfill the first of these two roles because they cannot be overridden from outside), so leaving parameters to handle the second of these two roles (the customisation). With the ANSI-style syntax, you override a parameter when you instantiate a module. You can associate the parameter with any static value, for example a parameter of the parent module, a localparam, a genvar or a literal (a hard-coded value in your code).
Because of this historical dual-role, in Verilog you must give a parameter a default value, even if it makes no sense. (And this restriction is lifted in SystemVerilog.)
Does giving the parameters different names and default values help your understanding?
// the default value
// |
module counter // V
#(parameter COUNTER_WIDTH = 1)
(
input wire CLK,
input wire RST,
input wire CE,
output reg[COUNTER_WIDTH-1:0] out = {COUNTER_WIDTH{1'b0}}
);
always #(posedge CLK) begin
if (RST == 1) begin
out <= {COUNTER_WIDTH{1'b0}};
end else begin
if (CE == 1) begin
out <= out + 1'b1;
end
end
end
endmodule
Then, in top module, let's give the parameter a different name:
// the default value
// |
module top_module // V
#(parameter COUNTER_NUM_BITS = 2)
(
input wire CLK,
input wire CE,
input wire RST,
output wire[COUNTER_NUM_BITS-1:0] out
);
counter #(
.COUNTER_WIDTH(COUNTER_NUM_BITS)
)
counter_inst(
.CLK(CLK),
.RST(RST),
.CE(CE),
.out(out)
);
endmodule
And again in the test fixture:
module test_fixture();
localparam COUNTER_SIZE = 8; // This is not overridden from outside, so using
// a localparam would be better here.
// (A localparam being a kind of parameter that
// cannot be overridden from outside. Normal
// languages would call it a constant.)
// inputs
reg CLK = 0;
reg RST = 0;
reg CE = 0;
// outputs
wire [COUNTER_SIZE-1:0] Q;
// instance of top module to be tested
top_module #(
.COUNTER_NUM_BITS(COUNTER_SIZE)
)
test_inst(
.CLK(CLK),
.RST(RST),
.CE(CE),
.out(Q)
);
endmodule
why do we have to declare the parameter within a module and connect it to a parameter within another module?
Because, you don't HAVE to give a parameter a value when you instance the module.
In which case the tools need to have at least some value to work with.
So where you do:
counter #(
.COUNTER_WIDTH(COUNTER_WIDTH)
)
counter_inst(
.CLK(CLK),
.RST(RST),
.CE(CE),
.out(out)
);
You may also use:
counter
counter_inst(
.CLK(CLK),
.RST(RST),
.CE(CE),
.out(out)
);
In which case the default value is used.

lua not modifying function arguments

I've been learning lua and can't seem to make a simple implementation of this binary tree work...
function createTree(tree, max)
if max > 0 then
tree = {data = max, left = {}, right = {}}
createTree(tree.left, max - 1)
createTree(tree.right, max - 1)
end
end
function printTree(tree)
if tree then
print(tree.data)
printTree(tree.left)
printTree(tree.right)
end
end
tree = {}
createTree(tree, 3)
printTree(tree)
the program just returns nil after execution. I've searched around the web to understand how argument passing works in lua (if it is by reference or by value) and found out that some types are passed by reference (like tables and functions) while others by value. Still, I made the global variable "tree" a table before passing it to the "createTree" function, and I even initialized "left" and "right" to be empty tables inside of "createTree" for the same purpose. What am I doing wrong?
It is probably necessary to initialize not by a new table, but only to set its values.
function createTree(tree, max)
if max > 0 then
tree.data = max
tree.left = {}
tree.right = {}
createTree(tree.left, max - 1)
createTree(tree.right, max - 1)
end
end
in Lua, arguments are passed by value. Assigning to an argument does not change the original variable.
Try this:
function createTree(max)
if max == 0 then
return nil
else
return {data = max, left = createTree(max-1), right = createTree(max-1)}
end
end
It is safe to think that for the most of the cases lua passes arguments by value. But for any object other than a number (numbers aren't objects actually), the "value" is actually a pointer to the said object.
When you do something like a={1,2,3} or b="asda" the values on the right are allocated somewhere dynamically, and a and b only get addresses of those. Thus, when you pass a to the function fun(a), the pointer is copied to a new variable inside function, but the a itself is unaffected:
function fun(p)
--p stores address of the same object, but `p` is not `a`
p[1]=3--by using the address you can
p[4]=1--alter the contents of the object
p[2]=nil--this will be seen outside
q={}
p={}--here you assign address of another object to the pointer
p=q--(here too)
end
Functions are also represented by pointers to them, you can use debug library to tinker with function object (change upvalues for example), this may affect how function executes, but, once again, you can not change where external references are pointing.
Strings are immutable objects, you can pass them around, there is a library that does stuff to them, but all the functions in that library return new string. So once, again external variable b from b="asda" would not be affected if you tried to do something with "asda" string inside the function.

Initializing ROM from array using functions, Synthesis ERROR (VHDL)

Ok, so I have a problem with a ROM initialization function.
Before I get into the problem let me explain a bit the nature of my problem and my code.
What I want to do is generate N number of ROMs which I have to use as an input for a module that runs a matching algorithm.
My problem is that I have a file with my signatures (let's say 64 in total) which I want to load in my different ROMs depending on how many I've generated (powers of 2 in my case, e.g. 8 roms of 8 signatures each).
I figured the best way to do it is load the whole text file into an array (using a function outside of the architecture body) which I will then use (again in a function) to load the data into a smaller array which will then be my ROM.
It seemed to me that the synthesizer would then just ignore the big array since I don't actually use it in my architecture.
Problem now is that since the second array input arguments are signal dependent, the synthesizer just ignores them and ties my array to zero (line 57).
Does anyone know how else if there's a way to make this architecture synthesize-able?
library ieee;
use ieee.std_logic_1164.all;
use IEEE.std_logic_signed.all;
use std.textio.all;
entity signatures_rom_partial is
generic(
data_width : integer := 160;
cycle_int : integer :=32;
rom_size : integer := 4
);
port ( clk : in std_logic;
reset : in std_logic;
readlne: in integer range 0 to cycle_int-1; -- user input for array data initialization
address: in integer range 0 to rom_size-1; -- address for data read
data: out std_logic_vector(data_width-1 downto 0) -- data output
);
end signatures_rom_partial;
architecture rom_arch of signatures_rom_partial is
type rom_type is array (0 to cycle_int-1) of bit_vector (data_width-1 downto 0); -- big array for all signatures, not used in arch
type test_type is array (0 to rom_size-1) of std_logic_vector (data_width-1 downto 0); -- smaller ROMs used in arch
--Read from file function--
----------------------------------------------------------------------------------------------------------
impure function InitRomFromFile (RomFileName : in string) return rom_type is --
file RomFile : text is in RomFileName; --
variable RomFileLine : line; --
variable rom : rom_type; --
--
begin --
for i in rom_type'range loop --
readline (RomFile, RomFileLine); --
read (RomFileLine, rom(i)); --
end loop; --
return rom; --
end function; --
----------------------------------------------------------------------------------------------------------
--Function for smaller ROM initialization--
----------------------------------------------------------------------------------------------------------
impure function initPartRom (rom : rom_type; readlne : integer) return test_type is --
variable test_array : test_type; --
--
begin --
for j in test_type'range loop --
test_array(j) := to_stdlogicvector(rom(j+readlne)); --
end loop; --
return test_array; --
end function; --
----------------------------------------------------------------------------------------------------------
constant rom : rom_type := InitRomFromFile("signatures_input.txt");
signal test_array : test_type := initPartRom(rom , readlne); --(LINE 57) SYNTHESIZER IGNORES THESE INPUT ARGUMENTS
begin
process(clk,reset)
begin
if reset='1' then
data<=(others=>'0');
elsif (clk'event and clk='1') then
data <= (test_array(address));
end if;
end process;
end rom_arch;
Synthesis is done using Xilinx ISE, simulation is done with Modelsim in which, my creation works fine :)
Thanks for any help!
With Xilinx ISE (14.7) it is possible to synthesize ROMs and RAMs even if the initial data is read from an external file by function.
The only requirement is, that the reading function must be computable at synthesis time. This is not true for your code because readlne is not static at the point the function is called. You should change it to a generic instead of an input and assign a different value to this generic for every other ROM instance. Then it should work as intended.
A sample implementation of how to read initialization data from a text file in (Xilinx) .mem format can be found in VHDL Library PoC in the namespace PoC.mem.ocrom or PoC.mem.ocram

Why isn't parameter being passed properly in Verilog?

I have two verlog modules as seen below. The parameter statement is supposed too allow me to pass the bus width i'd like to instantiate another module at.
I keep getting an error when trying to compile saying "Port expression 64 does not match expected width 1 or 2."
module LabL3;
parameter SIZE = 64;
reg [SIZE-1:0]a;
reg [SIZE-1:0]b;
reg c;
wire [SIZE-1:0]z;
integer i,j,k;
yMux #(SIZE) mux(z,a,b,c);
initial
begin
for(i=0;i<4;i=i+1)begin
for(j=0;j<4;j=j+1)begin
for(k=0;k<2;k=k+1)begin
a=i;b=j;c=k;
#1$display("a=%d b=%d c=%d z=%d",a,b,c,z);
end
end
end
end
endmodule
and the other file is:
module yMux(z,a,b,c);
parameter SIZE= 0;
output [SIZE-1:0]z;
input [SIZE-1:0]a,b;
input c;
yMux1 mux[SIZE-1:0](z,a,b,c);
endmodule
and lastly
module yMux1(z,a,b,c);
output z;
input a,b,c;
wire not_C, upper, lower;
not my_not(notC,c);
and upperAnd(upper,a,notC);
and lowerAnd(lower,c,b);
or my_or(z,upper,lower);
endmodule
and the command I am using is: iverilog LabL3.v yMux1.v yMux.v
I have tried the different syntax's for parameter passing. All give the same result.
Any hints would greatly be appreciated.
- Chris
You are using vectored instances:
yMux1 mux[SIZE-1:0](z,a,b,c);
Where you end up with SIZE number of yMux1 instances. This should connect z,a,b bitwise correctly and connect the single bit c to all yMux1 c ports via replication.
If you really want to drive all c ports to the same value I would try manually replicating the port with:
yMux1 mux[SIZE-1:0](z,a,b,{SIZE{c}});
Example on EDAPlayground looks fine to me. Could be an issue with the specific tool not supporting vectored instances correctly.
When possible I would recommend using named port connections (ANSI header style) from section 23.2.1 of the SystemVerilog IEEE 1800-2012 Standard.
This style is very clear as to your design intent, I find it much easier to read which relates to less bugs. It also allows easier refactoring of the code due to the named connections and not being order dependent.
module LabL3;
parameter SIZE = 64;
reg [SIZE-1:0] a;
reg [SIZE-1:0] b;
reg c;
wire [SIZE-1:0] z;
yMux #(
.SIZE(SIZE)
) mux (
.z(z),
.a(a),
.b(b),
.c(c)
);
yMux definiton:
module yMux #(
parameter SIZE= 0
) (
output [SIZE-1:0] z,
input [SIZE-1:0] a,
input [SIZE-1:0] b,
input c
);
// ...
endmodule
An example of the above code on EDAPlayground.

VHDL, using functions in for generate statement

VHDL, using functions in for generate statement
I have a component that should be instantiated about 8000 times, I used for-generate statement with the help of some constant values for reducing amount of code, but I had to declare a function for parametrization of component connections.
My function looks like this:
function dim1_calc (
cmp_index : integer;
prt_index : integer
) return integer is
variable updw : integer := 0;
variable shft_v : integer := 0;
variable result : integer := 0;
begin
if (cmp_index < max_up) then
updw := 1;
else
updw := 2;
end if;
case prt_index is
when 1 =>
shft_v := cnst_rom(updw)(1) + (i-1);
when 2 =>
shft_v := cnst_rom(updw)(2) + (i);
--
--
--
when 32 =>
shft_v := cnst_rom(updw)(32) + (i);
when others =>
shft_v := 0;
end case;
if (updw = 1) then
if (shft_v = min_up & ((prt_index mod 2) = 0)) then
result <= max_up;
elsif (shft_v = max_up & ((prt_index mod 2) = 1)) then
result <= min_up;
elsif (shft_v < max_up) then
result <= shft_v;
else
result <= shft_v - max_up;
end if;
else
--something like first condition statements...
--
--
end if;
return result;
end function;
and part of my code that uses this function plus some related part looks like this:
--these type definitions are in my package
type nx_bits_at is array (natural range <>) of std_logic_vector (bits-1 downto 0);
type mxn_bits_at is array (natural range <>) of nx_bits_at;
--
--
--
component pn_cmpn is
port(
clk : in std_logic;
bn_to_pn : in nx_bits_at(1 to row_wght);
pn_to_bn : out nx_bits_at(1 to row_wght)
);
end component;
--
--
--
signal v2c : mxn_bits_at(1 to bn_num)(1 to col_wght);
signal c2v : mxn_bits_at(1 to pn_num)(1 to row_wght);
--
--
--
gen_pn : for i in (1 to pn_num) generate
ins_pn : pn_cmpn port map (
clk => clk,
bn_to_pn(1) => b2p (dim1_calc(i, 1)) (dim2_calc(i, 1)),
bn_to_pn(2) => b2p (dim1_calc(i, 2)) (dim2_calc(i, 2)),
.
.
.
bn_to_pn(32) => b2p (dim1_calc(i, 32)) (dim2_calc(i, 32)),
pn_to_bn => p2b (i)
);
end generate;
I know that using too many sequential statements together is not appropriate in general, and I'm avoiding them as much as possible, but in this case I assumed that this function won't synthesize into some real hardware, and synthesizer just calculates the output value and will put it in corresponding instantiations of that component. Am I right? or this way of coding leads to extra hardware compared to just 8000 instantiations.
PS1: Initially I used "0 to..." for defining ranges of the 2nd and 3rd dimension of my arrays, but because of confusion that were made in dimension calculation function based on for-generate statement parameter, I replaced them with "1 to...". Is that an OK! coding style or should I avoid it?
PS2: Is there a way that port mapping part in above code combines into something like this:
(I know this is strongly wrong, it's just a clarification of what I want)
gen_pn : for i in (1 to pn_num) generate
ins_pn : pn_cmpn port map (
clk => clk,
gen_bn_to_pn : for j in (1 to 32) generate
bn_to_pn(j) => b2p (dim1_calc(i, j)) (dim2_calc(i, j)),
end generate;
pn_to_bn => p2b (i)
);
end generate;
Let me give another example
Assume that I have a component instantiation like this:
ins_test : test_comp port map (
clk => clk,
test_port(1) => test_sig(2)
test_port(2) => test_sig(3)
test_port(3) => test_sig(4)
);
Is there a way that I can use for generate here? something like:
ins_test : test_comp port map (
clk => clk,
gen_pn : for i in (1 to 3) generate
test_port(i) => test_sig(i+1)
end generate;
);
PS3: Is it possible to call a function inside another function in VHDL?
Functions are usable this way. If you encounter problems, I am sure they will regard details in the design or design tools, rather than the basic approach.
One potential issue is that the function refers to some external "things" such as max_up, i, cnst_rom whose declarations are not part of the function nor parameters to it. This makes it an "impure function" which - because it refers to external state or even modifies it - has restrictions on calling it (because the external state may change, results may depend on order of evaluation etc).
If you can make it pure, do so. I have a feeling that max_up, cnst_rom are constants : if they aren't used elsewhere, declare them local to the function. And i probably ought to be a parameter.
If this is not possible, make the external declarations constants, and preferably wrap them and the function together in a package.
This will just generate the values you need in a small, comprehensible, maintainable form, and not an infinite volume of hardware. I have used a complex nest of functions performing floating point arithmetic then fiddly range reduction and integer rounding to initialise a lookup table, so fundamentally the approach does work.
Potential pitfall:
Some design tools have trouble with perfectly valid VHDL, if its use is slightly unorthodox. Synplicity cannot synthesise some forms of function (which DO generate hardware) though has no trouble with the equivalent procedure returning the result through an OUT parameter!. XST is considerably better.
XST parsing my lookup table init has an absurd slowdown, quadratic in the number of function calls. But only if you are using the old VHDL parser (the default for Spartan-3). Spartan-6 uses the new parser and works fine ( under a second instead of half an hour!) as do Modelsim and Isim. (haven't tried Synplicity on that project)
Some tools object to unorthodox things in port maps : you may get away with function calls there; or you may have to workaround tool bugs by initialising constants with the calls, and using those constants in the port maps.
And your supplementary questions:
PS1) The correct coding style for an array range is ... whatever makes your intent clear.
If you find yourself mentally offsetting by 1 and getting confused or even making errors, STOP! and improve the design.
Some good array indexing styles:
type colour is (red, green, blue);
subtype brightness is natural range 0 to 255;
hue : array (colour) of brightness;
gamma : array (brightness) of brightness;
-- here 0 is a legitimate value
channel : array (1 to 99) of frequency;
PS2) I think you're asking if you can nest generate statements. Yes.
Details may be awkward and difficult, but yes.
PS3) Yes of course! You can even declare functions local to others; eliminating the possibility they will be accidentally called somewhere they make no sense. They (impure functions) can access the execution scope of the outer function (or process), simplifying parameter lists.
Q1 - in this case I assumed that this function won't synthesize into some ...
It depends on which synthesizer you're using. See this relevant question and comments below.
Q2 - PS1: Initially I used "0 to..." for defining ranges of the ...
Surely it's OK. And please allow we to post a suggestion on coding style here. (from this book)
When defining the loop parameter specification, either use a type (or subtype) definition, or use predefined object attributes (e.g., PredefinedObject'range, PredefinedObject'length - 1 downto 0). Avoid using discrete range (e.g., 1 to 4).
This rule makes the code more reusable and flexible for maintenance.
Q3 - PS2: Is there a way that port mapping part in above code combines into ...
I think this is why you asked the 4th question. So refer to the next answer:).
Q4 - Is it possible to call a function inside another function in VHDL?
Though I can't find some official reference to this, the answer is yes.
PS: Coding rules are defined by the synthesizer tools. So the best way to find an answer is to try it yourself.