首页 Signed Arithmetic in Verilog 2001

Signed Arithmetic in Verilog 2001

举报
开通vip

Signed Arithmetic in Verilog 2001SignedArithmeticinVerilog2001–OpportunitiesandHazardsDr.GregTumbush,StarkeyLabs,ColoradoSprings,COIntroductionStarkeyLabsisinthebusinessofdesigningandmanufacturinghearingaids.ThenewdigitalhearingsaidswedesignattheStarkeyLabsColoradoICDesignCenterutilizev...

Signed Arithmetic in Verilog 2001
SignedArithmeticinVerilog2001–OpportunitiesandHazardsDr.GregTumbush,StarkeyLabs,ColoradoSprings,COIntroductionStarkeyLabsisinthebusinessofdesigningandmanufacturinghearingaids.ThenewdigitalhearingsaidswedesignattheStarkeyLabsColoradoICDesignCenterutilizeverycomplexDSPalgorithmsimplementedinbothsoftwareandhardwareaccelerators.Thepredominantdatatypeusedinthesealgorithmsissigned.Theformatofthesignedtypeistwo’scomplement.Thedesignationofsignedandtwo’scomplementisusedinterchangeablythroughoutthisdocument.Verilog2001providesaveryrichsetofnewsigneddatatypes.However,thereareissueswhenperformingoperationssuchassignextension,truncationorrounding,saturation,addition,andmultiplicationwithsignedvalues.Thesenewdatatypes(intheory)freethedesignerfromworryingaboutsomeofthesesigneddatatypeissues.Morecompactandreadablecodeshouldresult.However,inthespiritofVerilog,usageofthisnewfunctionalityis“userbeware”!Arithmeticmanipulationbetweenmixesofsignedandunsignedmaysimulateandsynthesizeinunintendedways.Assignmentsbetweendifferentlysizedtypesmayalsonotresultinwhatthedesignerintended.Doestheusageofsigneddatatypesinarithmeticoperationsresultinsmallerorlargercircuits?Verilog1995providesonlyonesigneddatatype,integer.Theruleisthatifanyoperandinanexpressionisunsignedtheoperationisconsideredtobeunsigned.TherulestillappliesforVerilog2001butnowallregs,wires,andportscanbesigned.Inaddition,anumericvaluecanbedesignatedwitha‘ssimilartothe‘hhexdesignation.Signedfunctionsarealsosupportedaswellasthetypecastingoperators$signedand$unsigned.Therearemanynewrulesaboutwhenanoperationisunsigned,andsomemaysurpriseyou!InthispaperIwillprovidecodeexamplesofhowthenewsigneddatatypescanbeusedtocreatemorecompactcodeifsomesimplerulesarefollowed.RTLandgatelevelsimulationresultsofaddandmultiplyoperationsusingmixturesofsignedandunsigneddatatypeswillbeprovided.ArearesultsfromsynthesisusingDesignCompiler2003.12willbepresentedtocompareefficienciesoftheseoperations.Synthesiswarningsthatshouldbeinvestigatedthoroughlywillbeexplained.SuggestionsforimprovementintheVerilog2001language,suchassaturationsupport,willalsobeprovided.SignedDataTypesTable1demonstratestheconversionofadecimalvaluetoasigned3-bitvaluein2’scomplementformat.A3-bitsignedvaluewouldbedeclaredusingVerilog2001assigned[2:0]A;.DecimalValueSignedRepresentation33’b01123’b01013’b00103’b000-13’b111-23’b110-33’b101-43’b100Table1:Decimalto3-bitSignedTypeCastingThecastingoperators,$unsignedand$signed,onlyhaveeffectwhencastingasmallerbitwidthtoalargerbit.Castingusing$unsigned(signal_name)willzerofilltheinput.ForexampleA=$unsigned(B)willzerofillBandassignittoA.Castingusing$signed(signal_name)willsignextendtheinput.Forexample,A=$signed(B).IfthesignbitisXorZthevaluewillbesignextendedusingXorZ,respectively.AssigningtoasmallerbitwidthsignalwillsimplytruncatethenecessaryMSB’sasusual.Castingtothesamebitwidthwillhavenoeffectotherthantoremovesynthesiswarnings.SignedBasedValuesTheonlywaytodeclareasignedvalueinVerilog1995wastodeclareitasanintegerwhichlimitedthesizeofthevalueto32-bitsonly[1].Verilog2001providesthe‘sconstructfordeclaringandspecifyingasizedvalueassigned.Forexample,2representedasa3-bitsignedhexvaluewouldbespecifiedas3’sh2.Somewhatconfusingisspecifyingnegativesignedvalues.Thevalue-4representedasa3-bitsignedhexvaluewouldbespecifiedas-3’sh4.Adecimalnumberisalwayssigned.SignedAdditionAddingtwovaluesthataren-bitswidewillproducean+1bitwideresult.Thesignedvaluesmustbesignextended.Forexample,adding-2(3’b110)to3(3’b011)willresultin1(4’b0001).SeetheexampleinFigure1.4'b1110=-2+4'b0011=3signextend5'b10001=1discardoverflowFigure1:BasicSignedAdditionExampleTodothisadditionusingVerilog-1995constructswecouldusethecodeinCodeExample1.moduleadd_signed_1995(input[2:0]A,input[2:0]B,output[3:0]Sum);assignSum={A[2],A}+{B[2],B};endmodule//add_signed_1995CodeExample1:Addition-Verilog1995OrwecanusethenewsignedtypeandgetthecodeinCodeExample2.moduleadd_signed_2001(inputsigned[2:0]A,inputsigned[2:0]B,outputsigned[3:0]Sum);assignSum=A+B;endmodule//add_signed_2001CodeExample2:Addition-Verilog2001Bothaddersareexactlythesamesize.Soyouwillgetthesameresultswithouthavingtoworryaboutmanuallydoingthesignextension.Problemscreepupwhenmixingsignedandunsigned.Consideraddingtwo3-bitvalueswitha1-bitcarryin.SeeCodeExample3foravalidsolutionusingVerilog1995moduleadd_carry_signed_1995(input[2:0]A,input[2:0]B,inputcarry_in,output[3:0]Sum);assignSum={A[2],A}+{B[2],B}+carry_in;endmodule//add_carry_signed_1995CodeExample3:AddwithCarry-Verilog1995IntuitivelywewouldcreateCodeExample4tousesignedtypes.However,whensynthesizedthefollowingwarningoccurs:signedtounsignedconversionoccurs.(VER-318)Inadditionthereisafunctionalerror.Duetothecarry_inbeingunsignedtheoperationisunsignedandneithertheAnorBoperandissignextendedproperlyasinFigure1.moduleadd_carry_signed_2001(inputsigned[2:0]A,inputsigned[2:0]B,inputcarry_in,outputsigned[3:0]Sum);assignSum=A+B+carry_in;endmodule//add_carry_signed_2001CodeExample4:AdditionwithCarry–IncorrectWecanavoidthesynthesiswarningbyusingassignSum=A+B+$signed(carry_in).Butthiscreatesadifferentfunctionalerror.Whathappensifcarry_in=1?Inthiscasethe$signedoperatorsignextendsthecarry_insoitnowequals4’b1111andwewouldhavebeensubtracting1insteadofadding1.AsimilarfunctionalerroroccursifweuseCodeExample4butdeclarecarry_intobeasignedinput.SeeCodeExample5foravalidsolution.Usingthiscodeweavoidthesynthesiswarningandsignextendcarry_incorrectlywith0’s.moduleadd_carry_signed_final(inputsigned[2:0]A,inputsigned[2:0]B,inputcarry_in,outputsigned[3:0]Sum);assignSum=A+B+$signed({1'b0,carry_in});endmodule//add_carry_signed_finalCodeExample5:AddwithCarry-CorrectThecodeinCodeExample1andCodeExample2simulatethesamewithbothRTLandgatelevelverilog.Theyarealsothesamesize.ThecodeinCodeExample3andCodeExample5simulatethesameusingbothRTLandsynthesizedgatelevelverilog.Theyarealsothesamesize.CodeExample4issmallerinareabutfunctionallyincorrect.SignedMultiplicationMultiplyingtwovaluesthataren-bitswidewillproducea2nbitwideresult.Forexample,multiplying-3(3’b101)by2(3’b010)shouldresultin-6(6’b111010).Themultiplier(secondfactor)isexaminedbitbybitrighttoleft(leastsignificanttomostsignificantbit)todetermineifthemultiplicand(firstfactor)istobeaddedtothepartialresult.Ifso,themultiplicandisalignedsothattheleastsignificantbitisunderthecorrectmultiplierbitposition.Ifthemultiplicandisnegativeitmustbesignextended.However,iftheMSBofthemultiplieris1,themultiplicandisactuallysubtracted.Recallthatsubtractionisthesameasinvertandincrement.SeetheexampleinFigure2.3'b101=-3x3'b010=2signextend6'b111010=-60000001110100000003'b010=2x3'b101=-30000100000001110006'b111010=-6Invert2,add1,signextendmultiplicandmultiplierFigure2:SignedMultiplyExamplesUsingVerilog-1995constructsthecoderequiredtomultiplytwo3-bitsignedvaluesisinCodeExample6.modulemult_signed_1995(input[2:0]a,input[2:0]b,output[5:0]prod);wire[5:0]prod_intermediate0;wire[5:0]prod_intermediate1;wire[5:0]prod_intermediate2;wire[2:0]inv_add1;assignprod_intermediate0=b[0]?{{3{a[2]}},a}:6'b0;assignprod_intermediate1=b[1]?{{2{a[2]}},a,1'b0}:6'b0;//Dotheinvertandadd1ofa.assigninv_add1=~a+1'b1;assignprod_intermediate2=b[2]?{{1{inv_add1[2]}},inv_add1,2'b0}:6'b0;assignprod=prod_intermediate0+prod_intermediate1+prod_intermediate2;endmoduleCodeExample6:SignedMultiply-Verilog1995OrwecanusethenewsignedtypeandwritethecodeinCodeExample7.modulemult_signed_2001(inputsigned[2:0]a,inputsigned[2:0]b,outputsigned[5:0]prod);assignprod=a*b;endmoduleCodeExample7:SignedMultiply-Verilog2001Now,letsmultiplyasignedvaluebyanunsignedvalue.UsingVerilog1995constructsthecodeinCodeExample8results.Nowifwemultiply–3(3’b101)by2(3’b010)asusualwithCodeExample8weget–6(6’b111010).Whenusingamultiplierwithoneoperandunsignedbesureoftherangeofinputtotheunsignedoperand.Ifwetriedtomultiply2(3’b010)by–3(3’b101)wewouldget0xAbecause–3isactually5unsigned.Notethatbecausethemultiplicandisunsignedthiscodeismorecompactandresultsinasmallersizemultiplier.modulemult_signed_unsigned_1995(input[2:0]a,input[2:0]b,output[5:0]prod);wire[5:0]prod_intermediate0;wire[5:0]prod_intermediate1;wire[5:0]prod_intermediate2;assignprod_intermediate0=b[0]?{{3{a[2]}},a}:6'b0;assignprod_intermediate1=b[1]?{{2{a[2]}},a,1'b0}:6'b0;assignprod_intermediate2=b[2]?{{1{a[2]}},a,2'b0}:6'b0;assignprod=prod_intermediate0+prod_intermediate1+prod_intermediate2;endmoduleCodeExample8:SignedbyUnsignedMultiply-Verilog1995AftermigratingtoVerilog2001wemightbetemptedtouseCodeExample9.However,recalltherulethatifanyoperandofanoperationisunsignedtheentireoperationisunsigned.Whensynthesizedthefollowingwarningoccurs:signedtounsignedconversionoccurs.(VER-318).Nowifwemultiply–3(3’b101)by2(3’b010)asusualwiththiscodeweget0xA(6’b001010).Thereasonforthisisthatsincewemixedsignedwithunsignedweactuallymultiplied5by2andgot0xAsincetheoperationisconsideredunsigned.modulemult_signed_unsigned_2001(inputsigned[2:0]a,input[2:0]b,outputsigned[5:0]prod);assignprod=a*b;endmoduleCodeExample9:SignedbyUnsignedMultiply-IncorrectHowabouttryingCodeExample10?Thisworksformultiplying-2x3=-6butwhataboutiftheMSBofourunsignednumber=1?Inthiscasethemultiplierissignextendedwhichisalsoincorrect.Fortheoperation-2x7wewouldgetactuallyget2whilethecorrectansweris0x-E(6’b110010).modulemult_signed_unsigned_2001(inputsigned[2:0]a,input[2:0]b,outputsigned[5:0]prod);assignprod=a*$signed(b);endmoduleCodeExample10:SignedbyUnsignedMultiply-StillIncorrectThecorrectanswertothisproblemfollowsfromCodeExample5.Usingthiscodeweavoidthesynthesiswarningandsignextendbcorrectlywith0’s.ThecorrectcodeisinCodeExample11.modulemult_signed_unsigned_2001(inputsigned[2:0]a,input[2:0]b,outputsigned[5:0]prod);assignprod=a*$signed({1'b0,b});endmoduleCodeExample11:SignedbyUnsignedMultiply-CorrectCodeExample7synthesizestoabout18%smallerthanCodeExample6.Ibelievethatthisisbecausesynthesisfoundabetterimplementation.Thereisnoreasonwhywecannotreplicatethissizebymorecarefulhandcoding.TheRTLandgatelevelimplementationsimulatethesame.CodeExample11synthesizestoabout6%smallerthanthecodeinCodeExample8.Onceagain,Ibelievethatthisisbecausesynthesisfoundabetterimplementation.Thereisnoreasonwhywecannotreplicatethissizebymorecarefulhandcoding.TheRTLandgatelevelimplementationsimulatethesame.ThecodeinCodeExample9andCodeExample10aresmallerinareabutarefunctionallyincorrect.Whatisanexpression?TheVerilog-2001LRMstatesthattoevaluateanexpression“Coercethetypeofeachoperandoftheexpression(exceptingthosewhichareself-determined)tothetypeoftheexpression”[2].Thequestioniswhatisanexpression?ConsiderCodeExample12whichisdirectlyfromaSynopsys’sSolvNetarticle002590[3].Therearetwowaystolookatthiscode.Itcouldbeconsideredastwoexpressions,asignedmultiplyandthenanunsignedaddition.Itcanalsobeconsideredasoneexpression,anunsignedmultiplyfollowedbyanunsignedaddition.Resultswilldifferineachcase.modulemult_add(inputsigned[3:0]in1,in2,input[3:0]in3,output[7:0]o1;);assigno1=in1*in2+in3;endmoduleCodeExample12:MultiplyandAddItwasreportedthatolderversionsofDesignCompilerconsideredthiscodeastwoexpressionswhilesomesimulatorsatthetimeconsidereditasone.NewerversionofDesignCompilerandModelSimconsiderthiscodeasoneexpression,alleviatingaveryworrisomesimulation/synthesismismatch.ThisissueisslatedtobeclarifiedintheupcomingVerilog2005LRM.RulesforExpressionTypesLocatedintheVerilog2001LRMbutworthrepeatingherearetherulesfordeterminingtheresultingtypeofanexpression.Thefollowingoperationsareunsignedregardlessoftheoperands.1.Bit-selectresults2.Part-selectresults,eveniftheentirevectorisselected.3.Concatenationresults4.ComparisonresultsSignedShiftingShiftingofsignedvaluescreatesanotherproblemforVerilog1995.Considerasignednegativevaluethatisrightshifted.Thepositionsvacatedbytherightshiftwillbefilledinwithzeroswhichisincorrect.Instead,thesignbitshouldbeusedforvacatedbits.Anewoperator>>>isintroducedinVerilog2001toaccomplishexactlythis.Asignedleftshiftoperator(<<<)isalsoprovidedforlanguageconsistency[1].SignedSaturationInthissectionwepresentaconceptthatiswidelyusedinDSPmathbutisnoteasilyaccomplishedinVerilog.Whilesignextensionisusedwhenassigningasmallerbit-widthvariabletoalargerbit-widthvariable,theoppositeisaccomplishedusingsaturation.Thepossibleoutcomesofsaturationaremaxpositiveindicatingpositiveoverflow,maxnegativeindicatingnegativeunderflow,andsimplydroppingtheappropriatenumberofbitsstartingattheMSB.Saturationisaccomplishedbyexaminingthenumberofbitstosaturateplus1startingattheMSB.Ifallofthesebitsarethesamedropthenumberofbitstosaturate.IfthesebitsaredifferentexaminetheMSB.IftheMSBis0gotomaxpositive,elsegotomaxnegative.AmodulesattoaccomplishthisisinCodeExample13.UsageofthismoduleisinCodeExample14.modulesat(sat_in,sat_out);parameterIN_SIZE=21;//Defaultistosaturate22bitsto21bitsparameterOUT_SIZE=20;input[IN_SIZE:0]sat_in;outputreg[OUT_SIZE:0]sat_out;wire[OUT_SIZE:0]max_pos={1'b0,{OUT_SIZE{1'b1}}};wire[OUT_SIZE:0]max_neg={1'b1,{OUT_SIZE{1'b0}}};always@*begin//Arethebitstobesaturated+1thesame?if((sat_in[IN_SIZE:OUT_SIZE]=={IN_SIZE-OUT_SIZE+1{1'b0}})||(sat_in[IN_SIZE:OUT_SIZE]=={IN_SIZE-OUT_SIZE+1{1'b1}}))sat_out=sat_in[OUT_SIZE:0];elseif(sat_in[IN_SIZE])//negunderflow.gotomaxnegsat_out=max_neg;else//posoverflow,gotomaxpossat_out=max_pos;endendmoduleCodeExample13:SaturationModulewiresigned[4:0]A,B,C;regsigned[2:0]D,E,F;A=5'sb11101;B=5'sb01001;C=5'sb10001;//DroptwoMSB’s.Dwillequal3'sb101sat#(.IN_SIZE(4),.OUT_SIZE(2))satA(.sat_in(A),.sat_out(D));//Gotomaxpositive.Ewillequal3'sb011sat#(.IN_SIZE(4),.OUT_SIZE(2))satB(.sat_in(B),.sat_out(E));//Gotomaxnegative.Fwillequal3'sb100sat#(.IN_SIZE(4),.OUT_SIZE(2))satC(.sat_in(C),.sat_out(F));CodeExample14:UseofSaturationModuleSummaryThispaperstrovetogivetheuserastrongbackgroundontheuseofsignedtypesusingtheVerilog2001language.Theproperuseoftypecasting,addition,multiplication,shifting,andtruncationwaspresented.Inaddition,anexampleofasignedsaturationmodulealongwithexamplesofit’susewereincluded.ProperuseofthenewsignedcapabilityinVerilog2001canbesummarizedbyafewbasicrules.1.Ifanyoperandinanoperationisunsignedtheentireoperationisunsigned[2].2.Investigatefullyallsignedtounsignedconversionoccurs.(VER-318)synthesiswarnings.Thesepointtoincorrectfunctionality3.Allsignedoperandswillbesignedextendedtomatchthesizeofthelargestsignedoperand.4.Typecastingusing$unsignedwillmaketheoperationunsigned.Theoperandwillbesignextendedwith0’sifnecessary.5.Typecastingusing$signedmaketheoperandsigned.Theoperandwillbesignextendedwith1’sifnecessary.Padtheoperandwithasingle0beforethecastifthisisnotdesired.6.Expressiontypedependsonlyontheoperandsoroperation,itdoesnotdependoftheLHSoftheexpression.References1.S.Sutherland.Verilog2001AGuidetotheNewFeaturesoftheVerilogHardwareDescriptionLanguage.KluwerAcademicPublishers2.IEEEP1364-2005/D3.DraftStandardforVerilog®HardwareDescriptionLanguage.3.SynopsysInc,SynopsysSolvnet,solvnet.synopsys.com
本文档为【Signed Arithmetic in Verilog 2001】,请使用软件OFFICE或WPS软件打开。作品中的文字与图均可以修改和编辑, 图片更改请在作品中右键图片并更换,文字修改请直接点击文字进行修改,也可以新增和删除文档中的内容。
该文档来自用户分享,如有侵权行为请发邮件ishare@vip.sina.com联系网站客服,我们会及时删除。
[版权声明] 本站所有资料为用户分享产生,若发现您的权利被侵害,请联系客服邮件isharekefu@iask.cn,我们尽快处理。
本作品所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用。
网站提供的党政主题相关内容(国旗、国徽、党徽..)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。
下载需要: 免费 已有0 人下载
最新资料
资料动态
专题动态
is_136249
暂无简介~
格式:pdf
大小:157KB
软件:PDF阅读器
页数:5
分类:互联网
上传时间:2013-08-22
浏览量:15