Você está na página 1de 28

Hi Sai,

Following are the differences between shallow copy and deep copy.
Shallow Copy
* Shallow copy is also called address copy.
*A shallow copy of an object copies all the member field values.
* This work well if the fields are values but may not be what you want for fields that point to
dynamically allocated memory. The pointer will be copied, but the memory it points to will not be
copied. The field in both original object and the copy will then point to the same dynamically
allocated memory, which is not usually what you want.
*Shallow copy is the standard pointer assignment, It just copies the address of the pointer. It
doesnt allocate any memory or copy the contents being pointed to.

Deep copy
* A Deep copy duplicates the object or variable being pointed to so that the destination(The
object being assigned to) receives its own local copy.
*This way, the destination can do whatever it wants to its local copy and the object that was
copied from will not be affected.
*Doing deep copy requires our own copy constructor.
EXAMPLES:
Class members are values only
SHALLOW COPY
class Base;
int a =45,b =18;
endclass
program shallow_cp;
Base b1,b2;
initial begin
b1 =new();
b2 =new();
b2 =b1;

$display("Values after Copying");


$display("b1 Object Values =%p",b1);
$display("b2 Object Values =%p",b2);
b1.a =10;
b2.b =100; //b1 and b2 point to same memory location
$display("Values after Changing ");
$display("b1 Object Values =%p",b1);
$display("b2 Object Values =%p",b2);
end
endprogram
OUTPUT
Values after Copying
b1 Object Values ='{a:45, b:18}
b2 Object Values ='{a:45, b:18}
Values after Changing
b1 Object Values ='{a:10, b:100}
b2 Object Values ='{a:10, b:100}
DEEP COPY
class Base;
int a =45,b =18;
function copy(Base p1);
this.a = p1.a;
this.b =p1.b;
endfunction
endclass
program deep_cp;
Base b1,b2;
initial begin
b1 =new();
b2 =new();
b2.copy(b1); //b1 and b2 point to different memory location
$display("Values after Copying");
$display("b1 Object Values =%p",b1);

$display("b2 Object Values =%p",b2);


b1.a =10;
b2.b =100;
$display("Values after Changing ");
$display("b1 Object Values =%p",b1);
$display("b2 Object Values =%p",b2);
end
endprogram
OUTPUT
Values after Copying
b1 Object Values ='{a:45, b:18}
b2 Object Values ='{a:45, b:18}
Values after Changing
b1 Object Values ='{a:10, b:18}
b2 Object Values ='{a:45, b:100}

When Class contains Objects of other class.


Each class should have its own copy method.
class Mega;
int a =2,b =4;
endclass
class Giga;
Mega b1;
int d=8,e=16;
function new();
this.b1 =new();
//This class doesn't have its own copy constructor.
endfunction
function copy(Giga p1);
this.d = p1.d;
this.e =p1.e;
this.b1 =p1.b1;
endfunction

endclass
program deep_cp;
Giga p1,p2;
initial begin
p1 =new();
p2 =new();
p2.copy(p1);
$display("Values after Copying");
$display("p1 Object Values d=%0d e=%0d",p1.d,p1.e);
$display("p2 Object Values d=%0d e=%0d",p2.d,p2.e);
$display("Mega p1 a=%0d b=%0d",p1.b1.a,p1.b1.b);
$display("Mega p2 a=%0d b=%0d",p2.b1.a,p2.b1.b);
p1.d =100;
p2.e =1000;
p1.b1.a =200; //p1.b1 and p1.b1 point to same memory location but p1 and p2 points to different
memory location
p2.b1.b =400;
$display("Values after Changing ");
$display("p1 Object Values d=%0d e=%0d",p1.d,p1.e);
$display("p2 Object Values d=%0d e=%0d",p2.d,p2.e);
$display("Mega p1 a=%0d b=%0d",p1.b1.a,p1.b1.b);
$display("Mega p2 a=%0d b=%0d",p2.b1.a,p2.b1.b);
end
endprogram
OUTPUT
Values after Copying
p1 Object Values d=8 e=16
p2 Object Values d=8 e=16
Mega p1 a=2 b=4
Mega p2 a=2 b=4
Values after Changing
p1 Object Values d=100 e=16
p2 Object Values d=8 e=1000
Mega p1 a=200 b=400

Mega p2 a=200 b=400


