版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
Chapter10Code
Optimization
Asweimagined,thetargetcodemadebycompilershouldrunfasterortakelessspace,orboth..Infact,thisgoalisdifficulttobeachievedoronlycanbereachedinlimitedcases.Inordertoobtainthegoal,weusecodeimprovingtransformationswhichiscalledoptimizing.Ofcourse,codeoptimizationcanonlyguaranteethepossibilitythatthecodeisbest..
2Therearetwotypesofcodeoptimization,thefirstoneismachine-independentoptimizationswhichmeanstheoptimizationhasnorelationshipwithpropertiesofthetargetmachine,optimizationsofthistypeisonthelevelofintermediatecodeorsourceprogram.Thesecondoneistheoptimizationwhichisrelatedwithtargetmachine,namely,theoptimizationisbasedontheleveloftargetcode.Thepositionofcodeoptimizationincompilerisshownbelow..
3
4Asweallknow,acompilerisaprogramthatreadsthesourceprograminahigh-levellanguageandtranslatesitinto(typically)machinelanguage.Thisisacomplicatedprocessinvolvinganumberofstages.Ifthecompilerisanoptimizingcompiler,oneofthesestages"optimizes"themachinelanguagecodesothatiteithertakeslesstimetorunoroccupieslessmemoryorsometimesboth..5Ofcourse,whateveroptimizationsthecompilerdoes,itmustnotaffectthelogicoftheprogrami.e.theoptimizationmustpreservethemeaningoftheprogram.Onemightwonderwhattypeofoptimizationsthecompilerusestoproduceefficientmachinecode?Sinceinnocasethemeaningoftheprogrambeingcompiledshouldbechanged,thecompilermustinspecttheprogramverythoroughlyandfindoutthesuitableoptimizationsthatcanbeapplied..610.1Classificationsofoptimizations
Optimizationsthatareperformedautomaticallybyacompilerormanuallybytheprogrammer,canbeclassifiedbyvariouscharacteristicsThescopeoftheoptimization:(1)Localoptimizations-Performedinapartofoneprocedure.1)Commonsub-expressionelimination.
72)Usingregistersfortemporaryresults,andifpossibleforvariables.3)Replacingmultiplicationanddivisionbyshiftandaddoperations.(2)Globaloptimizations-Performedwiththehelpofdataflowanalysis.1)Codemotion(hoisting)outsideofloops.2)Constantpropagation.3)Strengthreductions.8Theimprovementinoptimization:(1)Spaceoptimizations-Reducesthesizeoftheexecutable/object.1)Constantfolding.2)Dead-codeelimination.3)RedundantCodeElimination.4)UnreachableCodeElimination.
9(2)Speedoptimizations-MostoptimizationsbelongtothiscategoryThecodetypesofoptimization:(1)Sourceprogramoptimization.(2)Threeaddresscodeoptimization.(3)Quadruplescodeoptimization.(4)
targetcodeoptimizations.1010.2SourceprogramoptimizationsSourceprogramoptimizationisthatoptimizationsworkregardlessofprocessororcompilerandtheobjectissourceprogram..1.Eliminatingcommonsub-expressionsRegisteroperationsaremuchfasterthanmemoryoperations,soallcompilerstrytoputinregistersdatathatissupposedtobeheavilyused,liketemporaryvariablesandarrayindexes.11Tofacilitatesuchregisterscheduling,thelargestsub-expressionsmaybecomputedbeforethesmallerones.Thisisanoldoptimizationtrickthatcompilersareabletoperformquitewell:.Example1:X=A*LOG(Y)+(LOG(Y)**2)
t=LOG(Y)X=A*t+(t**2)Optimize12Example2:
/*Sumneighborsofi,j*/up=val[(i-1)*n+j];down=val[(i+1)*n+j];left=val[i*n+j-1];right=val[i*n+j+1];sum=up+down+left+right;intinj=i*n+j;up=val[inj-n];down=val[inj+n];left=val[inj-1];right=val[inj+1];sum=up+down+left+right;Optimize132.RedundantCodeEliminationi:=m-1j:=nt:=4*nv:=a[t]s:=m-1u:=a[s]i:=i+1i:=m-1j:=nt:=4*nv:=a[t]u:=a[i]i:=i+1Optimize143.UnreachableCodeElimination
Acommonexampleofunreachablecodeeliminationisanifstatement.Ifthecompilerfindsoutthattheconditioninsidetheifisnevergoingtobetrue,thenthebodyoftheifstatementwillneverbeexecuted.Inthatcase,thecompilercancompletelyeliminatethisunreachablecode,thussavingthememoryspaceoccupiedbythecode..15i:=m-1if(j>0)gotoL1j:=nt:=4*nv:=a[t]L1:v:=a[i]i:=i+1……..i:=m-1v:=a[i]i:=i+1……..
Optimize164.DeadCodeEliminationDeadcodeisthecodeintheprogramthatwillneverbeexecutedforanyinputorotherconditions.Thedeadcodeexampleisanconstantthatithasneverbeenused,itisshownbelow.i:=m-1j:=nt:=4*nv:=a[t]i:=v+1……..i:=m-1j:=nt:=4*nv:=a[t]i:=v+1……..Optimize175.StrengthReductionToreplaceanequivalentbutcheaper(shorter)sequence.Onetypeofcodeoptimizationisstrengthreductioninwhicha"costly"operationisreplacedbyalessexpensiveone.Forexample,theevaluationofx2ismuchmoreefficientifwemultiplyxbyxratherthancalltheexponentiationroutine.Oneplacewherethisoptimizationcanbeappliedisinloops.18Replacecostlyoperationwithsimplerone.Shift,addinsteadofmultiplyordivide16*xx<<4Utilityofthisoptimizationismachinedependent.Dependsoncostofmultiplyordivideinstruction,shiftoraddisusuallyasinglecycleoperation.Recognizesequenceofproductsturnthemintoasequenceofadds.19Example1
i:=m-1j:=ii:=i+ii:=j+i……..i:=m-1j:=ii:=3*i……..Optimize20Example2
r1:=r2*2r1:=r2+r2r1:=r2<<1r1:=r2/2r1:=r2>>1r1:=0Optimizer1:=r2*0OptimizeOptimizeOptimize216.Constantfolding:Constantfoldingisthesimplestcodeoptimizationtounderstand.Letussupposethatyouwritethestatementx=45*88;inyourCprogram.Anon-optimizingcompilerwillgeneratecodetomultiply45by88andstorethevalueinx.Anoptimizingcompilerwilldetectthatboth45and88areconstants,sotheirproductwillalsobeaconstant.Henceitwillfind45*88=3960andgeneratecodethatsimplycopies3960intox.Thisisconstantfolding,andmeansthecalculationisdonejustonceatcompiletime,ratherthaneverytimetheprogramisrun.22r2:=3*2r2:=6OptimizeEliminationofredundantloadsandstores.
r2:=6i:=r2r3:=ir4:=r3*3r2:=6i:=r2r4:=r2*3Optimize23Constantpropagation:r2:=4r3:=r1+r2r2:=….r2:=4r3:=r1+4r2:=….r3:=r1+4r2:=….OptimizeOptimizer1:=3r2:=r1*2r1:=3r2:=3*2r1:=3r2:=6OptimizeOptimize24Copypropagation:Eliminationofuselessinstructionsr1:=r1+0r1:=r1*1r2:=r1r3:=r1+r2r2:=5r2:=r1r3:=r1+r1r2:=5r3:=r1+r1r2:=5OptimizeOptimize257.Loopoptimizations
Averyimportantpartforoptimizationisloops.Ifwemakethenumberofinstructionsinaloopdecreased,therunningtimeofaprogramwillbeimproved,thoughsometimes,itmaybecausethenumberofcodeoutsidetheloopincreased..26Therearethreewaysforloopoptimization:codemotion,induction-variableeliminationandreductioninstrength.Codemotionistomovecodeoutsidealoop;induction-variableeliminationmeanstoeliminateextravariablefromaloop;reductioninstrengthcanreplaceacomplicatedoperationbyasimpleone.Reducefrequencywithwhichcomputationperformed,ifitwillalwaysproducesameresult,somovingcodeoutofloop..
27Example1Example2
J=2*4While(i<=j)
While(i<=2*4)……OptimizeOptimizefor(i=0;i<n;i++)for(j=0;j<n;j++)a[n*i+j]=b[j];for(i=0;i<n;i++){intni=n*i;for(j=0;j<n;j++)a[ni+j]=b[j];}28Example3Movingasmuchaspossiblecomputationsoutsideloops,savescomputingtime.Inthefollowingexample(2.0*PI)isaninvariantexpressionthatthereisnoreasontorecomputeit100times..
DOI=1,100ARRAY(I)=2.0*PI*IENDDOt=2.0*PIDOI=1,100ARRAY(I)=t*IENDDOOptimize29Sowecanconcludethatthetransformationofloopoptimizationis(1)Takeanexpressiontransformationtogetthesameresultwiththetransformationbeforeandtoobtainindependentofthetimenumber.(2)Placetheexpressionbeforetheloop.3010.3Optimizationsofthree-
addresscode
Actually,thereareseveralblocksinoneprogram,namely,blockmeansapartofprogramwithoneentranceandoneexit,furthermore,blockrunningisinsequence.Forexample,figure10.2aisablock,ontheotherhandfigure10.2bisnotablock,becausetherearetwoexitsinit,soitisonlyapartofprogram..3132Combiningtheresultsoftwoexpressionsthattheyshouldbeinoneblock.Theprocedureofcombiningisfirstlytocalculatetheresultofconstantsinoneexpressionandthenusethenewresulttoreplaceallthecalculationwhichisrelatedwiththeconstants.Sothestepofcombiningindetailisasfollows..
33Step1recognizeconstantexpression.Step2replaceconstantexpressionbytheresultofconstantscomputingStep3generatetargetcodeaccordingtothecombineresults.34Example10.1
35Becausethevalueof“a”isknownatcompiling,wecancomputetheknownvaluesandreplacethembytheirresulttoobtaintheoptimizedthreeaddresscode..Beforecombiningconstant,weshouldfirstcreateasymboltable“Tab”whichhastwofields,fieldNstoresvariablename,fieldVdepositsthevariablevalue.Theformatofthreeaddresscodeisshownbelow,thefirstpartisoperatorω;secondoneisoperand1,wenameitP1;thethirdpartisoperand2,wecallitP2..36operatoroperand1operand2
ω
P1
P2
Wecombineconstantsfromtopofthreeaddresscodetotheendofthreeaddresscodeinblock,thepointerofthreeaddresscodeis“i”.37Thealgorithmofcombiningconstantsis:1Ifoperatordoesnotequalto“:=”:P1orP2isthevariablenameinsymboltable“Tab”,wecanusethevalueVofP1orP2toreplaceP1orP2inthreeaddresscode.Ifoperatorequalsto“:=”.(1)P1isvariablein“Tab”,wecanreplaceP1inthreeaddresscodebyitsvalueVin“Tab”..38(2)P1isconstant,wecanfindP2in“Tab”,ifP2isin“Tab”,wereplacevalueofP2byvalueofP1,ifP2isnotin“Tab”,store(P2,P1)to“Tab”,add1topointeriof“Tab”..(3)P1isnotconstantandthereisP2in“Tab”,deleteP2anditsvaluefrom“Tab”..392.IfbothP1andP2areconstant,wecancombinethem,namely,replace(ω,P1,P2)by(α,P1ωP2,0),formatofP1inthreeaddresscodeequalsP1ωP2here,formatP2inthreeaddresscodeequals0,αpresentstheresultofP1ωP2..3.IfP1orP2isthenumberofthreeaddresscode,andtheoperatorinthreeaddresscodebelongstothisnumberequaltoα,thenweuseP1inthreeaddresscodewhichbelongstothisnumberreplaceP1orP2inpresentthreeaddresscode.404.Ifiistheendnumberofthreeaddresscode,thenexit;ontheotherhand,ifiisnottheendnumberofthreeaddresscode,theni:=i+1,andreturntostep1.5.Thethreeaddresscodeswhichtheiroperatordoesnotequaltoαareoptimizedthreeaddresscodes.41WecanoptimizeExample10.1bytheoptimizationalgorithmabove.(1)(:=,10,a)(2)(+,a,20)(3)(:=,(2),b)(4)(/,b,a)(5)(:=,(4),c)(1)(:=,10,a)(2)(α,30,0)
(3)(:=,30,b)(4)(α=,3,0)(5)(:=,3,c)(1)(a,10)(2)(a,10)(3)(a,10)(b,30)(4)(a,10)(b,30)(5)(a,10)(b,30)(c,3)threeaddresscode
optimizing
symboltableofit42Theoptimizedthreeaddresscodeis(1)(:=,10,a)(3)(:=,30,b)(5)(:=,3,c)4310.4Optimizationsofquadruples
Actually,deadcodeeliminationisdoneinablock.Weshalltakeablockofquadruplesforexampletointroducewhichinstructionisextracodeandshouldbeeliminated..
44Example10.2
a:=b*c+a;d:=b*c+a;c:=b*c+a(1)(*,b,c,T1)(2)(+,T1,a,T2)(3)(:=,T2,,a)(4)(*,b,c,T3)(5)(+,T3,a,T4)(6)(:=,T4,,d)(7)(*,b,c,T5)(8)(+,T5,a,T6)(9)(:=,T6,,c)
Ablockfouraddresscodeoftheblock45Fromthecodeabove,weknowthatinstruction4and7aresamewithinstruction1,inaddition,theyhavethesameresults.Instruction8doesthesamewithcalculationofinstruction5.Inordertooptimizethecode,instruction4,7and8shouldnotbecomputed,becausetheycanbereplacedbyothers..Howtojudgetheextrainstructionsautomatically?Wecanusethedependingalgorithmtorecognizeit.46Dependingalgorithm
(1)Atfirst,wedefinethatdependingnumberforeveryinstructionis0,namely,dep(X)=0.(2)Iftheformatoffouraddresscodeis(ω,A,B,Ti),thendep(Ti)=max(dep(A),dep(B))+1(3)Ifvariable“a”isendowedvaluebyinstructioni,thatis(:=,b,,a),thendep(a)=i(4)Iftwoinstructioniandj(i<j)havethesameformatlike(ω,P1,P2,),andtheirdependingnumberissameaswell,wecanjudgethatinstructionjisextraandwouldnotbecomputedanymore,theinstructioncanbechanged
(Same,Ti,Tj,0)47especially,ifωisaoperatorwhichpositionofoperandscanbeexchanged,wecansay(ω,P1,P2,)havesameformatwith(ω,P2,P1,).
Withthehelpofdependingalgorithm,theoptimizedcodeofexample10.2isshownbytable10.1..484910.5Optimizationsoftargetcode
Theaimofoptimizedcodeistogenerateitstargetcode,sothissection,wewilltakeexpressionforexampletoexplainhowtooptimizetargetcode.Example10.3
Anexpression:a*b+c/d+a*(a*b+c/d)-a*(c/d+b*a)/dThetargetcodeoftheexpressionis:50CLAa/*push“a”tostack*/MULb/*“a”fromstackmultiple“b”,andthenpushthecomputingresulttostack*/STOT1/*storetheresultofstacktoT1*/CLAc/*push“c”tostack*/DIVd/*value“c”fromstackdividedby“d”,andthenpushthecomputingresulttostack*/ADDT1/*valuefromstackaddT1,andthenpushthecomputingresulttostack*/STOT1CLAaMULbSTOT2/*storetheresultofstacktoT2*/CLAcDIVdADDT2MULa/*valuefromstackmultiple“a”,andthenpushthecomputingresulttostack*/ADDT1STOT1CLAcDIVdSTOT2CLAbMULaADDT2/*valuefromstackaddT2,andthenpushthecomputingresulttostack*/MULaDIVd/*valuefromstackdividedby“d”,andthenpushthecomputingresulttostack*/RUBT1/*T1minusthevaluefromstack,andthenpushthe
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2026重庆垫江县砚台镇人民政府招聘政法社工1人备考题库附完整答案详解(全优)
- JJF(京) 154-2024 便携式血糖分析仪(电阻法) 校准规范
- 城市轨道交通调度员行车组织与安全防范绩效衡量表
- 486种血液代谢物与三种常见泌尿系肿瘤关联的双样本孟德尔随机化研究
- 有机肥-灌溉协同对民勤绿洲土壤性质与南瓜提质增效的调控效应
- 2025年中国千兆智能三层交换机数据监测报告
- 2025年中国冷却套数据监测报告
- 2025年中国儿童降温带数据监测报告
- 2025年中国二羟甲基丙烷数据监测报告
- 2025年中国下置式电启动汽油机数据监测报告
- 2026年表土剥离合同
- 2026青岛能源集团有限公司招聘笔试参考题库及答案解析
- 蒙阴县公费师范生招聘真题2025
- 明清时期小说课件
- 宜昌市西陵区(2025年)社区《网格员》典型题题库(含答案)
- AI在工业设计中的应用【文档课件】
- 国开2025年秋《数学思想与方法》大作业答案
- 第26课《古代诗歌五首:春望》教学课件
- 地方志编纂工作流程手册
- 儿童颜面部管理
- 中职flash考试试题及答案
评论
0/150
提交评论