I have to implement randomize() function in systemVerilog because the tool I use (model sim) doesn't support this function.
I implemented a basic function in a class with the following member:
bit [15:0] data_xi;
bit [15:0] data_xq;
the basic random function:
//function my_randomize
function int my_randomize(int seed);
int temp1, temp2;
temp1 = (($urandom(seed)) + 1);
data_xi = temp1 - 1;
temp2 = (($urandom(seed)) + 1);
data_xq = temp2 - 1;
if(temp1 != 0 || temp2 != 0 )
return 1;
else
return 0;
endfunction: my_randomize
Now I have to change it to static function which suppose to behave like randomize() with constraints.
How can I implement this?
1) To make your function like constraints, you can have inputs to your function to set the range or a modulo.
//function my_randomize
function int my_randomize(int seed, int temp1_min, int temp1_max, int temp2_min, int temp2_max, int temp3_min, int temp3_max);
int temp1, temp2, temp3;
temp1 = $urandom_range(temp1_min, temp1_max);
temp2 = (($urandom(seed)) % (temp2_max+1));
data_xi = temp2 - 1;
temp3 = ((($urandom($urandom(seed))) % temp3_max+1) + temp3_min;
data_xq = temp3 - 1;
if(temp1 != 0 || temp2 != 0 )
return 1;
else
return 0;
endfunction: my_randomize
Ofcourse you can decide how to implement the randomization for temp1, temp2 and temp3. These are some ideas.
2) If you want all classes to access this function, create a base class with the randomize functionality, and then derive all your classes from it. Although you won't have access to the derived class variables in this case, just base-class variables. You can always make this a virtual function to override in your derived class.
3) Note that using the same seed for $urandom/$urandom_range in the same thread will create the same random number.
Related
can any way to add new column to the end of this matrix(population) with size 10 row and 5 column
that containe integers number of 1 and 0 to calculate weigth of each row of this matrix and put it in this column /
i write this code as a smart contract in solidity language
// SPDX-License-Identifier: GPL-3.0
//pragma experimental ABIEncoderV2;
pragma solidity ^0.4.26;
contract Genetic{
uint[5][10] population ;
function expand(uint256 randomValue) public view returns (uint256[] memory expandedValues) {
expandedValues = new uint256[](50);
for (uint256 i = 0; i < 50; i++) {
expandedValues[i] = uint256(keccak256(abi.encode(randomValue, i)))%2;
}
return expandedValues;
}
function getPopulation () public view returns( uint [5][10] ){
uint[] memory chromosom = new uint[](50);
uint r;
chromosom =expand(r);
for(uint i =0; i < 10; i++){
for(uint j =0 ;j< 5; j++){
population [i][j] = chromosom[(i*5) + j];
}
}
return population;
}
}
I am trying to implement a doubly linked list in c++, but I get an error when I try to implement an insert() function. This is the struct of the Node:
struct NodoLDL
{
T dato;
NodoLDL *anterior;
NodoLDL *siguiente;
NodoLDL(const T &elem, NodoLDL *ant = nullptr, NodoLDL *sig = nullptr):
dato(elem),
anterior(ant),
siguiente(sig)
{}
};
And this is the list class:
template <typename T>
class LDL
{
private:
#include "nodoldl.h"
size_t listSize;
NodoLDL *listFront; //head
NodoLDL *listBack; //tail
public:
LDL() : listSize(0), listFront(nullptr), listBack(nullptr)
{}
void insert(size_t position, const T &elem);
(. . .)
}
This is the insert() function I am using, but I get segmentation fault on "temp2->anterior = temp3"
template<typename T>
void LDL<T>::insert(size_t position, const T &elem)
{
if(empty()){
listFront = new NodoLDL(elem);
listBack = listFront;
listSize+=1;
}else if(listSize>0 && position==0){ //push_front()
//The implementation for push_front() works fine.
}else if(position==listSize){ //push_back()
//The implementation for push_back() also works fine.
}else if(position > 0 && position<listSize){
NodoLDL *temp1, *temp2, *temp3;
temp1 = listFront;
for(size_t i=0; i<position; i++){
temp1 = temp1->siguiente;
}
temp2 = temp1->siguiente;
temp3 = new NodoLDL (elem);
temp1 -> siguiente = temp3;
temp3 -> anterior = temp1;
temp3 -> siguiente = temp2;
temp2 -> anterior = temp3;
listSize+=1;
}else if(position > listSize){
throw invalid_argument("insert() on invalid position");
}
}
Insert at the beginning and at the end works, but it doesn't if I insert in the middle of the list, how can I fix it? Why is that logic wrong?
I am not sure if it is only that line or all the logic in else if(position>0 && position<listSize) is incorrect.
Okay, so first and foremost you have to check if you only have one element on the list. In that case you cannot do:
temp2 = temp1->siguiente;
temp3 = new NodoLDL (elem);
temp1 -> siguiente = temp3;
temp3 -> anterior = temp1;
temp3 -> siguiente = temp2;
temp2 -> anterior = temp3;
If you do such thing temp1->siguiente would be a null pointer, and as such, temp2 will also be a null pointer. Your segmentation fault will occur when you call temp2->anterior. Since you will be accesing to a field where there is nothing.
I will encourage you to try and always separate this kind of procedure in different functions. One for push-back and one for push-front to call either in the first if.
template<typename T>
void LDL<T>::insert(size_t position, const T &elem) {
if (position > listSize) { //I tend to always check this things first
throw invalid_argument("insert() on invalid position");
}
if (empty() || position == 0) {
push_front(elem);
return;
}
if (position == listSize){ //push_back()
push_back(elem)
return;
}
NodoLDL *temp1, *temp2, *temp3;
temp1 = listFront;
for(size_t i=0; i<position; i++){
temp1 = temp1->siguiente;
}
temp2 = temp1->siguiente;
temp3 = new NodoLDL (elem);
temp1 -> siguiente = temp3;
temp3 -> anterior = temp1;
temp3 -> siguiente = temp2;
temp2 -> anterior = temp3;
listSize++;
}
In theory your insert should work in any case, but I understand if you're just starting to learn and see the solution better this way. Linus Torvalds has a nice TedTalk where he talks about writting beautiful code and I think the example he choses for that class is a list insert.
I got this error in C++. I am trying to implement Strassen matrix multiplication with multi_array. I assign one array to another which they same dimension.
Like that A11[i][j][k] = A[i][j][k]. I think reason is that kind of lines.
Assertion failed: (size_type(idx - index_bases[0]) < extents[0]),
function access, file
/usr/local/Cellar/boost/1.65.1/include/boost/multi_array/base.hpp,
line 136. Abort trap: 6
Do you know the reason? What does this error mean?
typedef boost::multi_array<int_type, 3> array_type;
array_type::extent_gen extents;
array_type A(boost::extents[size][size][noc]);
array_type B(boost::extents[size][size][noc]);
array_type C(boost::extents[size][size][noc]);
std::fill( A.origin(), A.origin() + A.num_elements(), 0 );
std::fill( B.origin(), B.origin() + B.num_elements(), 0 );
std::fill( C.origin(), C.origin() + C.num_elements(), 0 );
array_type Strr(int size,int noc,array_type A,array_type B, array_type C) {
if(size == 2) { //2-order
C=Matrix_Multiply(size,noc, A, B, C);
} else {
//
for(int i=0; i<size/2; i++) {
for(int j=0; j<size/2; j++) {
for(int k=0; k<noc; j++) {
A11[i][j][k] = A[i][j][k] ;
A12[i][j][k] = A[i][j+size/2][k] ;
}
}
}
My code is like that: I do not know what the problem is.
Error:Assertion failed: (size_type(idx - index_bases[0]) < extents[0]), function access, file /usr/local/Cellar/boost/1.65.1/include/boost/multi_array/base.hpp, line 136.
In the inner most loop you have:
for (int k = 0; k < noc; j++) {
You must have meant ++k instead of ++j:
for (int k = 0; k < noc; ++k) {
I'd simplify main too:
int dim[] = {size,size,noc};
array_type A(dim), B(dim), C(dim);
Value-initialization is done by default.
The idea of multi_array is that the arrays self-describe, instead of you passing separate parameters (size and noc e.g.):
array_type Strr(array_type A, array_type B) {
static_assert(array_type::dimensionality == 3, "static invariant");
size_t size = A.shape()[0];
size_t noc = A.shape()[2];
assert(A.shape()[0] == A.shape()[1]);
assert(std::equal_range(A.shape(), A.shape()+3, B.shape()));
assert(std::equal_range(A.shape(), A.shape()+3, C.shape()));
I was investigating the delay_ms function of avr-gcc. In delay.h I found its definition:
void _delay_ms(double __ms)
{
double __tmp ;
#if __HAS_DELAY_CYCLES && defined(__OPTIMIZE__) && \
!defined(__DELAY_BACKWARD_COMPATIBLE__) && \
__STDC_HOSTED__
uint32_t __ticks_dc;
extern void __builtin_avr_delay_cycles(unsigned long);
__tmp = ((F_CPU) / 1e3) * __ms;
#if defined(__DELAY_ROUND_DOWN__)
__ticks_dc = (uint32_t)fabs(__tmp);
#elif defined(__DELAY_ROUND_CLOSEST__)
__ticks_dc = (uint32_t)(fabs(__tmp)+0.5);
#else
//round up by default
__ticks_dc = (uint32_t)(ceil(fabs(__tmp)));
#endif
__builtin_avr_delay_cycles(__ticks_dc);
#else
...
}
I am interested in how the __builtin_avr_delay_cycles function looks like internally and where it is defined? Where can I find the source?
As said in my comment to this very question on electronics.SE:
Compiler builtins are kinda funky to find, always, because they are not just C functions, but things that get inserted while parsing/compiling the code (at various levels of abstraction from the textual representation of the code itself. compiler theory stuff). What you're looking for is the function avr_expand_builtin in the GCC source tree. There's a case AVR_BUILTIN_DELAY_CYCLES in there. Look for what happens there.
Which is:
/* Implement `TARGET_EXPAND_BUILTIN'. */
/* Expand an expression EXP that calls a built-in function,
with result going to TARGET if that's convenient
(and in mode MODE if that's convenient).
SUBTARGET may be used as the target for computing one of EXP's operands.
IGNORE is nonzero if the value is to be ignored. */
static rtx
avr_expand_builtin (tree exp, rtx target,
rtx subtarget ATTRIBUTE_UNUSED,
machine_mode mode ATTRIBUTE_UNUSED,
int ignore)
{
tree fndecl = TREE_OPERAND (CALL_EXPR_FN (exp), 0);
const char *bname = IDENTIFIER_POINTER (DECL_NAME (fndecl));
unsigned int id = DECL_FUNCTION_CODE (fndecl);
const struct avr_builtin_description *d = &avr_bdesc[id];
tree arg0;
rtx op0;
gcc_assert (id < AVR_BUILTIN_COUNT);
switch (id)
{
case AVR_BUILTIN_NOP:
emit_insn (gen_nopv (GEN_INT (1)));
return 0;
case AVR_BUILTIN_DELAY_CYCLES:
{
arg0 = CALL_EXPR_ARG (exp, 0);
op0 = expand_expr (arg0, NULL_RTX, VOIDmode, EXPAND_NORMAL);
if (!CONST_INT_P (op0))
error ("%s expects a compile time integer constant", bname);
else
avr_expand_delay_cycles (op0);
return NULL_RTX;
}
…
thus, the function you're looking for is avr_expand_delay_cycles in the same file:
static void
avr_expand_delay_cycles (rtx operands0)
{
unsigned HOST_WIDE_INT cycles = UINTVAL (operands0) & GET_MODE_MASK (SImode);
unsigned HOST_WIDE_INT cycles_used;
unsigned HOST_WIDE_INT loop_count;
if (IN_RANGE (cycles, 83886082, 0xFFFFFFFF))
{
loop_count = ((cycles - 9) / 6) + 1;
cycles_used = ((loop_count - 1) * 6) + 9;
emit_insn (gen_delay_cycles_4 (gen_int_mode (loop_count, SImode),
avr_mem_clobber()));
cycles -= cycles_used;
}
if (IN_RANGE (cycles, 262145, 83886081))
{
loop_count = ((cycles - 7) / 5) + 1;
if (loop_count > 0xFFFFFF)
loop_count = 0xFFFFFF;
cycles_used = ((loop_count - 1) * 5) + 7;
emit_insn (gen_delay_cycles_3 (gen_int_mode (loop_count, SImode),
avr_mem_clobber()));
cycles -= cycles_used;
}
if (IN_RANGE (cycles, 768, 262144))
{
loop_count = ((cycles - 5) / 4) + 1;
if (loop_count > 0xFFFF)
loop_count = 0xFFFF;
cycles_used = ((loop_count - 1) * 4) + 5;
emit_insn (gen_delay_cycles_2 (gen_int_mode (loop_count, HImode),
avr_mem_clobber()));
cycles -= cycles_used;
}
if (IN_RANGE (cycles, 6, 767))
{
loop_count = cycles / 3;
if (loop_count > 255)
loop_count = 255;
cycles_used = loop_count * 3;
emit_insn (gen_delay_cycles_1 (gen_int_mode (loop_count, QImode),
avr_mem_clobber()));
cycles -= cycles_used;
}
while (cycles >= 2)
{
emit_insn (gen_nopv (GEN_INT (2)));
cycles -= 2;
}
if (cycles == 1)
{
emit_insn (gen_nopv (GEN_INT (1)));
cycles--;
}
}
Of biggest interest here is that this modifies a node in the Abstract Syntax Tree, and emits instructions there.
I'd like to know if it's possible to do some kind of forward conditioned slicing with Frama-C and I'm playing with some examples to understand how one could achieve this.
I've got this simple example which seems to result in an imprecise slice and I can't understand why. Here is the function I'd like to slice :
int f(int a){
int x;
if(a == 0)
x = 0;
else if(a != 0)
x = 1;
return x;
}
If I use this specification :
/*# requires a == 0;
# ensures \old(a) == a;
# ensures \result == 0;
*/
then Frama-C returns the following slice (which is precise), using "f -slice-return" criterion and f as entry point :
/*# ensures \result ≡ 0; */
int f(void){
int x;
x = 0;
return x;
}
But when using this specification :
/*# requires a != 0;
# ensures \old(a) == a;
# ensures \result == 1;
*/
then all instructions (& annotations) remain (when I was waiting for this slice to be returned :
/*# ensures \result ≡ 1; */
int f(void){
int x;
x = 1;
return x;
}
)
In the last case, is the slice imprecise? In this case, what could be the cause?
Regards,
Romain
Edit : I wrote "else if(a != 0) ..." but the problem remains with "else ..."
In Frama-C, the slicing plug-in relies on the result of a preliminary static analysis plug-in called the value analysis.
This value analysis can represent the values for variable a when a == 0 (the set of values is in this case { 0 }) but has a hard time to represent the values for a when it is known that a != 0. In the latter case, if a is not already known to be positive or negative, the value analysis plug-in needs to approximate the set of values for a. If a was known to be positive, for instance if it was an unsigned int, then the nonzero values could be represented as an interval, but the value analysis plug-in cannot represent “all values of type int except 0”.
If you are willing to change the pre-condition, you can write it in a form that is more easily understood by the value analysis plug-in (together with value analysis option -slevel):
$ cat t.c
/*# requires a < 0 || a > 0 ;
# ensures \old(a) == a;
# ensures \result == 0;
*/
int f(int a){
int x;
if(a == 0)
x = 0;
else if(a != 0)
x = 1;
return x;
}
$ frama-c -slevel 10 t.c -main f -slice-return f -then-on 'Slicing export' -print
…
/* Generated by Frama-C */
/*# ensures \result ≡ 0; */
int f(void)
{
int x;
x = 1;
return x;
}
This has no relevance whatsoever with your main question, but your ensures a == \old(a) clause is not doing what you expect. If you pretty-print your source code with option -print, you will see it has been silently transformed into ensures \old(a) == \old(a).
The ACSL language does not permit referring about the value of formal variables in the post-state, mostly because this is meaningless from the point of view of the caller. (The stack frame of the callee is popped after the call terminates.)