Deep copy when class contains other class object.
class Mega;
int a =2,b =4;
function Mega copy();
copy = new();
this.a =copy.a;
this.b =copy.b;
endfunction
endclass
class Giga;
Mega b1;
int d=8,e=16;
function new();
this.b1 =new();
endfunction
function Giga copy();
copy = new();
this.d = copy.d;
this.e =copy.e;
this.b1 =b1.copy() ;
endfunction
endclass
program deep_cp;
Giga p1,p2;
initial begin
p1 =new();
p2 =new();
p2 = p1.copy();
$display("Values after Copying");
$display("p1 Object Values d=%0d e=%0d",p1.d,p1.e);

$display("p2 Object Values d=%0d e=%0d",p2.d,p2.e);


$display("Mega p1 a=%0d b=%0d",p1.b1.a,p1.b1.b);
$display("Mega p2 a=%0d b=%0d",p2.b1.a,p2.b1.b);
p1.d =100;
p2.e =1000;
p1.b1.a =200;
p2.b1.b =400;
$display("Values after Changing ");
$display("p1 Object Values d=%0d e=%0d",p1.d,p1.e);
$display("p2 Object Values d=%0d e=%0d",p2.d,p2.e);
$display("Mega p1 a=%0d b=%0d",p1.b1.a,p1.b1.b);
$display("Mega p2 a=%0d b=%0d",p2.b1.a,p2.b1.b);
end
endprogram
OUTPUT
Values after Copying
p1 Object Values d=8 e=16
p2 Object Values d=8 e=16
Mega p1 a=2 b=4
Mega p2 a=2 b=4
Values after Changing
p1 Object Values d=100 e=16
p2 Object Values d=8 e=1000
Mega p1 a=200 b=4
Mega p2 a=2 b=400
===============================================
Thanks,
Nithin

//--------------------------------------------------------------------------------------------------------------------------

1.The"Deepness"ofthecopyalwayshastobethoughtaboutintwodimensions:deepnessin
relationtoinheritanceanddeepnessinrelationtohandles(ieISAvsHASA).Thedeepnessin
onedimensionisentirelyorthogonaltodeepnessintheother.
2.Anexplanationintermsofpointersisn'talotofhelp,sinceSVuseshandlesnotpointers.
Handlesareeffectivelypointerswithautomaticgarbagecollection.
3.I'mnoexpertintheVMM,soIwillanswerintermsoftheAVM.
Considerthefollowingarrangement:
Code:
classA;
inta;
endclass
classB;
intb;
endclass
classCextendsA;
intc;
Bb;
endclass
Cc=new();
Aa=c;

Now,whatdoesitmeanto"copy"theobjectpointedtobythehandle"a"?
Itcouldmean:
(i)wecreateanewAwhichisONLYanA(ie,wedoacopywhichshallowinrelationtothe
inhertancehierarchy)
(ii)wecreateanewAwhichisALSOaC,butwedonotcopyB(ie,wedoacopywhichis
deepinrelationtotheinheritancehiearchybutshallowinrelationtoreferences)

(iii)wecreateanewAwhichisALSOaC,andwedocopyB(iewedoacopywhichisdeep
bothinrelationtotheinheritanceandthereferencetoB).
TheAVMhastwomethodswhichprovidesomekindofcopyingmechanism:copyandclone.
Bydefinition,copyisshallowinrelationtotheinheritancehierarchyanddoesnotassumethat
thetargetofthecopyhasbeenallocated.Incontrast,clone(whichusuallyusescopy)isdeepin
relationtotheinheritancehierarchyanddoesitsownallocation.
Bothcopyandcloneareundefinedinrelationtoreferences(andinfact,theymaywellbedeep
inrelationtosomereferencesandshallowinrelationtoothers).Inotherwords,thedesignerof
theclassneedstodecideforthemselveswhichreferencesshouldorshouldnotbecopied,andif
theyaregoingtobecopiedhowtheyshouldbecopied.
Code:
classAextendsavm_transaction;
inta;
functionvoidcopy(inputAt);
a=t.a;
endfunction
functionavm_transactionclone();
At=new();
t.copy(this);
returnt;
endclass
classBextendsavm_transaction;
intb;
functionvoidcopy(inputBt);
b=t.b;
endfunction
functionavm_transactionclone();
Bt=new();
t.copy(this);
returnt;
endfunction
endclass

classCextendsA;
intc;
Bb;
functionvoidcopy(inputCt);
super.copy(this);//copycontentsofA
c=t.c;//copycontentsofc
//pickoneof:
//b=t.b;//OPTIONALcopyofreferenceOR
//b=new();
//b.copy(t.b);//OPTIONALcopyof"ONLYB"OR
$cast(b,t.b.clone());//OPTIONALdeepcloneoft's"B"
endfunction
functionavm_transactionclone();
Ct=new();
t.copy(this);
returnt;
endfunction
endclass
Cc=new();
Aa=c;
Aa1=new();
Aa2;
a1.copy(a);//"ONLYA"don'tcarethataisactuallyaC
$cast(a2,a.clone());//a2isnow"really"aC

Inthecodeabove,a1isshallowinrelationtoinheritanceieitignoresthefactthataisactuallya
C.

a2isacloneofainotherwords,itisalsoaC.ItisuptothedesignerofCwhetherthismeans
thatBiscopiedbyreference,bycopy,orbyclone.
TheuncommentedcodeaboveactuallydoesacloneofBinsideCinotherwords,Cchoosesto
doacopywhichisdeepinrelationtoanyinheritancehierarchyof"b".Someotheralternatives
areinthecodebutcommentedout.
SomeonemorefamiliarwiththeVMMcancommentonhowthesevariouskindsofcopycanbe
achievedwiththeVMM.
Adam.

//
AndIwillanswerintermsoftheVMM.
Code:
classAextendsvmm_data;
inta;
virtualfunctionvmm_datacopy(vmm_datato=null);
Acpy;
if(to==null)cpy=new;
else$cast(cpy,to);
super.copy_data(cpy);
cpy.a=this.a;
returnt;
endclass

classBextendsvmm_data;
intb;
virtualfunctionvmm_datacopy(vmm_datato=null);
Bcpy;
if(to==null)cpy=new;
else$cast(cpy,to);
super.copy_data(cpy);
cpy.b=this.b;
returnt;
endfunction
endclass
classCextendsA;
intc;
Bb;
virtualfunctionvmm_datacopy(vmm_datato=null);
Ccpy;
if(to==null)cpy=new;
else$cast(cpy,to);
super.copy(this);//copycontentsofA
c=this.c;//copycontentsofc
//pickoneof:
//b=this.b;//OPTIONALcopyofreferenceOR
//b=newthis.b;//OPTIONALcopyof"ONLYB"OR
$cast(b,this.b.copy());//OPTIONALdeepcopyof"B"
endfunction
endclass
Cc=new();
Aa=c;
Aa1=newa;//"ONLYA"don'tcarethataisactuallyaC
Aa2;
$cast(a2,a.clone());//a2isnow"really"aC

VMMdoesnothaveashallowwrtinheritancecopy()methodbydefaultastheSystemVerilog
newoperatordoesthatnatively.

//======================================================================

DeepversusShallowCopy
Irecentlygotanemailaskingaboutcopyingobjectsanddecideditwouldbeagreatblogpost.

Specifically,thequestionaskedaboutthedifferencesbetweendeepversusshallowcopyand
whenoneshouldchooseonetechniqueversusanother.
Theshortansweristhereisnorightanswer.Thelonganswer,well,isalittlelonger
InanyObjectbasedsystem,copyinganobjectisnotatrivialexercise.Aswetalkedaboutinthe
OOPConnectionschapter,yourverificationsystemisameshofobjects.Copyingapieceofthat
meshistricky.Butevenbeyondthatistheseeminglysimpletaskofcopyingdata.
SupposeyouaretryingtoverifyaSOCthatmovesdatatoandfromsomeinterfaces(RAM,
ethernet,PCI,etc).Youprobablyhavetheclassicgeneratorconnectedtodriverandchecker
throughachannelmodel.
Beforeyouhavetoconsidershallowversusdeepcopy,youhavetodecideifyouwanttocopy
thedata.Ingeneral,youdowanttocopythedata,butthereisatleastonecasewhereyoudonot.
Thisisthecasewherethedriverandthecheckerneedtocommunicatesomeinformationabout
thedatatransactioninthechannel.Perhapsitsareadcompletion,orawritestatusword.
Letsassumeourexampleshouldcopythedata.So,whatthenisdeepcopy?Adeepcopyisa
recursivereplicationofthemembersintheclass/struct.Forexample,ifourdatabetweenthe
generatoranddriver/checkerwasalistofblocksoflowerlevelrandomdatatobesent,boththe
listandtheblockswouldbecopied.
Ashallowcopy,bycontrast,wouldonlycopythelist.Ashallowcopydoesnotrecursebeyond
thetoplevelobject(theonebeingcopied).Inourexample,therewouldonlybeoneinstance
oftheblocksoflowerleveldata.
Ifyourdataonlyconsistsofintegraltypes,thereisnodifferencebetweendeepandshallow
copy.Iftherearepointersinyourclass/structthenyouneedtothinkaboutwhatyouwantto
happen.
Now,ifyoudatahasANYvirtualfunctions(i.e.notjustaclumpofdata),thenyoureallyneed
tothink.Mygeneralruleisthatyouareprobablydoingsomethingwrong.Gobackandrethink
whyyourdesignneedsbothvirtualdatamembersandneedstocopy.
Ifyoureallydoneedtocopyaclass/structwithvirtualmethods,yougenerallyendupwithatwo
methodscheme.Onemethodmakes/newstherighttypeofobject(becausethisisavirtual
method)andthesecondmethodcopiesthedata.Prettydarnhorrible.

Mygeneraladviceistousepointersformostthingsinachannel.Thenyoudonothavetoworry
aboutcopying.Butifyoudohavetocopy,makesureyouthinkaboutallthemembers,dataand
methods.

//===================================================================

SystemVeriloghastwosimilardatatypesthatallowvariablestobegroupedtogetherina
handypackage:thestructandtheclass.Ivehearditoftensaid,whenexplainingwhataclass(an
objectorienteddatatype)is,thatitisjustlikeaCstructwithfunctions.Iusedtohaveno
problemwiththat,until,whenreviewinganddebuggingtestbenchcode,Istartedseeingsome
problemsrelatedtothewayclasseshavetobetreateddifferentlytostructs.Oneofthemost
commonerrorsIvefoundiswhendatastructurescomposedofclassesarecopied.
Considerthefollowing:
class FooDataClass;
integer D1;
integer D2;
endclass
struct {
integer D1;
integer D2;
} FooDataStruct;
program test;
FooDataClass X[] =
FooDataClass Y[];
FooDataStruct A[] =
FooDataStruct B[];
...
Y = X; // copy array
B = A; // copy array
...
endprogram

new[5]; //
//
new[5]; //
//

array
array
array
array

of
of
of
of

classes
classes
structs
structs

of classes
of structs

Inthecaseofthestruct,itspossibletocopythedynamicarrayA[]toB[],sizingBtothesame
asAautomatically.Itsequivalentto:
B = new[A.size()];
foreach(A[i]) begin
B[i].D1 = A[i].D1; // copy value of A[i].D1 to B[i].D1
B[i].D2 = A[i].D2; // copy value of A[i].D2 to B[i].D2
end

Importantly,B[]hasitsveryowncopyofthevaluesofvariablesD1andD2foreachelementin
thearray.So,ifA[2].D1wasmodified,B[2].D1wouldnotbe.
Inthecaseoftheclass,whenwecopythedynamicarrayX[]toY[],Yisstillsizedtothesame
asXautomatically,butsomethingsubtlydifferenthappens(thatoftencatchespeopleout),with

D1andD2.Whenarraysofclassesarecopied,thereferences(akahandles)totheclassare
copied,notthevaluesoftheclassmembersthemselves.Itsequivalentto:
Y = new[X.size()];
foreach(X[i]) begin
Y[i] = X[i]; // copy reference to class X[i] into Y[i]
end

ThismeansthatY[]doesnothaveitsowncopyofthevaluesofvariablesD1andD2foreach
elementinthearray.IfX[2].D1wasmodifiedY[2].D1wouldalsobemodified.Infacttheyare
thesamevariable,pointedtobythereferenceY[2],whichisequaltoX[2].Thats,mostoften
times,notthedesiredbehaviorofthecode.Codingerrorslikethiscanbetrickytotrackdown
andmaystayhiddenforsometime.
Onceyouvecreatedaclass,peoplemightstartusingitallovertheplace.People,whomightnot
haveaccesstomodifyyourclasscode,onlyuseit.Thishasanimpactontheabovementioned
differencebetweenclassesandstructs.Ifyouwanttoenablepeopletomakecopiesofthedata
values,asopposedtojustthereferences,thenyou(asthedeveloperoftheclass),shouldprovide
amechanismtodeepcopytheclass.SowithFooDataClasswemightdo:
function void FooDataClass::copy(FooDataClass c);
this.D1 = c.D1;
this.D2 = c.D2;
endfunction

Herewecopythevaluesofanotherclassofthesametypeintoourclass.Itisnowpossibleto
makeY[]haveitsveryowncopyofthevaluesofvariablesD1andD2foreachelementinthe
array.So,ifX[2].D1wasmodified,Y[2].D1wouldnotbe.However,westillhavetodo
somethingdifferentforclassesthanwedoforstructs.Somethinglike:
// copy of values of values in X[] to Y[]
foreach(X[i]) begin
Y[i] = new;
// create new instance of the class
Y[i].copy(X[i]); // copies *values* in class from X to Y
end

So,whenyouarereviewingcode,itsalwaysprudenttolookforplaceswhereclassesorthings
containingclassesareexplicitlyorimplicitlycopied.
ThisentrywaspostedbyJasonSprottonSunday,January20,2008at4:24amandisfiledunderNews,
SystemVerilog.YoucanfollowanyresponsestothisentrythroughtheRSS2.0feed.Bothcommentsandpingsare
currentlyclosed.

2 Responses to SystemVerilog Gotcha: (when copying) a struct is not a class by


another name
1. Daniel Prsch Says:

January 22nd, 2008 at 7:37 am

HiVerilab,
justashortnote,youdefineA,BasclassesandX,Yasstructsinthecode,butreferto
A,BasstructsandX,Yasclassesinthetext.Thisisconfusing,Iguessthetextis
correct?!
WhatwouldhappenifIdidnthavearraysofclasses/structsbutasingleclassanda
singlestruct,Iguessthesamerulewouldapply,i.e.copybyreferenceforclassesand
copybyvalueforstructs?
TheresnoCopyConstructorinSV,isthere?Wouldbehandy
Rgds,
Daniel
2. Jason Sprott Says:

January 23rd, 2008 at 2:28 am

HiDaniel
Thanksforpointingoutthaterror(nowcorrected).Ifixedthevariablenamesandalso
addedthenew()oftheelementsinY[],insidetheforeachloop,forclarity.
Yes,whenastructiscopiedthevaluesarecopied.Whenaclassiscopiedthereferenceis
copied,orashallowcopyistaken(asdescribedinIEEE18002005,Section7.11).Ifind
peopletypicallyrememberthatwhentheyaredealingwiththeclassitself.Whenclasses
areinsidesomethingelse,itseasytoforget,becausewearecopyingthethingandmay
notevenhavevisibilityofitscontents.Arraysofclassesfallintothatcategory,buta
classcomposedofotherclassesisanotherbigonetowatch.
Thereisnomethodforadeepcopy/clonedefinedintheSystemVeriloglanguage.Both
theAVMandVMMdefinemethodsforcopyingobjectsaspartofthemethodology.In
Verawehadabuiltinmethodcalledobject_copy()aspartofthelanguage.This
providedadeepcopyofanyobject,withoutyouhavingtowriteanythingyourself.I

foundituseful,buttheproblemwasthattherewasnocontrol,soyoucouldendup
copyingsomething*very*large.
Ofcoursewhenwritingcustomcopyfunctionswesometimesputbugsinthemtoo.
Jason

//====================================================================
SystemVerilog Interview Questions
1. How many array types in SystemVerilog? How do you use them?
array_name[ ] dynamic array
e.g . dyna_arr_1 = new[100] (dyna_arr_1);
dyna_arr_2 = new[4]('{4,5,6}); // elements are {4,5,6,0}
array [5] fixed array
e.g. register1 [6][7:0] = `1;
array[$] queue
e.g. int q[$] = { 2, 4, 8 };
q = {};
// clear the queue (delete all items)
e = q[0];
// read the first (leftmost) item
e = q[$];
// read the last (rightmost) item
array[string] or array[%] associate array
e.g. //associative array of 4-state integers indexed by strings, default is '1.
integer tab [string] = '{"Peter":20, "Paul":22, "Mary":23, default:-1 };
2) What is the Polymorphism?

Polymorphism allows an entity to take a variety of representations. Polymorphism means the


ability to request that the same Operations be performed by a wide range of different types of
things. Effectively, this means that you can ask many different objects to perform the same
action. Override polymorphism is an override of existing code. Subclasses of existing classes
are given a "replacement method" for methods in the superclass. Superclass objects may also
use the replacement methods when dealing with objects of the subtype. The replacement
method that a subclass provides has exactly the same signature as the original method in the
superclass.
EXAMPLE: with virtual
class A ;
virtual task disp ();
$display(" This is class A ");
endtask
endclass
class EA extends A ;
task disp ();
$display(" This is Extended class A ");
endtask
endclass
program main ;
EA my_ea;
A my_a;
initial
begin
my_a = new();
my_a.disp();
my_ea = new();
my_a = my_ea;
my_a.disp();
end
endprogram
RESULTS
This is class A
This is Extended class A

3) how the copy works?

Answers:
There are 2 types of copy. Show copy or deep copy

For example:

class B;
int
endclass

program main;
initial
begin
B b1;
B b2;
b1 = new();
b1.i = 123;
b2 = b1;
copied.
$display( b2.i );
end
endprogram
RESULTS:

// b1 and b2 point to the same memory. The properties did not get

123

A shallow copy of an object copies all of the member field values.


program main;
initial
begin
B b1;
B b2;
b1 = new();

b1.i = 123;
b2 = new b1; // shallow copy of b1
b2.i = 321;
$display( b1.i );
$display( b2.i );
end
endprogram
RESULTS:
123
321
If the value of b1 change, it will also change the value of b1. It's because it's pointing to the
same memory.

To avoid this, we need to use the deep copy.

Deep Copy
A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by
the fields. To make a deep copy, you must write a copy constructor and overload the
assignment operator, otherwise the copy will point to the original, with disasterous
consequences.

EXAMPLE:
class A;
int i;
endclass
class B;
A a;
task copy(A a);
this.a = new a;
endtask
endclass

program main;
initial
begin
B b1;
B b2;
b1 = new();
b1.a = new();
b1.a.i = 123;
b2 = new b1;
b2.copy(b1.a);
$display( b1.a.i );
$display( b2.a.i );
b1.a.i = 321;
$display( b1.a.i );
$display( b2.a.i );
end
endprogram
RESULTS:
123
123
321
123

//=========================================================

Hieveryone,
pleaselookatthefollowingcode.
classobj_change;
inti;
endclass
classdsp;
taskdisplay(obj_changeoj);
#2$display("&&&&&&&&&&&&&&&&obj.i=%d",oj.i);
endtask
endclass
moduleobj_change_mod;
obj_changeobj;
dspdsp_obj;
initial
begin
dsp_obj=new;

obj=new;
obj.i=10;
$display("$$$$$$$$$obj.i=%d",obj.i);
fork
dsp_obj.display(obj);
join_none
#1obj.i=40;
$display("*********obj.i=%d",obj.i);
end
endmodule
OBSERVEDOUTPUTS:
$$$$$$$$$obj.i=10
*********obj.i=40
&&&&&&&&&&&&&&&&obj.i=40
whyIamgettingtheseoutputs?Shallowcopyfromactualargument(obj)toformalargument(oj)
isnotoccurring.
Ithinkthiscomesunder"PASSbyVALUE"functioncallingtype.

//=======================================================================
====
The UVM clone method is used to provide a deep copy of an object. We can call clone() on any
object, and it will use the clone() method of its actual class, without the calling code needing to
know what that class is.
Clone first allocates new memory for the object, then copies over each field to the new object. If
a field is an object handle, then instead of copying the handle (which would do a "Shallow"
copy) you would call fieldname.clone() to recursively allocate memory for that field (a "Deep"
copy).

[B]clone[/B]() means construct followed by a call to [B]copy[/B](). [B]clone[/B]() is virtual so that


you can construct the same object type as the one you started with. [B]clone[/B]() calls
[B]copy[/B]() to perform a deep copy of the object type you just created. The [B]copy[/B]()
method by itself just copies class member values from one object to another. Normally, the
copy() method only copies the class members for the current class type, then it calls
super.copy() to copy the class members of the base class.

Interview Questions
1. What's difference between static and automatic task/program?
If you use static task for multiple places in your testbench, the local variables will share
the common, static storage. In this case, different threads will step on each other's
values.By using atuotmic storage, it will make a copy of local variables and use them.
Not a common static storage any more.
e.g. program automatic initialization;
......
endprogram
2. What's the packed array and unpacked array?
unpacked array is an array with gap between variables.

e.g. bit[7:0] b_unpack[3]; // unpacked


Te system verilog simulators store each element on a 32-bit word boundary. In other
words, you are using only lower 8 bits, the other 24 bits per word space is wasted.
Packed array is an array without gap. Unpacked array is good for local individual
variable access.
e.g. bit[3:0] [7:0] bytes; // 4 bytes packed into 32 bits
In this case, all 32 bits word are packed with 4 bytes. A packed array is handy if you
need to convert to and from scalars.
3. What's different between logic and wire?
Logic and wire are almost the same except wire can be driven by multiple sources. Logic
can only driven by single source.
4. How the copying of objects works?
There are two types of copy 1)Shallow Copy 2) Deep Copy
typedef enum {READ,WRITE}rw_t;
class ID;
string id;
endclass
class packet;
ID id;
rand bit [7:0]data;
rand bit [7:0]address;
rw_t rw;
function new();
id=new;
data=0;
address=0;
rw=READ;
endfunction:new
function packet deep_copy;
deep_copy=new;
deep_copy.data=this.data;
deep_copy.address=this.address;
deep_copy.rw=this.rw;
deep_copy.id.id=this.id.id;
endfunction
function void print (string str);

$display("*************************%s**************************",str);
$display("data:%d -> address:%d-->rw:%s-->id:%s",this.data,this.address,this.rw,this.id.id);
endfunction
endclass:packet
program prg;
packet p1,p2;
initial begin
p1=new;
p1.data=10; p1.rw=WRITE; p1.id.id="P1";
//shallow copy will copy class variables and handles(pointers) in the class
p2=new p1;
p2.print("p2");
p2.data=30; p2.rw=READ;p2.id.id="P2";
p2.print("p2");
p1.print("p1");
//Deep Copy:all variable and variable in the object also copied not handle
p3=p1.deep_copy();
end
endprogram:pr

Why we do Gate level simulation ?

With wide acceptance of STA and Formal verification tools by the industry one question still
arises in the minds of many, "Why do we need gate level simulation?"
The common reasons quoted by many engineers are simple..
1. To check if reset release, initialization sequence and boot-up is proper.
2. Since Scan insertions occur during and after synthesis, they are not checked by
simulations.
3. STA does not analyze asynchronous interfaces.
4. Unwarranted usage of wild cards in static timing constraints set false and multi cycle
paths where they dont belong. This can also be due to design changes, misunderstanding or typos.
5. Usage of create_clock instead of using create_generated_clock between clock domains.

6. For switching factor to estimate power.


7. X's in RTL sim can be pessimistic or optimistic. Any unintended dependencies on initial
conditions can be found through GLS.
8. Design changes, wrong understanding of the design can lead to incorrect false paths or
multicycle paths in the constraints.
9. Can be used to study the activity factor for power estimation.
10. It's an excellent feel good quotient that the design has been implemented correctly.

SomedesignteamsuseGLSonlyinazerodelay,idealclockmodetocheckthatthedesigncan
comeoutofresetcleanlyorthattheteststructureshavebeeninsertedproperly.Otherteamsdo
fullybackannotatedsimulationasawaytocheckthatthestatictimingconstraintshavebeenset
upcorrectly.
Inallcases,gettingagatelevelsimulationupandrunningisgenerallyaccompaniedbyaseries
of challenges so frustrating that they precipitate a shower of adjectives as caustic as those
typicallydirectedatyourmostunreliableinternetserviceprovider.Therearemanysourcesof
troubleingatelevelsimulation.Thisserieswilllookatexamplesofproblemsthatcancome
fromyourlibraryvendor,problemsthatcomefromthedesign,andproblemsthatcancomefrom
synthesis.Itwillalsolookatsomeoftheadditionalchallengesthatarisewhenrunninggatelevel
simulationwithbackannotatedSDF.

Você também pode gostar